SemaExpr.cpp revision 3c3b7f90a863af43fa63043d396553ecf205351c
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/ASTMutationListener.h"
20#include "clang/AST/CXXInheritance.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/EvaluatedExprVisitor.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprObjC.h"
27#include "clang/AST/RecursiveASTVisitor.h"
28#include "clang/AST/TypeLoc.h"
29#include "clang/Basic/PartialDiagnostic.h"
30#include "clang/Basic/SourceManager.h"
31#include "clang/Basic/TargetInfo.h"
32#include "clang/Lex/LiteralSupport.h"
33#include "clang/Lex/Preprocessor.h"
34#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Designator.h"
36#include "clang/Sema/Scope.h"
37#include "clang/Sema/ScopeInfo.h"
38#include "clang/Sema/ParsedTemplate.h"
39#include "clang/Sema/SemaFixItUtils.h"
40#include "clang/Sema/Template.h"
41using namespace clang;
42using namespace sema;
43
44/// \brief Determine whether the use of this declaration is valid, without
45/// emitting diagnostics.
46bool Sema::CanUseDecl(NamedDecl *D) {
47  // See if this is an auto-typed variable whose initializer we are parsing.
48  if (ParsingInitForAutoVars.count(D))
49    return false;
50
51  // See if this is a deleted function.
52  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
53    if (FD->isDeleted())
54      return false;
55  }
56
57  // See if this function is unavailable.
58  if (D->getAvailability() == AR_Unavailable &&
59      cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
60    return false;
61
62  return true;
63}
64
65static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
66                              NamedDecl *D, SourceLocation Loc,
67                              const ObjCInterfaceDecl *UnknownObjCClass) {
68  // See if this declaration is unavailable or deprecated.
69  std::string Message;
70  AvailabilityResult Result = D->getAvailability(&Message);
71  switch (Result) {
72    case AR_Available:
73    case AR_NotYetIntroduced:
74      break;
75
76    case AR_Deprecated:
77      S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
78      break;
79
80    case AR_Unavailable:
81      if (S.getCurContextAvailability() != AR_Unavailable) {
82        if (Message.empty()) {
83          if (!UnknownObjCClass)
84            S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
85          else
86            S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
87              << D->getDeclName();
88        }
89        else
90          S.Diag(Loc, diag::err_unavailable_message)
91            << D->getDeclName() << Message;
92          S.Diag(D->getLocation(), diag::note_unavailable_here)
93          << isa<FunctionDecl>(D) << false;
94      }
95      break;
96    }
97    return Result;
98}
99
100/// \brief Determine whether the use of this declaration is valid, and
101/// emit any corresponding diagnostics.
102///
103/// This routine diagnoses various problems with referencing
104/// declarations that can occur when using a declaration. For example,
105/// it might warn if a deprecated or unavailable declaration is being
106/// used, or produce an error (and return true) if a C++0x deleted
107/// function is being used.
108///
109/// \returns true if there was an error (this declaration cannot be
110/// referenced), false otherwise.
111///
112bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
113                             const ObjCInterfaceDecl *UnknownObjCClass) {
114  if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
115    // If there were any diagnostics suppressed by template argument deduction,
116    // emit them now.
117    llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
118      Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
119    if (Pos != SuppressedDiagnostics.end()) {
120      SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
121      for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
122        Diag(Suppressed[I].first, Suppressed[I].second);
123
124      // Clear out the list of suppressed diagnostics, so that we don't emit
125      // them again for this specialization. However, we don't obsolete this
126      // entry from the table, because we want to avoid ever emitting these
127      // diagnostics again.
128      Suppressed.clear();
129    }
130  }
131
132  // See if this is an auto-typed variable whose initializer we are parsing.
133  if (ParsingInitForAutoVars.count(D)) {
134    Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
135      << D->getDeclName();
136    return true;
137  }
138
139  // See if this is a deleted function.
140  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
141    if (FD->isDeleted()) {
142      Diag(Loc, diag::err_deleted_function_use);
143      Diag(D->getLocation(), diag::note_unavailable_here) << 1 << true;
144      return true;
145    }
146  }
147  AvailabilityResult Result =
148    DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
149
150  // Warn if this is used but marked unused.
151  if (D->hasAttr<UnusedAttr>())
152    Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
153  // For available enumerator, it will become unavailable/deprecated
154  // if its enum declaration is as such.
155  if (Result == AR_Available)
156    if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
157      const DeclContext *DC = ECD->getDeclContext();
158      if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
159        DiagnoseAvailabilityOfDecl(*this,
160                          const_cast< EnumDecl *>(TheEnumDecl),
161                          Loc, UnknownObjCClass);
162    }
163  return false;
164}
165
166/// \brief Retrieve the message suffix that should be added to a
167/// diagnostic complaining about the given function being deleted or
168/// unavailable.
169std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
170  // FIXME: C++0x implicitly-deleted special member functions could be
171  // detected here so that we could improve diagnostics to say, e.g.,
172  // "base class 'A' had a deleted copy constructor".
173  if (FD->isDeleted())
174    return std::string();
175
176  std::string Message;
177  if (FD->getAvailability(&Message))
178    return ": " + Message;
179
180  return std::string();
181}
182
183/// DiagnoseSentinelCalls - This routine checks whether a call or
184/// message-send is to a declaration with the sentinel attribute, and
185/// if so, it checks that the requirements of the sentinel are
186/// satisfied.
187void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
188                                 Expr **args, unsigned numArgs) {
189  const SentinelAttr *attr = D->getAttr<SentinelAttr>();
190  if (!attr)
191    return;
192
193  // The number of formal parameters of the declaration.
194  unsigned numFormalParams;
195
196  // The kind of declaration.  This is also an index into a %select in
197  // the diagnostic.
198  enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
199
200  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
201    numFormalParams = MD->param_size();
202    calleeType = CT_Method;
203  } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
204    numFormalParams = FD->param_size();
205    calleeType = CT_Function;
206  } else if (isa<VarDecl>(D)) {
207    QualType type = cast<ValueDecl>(D)->getType();
208    const FunctionType *fn = 0;
209    if (const PointerType *ptr = type->getAs<PointerType>()) {
210      fn = ptr->getPointeeType()->getAs<FunctionType>();
211      if (!fn) return;
212      calleeType = CT_Function;
213    } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
214      fn = ptr->getPointeeType()->castAs<FunctionType>();
215      calleeType = CT_Block;
216    } else {
217      return;
218    }
219
220    if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
221      numFormalParams = proto->getNumArgs();
222    } else {
223      numFormalParams = 0;
224    }
225  } else {
226    return;
227  }
228
229  // "nullPos" is the number of formal parameters at the end which
230  // effectively count as part of the variadic arguments.  This is
231  // useful if you would prefer to not have *any* formal parameters,
232  // but the language forces you to have at least one.
233  unsigned nullPos = attr->getNullPos();
234  assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
235  numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
236
237  // The number of arguments which should follow the sentinel.
238  unsigned numArgsAfterSentinel = attr->getSentinel();
239
240  // If there aren't enough arguments for all the formal parameters,
241  // the sentinel, and the args after the sentinel, complain.
242  if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
243    Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
244    Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
245    return;
246  }
247
248  // Otherwise, find the sentinel expression.
249  Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
250  if (!sentinelExpr) return;
251  if (sentinelExpr->isValueDependent()) return;
252
253  // nullptr_t is always treated as null.
254  if (sentinelExpr->getType()->isNullPtrType()) return;
255
256  if (sentinelExpr->getType()->isAnyPointerType() &&
257      sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
258                                            Expr::NPC_ValueDependentIsNull))
259    return;
260
261  // Unfortunately, __null has type 'int'.
262  if (isa<GNUNullExpr>(sentinelExpr)) return;
263
264  // Pick a reasonable string to insert.  Optimistically use 'nil' or
265  // 'NULL' if those are actually defined in the context.  Only use
266  // 'nil' for ObjC methods, where it's much more likely that the
267  // variadic arguments form a list of object pointers.
268  SourceLocation MissingNilLoc
269    = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
270  std::string NullValue;
271  if (calleeType == CT_Method &&
272      PP.getIdentifierInfo("nil")->hasMacroDefinition())
273    NullValue = "nil";
274  else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
275    NullValue = "NULL";
276  else
277    NullValue = "(void*) 0";
278
279  if (MissingNilLoc.isInvalid())
280    Diag(Loc, diag::warn_missing_sentinel) << calleeType;
281  else
282    Diag(MissingNilLoc, diag::warn_missing_sentinel)
283      << calleeType
284      << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
285  Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
286}
287
288SourceRange Sema::getExprRange(Expr *E) const {
289  return E ? E->getSourceRange() : SourceRange();
290}
291
292//===----------------------------------------------------------------------===//
293//  Standard Promotions and Conversions
294//===----------------------------------------------------------------------===//
295
296/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
297ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
298  // Handle any placeholder expressions which made it here.
299  if (E->getType()->isPlaceholderType()) {
300    ExprResult result = CheckPlaceholderExpr(E);
301    if (result.isInvalid()) return ExprError();
302    E = result.take();
303  }
304
305  QualType Ty = E->getType();
306  assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
307
308  if (Ty->isFunctionType())
309    E = ImpCastExprToType(E, Context.getPointerType(Ty),
310                          CK_FunctionToPointerDecay).take();
311  else if (Ty->isArrayType()) {
312    // In C90 mode, arrays only promote to pointers if the array expression is
313    // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
314    // type 'array of type' is converted to an expression that has type 'pointer
315    // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
316    // that has type 'array of type' ...".  The relevant change is "an lvalue"
317    // (C90) to "an expression" (C99).
318    //
319    // C++ 4.2p1:
320    // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
321    // T" can be converted to an rvalue of type "pointer to T".
322    //
323    if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
324      E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
325                            CK_ArrayToPointerDecay).take();
326  }
327  return Owned(E);
328}
329
330static void CheckForNullPointerDereference(Sema &S, Expr *E) {
331  // Check to see if we are dereferencing a null pointer.  If so,
332  // and if not volatile-qualified, this is undefined behavior that the
333  // optimizer will delete, so warn about it.  People sometimes try to use this
334  // to get a deterministic trap and are surprised by clang's behavior.  This
335  // only handles the pattern "*null", which is a very syntactic check.
336  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
337    if (UO->getOpcode() == UO_Deref &&
338        UO->getSubExpr()->IgnoreParenCasts()->
339          isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
340        !UO->getType().isVolatileQualified()) {
341    S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
342                          S.PDiag(diag::warn_indirection_through_null)
343                            << UO->getSubExpr()->getSourceRange());
344    S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
345                        S.PDiag(diag::note_indirection_through_null));
346  }
347}
348
349ExprResult Sema::DefaultLvalueConversion(Expr *E) {
350  // Handle any placeholder expressions which made it here.
351  if (E->getType()->isPlaceholderType()) {
352    ExprResult result = CheckPlaceholderExpr(E);
353    if (result.isInvalid()) return ExprError();
354    E = result.take();
355  }
356
357  // C++ [conv.lval]p1:
358  //   A glvalue of a non-function, non-array type T can be
359  //   converted to a prvalue.
360  if (!E->isGLValue()) return Owned(E);
361
362  QualType T = E->getType();
363  assert(!T.isNull() && "r-value conversion on typeless expression?");
364
365  // We can't do lvalue-to-rvalue on atomics yet.
366  if (T->isAtomicType())
367    return Owned(E);
368
369  // We don't want to throw lvalue-to-rvalue casts on top of
370  // expressions of certain types in C++.
371  if (getLangOptions().CPlusPlus &&
372      (E->getType() == Context.OverloadTy ||
373       T->isDependentType() ||
374       T->isRecordType()))
375    return Owned(E);
376
377  // The C standard is actually really unclear on this point, and
378  // DR106 tells us what the result should be but not why.  It's
379  // generally best to say that void types just doesn't undergo
380  // lvalue-to-rvalue at all.  Note that expressions of unqualified
381  // 'void' type are never l-values, but qualified void can be.
382  if (T->isVoidType())
383    return Owned(E);
384
385  CheckForNullPointerDereference(*this, E);
386
387  // C++ [conv.lval]p1:
388  //   [...] If T is a non-class type, the type of the prvalue is the
389  //   cv-unqualified version of T. Otherwise, the type of the
390  //   rvalue is T.
391  //
392  // C99 6.3.2.1p2:
393  //   If the lvalue has qualified type, the value has the unqualified
394  //   version of the type of the lvalue; otherwise, the value has the
395  //   type of the lvalue.
396  if (T.hasQualifiers())
397    T = T.getUnqualifiedType();
398
399  ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
400                                                  E, 0, VK_RValue));
401
402  return Res;
403}
404
405ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
406  ExprResult Res = DefaultFunctionArrayConversion(E);
407  if (Res.isInvalid())
408    return ExprError();
409  Res = DefaultLvalueConversion(Res.take());
410  if (Res.isInvalid())
411    return ExprError();
412  return move(Res);
413}
414
415
416/// UsualUnaryConversions - Performs various conversions that are common to most
417/// operators (C99 6.3). The conversions of array and function types are
418/// sometimes suppressed. For example, the array->pointer conversion doesn't
419/// apply if the array is an argument to the sizeof or address (&) operators.
420/// In these instances, this routine should *not* be called.
421ExprResult Sema::UsualUnaryConversions(Expr *E) {
422  // First, convert to an r-value.
423  ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
424  if (Res.isInvalid())
425    return Owned(E);
426  E = Res.take();
427
428  QualType Ty = E->getType();
429  assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
430
431  // Half FP is a bit different: it's a storage-only type, meaning that any
432  // "use" of it should be promoted to float.
433  if (Ty->isHalfType())
434    return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
435
436  // Try to perform integral promotions if the object has a theoretically
437  // promotable type.
438  if (Ty->isIntegralOrUnscopedEnumerationType()) {
439    // C99 6.3.1.1p2:
440    //
441    //   The following may be used in an expression wherever an int or
442    //   unsigned int may be used:
443    //     - an object or expression with an integer type whose integer
444    //       conversion rank is less than or equal to the rank of int
445    //       and unsigned int.
446    //     - A bit-field of type _Bool, int, signed int, or unsigned int.
447    //
448    //   If an int can represent all values of the original type, the
449    //   value is converted to an int; otherwise, it is converted to an
450    //   unsigned int. These are called the integer promotions. All
451    //   other types are unchanged by the integer promotions.
452
453    QualType PTy = Context.isPromotableBitField(E);
454    if (!PTy.isNull()) {
455      E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
456      return Owned(E);
457    }
458    if (Ty->isPromotableIntegerType()) {
459      QualType PT = Context.getPromotedIntegerType(Ty);
460      E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
461      return Owned(E);
462    }
463  }
464  return Owned(E);
465}
466
467/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
468/// do not have a prototype. Arguments that have type float are promoted to
469/// double. All other argument types are converted by UsualUnaryConversions().
470ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
471  QualType Ty = E->getType();
472  assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
473
474  ExprResult Res = UsualUnaryConversions(E);
475  if (Res.isInvalid())
476    return Owned(E);
477  E = Res.take();
478
479  // If this is a 'float' (CVR qualified or typedef) promote to double.
480  if (Ty->isSpecificBuiltinType(BuiltinType::Float))
481    E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
482
483  // C++ performs lvalue-to-rvalue conversion as a default argument
484  // promotion, even on class types, but note:
485  //   C++11 [conv.lval]p2:
486  //     When an lvalue-to-rvalue conversion occurs in an unevaluated
487  //     operand or a subexpression thereof the value contained in the
488  //     referenced object is not accessed. Otherwise, if the glvalue
489  //     has a class type, the conversion copy-initializes a temporary
490  //     of type T from the glvalue and the result of the conversion
491  //     is a prvalue for the temporary.
492  // FIXME: add some way to gate this entire thing for correctness in
493  // potentially potentially evaluated contexts.
494  if (getLangOptions().CPlusPlus && E->isGLValue() &&
495      ExprEvalContexts.back().Context != Unevaluated) {
496    ExprResult Temp = PerformCopyInitialization(
497                       InitializedEntity::InitializeTemporary(E->getType()),
498                                                E->getExprLoc(),
499                                                Owned(E));
500    if (Temp.isInvalid())
501      return ExprError();
502    E = Temp.get();
503  }
504
505  return Owned(E);
506}
507
508/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
509/// will warn if the resulting type is not a POD type, and rejects ObjC
510/// interfaces passed by value.
511ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
512                                                  FunctionDecl *FDecl) {
513  if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
514    // Strip the unbridged-cast placeholder expression off, if applicable.
515    if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
516        (CT == VariadicMethod ||
517         (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
518      E = stripARCUnbridgedCast(E);
519
520    // Otherwise, do normal placeholder checking.
521    } else {
522      ExprResult ExprRes = CheckPlaceholderExpr(E);
523      if (ExprRes.isInvalid())
524        return ExprError();
525      E = ExprRes.take();
526    }
527  }
528
529  ExprResult ExprRes = DefaultArgumentPromotion(E);
530  if (ExprRes.isInvalid())
531    return ExprError();
532  E = ExprRes.take();
533
534  // Don't allow one to pass an Objective-C interface to a vararg.
535  if (E->getType()->isObjCObjectType() &&
536    DiagRuntimeBehavior(E->getLocStart(), 0,
537                        PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
538                          << E->getType() << CT))
539    return ExprError();
540
541  // Complain about passing non-POD types through varargs. However, don't
542  // perform this check for incomplete types, which we can get here when we're
543  // in an unevaluated context.
544  if (!E->getType()->isIncompleteType() && !E->getType().isPODType(Context)) {
545    // C++0x [expr.call]p7:
546    //   Passing a potentially-evaluated argument of class type (Clause 9)
547    //   having a non-trivial copy constructor, a non-trivial move constructor,
548    //   or a non-trivial destructor, with no corresponding parameter,
549    //   is conditionally-supported with implementation-defined semantics.
550    bool TrivialEnough = false;
551    if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType())  {
552      if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
553        if (Record->hasTrivialCopyConstructor() &&
554            Record->hasTrivialMoveConstructor() &&
555            Record->hasTrivialDestructor()) {
556          DiagRuntimeBehavior(E->getLocStart(), 0,
557            PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
558              << E->getType() << CT);
559          TrivialEnough = true;
560        }
561      }
562    }
563
564    if (!TrivialEnough &&
565        getLangOptions().ObjCAutoRefCount &&
566        E->getType()->isObjCLifetimeType())
567      TrivialEnough = true;
568
569    if (TrivialEnough) {
570      // Nothing to diagnose. This is okay.
571    } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
572                          PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
573                            << getLangOptions().CPlusPlus0x << E->getType()
574                            << CT)) {
575      // Turn this into a trap.
576      CXXScopeSpec SS;
577      UnqualifiedId Name;
578      Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
579                         E->getLocStart());
580      ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
581      if (TrapFn.isInvalid())
582        return ExprError();
583
584      ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
585                                      MultiExprArg(), E->getLocEnd());
586      if (Call.isInvalid())
587        return ExprError();
588
589      ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
590                                    Call.get(), E);
591      if (Comma.isInvalid())
592        return ExprError();
593      E = Comma.get();
594    }
595  }
596
597  return Owned(E);
598}
599
600/// \brief Converts an integer to complex float type.  Helper function of
601/// UsualArithmeticConversions()
602///
603/// \return false if the integer expression is an integer type and is
604/// successfully converted to the complex type.
605static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
606                                                  ExprResult &ComplexExpr,
607                                                  QualType IntTy,
608                                                  QualType ComplexTy,
609                                                  bool SkipCast) {
610  if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
611  if (SkipCast) return false;
612  if (IntTy->isIntegerType()) {
613    QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
614    IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
615    IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
616                                  CK_FloatingRealToComplex);
617  } else {
618    assert(IntTy->isComplexIntegerType());
619    IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
620                                  CK_IntegralComplexToFloatingComplex);
621  }
622  return false;
623}
624
625/// \brief Takes two complex float types and converts them to the same type.
626/// Helper function of UsualArithmeticConversions()
627static QualType
628handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
629                                            ExprResult &RHS, QualType LHSType,
630                                            QualType RHSType,
631                                            bool IsCompAssign) {
632  int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
633
634  if (order < 0) {
635    // _Complex float -> _Complex double
636    if (!IsCompAssign)
637      LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
638    return RHSType;
639  }
640  if (order > 0)
641    // _Complex float -> _Complex double
642    RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
643  return LHSType;
644}
645
646/// \brief Converts otherExpr to complex float and promotes complexExpr if
647/// necessary.  Helper function of UsualArithmeticConversions()
648static QualType handleOtherComplexFloatConversion(Sema &S,
649                                                  ExprResult &ComplexExpr,
650                                                  ExprResult &OtherExpr,
651                                                  QualType ComplexTy,
652                                                  QualType OtherTy,
653                                                  bool ConvertComplexExpr,
654                                                  bool ConvertOtherExpr) {
655  int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
656
657  // If just the complexExpr is complex, the otherExpr needs to be converted,
658  // and the complexExpr might need to be promoted.
659  if (order > 0) { // complexExpr is wider
660    // float -> _Complex double
661    if (ConvertOtherExpr) {
662      QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
663      OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
664      OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
665                                      CK_FloatingRealToComplex);
666    }
667    return ComplexTy;
668  }
669
670  // otherTy is at least as wide.  Find its corresponding complex type.
671  QualType result = (order == 0 ? ComplexTy :
672                                  S.Context.getComplexType(OtherTy));
673
674  // double -> _Complex double
675  if (ConvertOtherExpr)
676    OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
677                                    CK_FloatingRealToComplex);
678
679  // _Complex float -> _Complex double
680  if (ConvertComplexExpr && order < 0)
681    ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
682                                      CK_FloatingComplexCast);
683
684  return result;
685}
686
687/// \brief Handle arithmetic conversion with complex types.  Helper function of
688/// UsualArithmeticConversions()
689static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
690                                             ExprResult &RHS, QualType LHSType,
691                                             QualType RHSType,
692                                             bool IsCompAssign) {
693  // if we have an integer operand, the result is the complex type.
694  if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
695                                             /*skipCast*/false))
696    return LHSType;
697  if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
698                                             /*skipCast*/IsCompAssign))
699    return RHSType;
700
701  // This handles complex/complex, complex/float, or float/complex.
702  // When both operands are complex, the shorter operand is converted to the
703  // type of the longer, and that is the type of the result. This corresponds
704  // to what is done when combining two real floating-point operands.
705  // The fun begins when size promotion occur across type domains.
706  // From H&S 6.3.4: When one operand is complex and the other is a real
707  // floating-point type, the less precise type is converted, within it's
708  // real or complex domain, to the precision of the other type. For example,
709  // when combining a "long double" with a "double _Complex", the
710  // "double _Complex" is promoted to "long double _Complex".
711
712  bool LHSComplexFloat = LHSType->isComplexType();
713  bool RHSComplexFloat = RHSType->isComplexType();
714
715  // If both are complex, just cast to the more precise type.
716  if (LHSComplexFloat && RHSComplexFloat)
717    return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
718                                                       LHSType, RHSType,
719                                                       IsCompAssign);
720
721  // If only one operand is complex, promote it if necessary and convert the
722  // other operand to complex.
723  if (LHSComplexFloat)
724    return handleOtherComplexFloatConversion(
725        S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
726        /*convertOtherExpr*/ true);
727
728  assert(RHSComplexFloat);
729  return handleOtherComplexFloatConversion(
730      S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
731      /*convertOtherExpr*/ !IsCompAssign);
732}
733
734/// \brief Hande arithmetic conversion from integer to float.  Helper function
735/// of UsualArithmeticConversions()
736static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
737                                           ExprResult &IntExpr,
738                                           QualType FloatTy, QualType IntTy,
739                                           bool ConvertFloat, bool ConvertInt) {
740  if (IntTy->isIntegerType()) {
741    if (ConvertInt)
742      // Convert intExpr to the lhs floating point type.
743      IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
744                                    CK_IntegralToFloating);
745    return FloatTy;
746  }
747
748  // Convert both sides to the appropriate complex float.
749  assert(IntTy->isComplexIntegerType());
750  QualType result = S.Context.getComplexType(FloatTy);
751
752  // _Complex int -> _Complex float
753  if (ConvertInt)
754    IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
755                                  CK_IntegralComplexToFloatingComplex);
756
757  // float -> _Complex float
758  if (ConvertFloat)
759    FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
760                                    CK_FloatingRealToComplex);
761
762  return result;
763}
764
765/// \brief Handle arithmethic conversion with floating point types.  Helper
766/// function of UsualArithmeticConversions()
767static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
768                                      ExprResult &RHS, QualType LHSType,
769                                      QualType RHSType, bool IsCompAssign) {
770  bool LHSFloat = LHSType->isRealFloatingType();
771  bool RHSFloat = RHSType->isRealFloatingType();
772
773  // If we have two real floating types, convert the smaller operand
774  // to the bigger result.
775  if (LHSFloat && RHSFloat) {
776    int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
777    if (order > 0) {
778      RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
779      return LHSType;
780    }
781
782    assert(order < 0 && "illegal float comparison");
783    if (!IsCompAssign)
784      LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
785    return RHSType;
786  }
787
788  if (LHSFloat)
789    return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
790                                      /*convertFloat=*/!IsCompAssign,
791                                      /*convertInt=*/ true);
792  assert(RHSFloat);
793  return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
794                                    /*convertInt=*/ true,
795                                    /*convertFloat=*/!IsCompAssign);
796}
797
798/// \brief Handle conversions with GCC complex int extension.  Helper function
799/// of UsualArithmeticConversions()
800// FIXME: if the operands are (int, _Complex long), we currently
801// don't promote the complex.  Also, signedness?
802static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
803                                           ExprResult &RHS, QualType LHSType,
804                                           QualType RHSType,
805                                           bool IsCompAssign) {
806  const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
807  const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
808
809  if (LHSComplexInt && RHSComplexInt) {
810    int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
811                                              RHSComplexInt->getElementType());
812    assert(order && "inequal types with equal element ordering");
813    if (order > 0) {
814      // _Complex int -> _Complex long
815      RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
816      return LHSType;
817    }
818
819    if (!IsCompAssign)
820      LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
821    return RHSType;
822  }
823
824  if (LHSComplexInt) {
825    // int -> _Complex int
826    RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
827    return LHSType;
828  }
829
830  assert(RHSComplexInt);
831  // int -> _Complex int
832  if (!IsCompAssign)
833    LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
834  return RHSType;
835}
836
837/// \brief Handle integer arithmetic conversions.  Helper function of
838/// UsualArithmeticConversions()
839static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
840                                        ExprResult &RHS, QualType LHSType,
841                                        QualType RHSType, bool IsCompAssign) {
842  // The rules for this case are in C99 6.3.1.8
843  int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
844  bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
845  bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
846  if (LHSSigned == RHSSigned) {
847    // Same signedness; use the higher-ranked type
848    if (order >= 0) {
849      RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
850      return LHSType;
851    } else if (!IsCompAssign)
852      LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
853    return RHSType;
854  } else if (order != (LHSSigned ? 1 : -1)) {
855    // The unsigned type has greater than or equal rank to the
856    // signed type, so use the unsigned type
857    if (RHSSigned) {
858      RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
859      return LHSType;
860    } else if (!IsCompAssign)
861      LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
862    return RHSType;
863  } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
864    // The two types are different widths; if we are here, that
865    // means the signed type is larger than the unsigned type, so
866    // use the signed type.
867    if (LHSSigned) {
868      RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
869      return LHSType;
870    } else if (!IsCompAssign)
871      LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
872    return RHSType;
873  } else {
874    // The signed type is higher-ranked than the unsigned type,
875    // but isn't actually any bigger (like unsigned int and long
876    // on most 32-bit systems).  Use the unsigned type corresponding
877    // to the signed type.
878    QualType result =
879      S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
880    RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
881    if (!IsCompAssign)
882      LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
883    return result;
884  }
885}
886
887/// UsualArithmeticConversions - Performs various conversions that are common to
888/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
889/// routine returns the first non-arithmetic type found. The client is
890/// responsible for emitting appropriate error diagnostics.
891/// FIXME: verify the conversion rules for "complex int" are consistent with
892/// GCC.
893QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
894                                          bool IsCompAssign) {
895  if (!IsCompAssign) {
896    LHS = UsualUnaryConversions(LHS.take());
897    if (LHS.isInvalid())
898      return QualType();
899  }
900
901  RHS = UsualUnaryConversions(RHS.take());
902  if (RHS.isInvalid())
903    return QualType();
904
905  // For conversion purposes, we ignore any qualifiers.
906  // For example, "const float" and "float" are equivalent.
907  QualType LHSType =
908    Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
909  QualType RHSType =
910    Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
911
912  // If both types are identical, no conversion is needed.
913  if (LHSType == RHSType)
914    return LHSType;
915
916  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
917  // The caller can deal with this (e.g. pointer + int).
918  if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
919    return LHSType;
920
921  // Apply unary and bitfield promotions to the LHS's type.
922  QualType LHSUnpromotedType = LHSType;
923  if (LHSType->isPromotableIntegerType())
924    LHSType = Context.getPromotedIntegerType(LHSType);
925  QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
926  if (!LHSBitfieldPromoteTy.isNull())
927    LHSType = LHSBitfieldPromoteTy;
928  if (LHSType != LHSUnpromotedType && !IsCompAssign)
929    LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
930
931  // If both types are identical, no conversion is needed.
932  if (LHSType == RHSType)
933    return LHSType;
934
935  // At this point, we have two different arithmetic types.
936
937  // Handle complex types first (C99 6.3.1.8p1).
938  if (LHSType->isComplexType() || RHSType->isComplexType())
939    return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
940                                        IsCompAssign);
941
942  // Now handle "real" floating types (i.e. float, double, long double).
943  if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
944    return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
945                                 IsCompAssign);
946
947  // Handle GCC complex int extension.
948  if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
949    return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
950                                      IsCompAssign);
951
952  // Finally, we have two differing integer types.
953  return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
954                                 IsCompAssign);
955}
956
957//===----------------------------------------------------------------------===//
958//  Semantic Analysis for various Expression Types
959//===----------------------------------------------------------------------===//
960
961
962ExprResult
963Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
964                                SourceLocation DefaultLoc,
965                                SourceLocation RParenLoc,
966                                Expr *ControllingExpr,
967                                MultiTypeArg ArgTypes,
968                                MultiExprArg ArgExprs) {
969  unsigned NumAssocs = ArgTypes.size();
970  assert(NumAssocs == ArgExprs.size());
971
972  ParsedType *ParsedTypes = ArgTypes.release();
973  Expr **Exprs = ArgExprs.release();
974
975  TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
976  for (unsigned i = 0; i < NumAssocs; ++i) {
977    if (ParsedTypes[i])
978      (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
979    else
980      Types[i] = 0;
981  }
982
983  ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
984                                             ControllingExpr, Types, Exprs,
985                                             NumAssocs);
986  delete [] Types;
987  return ER;
988}
989
990ExprResult
991Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
992                                 SourceLocation DefaultLoc,
993                                 SourceLocation RParenLoc,
994                                 Expr *ControllingExpr,
995                                 TypeSourceInfo **Types,
996                                 Expr **Exprs,
997                                 unsigned NumAssocs) {
998  bool TypeErrorFound = false,
999       IsResultDependent = ControllingExpr->isTypeDependent(),
1000       ContainsUnexpandedParameterPack
1001         = ControllingExpr->containsUnexpandedParameterPack();
1002
1003  for (unsigned i = 0; i < NumAssocs; ++i) {
1004    if (Exprs[i]->containsUnexpandedParameterPack())
1005      ContainsUnexpandedParameterPack = true;
1006
1007    if (Types[i]) {
1008      if (Types[i]->getType()->containsUnexpandedParameterPack())
1009        ContainsUnexpandedParameterPack = true;
1010
1011      if (Types[i]->getType()->isDependentType()) {
1012        IsResultDependent = true;
1013      } else {
1014        // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
1015        // complete object type other than a variably modified type."
1016        unsigned D = 0;
1017        if (Types[i]->getType()->isIncompleteType())
1018          D = diag::err_assoc_type_incomplete;
1019        else if (!Types[i]->getType()->isObjectType())
1020          D = diag::err_assoc_type_nonobject;
1021        else if (Types[i]->getType()->isVariablyModifiedType())
1022          D = diag::err_assoc_type_variably_modified;
1023
1024        if (D != 0) {
1025          Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1026            << Types[i]->getTypeLoc().getSourceRange()
1027            << Types[i]->getType();
1028          TypeErrorFound = true;
1029        }
1030
1031        // C1X 6.5.1.1p2 "No two generic associations in the same generic
1032        // selection shall specify compatible types."
1033        for (unsigned j = i+1; j < NumAssocs; ++j)
1034          if (Types[j] && !Types[j]->getType()->isDependentType() &&
1035              Context.typesAreCompatible(Types[i]->getType(),
1036                                         Types[j]->getType())) {
1037            Diag(Types[j]->getTypeLoc().getBeginLoc(),
1038                 diag::err_assoc_compatible_types)
1039              << Types[j]->getTypeLoc().getSourceRange()
1040              << Types[j]->getType()
1041              << Types[i]->getType();
1042            Diag(Types[i]->getTypeLoc().getBeginLoc(),
1043                 diag::note_compat_assoc)
1044              << Types[i]->getTypeLoc().getSourceRange()
1045              << Types[i]->getType();
1046            TypeErrorFound = true;
1047          }
1048      }
1049    }
1050  }
1051  if (TypeErrorFound)
1052    return ExprError();
1053
1054  // If we determined that the generic selection is result-dependent, don't
1055  // try to compute the result expression.
1056  if (IsResultDependent)
1057    return Owned(new (Context) GenericSelectionExpr(
1058                   Context, KeyLoc, ControllingExpr,
1059                   Types, Exprs, NumAssocs, DefaultLoc,
1060                   RParenLoc, ContainsUnexpandedParameterPack));
1061
1062  SmallVector<unsigned, 1> CompatIndices;
1063  unsigned DefaultIndex = -1U;
1064  for (unsigned i = 0; i < NumAssocs; ++i) {
1065    if (!Types[i])
1066      DefaultIndex = i;
1067    else if (Context.typesAreCompatible(ControllingExpr->getType(),
1068                                        Types[i]->getType()))
1069      CompatIndices.push_back(i);
1070  }
1071
1072  // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
1073  // type compatible with at most one of the types named in its generic
1074  // association list."
1075  if (CompatIndices.size() > 1) {
1076    // We strip parens here because the controlling expression is typically
1077    // parenthesized in macro definitions.
1078    ControllingExpr = ControllingExpr->IgnoreParens();
1079    Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1080      << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1081      << (unsigned) CompatIndices.size();
1082    for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
1083         E = CompatIndices.end(); I != E; ++I) {
1084      Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1085           diag::note_compat_assoc)
1086        << Types[*I]->getTypeLoc().getSourceRange()
1087        << Types[*I]->getType();
1088    }
1089    return ExprError();
1090  }
1091
1092  // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
1093  // its controlling expression shall have type compatible with exactly one of
1094  // the types named in its generic association list."
1095  if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1096    // We strip parens here because the controlling expression is typically
1097    // parenthesized in macro definitions.
1098    ControllingExpr = ControllingExpr->IgnoreParens();
1099    Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1100      << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1101    return ExprError();
1102  }
1103
1104  // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
1105  // type name that is compatible with the type of the controlling expression,
1106  // then the result expression of the generic selection is the expression
1107  // in that generic association. Otherwise, the result expression of the
1108  // generic selection is the expression in the default generic association."
1109  unsigned ResultIndex =
1110    CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1111
1112  return Owned(new (Context) GenericSelectionExpr(
1113                 Context, KeyLoc, ControllingExpr,
1114                 Types, Exprs, NumAssocs, DefaultLoc,
1115                 RParenLoc, ContainsUnexpandedParameterPack,
1116                 ResultIndex));
1117}
1118
1119/// ActOnStringLiteral - The specified tokens were lexed as pasted string
1120/// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1121/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1122/// multiple tokens.  However, the common case is that StringToks points to one
1123/// string.
1124///
1125ExprResult
1126Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
1127  assert(NumStringToks && "Must have at least one string!");
1128
1129  StringLiteralParser Literal(StringToks, NumStringToks, PP);
1130  if (Literal.hadError)
1131    return ExprError();
1132
1133  SmallVector<SourceLocation, 4> StringTokLocs;
1134  for (unsigned i = 0; i != NumStringToks; ++i)
1135    StringTokLocs.push_back(StringToks[i].getLocation());
1136
1137  QualType StrTy = Context.CharTy;
1138  if (Literal.isWide())
1139    StrTy = Context.getWCharType();
1140  else if (Literal.isUTF16())
1141    StrTy = Context.Char16Ty;
1142  else if (Literal.isUTF32())
1143    StrTy = Context.Char32Ty;
1144  else if (Literal.Pascal)
1145    StrTy = Context.UnsignedCharTy;
1146
1147  StringLiteral::StringKind Kind = StringLiteral::Ascii;
1148  if (Literal.isWide())
1149    Kind = StringLiteral::Wide;
1150  else if (Literal.isUTF8())
1151    Kind = StringLiteral::UTF8;
1152  else if (Literal.isUTF16())
1153    Kind = StringLiteral::UTF16;
1154  else if (Literal.isUTF32())
1155    Kind = StringLiteral::UTF32;
1156
1157  // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1158  if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
1159    StrTy.addConst();
1160
1161  // Get an array type for the string, according to C99 6.4.5.  This includes
1162  // the nul terminator character as well as the string length for pascal
1163  // strings.
1164  StrTy = Context.getConstantArrayType(StrTy,
1165                                 llvm::APInt(32, Literal.GetNumStringChars()+1),
1166                                       ArrayType::Normal, 0);
1167
1168  // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1169  return Owned(StringLiteral::Create(Context, Literal.GetString(),
1170                                     Kind, Literal.Pascal, StrTy,
1171                                     &StringTokLocs[0],
1172                                     StringTokLocs.size()));
1173}
1174
1175enum CaptureResult {
1176  /// No capture is required.
1177  CR_NoCapture,
1178
1179  /// A capture is required.
1180  CR_Capture,
1181
1182  /// A by-ref capture is required.
1183  CR_CaptureByRef,
1184
1185  /// An error occurred when trying to capture the given variable.
1186  CR_Error
1187};
1188
1189/// Diagnose an uncapturable value reference.
1190///
1191/// \param var - the variable referenced
1192/// \param DC - the context which we couldn't capture through
1193static CaptureResult
1194diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
1195                                   VarDecl *var, DeclContext *DC) {
1196  switch (S.ExprEvalContexts.back().Context) {
1197  case Sema::Unevaluated:
1198    // The argument will never be evaluated, so don't complain.
1199    return CR_NoCapture;
1200
1201  case Sema::PotentiallyEvaluated:
1202  case Sema::PotentiallyEvaluatedIfUsed:
1203    break;
1204
1205  case Sema::PotentiallyPotentiallyEvaluated:
1206    // FIXME: delay these!
1207    break;
1208  }
1209
1210  // Don't diagnose about capture if we're not actually in code right
1211  // now; in general, there are more appropriate places that will
1212  // diagnose this.
1213  if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1214
1215  // Certain madnesses can happen with parameter declarations, which
1216  // we want to ignore.
1217  if (isa<ParmVarDecl>(var)) {
1218    // - If the parameter still belongs to the translation unit, then
1219    //   we're actually just using one parameter in the declaration of
1220    //   the next.  This is useful in e.g. VLAs.
1221    if (isa<TranslationUnitDecl>(var->getDeclContext()))
1222      return CR_NoCapture;
1223
1224    // - This particular madness can happen in ill-formed default
1225    //   arguments; claim it's okay and let downstream code handle it.
1226    if (S.CurContext == var->getDeclContext()->getParent())
1227      return CR_NoCapture;
1228  }
1229
1230  DeclarationName functionName;
1231  if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1232    functionName = fn->getDeclName();
1233  // FIXME: variable from enclosing block that we couldn't capture from!
1234
1235  S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1236    << var->getIdentifier() << functionName;
1237  S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1238    << var->getIdentifier();
1239
1240  return CR_Error;
1241}
1242
1243/// There is a well-formed capture at a particular scope level;
1244/// propagate it through all the nested blocks.
1245static CaptureResult propagateCapture(Sema &S, unsigned ValidScopeIndex,
1246                                      const BlockDecl::Capture &Capture) {
1247  VarDecl *var = Capture.getVariable();
1248
1249  // Update all the inner blocks with the capture information.
1250  for (unsigned i = ValidScopeIndex + 1, e = S.FunctionScopes.size();
1251         i != e; ++i) {
1252    BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1253    innerBlock->Captures.push_back(
1254      BlockDecl::Capture(Capture.getVariable(), Capture.isByRef(),
1255                         /*nested*/ true, Capture.getCopyExpr()));
1256    innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1257  }
1258
1259  return Capture.isByRef() ? CR_CaptureByRef : CR_Capture;
1260}
1261
1262/// shouldCaptureValueReference - Determine if a reference to the
1263/// given value in the current context requires a variable capture.
1264///
1265/// This also keeps the captures set in the BlockScopeInfo records
1266/// up-to-date.
1267static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
1268                                                 ValueDecl *Value) {
1269  // Only variables ever require capture.
1270  VarDecl *var = dyn_cast<VarDecl>(Value);
1271  if (!var) return CR_NoCapture;
1272
1273  // Fast path: variables from the current context never require capture.
1274  DeclContext *DC = S.CurContext;
1275  if (var->getDeclContext() == DC) return CR_NoCapture;
1276
1277  // Only variables with local storage require capture.
1278  // FIXME: What about 'const' variables in C++?
1279  if (!var->hasLocalStorage()) return CR_NoCapture;
1280
1281  // Otherwise, we need to capture.
1282
1283  unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
1284  do {
1285    // Only blocks (and eventually C++0x closures) can capture; other
1286    // scopes don't work.
1287    if (!isa<BlockDecl>(DC))
1288      return diagnoseUncapturableValueReference(S, loc, var, DC);
1289
1290    BlockScopeInfo *blockScope =
1291      cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1292    assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1293
1294    // Check whether we've already captured it in this block.  If so,
1295    // we're done.
1296    if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1297      return propagateCapture(S, functionScopesIndex,
1298                              blockScope->Captures[indexPlus1 - 1]);
1299
1300    functionScopesIndex--;
1301    DC = cast<BlockDecl>(DC)->getDeclContext();
1302  } while (var->getDeclContext() != DC);
1303
1304  // Okay, we descended all the way to the block that defines the variable.
1305  // Actually try to capture it.
1306  QualType type = var->getType();
1307
1308  // Prohibit variably-modified types.
1309  if (type->isVariablyModifiedType()) {
1310    S.Diag(loc, diag::err_ref_vm_type);
1311    S.Diag(var->getLocation(), diag::note_declared_at);
1312    return CR_Error;
1313  }
1314
1315  // Prohibit arrays, even in __block variables, but not references to
1316  // them.
1317  if (type->isArrayType()) {
1318    S.Diag(loc, diag::err_ref_array_type);
1319    S.Diag(var->getLocation(), diag::note_declared_at);
1320    return CR_Error;
1321  }
1322
1323  S.MarkDeclarationReferenced(loc, var);
1324
1325  // The BlocksAttr indicates the variable is bound by-reference.
1326  bool byRef = var->hasAttr<BlocksAttr>();
1327
1328  // Build a copy expression.
1329  Expr *copyExpr = 0;
1330  const RecordType *rtype;
1331  if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1332      (rtype = type->getAs<RecordType>())) {
1333
1334    // The capture logic needs the destructor, so make sure we mark it.
1335    // Usually this is unnecessary because most local variables have
1336    // their destructors marked at declaration time, but parameters are
1337    // an exception because it's technically only the call site that
1338    // actually requires the destructor.
1339    if (isa<ParmVarDecl>(var))
1340      S.FinalizeVarWithDestructor(var, rtype);
1341
1342    // According to the blocks spec, the capture of a variable from
1343    // the stack requires a const copy constructor.  This is not true
1344    // of the copy/move done to move a __block variable to the heap.
1345    type.addConst();
1346
1347    Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1348    ExprResult result =
1349      S.PerformCopyInitialization(
1350                      InitializedEntity::InitializeBlock(var->getLocation(),
1351                                                         type, false),
1352                                  loc, S.Owned(declRef));
1353
1354    // Build a full-expression copy expression if initialization
1355    // succeeded and used a non-trivial constructor.  Recover from
1356    // errors by pretending that the copy isn't necessary.
1357    if (!result.isInvalid() &&
1358        !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1359      result = S.MaybeCreateExprWithCleanups(result);
1360      copyExpr = result.take();
1361    }
1362  }
1363
1364  // We're currently at the declarer; go back to the closure.
1365  functionScopesIndex++;
1366  BlockScopeInfo *blockScope =
1367    cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1368
1369  // Build a valid capture in this scope.
1370  blockScope->Captures.push_back(
1371                 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1372  blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1373
1374  // Propagate that to inner captures if necessary.
1375  return propagateCapture(S, functionScopesIndex,
1376                          blockScope->Captures.back());
1377}
1378
1379static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *VD,
1380                                        const DeclarationNameInfo &NameInfo,
1381                                        bool ByRef) {
1382  assert(isa<VarDecl>(VD) && "capturing non-variable");
1383
1384  VarDecl *var = cast<VarDecl>(VD);
1385  assert(var->hasLocalStorage() && "capturing non-local");
1386  assert(ByRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
1387
1388  QualType exprType = var->getType().getNonReferenceType();
1389
1390  BlockDeclRefExpr *BDRE;
1391  if (!ByRef) {
1392    // The variable will be bound by copy; make it const within the
1393    // closure, but record that this was done in the expression.
1394    bool constAdded = !exprType.isConstQualified();
1395    exprType.addConst();
1396
1397    BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1398                                            NameInfo.getLoc(), false,
1399                                            constAdded);
1400  } else {
1401    BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1402                                            NameInfo.getLoc(), true);
1403  }
1404
1405  return S.Owned(BDRE);
1406}
1407
1408ExprResult
1409Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1410                       SourceLocation Loc,
1411                       const CXXScopeSpec *SS) {
1412  DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1413  return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1414}
1415
1416/// BuildDeclRefExpr - Build an expression that references a
1417/// declaration that does not require a closure capture.
1418ExprResult
1419Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1420                       const DeclarationNameInfo &NameInfo,
1421                       const CXXScopeSpec *SS) {
1422  if (getLangOptions().CUDA)
1423    if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1424      if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1425        CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1426                           CalleeTarget = IdentifyCUDATarget(Callee);
1427        if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1428          Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1429            << CalleeTarget << D->getIdentifier() << CallerTarget;
1430          Diag(D->getLocation(), diag::note_previous_decl)
1431            << D->getIdentifier();
1432          return ExprError();
1433        }
1434      }
1435
1436  MarkDeclarationReferenced(NameInfo.getLoc(), D);
1437
1438  Expr *E = DeclRefExpr::Create(Context,
1439                                SS? SS->getWithLocInContext(Context)
1440                                  : NestedNameSpecifierLoc(),
1441                                D, NameInfo, Ty, VK);
1442
1443  // Just in case we're building an illegal pointer-to-member.
1444  FieldDecl *FD = dyn_cast<FieldDecl>(D);
1445  if (FD && FD->isBitField())
1446    E->setObjectKind(OK_BitField);
1447
1448  return Owned(E);
1449}
1450
1451/// Decomposes the given name into a DeclarationNameInfo, its location, and
1452/// possibly a list of template arguments.
1453///
1454/// If this produces template arguments, it is permitted to call
1455/// DecomposeTemplateName.
1456///
1457/// This actually loses a lot of source location information for
1458/// non-standard name kinds; we should consider preserving that in
1459/// some way.
1460void
1461Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1462                             TemplateArgumentListInfo &Buffer,
1463                             DeclarationNameInfo &NameInfo,
1464                             const TemplateArgumentListInfo *&TemplateArgs) {
1465  if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1466    Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1467    Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1468
1469    ASTTemplateArgsPtr TemplateArgsPtr(*this,
1470                                       Id.TemplateId->getTemplateArgs(),
1471                                       Id.TemplateId->NumArgs);
1472    translateTemplateArguments(TemplateArgsPtr, Buffer);
1473    TemplateArgsPtr.release();
1474
1475    TemplateName TName = Id.TemplateId->Template.get();
1476    SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1477    NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1478    TemplateArgs = &Buffer;
1479  } else {
1480    NameInfo = GetNameFromUnqualifiedId(Id);
1481    TemplateArgs = 0;
1482  }
1483}
1484
1485/// Diagnose an empty lookup.
1486///
1487/// \return false if new lookup candidates were found
1488bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1489                               CorrectTypoContext CTC,
1490                               TemplateArgumentListInfo *ExplicitTemplateArgs,
1491                               Expr **Args, unsigned NumArgs) {
1492  DeclarationName Name = R.getLookupName();
1493
1494  unsigned diagnostic = diag::err_undeclared_var_use;
1495  unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1496  if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1497      Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1498      Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1499    diagnostic = diag::err_undeclared_use;
1500    diagnostic_suggest = diag::err_undeclared_use_suggest;
1501  }
1502
1503  // If the original lookup was an unqualified lookup, fake an
1504  // unqualified lookup.  This is useful when (for example) the
1505  // original lookup would not have found something because it was a
1506  // dependent name.
1507  for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
1508       DC; DC = DC->getParent()) {
1509    if (isa<CXXRecordDecl>(DC)) {
1510      LookupQualifiedName(R, DC);
1511
1512      if (!R.empty()) {
1513        // Don't give errors about ambiguities in this lookup.
1514        R.suppressDiagnostics();
1515
1516        CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1517        bool isInstance = CurMethod &&
1518                          CurMethod->isInstance() &&
1519                          DC == CurMethod->getParent();
1520
1521        // Give a code modification hint to insert 'this->'.
1522        // TODO: fixit for inserting 'Base<T>::' in the other cases.
1523        // Actually quite difficult!
1524        if (isInstance) {
1525          UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1526              CallsUndergoingInstantiation.back()->getCallee());
1527          CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
1528              CurMethod->getInstantiatedFromMemberFunction());
1529          if (DepMethod) {
1530            if (getLangOptions().MicrosoftExt)
1531              diagnostic = diag::warn_found_via_dependent_bases_lookup;
1532            Diag(R.getNameLoc(), diagnostic) << Name
1533              << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1534            QualType DepThisType = DepMethod->getThisType(Context);
1535            CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1536                                       R.getNameLoc(), DepThisType, false);
1537            TemplateArgumentListInfo TList;
1538            if (ULE->hasExplicitTemplateArgs())
1539              ULE->copyTemplateArgumentsInto(TList);
1540
1541            CXXScopeSpec SS;
1542            SS.Adopt(ULE->getQualifierLoc());
1543            CXXDependentScopeMemberExpr *DepExpr =
1544                CXXDependentScopeMemberExpr::Create(
1545                    Context, DepThis, DepThisType, true, SourceLocation(),
1546                    SS.getWithLocInContext(Context), NULL,
1547                    R.getLookupNameInfo(),
1548                    ULE->hasExplicitTemplateArgs() ? &TList : 0);
1549            CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1550          } else {
1551            // FIXME: we should be able to handle this case too. It is correct
1552            // to add this-> here. This is a workaround for PR7947.
1553            Diag(R.getNameLoc(), diagnostic) << Name;
1554          }
1555        } else {
1556          Diag(R.getNameLoc(), diagnostic) << Name;
1557        }
1558
1559        // Do we really want to note all of these?
1560        for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1561          Diag((*I)->getLocation(), diag::note_dependent_var_use);
1562
1563        // Tell the callee to try to recover.
1564        return false;
1565      }
1566
1567      R.clear();
1568    }
1569  }
1570
1571  // We didn't find anything, so try to correct for a typo.
1572  TypoCorrection Corrected;
1573  if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1574                                    S, &SS, NULL, false, CTC))) {
1575    std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1576    std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1577    R.setLookupName(Corrected.getCorrection());
1578
1579    if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
1580      if (Corrected.isOverloaded()) {
1581        OverloadCandidateSet OCS(R.getNameLoc());
1582        OverloadCandidateSet::iterator Best;
1583        for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1584                                        CDEnd = Corrected.end();
1585             CD != CDEnd; ++CD) {
1586          if (FunctionTemplateDecl *FTD =
1587                   dyn_cast<FunctionTemplateDecl>(*CD))
1588            AddTemplateOverloadCandidate(
1589                FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1590                Args, NumArgs, OCS);
1591          else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1592            if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1593              AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1594                                   Args, NumArgs, OCS);
1595        }
1596        switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1597          case OR_Success:
1598            ND = Best->Function;
1599            break;
1600          default:
1601            break;
1602        }
1603      }
1604      R.addDecl(ND);
1605      if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
1606        if (SS.isEmpty())
1607          Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1608            << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1609        else
1610          Diag(R.getNameLoc(), diag::err_no_member_suggest)
1611            << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1612            << SS.getRange()
1613            << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1614        if (ND)
1615          Diag(ND->getLocation(), diag::note_previous_decl)
1616            << CorrectedQuotedStr;
1617
1618        // Tell the callee to try to recover.
1619        return false;
1620      }
1621
1622      if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
1623        // FIXME: If we ended up with a typo for a type name or
1624        // Objective-C class name, we're in trouble because the parser
1625        // is in the wrong place to recover. Suggest the typo
1626        // correction, but don't make it a fix-it since we're not going
1627        // to recover well anyway.
1628        if (SS.isEmpty())
1629          Diag(R.getNameLoc(), diagnostic_suggest)
1630            << Name << CorrectedQuotedStr;
1631        else
1632          Diag(R.getNameLoc(), diag::err_no_member_suggest)
1633            << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1634            << SS.getRange();
1635
1636        // Don't try to recover; it won't work.
1637        return true;
1638      }
1639    } else {
1640      // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1641      // because we aren't able to recover.
1642      if (SS.isEmpty())
1643        Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
1644      else
1645        Diag(R.getNameLoc(), diag::err_no_member_suggest)
1646        << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1647        << SS.getRange();
1648      return true;
1649    }
1650  }
1651  R.clear();
1652
1653  // Emit a special diagnostic for failed member lookups.
1654  // FIXME: computing the declaration context might fail here (?)
1655  if (!SS.isEmpty()) {
1656    Diag(R.getNameLoc(), diag::err_no_member)
1657      << Name << computeDeclContext(SS, false)
1658      << SS.getRange();
1659    return true;
1660  }
1661
1662  // Give up, we can't recover.
1663  Diag(R.getNameLoc(), diagnostic) << Name;
1664  return true;
1665}
1666
1667ExprResult Sema::ActOnIdExpression(Scope *S,
1668                                   CXXScopeSpec &SS,
1669                                   UnqualifiedId &Id,
1670                                   bool HasTrailingLParen,
1671                                   bool IsAddressOfOperand) {
1672  assert(!(IsAddressOfOperand && HasTrailingLParen) &&
1673         "cannot be direct & operand and have a trailing lparen");
1674
1675  if (SS.isInvalid())
1676    return ExprError();
1677
1678  TemplateArgumentListInfo TemplateArgsBuffer;
1679
1680  // Decompose the UnqualifiedId into the following data.
1681  DeclarationNameInfo NameInfo;
1682  const TemplateArgumentListInfo *TemplateArgs;
1683  DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
1684
1685  DeclarationName Name = NameInfo.getName();
1686  IdentifierInfo *II = Name.getAsIdentifierInfo();
1687  SourceLocation NameLoc = NameInfo.getLoc();
1688
1689  // C++ [temp.dep.expr]p3:
1690  //   An id-expression is type-dependent if it contains:
1691  //     -- an identifier that was declared with a dependent type,
1692  //        (note: handled after lookup)
1693  //     -- a template-id that is dependent,
1694  //        (note: handled in BuildTemplateIdExpr)
1695  //     -- a conversion-function-id that specifies a dependent type,
1696  //     -- a nested-name-specifier that contains a class-name that
1697  //        names a dependent type.
1698  // Determine whether this is a member of an unknown specialization;
1699  // we need to handle these differently.
1700  bool DependentID = false;
1701  if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1702      Name.getCXXNameType()->isDependentType()) {
1703    DependentID = true;
1704  } else if (SS.isSet()) {
1705    if (DeclContext *DC = computeDeclContext(SS, false)) {
1706      if (RequireCompleteDeclContext(SS, DC))
1707        return ExprError();
1708    } else {
1709      DependentID = true;
1710    }
1711  }
1712
1713  if (DependentID)
1714    return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
1715                                      TemplateArgs);
1716
1717  bool IvarLookupFollowUp = false;
1718  // Perform the required lookup.
1719  LookupResult R(*this, NameInfo,
1720                 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1721                  ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
1722  if (TemplateArgs) {
1723    // Lookup the template name again to correctly establish the context in
1724    // which it was found. This is really unfortunate as we already did the
1725    // lookup to determine that it was a template name in the first place. If
1726    // this becomes a performance hit, we can work harder to preserve those
1727    // results until we get here but it's likely not worth it.
1728    bool MemberOfUnknownSpecialization;
1729    LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1730                       MemberOfUnknownSpecialization);
1731
1732    if (MemberOfUnknownSpecialization ||
1733        (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1734      return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
1735                                        TemplateArgs);
1736  } else {
1737    IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
1738    LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
1739
1740    // If the result might be in a dependent base class, this is a dependent
1741    // id-expression.
1742    if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1743      return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
1744                                        TemplateArgs);
1745
1746    // If this reference is in an Objective-C method, then we need to do
1747    // some special Objective-C lookup, too.
1748    if (IvarLookupFollowUp) {
1749      ExprResult E(LookupInObjCMethod(R, S, II, true));
1750      if (E.isInvalid())
1751        return ExprError();
1752
1753      if (Expr *Ex = E.takeAs<Expr>())
1754        return Owned(Ex);
1755
1756      // for further use, this must be set to false if in class method.
1757      IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
1758    }
1759  }
1760
1761  if (R.isAmbiguous())
1762    return ExprError();
1763
1764  // Determine whether this name might be a candidate for
1765  // argument-dependent lookup.
1766  bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
1767
1768  if (R.empty() && !ADL) {
1769    // Otherwise, this could be an implicitly declared function reference (legal
1770    // in C90, extension in C99, forbidden in C++).
1771    if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1772      NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1773      if (D) R.addDecl(D);
1774    }
1775
1776    // If this name wasn't predeclared and if this is not a function
1777    // call, diagnose the problem.
1778    if (R.empty()) {
1779
1780      // In Microsoft mode, if we are inside a template class member function
1781      // and we can't resolve an identifier then assume the identifier is type
1782      // dependent. The goal is to postpone name lookup to instantiation time
1783      // to be able to search into type dependent base classes.
1784      if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
1785          isa<CXXMethodDecl>(CurContext))
1786        return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
1787                                          TemplateArgs);
1788
1789      if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
1790        return ExprError();
1791
1792      assert(!R.empty() &&
1793             "DiagnoseEmptyLookup returned false but added no results");
1794
1795      // If we found an Objective-C instance variable, let
1796      // LookupInObjCMethod build the appropriate expression to
1797      // reference the ivar.
1798      if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1799        R.clear();
1800        ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1801        // In a hopelessly buggy code, Objective-C instance variable
1802        // lookup fails and no expression will be built to reference it.
1803        if (!E.isInvalid() && !E.get())
1804          return ExprError();
1805        return move(E);
1806      }
1807    }
1808  }
1809
1810  // This is guaranteed from this point on.
1811  assert(!R.empty() || ADL);
1812
1813  // Check whether this might be a C++ implicit instance member access.
1814  // C++ [class.mfct.non-static]p3:
1815  //   When an id-expression that is not part of a class member access
1816  //   syntax and not used to form a pointer to member is used in the
1817  //   body of a non-static member function of class X, if name lookup
1818  //   resolves the name in the id-expression to a non-static non-type
1819  //   member of some class C, the id-expression is transformed into a
1820  //   class member access expression using (*this) as the
1821  //   postfix-expression to the left of the . operator.
1822  //
1823  // But we don't actually need to do this for '&' operands if R
1824  // resolved to a function or overloaded function set, because the
1825  // expression is ill-formed if it actually works out to be a
1826  // non-static member function:
1827  //
1828  // C++ [expr.ref]p4:
1829  //   Otherwise, if E1.E2 refers to a non-static member function. . .
1830  //   [t]he expression can be used only as the left-hand operand of a
1831  //   member function call.
1832  //
1833  // There are other safeguards against such uses, but it's important
1834  // to get this right here so that we don't end up making a
1835  // spuriously dependent expression if we're inside a dependent
1836  // instance method.
1837  if (!R.empty() && (*R.begin())->isCXXClassMember()) {
1838    bool MightBeImplicitMember;
1839    if (!IsAddressOfOperand)
1840      MightBeImplicitMember = true;
1841    else if (!SS.isEmpty())
1842      MightBeImplicitMember = false;
1843    else if (R.isOverloadedResult())
1844      MightBeImplicitMember = false;
1845    else if (R.isUnresolvableResult())
1846      MightBeImplicitMember = true;
1847    else
1848      MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1849                              isa<IndirectFieldDecl>(R.getFoundDecl());
1850
1851    if (MightBeImplicitMember)
1852      return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
1853  }
1854
1855  if (TemplateArgs)
1856    return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
1857
1858  return BuildDeclarationNameExpr(SS, R, ADL);
1859}
1860
1861/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1862/// declaration name, generally during template instantiation.
1863/// There's a large number of things which don't need to be done along
1864/// this path.
1865ExprResult
1866Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
1867                                        const DeclarationNameInfo &NameInfo) {
1868  DeclContext *DC;
1869  if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
1870    return BuildDependentDeclRefExpr(SS, NameInfo, 0);
1871
1872  if (RequireCompleteDeclContext(SS, DC))
1873    return ExprError();
1874
1875  LookupResult R(*this, NameInfo, LookupOrdinaryName);
1876  LookupQualifiedName(R, DC);
1877
1878  if (R.isAmbiguous())
1879    return ExprError();
1880
1881  if (R.empty()) {
1882    Diag(NameInfo.getLoc(), diag::err_no_member)
1883      << NameInfo.getName() << DC << SS.getRange();
1884    return ExprError();
1885  }
1886
1887  return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1888}
1889
1890/// LookupInObjCMethod - The parser has read a name in, and Sema has
1891/// detected that we're currently inside an ObjC method.  Perform some
1892/// additional lookup.
1893///
1894/// Ideally, most of this would be done by lookup, but there's
1895/// actually quite a lot of extra work involved.
1896///
1897/// Returns a null sentinel to indicate trivial success.
1898ExprResult
1899Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1900                         IdentifierInfo *II, bool AllowBuiltinCreation) {
1901  SourceLocation Loc = Lookup.getNameLoc();
1902  ObjCMethodDecl *CurMethod = getCurMethodDecl();
1903
1904  // There are two cases to handle here.  1) scoped lookup could have failed,
1905  // in which case we should look for an ivar.  2) scoped lookup could have
1906  // found a decl, but that decl is outside the current instance method (i.e.
1907  // a global variable).  In these two cases, we do a lookup for an ivar with
1908  // this name, if the lookup sucedes, we replace it our current decl.
1909
1910  // If we're in a class method, we don't normally want to look for
1911  // ivars.  But if we don't find anything else, and there's an
1912  // ivar, that's an error.
1913  bool IsClassMethod = CurMethod->isClassMethod();
1914
1915  bool LookForIvars;
1916  if (Lookup.empty())
1917    LookForIvars = true;
1918  else if (IsClassMethod)
1919    LookForIvars = false;
1920  else
1921    LookForIvars = (Lookup.isSingleResult() &&
1922                    Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1923  ObjCInterfaceDecl *IFace = 0;
1924  if (LookForIvars) {
1925    IFace = CurMethod->getClassInterface();
1926    ObjCInterfaceDecl *ClassDeclared;
1927    ObjCIvarDecl *IV = 0;
1928    if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
1929      // Diagnose using an ivar in a class method.
1930      if (IsClassMethod)
1931        return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1932                         << IV->getDeclName());
1933
1934      // If we're referencing an invalid decl, just return this as a silent
1935      // error node.  The error diagnostic was already emitted on the decl.
1936      if (IV->isInvalidDecl())
1937        return ExprError();
1938
1939      // Check if referencing a field with __attribute__((deprecated)).
1940      if (DiagnoseUseOfDecl(IV, Loc))
1941        return ExprError();
1942
1943      // Diagnose the use of an ivar outside of the declaring class.
1944      if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1945          ClassDeclared != IFace)
1946        Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1947
1948      // FIXME: This should use a new expr for a direct reference, don't
1949      // turn this into Self->ivar, just return a BareIVarExpr or something.
1950      IdentifierInfo &II = Context.Idents.get("self");
1951      UnqualifiedId SelfName;
1952      SelfName.setIdentifier(&II, SourceLocation());
1953      SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
1954      CXXScopeSpec SelfScopeSpec;
1955      ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1956                                              SelfName, false, false);
1957      if (SelfExpr.isInvalid())
1958        return ExprError();
1959
1960      SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1961      if (SelfExpr.isInvalid())
1962        return ExprError();
1963
1964      MarkDeclarationReferenced(Loc, IV);
1965      return Owned(new (Context)
1966                   ObjCIvarRefExpr(IV, IV->getType(), Loc,
1967                                   SelfExpr.take(), true, true));
1968    }
1969  } else if (CurMethod->isInstanceMethod()) {
1970    // We should warn if a local variable hides an ivar.
1971    ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
1972    ObjCInterfaceDecl *ClassDeclared;
1973    if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1974      if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1975          IFace == ClassDeclared)
1976        Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1977    }
1978  }
1979
1980  if (Lookup.empty() && II && AllowBuiltinCreation) {
1981    // FIXME. Consolidate this with similar code in LookupName.
1982    if (unsigned BuiltinID = II->getBuiltinID()) {
1983      if (!(getLangOptions().CPlusPlus &&
1984            Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1985        NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1986                                           S, Lookup.isForRedeclaration(),
1987                                           Lookup.getNameLoc());
1988        if (D) Lookup.addDecl(D);
1989      }
1990    }
1991  }
1992  // Sentinel value saying that we didn't do anything special.
1993  return Owned((Expr*) 0);
1994}
1995
1996/// \brief Cast a base object to a member's actual type.
1997///
1998/// Logically this happens in three phases:
1999///
2000/// * First we cast from the base type to the naming class.
2001///   The naming class is the class into which we were looking
2002///   when we found the member;  it's the qualifier type if a
2003///   qualifier was provided, and otherwise it's the base type.
2004///
2005/// * Next we cast from the naming class to the declaring class.
2006///   If the member we found was brought into a class's scope by
2007///   a using declaration, this is that class;  otherwise it's
2008///   the class declaring the member.
2009///
2010/// * Finally we cast from the declaring class to the "true"
2011///   declaring class of the member.  This conversion does not
2012///   obey access control.
2013ExprResult
2014Sema::PerformObjectMemberConversion(Expr *From,
2015                                    NestedNameSpecifier *Qualifier,
2016                                    NamedDecl *FoundDecl,
2017                                    NamedDecl *Member) {
2018  CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2019  if (!RD)
2020    return Owned(From);
2021
2022  QualType DestRecordType;
2023  QualType DestType;
2024  QualType FromRecordType;
2025  QualType FromType = From->getType();
2026  bool PointerConversions = false;
2027  if (isa<FieldDecl>(Member)) {
2028    DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2029
2030    if (FromType->getAs<PointerType>()) {
2031      DestType = Context.getPointerType(DestRecordType);
2032      FromRecordType = FromType->getPointeeType();
2033      PointerConversions = true;
2034    } else {
2035      DestType = DestRecordType;
2036      FromRecordType = FromType;
2037    }
2038  } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2039    if (Method->isStatic())
2040      return Owned(From);
2041
2042    DestType = Method->getThisType(Context);
2043    DestRecordType = DestType->getPointeeType();
2044
2045    if (FromType->getAs<PointerType>()) {
2046      FromRecordType = FromType->getPointeeType();
2047      PointerConversions = true;
2048    } else {
2049      FromRecordType = FromType;
2050      DestType = DestRecordType;
2051    }
2052  } else {
2053    // No conversion necessary.
2054    return Owned(From);
2055  }
2056
2057  if (DestType->isDependentType() || FromType->isDependentType())
2058    return Owned(From);
2059
2060  // If the unqualified types are the same, no conversion is necessary.
2061  if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2062    return Owned(From);
2063
2064  SourceRange FromRange = From->getSourceRange();
2065  SourceLocation FromLoc = FromRange.getBegin();
2066
2067  ExprValueKind VK = From->getValueKind();
2068
2069  // C++ [class.member.lookup]p8:
2070  //   [...] Ambiguities can often be resolved by qualifying a name with its
2071  //   class name.
2072  //
2073  // If the member was a qualified name and the qualified referred to a
2074  // specific base subobject type, we'll cast to that intermediate type
2075  // first and then to the object in which the member is declared. That allows
2076  // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2077  //
2078  //   class Base { public: int x; };
2079  //   class Derived1 : public Base { };
2080  //   class Derived2 : public Base { };
2081  //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2082  //
2083  //   void VeryDerived::f() {
2084  //     x = 17; // error: ambiguous base subobjects
2085  //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2086  //   }
2087  if (Qualifier) {
2088    QualType QType = QualType(Qualifier->getAsType(), 0);
2089    assert(!QType.isNull() && "lookup done with dependent qualifier?");
2090    assert(QType->isRecordType() && "lookup done with non-record type");
2091
2092    QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2093
2094    // In C++98, the qualifier type doesn't actually have to be a base
2095    // type of the object type, in which case we just ignore it.
2096    // Otherwise build the appropriate casts.
2097    if (IsDerivedFrom(FromRecordType, QRecordType)) {
2098      CXXCastPath BasePath;
2099      if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2100                                       FromLoc, FromRange, &BasePath))
2101        return ExprError();
2102
2103      if (PointerConversions)
2104        QType = Context.getPointerType(QType);
2105      From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2106                               VK, &BasePath).take();
2107
2108      FromType = QType;
2109      FromRecordType = QRecordType;
2110
2111      // If the qualifier type was the same as the destination type,
2112      // we're done.
2113      if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2114        return Owned(From);
2115    }
2116  }
2117
2118  bool IgnoreAccess = false;
2119
2120  // If we actually found the member through a using declaration, cast
2121  // down to the using declaration's type.
2122  //
2123  // Pointer equality is fine here because only one declaration of a
2124  // class ever has member declarations.
2125  if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2126    assert(isa<UsingShadowDecl>(FoundDecl));
2127    QualType URecordType = Context.getTypeDeclType(
2128                           cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2129
2130    // We only need to do this if the naming-class to declaring-class
2131    // conversion is non-trivial.
2132    if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2133      assert(IsDerivedFrom(FromRecordType, URecordType));
2134      CXXCastPath BasePath;
2135      if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2136                                       FromLoc, FromRange, &BasePath))
2137        return ExprError();
2138
2139      QualType UType = URecordType;
2140      if (PointerConversions)
2141        UType = Context.getPointerType(UType);
2142      From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2143                               VK, &BasePath).take();
2144      FromType = UType;
2145      FromRecordType = URecordType;
2146    }
2147
2148    // We don't do access control for the conversion from the
2149    // declaring class to the true declaring class.
2150    IgnoreAccess = true;
2151  }
2152
2153  CXXCastPath BasePath;
2154  if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2155                                   FromLoc, FromRange, &BasePath,
2156                                   IgnoreAccess))
2157    return ExprError();
2158
2159  return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2160                           VK, &BasePath);
2161}
2162
2163bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2164                                      const LookupResult &R,
2165                                      bool HasTrailingLParen) {
2166  // Only when used directly as the postfix-expression of a call.
2167  if (!HasTrailingLParen)
2168    return false;
2169
2170  // Never if a scope specifier was provided.
2171  if (SS.isSet())
2172    return false;
2173
2174  // Only in C++ or ObjC++.
2175  if (!getLangOptions().CPlusPlus)
2176    return false;
2177
2178  // Turn off ADL when we find certain kinds of declarations during
2179  // normal lookup:
2180  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2181    NamedDecl *D = *I;
2182
2183    // C++0x [basic.lookup.argdep]p3:
2184    //     -- a declaration of a class member
2185    // Since using decls preserve this property, we check this on the
2186    // original decl.
2187    if (D->isCXXClassMember())
2188      return false;
2189
2190    // C++0x [basic.lookup.argdep]p3:
2191    //     -- a block-scope function declaration that is not a
2192    //        using-declaration
2193    // NOTE: we also trigger this for function templates (in fact, we
2194    // don't check the decl type at all, since all other decl types
2195    // turn off ADL anyway).
2196    if (isa<UsingShadowDecl>(D))
2197      D = cast<UsingShadowDecl>(D)->getTargetDecl();
2198    else if (D->getDeclContext()->isFunctionOrMethod())
2199      return false;
2200
2201    // C++0x [basic.lookup.argdep]p3:
2202    //     -- a declaration that is neither a function or a function
2203    //        template
2204    // And also for builtin functions.
2205    if (isa<FunctionDecl>(D)) {
2206      FunctionDecl *FDecl = cast<FunctionDecl>(D);
2207
2208      // But also builtin functions.
2209      if (FDecl->getBuiltinID() && FDecl->isImplicit())
2210        return false;
2211    } else if (!isa<FunctionTemplateDecl>(D))
2212      return false;
2213  }
2214
2215  return true;
2216}
2217
2218
2219/// Diagnoses obvious problems with the use of the given declaration
2220/// as an expression.  This is only actually called for lookups that
2221/// were not overloaded, and it doesn't promise that the declaration
2222/// will in fact be used.
2223static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2224  if (isa<TypedefNameDecl>(D)) {
2225    S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2226    return true;
2227  }
2228
2229  if (isa<ObjCInterfaceDecl>(D)) {
2230    S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2231    return true;
2232  }
2233
2234  if (isa<NamespaceDecl>(D)) {
2235    S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2236    return true;
2237  }
2238
2239  return false;
2240}
2241
2242ExprResult
2243Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2244                               LookupResult &R,
2245                               bool NeedsADL) {
2246  // If this is a single, fully-resolved result and we don't need ADL,
2247  // just build an ordinary singleton decl ref.
2248  if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2249    return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2250                                    R.getFoundDecl());
2251
2252  // We only need to check the declaration if there's exactly one
2253  // result, because in the overloaded case the results can only be
2254  // functions and function templates.
2255  if (R.isSingleResult() &&
2256      CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2257    return ExprError();
2258
2259  // Otherwise, just build an unresolved lookup expression.  Suppress
2260  // any lookup-related diagnostics; we'll hash these out later, when
2261  // we've picked a target.
2262  R.suppressDiagnostics();
2263
2264  UnresolvedLookupExpr *ULE
2265    = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2266                                   SS.getWithLocInContext(Context),
2267                                   R.getLookupNameInfo(),
2268                                   NeedsADL, R.isOverloadedResult(),
2269                                   R.begin(), R.end());
2270
2271  return Owned(ULE);
2272}
2273
2274/// \brief Complete semantic analysis for a reference to the given declaration.
2275ExprResult
2276Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2277                               const DeclarationNameInfo &NameInfo,
2278                               NamedDecl *D) {
2279  assert(D && "Cannot refer to a NULL declaration");
2280  assert(!isa<FunctionTemplateDecl>(D) &&
2281         "Cannot refer unambiguously to a function template");
2282
2283  SourceLocation Loc = NameInfo.getLoc();
2284  if (CheckDeclInExpr(*this, Loc, D))
2285    return ExprError();
2286
2287  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2288    // Specifically diagnose references to class templates that are missing
2289    // a template argument list.
2290    Diag(Loc, diag::err_template_decl_ref)
2291      << Template << SS.getRange();
2292    Diag(Template->getLocation(), diag::note_template_decl_here);
2293    return ExprError();
2294  }
2295
2296  // Make sure that we're referring to a value.
2297  ValueDecl *VD = dyn_cast<ValueDecl>(D);
2298  if (!VD) {
2299    Diag(Loc, diag::err_ref_non_value)
2300      << D << SS.getRange();
2301    Diag(D->getLocation(), diag::note_declared_at);
2302    return ExprError();
2303  }
2304
2305  // Check whether this declaration can be used. Note that we suppress
2306  // this check when we're going to perform argument-dependent lookup
2307  // on this function name, because this might not be the function
2308  // that overload resolution actually selects.
2309  if (DiagnoseUseOfDecl(VD, Loc))
2310    return ExprError();
2311
2312  // Only create DeclRefExpr's for valid Decl's.
2313  if (VD->isInvalidDecl())
2314    return ExprError();
2315
2316  // Handle members of anonymous structs and unions.  If we got here,
2317  // and the reference is to a class member indirect field, then this
2318  // must be the subject of a pointer-to-member expression.
2319  if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2320    if (!indirectField->isCXXClassMember())
2321      return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2322                                                      indirectField);
2323
2324  // If the identifier reference is inside a block, and it refers to a value
2325  // that is outside the block, create a BlockDeclRefExpr instead of a
2326  // DeclRefExpr.  This ensures the value is treated as a copy-in snapshot when
2327  // the block is formed.
2328  //
2329  // We do not do this for things like enum constants, global variables, etc,
2330  // as they do not get snapshotted.
2331  //
2332  switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
2333  case CR_Error:
2334    return ExprError();
2335
2336  case CR_Capture:
2337    assert(!SS.isSet() && "referenced local variable with scope specifier?");
2338    return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2339
2340  case CR_CaptureByRef:
2341    assert(!SS.isSet() && "referenced local variable with scope specifier?");
2342    return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
2343
2344  case CR_NoCapture: {
2345    // If this reference is not in a block or if the referenced
2346    // variable is within the block, create a normal DeclRefExpr.
2347
2348    QualType type = VD->getType();
2349    ExprValueKind valueKind = VK_RValue;
2350
2351    switch (D->getKind()) {
2352    // Ignore all the non-ValueDecl kinds.
2353#define ABSTRACT_DECL(kind)
2354#define VALUE(type, base)
2355#define DECL(type, base) \
2356    case Decl::type:
2357#include "clang/AST/DeclNodes.inc"
2358      llvm_unreachable("invalid value decl kind");
2359      return ExprError();
2360
2361    // These shouldn't make it here.
2362    case Decl::ObjCAtDefsField:
2363    case Decl::ObjCIvar:
2364      llvm_unreachable("forming non-member reference to ivar?");
2365      return ExprError();
2366
2367    // Enum constants are always r-values and never references.
2368    // Unresolved using declarations are dependent.
2369    case Decl::EnumConstant:
2370    case Decl::UnresolvedUsingValue:
2371      valueKind = VK_RValue;
2372      break;
2373
2374    // Fields and indirect fields that got here must be for
2375    // pointer-to-member expressions; we just call them l-values for
2376    // internal consistency, because this subexpression doesn't really
2377    // exist in the high-level semantics.
2378    case Decl::Field:
2379    case Decl::IndirectField:
2380      assert(getLangOptions().CPlusPlus &&
2381             "building reference to field in C?");
2382
2383      // These can't have reference type in well-formed programs, but
2384      // for internal consistency we do this anyway.
2385      type = type.getNonReferenceType();
2386      valueKind = VK_LValue;
2387      break;
2388
2389    // Non-type template parameters are either l-values or r-values
2390    // depending on the type.
2391    case Decl::NonTypeTemplateParm: {
2392      if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2393        type = reftype->getPointeeType();
2394        valueKind = VK_LValue; // even if the parameter is an r-value reference
2395        break;
2396      }
2397
2398      // For non-references, we need to strip qualifiers just in case
2399      // the template parameter was declared as 'const int' or whatever.
2400      valueKind = VK_RValue;
2401      type = type.getUnqualifiedType();
2402      break;
2403    }
2404
2405    case Decl::Var:
2406      // In C, "extern void blah;" is valid and is an r-value.
2407      if (!getLangOptions().CPlusPlus &&
2408          !type.hasQualifiers() &&
2409          type->isVoidType()) {
2410        valueKind = VK_RValue;
2411        break;
2412      }
2413      // fallthrough
2414
2415    case Decl::ImplicitParam:
2416    case Decl::ParmVar:
2417      // These are always l-values.
2418      valueKind = VK_LValue;
2419      type = type.getNonReferenceType();
2420      break;
2421
2422    case Decl::Function: {
2423      const FunctionType *fty = type->castAs<FunctionType>();
2424
2425      // If we're referring to a function with an __unknown_anytype
2426      // result type, make the entire expression __unknown_anytype.
2427      if (fty->getResultType() == Context.UnknownAnyTy) {
2428        type = Context.UnknownAnyTy;
2429        valueKind = VK_RValue;
2430        break;
2431      }
2432
2433      // Functions are l-values in C++.
2434      if (getLangOptions().CPlusPlus) {
2435        valueKind = VK_LValue;
2436        break;
2437      }
2438
2439      // C99 DR 316 says that, if a function type comes from a
2440      // function definition (without a prototype), that type is only
2441      // used for checking compatibility. Therefore, when referencing
2442      // the function, we pretend that we don't have the full function
2443      // type.
2444      if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2445          isa<FunctionProtoType>(fty))
2446        type = Context.getFunctionNoProtoType(fty->getResultType(),
2447                                              fty->getExtInfo());
2448
2449      // Functions are r-values in C.
2450      valueKind = VK_RValue;
2451      break;
2452    }
2453
2454    case Decl::CXXMethod:
2455      // If we're referring to a method with an __unknown_anytype
2456      // result type, make the entire expression __unknown_anytype.
2457      // This should only be possible with a type written directly.
2458      if (const FunctionProtoType *proto
2459            = dyn_cast<FunctionProtoType>(VD->getType()))
2460        if (proto->getResultType() == Context.UnknownAnyTy) {
2461          type = Context.UnknownAnyTy;
2462          valueKind = VK_RValue;
2463          break;
2464        }
2465
2466      // C++ methods are l-values if static, r-values if non-static.
2467      if (cast<CXXMethodDecl>(VD)->isStatic()) {
2468        valueKind = VK_LValue;
2469        break;
2470      }
2471      // fallthrough
2472
2473    case Decl::CXXConversion:
2474    case Decl::CXXDestructor:
2475    case Decl::CXXConstructor:
2476      valueKind = VK_RValue;
2477      break;
2478    }
2479
2480    return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2481  }
2482
2483  }
2484
2485  llvm_unreachable("unknown capture result");
2486  return ExprError();
2487}
2488
2489ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2490  PredefinedExpr::IdentType IT;
2491
2492  switch (Kind) {
2493  default: llvm_unreachable("Unknown simple primary expr!");
2494  case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2495  case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2496  case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2497  }
2498
2499  // Pre-defined identifiers are of type char[x], where x is the length of the
2500  // string.
2501
2502  Decl *currentDecl = getCurFunctionOrMethodDecl();
2503  if (!currentDecl && getCurBlock())
2504    currentDecl = getCurBlock()->TheDecl;
2505  if (!currentDecl) {
2506    Diag(Loc, diag::ext_predef_outside_function);
2507    currentDecl = Context.getTranslationUnitDecl();
2508  }
2509
2510  QualType ResTy;
2511  if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2512    ResTy = Context.DependentTy;
2513  } else {
2514    unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2515
2516    llvm::APInt LengthI(32, Length + 1);
2517    ResTy = Context.CharTy.withConst();
2518    ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2519  }
2520  return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
2521}
2522
2523ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
2524  llvm::SmallString<16> CharBuffer;
2525  bool Invalid = false;
2526  StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2527  if (Invalid)
2528    return ExprError();
2529
2530  CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2531                            PP, Tok.getKind());
2532  if (Literal.hadError())
2533    return ExprError();
2534
2535  QualType Ty;
2536  if (!getLangOptions().CPlusPlus)
2537    Ty = Context.IntTy;   // 'x' and L'x' -> int in C.
2538  else if (Literal.isWide())
2539    Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
2540  else if (Literal.isUTF16())
2541    Ty = Context.Char16Ty; // u'x' -> char16_t in C++0x.
2542  else if (Literal.isUTF32())
2543    Ty = Context.Char32Ty; // U'x' -> char32_t in C++0x.
2544  else if (Literal.isMultiChar())
2545    Ty = Context.IntTy;   // 'wxyz' -> int in C++.
2546  else
2547    Ty = Context.CharTy;  // 'x' -> char in C++
2548
2549  CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2550  if (Literal.isWide())
2551    Kind = CharacterLiteral::Wide;
2552  else if (Literal.isUTF16())
2553    Kind = CharacterLiteral::UTF16;
2554  else if (Literal.isUTF32())
2555    Kind = CharacterLiteral::UTF32;
2556
2557  return Owned(new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2558                                              Tok.getLocation()));
2559}
2560
2561ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
2562  // Fast path for a single digit (which is quite common).  A single digit
2563  // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2564  if (Tok.getLength() == 1) {
2565    const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
2566    unsigned IntSize = Context.getTargetInfo().getIntWidth();
2567    return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
2568                    Context.IntTy, Tok.getLocation()));
2569  }
2570
2571  llvm::SmallString<512> IntegerBuffer;
2572  // Add padding so that NumericLiteralParser can overread by one character.
2573  IntegerBuffer.resize(Tok.getLength()+1);
2574  const char *ThisTokBegin = &IntegerBuffer[0];
2575
2576  // Get the spelling of the token, which eliminates trigraphs, etc.
2577  bool Invalid = false;
2578  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2579  if (Invalid)
2580    return ExprError();
2581
2582  NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
2583                               Tok.getLocation(), PP);
2584  if (Literal.hadError)
2585    return ExprError();
2586
2587  Expr *Res;
2588
2589  if (Literal.isFloatingLiteral()) {
2590    QualType Ty;
2591    if (Literal.isFloat)
2592      Ty = Context.FloatTy;
2593    else if (!Literal.isLong)
2594      Ty = Context.DoubleTy;
2595    else
2596      Ty = Context.LongDoubleTy;
2597
2598    const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2599
2600    using llvm::APFloat;
2601    APFloat Val(Format);
2602
2603    APFloat::opStatus result = Literal.GetFloatValue(Val);
2604
2605    // Overflow is always an error, but underflow is only an error if
2606    // we underflowed to zero (APFloat reports denormals as underflow).
2607    if ((result & APFloat::opOverflow) ||
2608        ((result & APFloat::opUnderflow) && Val.isZero())) {
2609      unsigned diagnostic;
2610      llvm::SmallString<20> buffer;
2611      if (result & APFloat::opOverflow) {
2612        diagnostic = diag::warn_float_overflow;
2613        APFloat::getLargest(Format).toString(buffer);
2614      } else {
2615        diagnostic = diag::warn_float_underflow;
2616        APFloat::getSmallest(Format).toString(buffer);
2617      }
2618
2619      Diag(Tok.getLocation(), diagnostic)
2620        << Ty
2621        << StringRef(buffer.data(), buffer.size());
2622    }
2623
2624    bool isExact = (result == APFloat::opOK);
2625    Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
2626
2627    if (Ty == Context.DoubleTy) {
2628      if (getLangOptions().SinglePrecisionConstants) {
2629        Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2630      } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2631        Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
2632        Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2633      }
2634    }
2635  } else if (!Literal.isIntegerLiteral()) {
2636    return ExprError();
2637  } else {
2638    QualType Ty;
2639
2640    // long long is a C99 feature.
2641    if (!getLangOptions().C99 && Literal.isLongLong)
2642      Diag(Tok.getLocation(),
2643           getLangOptions().CPlusPlus0x ?
2644             diag::warn_cxx98_compat_longlong : diag::ext_longlong);
2645
2646    // Get the value in the widest-possible width.
2647    llvm::APInt ResultVal(Context.getTargetInfo().getIntMaxTWidth(), 0);
2648
2649    if (Literal.GetIntegerValue(ResultVal)) {
2650      // If this value didn't fit into uintmax_t, warn and force to ull.
2651      Diag(Tok.getLocation(), diag::warn_integer_too_large);
2652      Ty = Context.UnsignedLongLongTy;
2653      assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
2654             "long long is not intmax_t?");
2655    } else {
2656      // If this value fits into a ULL, try to figure out what else it fits into
2657      // according to the rules of C99 6.4.4.1p5.
2658
2659      // Octal, Hexadecimal, and integers with a U suffix are allowed to
2660      // be an unsigned int.
2661      bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2662
2663      // Check from smallest to largest, picking the smallest type we can.
2664      unsigned Width = 0;
2665      if (!Literal.isLong && !Literal.isLongLong) {
2666        // Are int/unsigned possibilities?
2667        unsigned IntSize = Context.getTargetInfo().getIntWidth();
2668
2669        // Does it fit in a unsigned int?
2670        if (ResultVal.isIntN(IntSize)) {
2671          // Does it fit in a signed int?
2672          if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
2673            Ty = Context.IntTy;
2674          else if (AllowUnsigned)
2675            Ty = Context.UnsignedIntTy;
2676          Width = IntSize;
2677        }
2678      }
2679
2680      // Are long/unsigned long possibilities?
2681      if (Ty.isNull() && !Literal.isLongLong) {
2682        unsigned LongSize = Context.getTargetInfo().getLongWidth();
2683
2684        // Does it fit in a unsigned long?
2685        if (ResultVal.isIntN(LongSize)) {
2686          // Does it fit in a signed long?
2687          if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
2688            Ty = Context.LongTy;
2689          else if (AllowUnsigned)
2690            Ty = Context.UnsignedLongTy;
2691          Width = LongSize;
2692        }
2693      }
2694
2695      // Finally, check long long if needed.
2696      if (Ty.isNull()) {
2697        unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
2698
2699        // Does it fit in a unsigned long long?
2700        if (ResultVal.isIntN(LongLongSize)) {
2701          // Does it fit in a signed long long?
2702          // To be compatible with MSVC, hex integer literals ending with the
2703          // LL or i64 suffix are always signed in Microsoft mode.
2704          if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2705              (getLangOptions().MicrosoftExt && Literal.isLongLong)))
2706            Ty = Context.LongLongTy;
2707          else if (AllowUnsigned)
2708            Ty = Context.UnsignedLongLongTy;
2709          Width = LongLongSize;
2710        }
2711      }
2712
2713      // If we still couldn't decide a type, we probably have something that
2714      // does not fit in a signed long long, but has no U suffix.
2715      if (Ty.isNull()) {
2716        Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
2717        Ty = Context.UnsignedLongLongTy;
2718        Width = Context.getTargetInfo().getLongLongWidth();
2719      }
2720
2721      if (ResultVal.getBitWidth() != Width)
2722        ResultVal = ResultVal.trunc(Width);
2723    }
2724    Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
2725  }
2726
2727  // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2728  if (Literal.isImaginary)
2729    Res = new (Context) ImaginaryLiteral(Res,
2730                                        Context.getComplexType(Res->getType()));
2731
2732  return Owned(Res);
2733}
2734
2735ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
2736  assert((E != 0) && "ActOnParenExpr() missing expr");
2737  return Owned(new (Context) ParenExpr(L, R, E));
2738}
2739
2740static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2741                                         SourceLocation Loc,
2742                                         SourceRange ArgRange) {
2743  // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2744  // scalar or vector data type argument..."
2745  // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2746  // type (C99 6.2.5p18) or void.
2747  if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2748    S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2749      << T << ArgRange;
2750    return true;
2751  }
2752
2753  assert((T->isVoidType() || !T->isIncompleteType()) &&
2754         "Scalar types should always be complete");
2755  return false;
2756}
2757
2758static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2759                                           SourceLocation Loc,
2760                                           SourceRange ArgRange,
2761                                           UnaryExprOrTypeTrait TraitKind) {
2762  // C99 6.5.3.4p1:
2763  if (T->isFunctionType()) {
2764    // alignof(function) is allowed as an extension.
2765    if (TraitKind == UETT_SizeOf)
2766      S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2767    return false;
2768  }
2769
2770  // Allow sizeof(void)/alignof(void) as an extension.
2771  if (T->isVoidType()) {
2772    S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2773    return false;
2774  }
2775
2776  return true;
2777}
2778
2779static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2780                                             SourceLocation Loc,
2781                                             SourceRange ArgRange,
2782                                             UnaryExprOrTypeTrait TraitKind) {
2783  // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2784  if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2785    S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2786      << T << (TraitKind == UETT_SizeOf)
2787      << ArgRange;
2788    return true;
2789  }
2790
2791  return false;
2792}
2793
2794/// \brief Check the constrains on expression operands to unary type expression
2795/// and type traits.
2796///
2797/// Completes any types necessary and validates the constraints on the operand
2798/// expression. The logic mostly mirrors the type-based overload, but may modify
2799/// the expression as it completes the type for that expression through template
2800/// instantiation, etc.
2801bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
2802                                            UnaryExprOrTypeTrait ExprKind) {
2803  QualType ExprTy = E->getType();
2804
2805  // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2806  //   the result is the size of the referenced type."
2807  // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2808  //   result shall be the alignment of the referenced type."
2809  if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2810    ExprTy = Ref->getPointeeType();
2811
2812  if (ExprKind == UETT_VecStep)
2813    return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2814                                        E->getSourceRange());
2815
2816  // Whitelist some types as extensions
2817  if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2818                                      E->getSourceRange(), ExprKind))
2819    return false;
2820
2821  if (RequireCompleteExprType(E,
2822                              PDiag(diag::err_sizeof_alignof_incomplete_type)
2823                              << ExprKind << E->getSourceRange(),
2824                              std::make_pair(SourceLocation(), PDiag(0))))
2825    return true;
2826
2827  // Completeing the expression's type may have changed it.
2828  ExprTy = E->getType();
2829  if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2830    ExprTy = Ref->getPointeeType();
2831
2832  if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2833                                       E->getSourceRange(), ExprKind))
2834    return true;
2835
2836  if (ExprKind == UETT_SizeOf) {
2837    if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
2838      if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2839        QualType OType = PVD->getOriginalType();
2840        QualType Type = PVD->getType();
2841        if (Type->isPointerType() && OType->isArrayType()) {
2842          Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
2843            << Type << OType;
2844          Diag(PVD->getLocation(), diag::note_declared_at);
2845        }
2846      }
2847    }
2848  }
2849
2850  return false;
2851}
2852
2853/// \brief Check the constraints on operands to unary expression and type
2854/// traits.
2855///
2856/// This will complete any types necessary, and validate the various constraints
2857/// on those operands.
2858///
2859/// The UsualUnaryConversions() function is *not* called by this routine.
2860/// C99 6.3.2.1p[2-4] all state:
2861///   Except when it is the operand of the sizeof operator ...
2862///
2863/// C++ [expr.sizeof]p4
2864///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2865///   standard conversions are not applied to the operand of sizeof.
2866///
2867/// This policy is followed for all of the unary trait expressions.
2868bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
2869                                            SourceLocation OpLoc,
2870                                            SourceRange ExprRange,
2871                                            UnaryExprOrTypeTrait ExprKind) {
2872  if (ExprType->isDependentType())
2873    return false;
2874
2875  // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2876  //   the result is the size of the referenced type."
2877  // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2878  //   result shall be the alignment of the referenced type."
2879  if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
2880    ExprType = Ref->getPointeeType();
2881
2882  if (ExprKind == UETT_VecStep)
2883    return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
2884
2885  // Whitelist some types as extensions
2886  if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
2887                                      ExprKind))
2888    return false;
2889
2890  if (RequireCompleteType(OpLoc, ExprType,
2891                          PDiag(diag::err_sizeof_alignof_incomplete_type)
2892                          << ExprKind << ExprRange))
2893    return true;
2894
2895  if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
2896                                       ExprKind))
2897    return true;
2898
2899  return false;
2900}
2901
2902static bool CheckAlignOfExpr(Sema &S, Expr *E) {
2903  E = E->IgnoreParens();
2904
2905  // alignof decl is always ok.
2906  if (isa<DeclRefExpr>(E))
2907    return false;
2908
2909  // Cannot know anything else if the expression is dependent.
2910  if (E->isTypeDependent())
2911    return false;
2912
2913  if (E->getBitField()) {
2914    S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2915       << 1 << E->getSourceRange();
2916    return true;
2917  }
2918
2919  // Alignment of a field access is always okay, so long as it isn't a
2920  // bit-field.
2921  if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2922    if (isa<FieldDecl>(ME->getMemberDecl()))
2923      return false;
2924
2925  return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
2926}
2927
2928bool Sema::CheckVecStepExpr(Expr *E) {
2929  E = E->IgnoreParens();
2930
2931  // Cannot know anything else if the expression is dependent.
2932  if (E->isTypeDependent())
2933    return false;
2934
2935  return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
2936}
2937
2938/// \brief Build a sizeof or alignof expression given a type operand.
2939ExprResult
2940Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2941                                     SourceLocation OpLoc,
2942                                     UnaryExprOrTypeTrait ExprKind,
2943                                     SourceRange R) {
2944  if (!TInfo)
2945    return ExprError();
2946
2947  QualType T = TInfo->getType();
2948
2949  if (!T->isDependentType() &&
2950      CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
2951    return ExprError();
2952
2953  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2954  return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2955                                                      Context.getSizeType(),
2956                                                      OpLoc, R.getEnd()));
2957}
2958
2959/// \brief Build a sizeof or alignof expression given an expression
2960/// operand.
2961ExprResult
2962Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2963                                     UnaryExprOrTypeTrait ExprKind) {
2964  ExprResult PE = CheckPlaceholderExpr(E);
2965  if (PE.isInvalid())
2966    return ExprError();
2967
2968  E = PE.get();
2969
2970  // Verify that the operand is valid.
2971  bool isInvalid = false;
2972  if (E->isTypeDependent()) {
2973    // Delay type-checking for type-dependent expressions.
2974  } else if (ExprKind == UETT_AlignOf) {
2975    isInvalid = CheckAlignOfExpr(*this, E);
2976  } else if (ExprKind == UETT_VecStep) {
2977    isInvalid = CheckVecStepExpr(E);
2978  } else if (E->getBitField()) {  // C99 6.5.3.4p1.
2979    Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
2980    isInvalid = true;
2981  } else {
2982    isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
2983  }
2984
2985  if (isInvalid)
2986    return ExprError();
2987
2988  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2989  return Owned(new (Context) UnaryExprOrTypeTraitExpr(
2990      ExprKind, E, Context.getSizeType(), OpLoc,
2991      E->getSourceRange().getEnd()));
2992}
2993
2994/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2995/// expr and the same for @c alignof and @c __alignof
2996/// Note that the ArgRange is invalid if isType is false.
2997ExprResult
2998Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
2999                                    UnaryExprOrTypeTrait ExprKind, bool IsType,
3000                                    void *TyOrEx, const SourceRange &ArgRange) {
3001  // If error parsing type, ignore.
3002  if (TyOrEx == 0) return ExprError();
3003
3004  if (IsType) {
3005    TypeSourceInfo *TInfo;
3006    (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3007    return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3008  }
3009
3010  Expr *ArgEx = (Expr *)TyOrEx;
3011  ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3012  return move(Result);
3013}
3014
3015static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3016                                     bool IsReal) {
3017  if (V.get()->isTypeDependent())
3018    return S.Context.DependentTy;
3019
3020  // _Real and _Imag are only l-values for normal l-values.
3021  if (V.get()->getObjectKind() != OK_Ordinary) {
3022    V = S.DefaultLvalueConversion(V.take());
3023    if (V.isInvalid())
3024      return QualType();
3025  }
3026
3027  // These operators return the element type of a complex type.
3028  if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3029    return CT->getElementType();
3030
3031  // Otherwise they pass through real integer and floating point types here.
3032  if (V.get()->getType()->isArithmeticType())
3033    return V.get()->getType();
3034
3035  // Test for placeholders.
3036  ExprResult PR = S.CheckPlaceholderExpr(V.get());
3037  if (PR.isInvalid()) return QualType();
3038  if (PR.get() != V.get()) {
3039    V = move(PR);
3040    return CheckRealImagOperand(S, V, Loc, IsReal);
3041  }
3042
3043  // Reject anything else.
3044  S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3045    << (IsReal ? "__real" : "__imag");
3046  return QualType();
3047}
3048
3049
3050
3051ExprResult
3052Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3053                          tok::TokenKind Kind, Expr *Input) {
3054  UnaryOperatorKind Opc;
3055  switch (Kind) {
3056  default: llvm_unreachable("Unknown unary op!");
3057  case tok::plusplus:   Opc = UO_PostInc; break;
3058  case tok::minusminus: Opc = UO_PostDec; break;
3059  }
3060
3061  return BuildUnaryOp(S, OpLoc, Opc, Input);
3062}
3063
3064ExprResult
3065Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3066                              Expr *Idx, SourceLocation RLoc) {
3067  // Since this might be a postfix expression, get rid of ParenListExprs.
3068  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
3069  if (Result.isInvalid()) return ExprError();
3070  Base = Result.take();
3071
3072  Expr *LHSExp = Base, *RHSExp = Idx;
3073
3074  if (getLangOptions().CPlusPlus &&
3075      (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
3076    return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3077                                                  Context.DependentTy,
3078                                                  VK_LValue, OK_Ordinary,
3079                                                  RLoc));
3080  }
3081
3082  if (getLangOptions().CPlusPlus &&
3083      (LHSExp->getType()->isRecordType() ||
3084       LHSExp->getType()->isEnumeralType() ||
3085       RHSExp->getType()->isRecordType() ||
3086       RHSExp->getType()->isEnumeralType())) {
3087    return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
3088  }
3089
3090  return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
3091}
3092
3093
3094ExprResult
3095Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3096                                      Expr *Idx, SourceLocation RLoc) {
3097  Expr *LHSExp = Base;
3098  Expr *RHSExp = Idx;
3099
3100  // Perform default conversions.
3101  if (!LHSExp->getType()->getAs<VectorType>()) {
3102    ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3103    if (Result.isInvalid())
3104      return ExprError();
3105    LHSExp = Result.take();
3106  }
3107  ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3108  if (Result.isInvalid())
3109    return ExprError();
3110  RHSExp = Result.take();
3111
3112  QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3113  ExprValueKind VK = VK_LValue;
3114  ExprObjectKind OK = OK_Ordinary;
3115
3116  // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3117  // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3118  // in the subscript position. As a result, we need to derive the array base
3119  // and index from the expression types.
3120  Expr *BaseExpr, *IndexExpr;
3121  QualType ResultType;
3122  if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3123    BaseExpr = LHSExp;
3124    IndexExpr = RHSExp;
3125    ResultType = Context.DependentTy;
3126  } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3127    BaseExpr = LHSExp;
3128    IndexExpr = RHSExp;
3129    ResultType = PTy->getPointeeType();
3130  } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3131     // Handle the uncommon case of "123[Ptr]".
3132    BaseExpr = RHSExp;
3133    IndexExpr = LHSExp;
3134    ResultType = PTy->getPointeeType();
3135  } else if (const ObjCObjectPointerType *PTy =
3136               LHSTy->getAs<ObjCObjectPointerType>()) {
3137    BaseExpr = LHSExp;
3138    IndexExpr = RHSExp;
3139    ResultType = PTy->getPointeeType();
3140  } else if (const ObjCObjectPointerType *PTy =
3141               RHSTy->getAs<ObjCObjectPointerType>()) {
3142     // Handle the uncommon case of "123[Ptr]".
3143    BaseExpr = RHSExp;
3144    IndexExpr = LHSExp;
3145    ResultType = PTy->getPointeeType();
3146  } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3147    BaseExpr = LHSExp;    // vectors: V[123]
3148    IndexExpr = RHSExp;
3149    VK = LHSExp->getValueKind();
3150    if (VK != VK_RValue)
3151      OK = OK_VectorComponent;
3152
3153    // FIXME: need to deal with const...
3154    ResultType = VTy->getElementType();
3155  } else if (LHSTy->isArrayType()) {
3156    // If we see an array that wasn't promoted by
3157    // DefaultFunctionArrayLvalueConversion, it must be an array that
3158    // wasn't promoted because of the C90 rule that doesn't
3159    // allow promoting non-lvalue arrays.  Warn, then
3160    // force the promotion here.
3161    Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3162        LHSExp->getSourceRange();
3163    LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3164                               CK_ArrayToPointerDecay).take();
3165    LHSTy = LHSExp->getType();
3166
3167    BaseExpr = LHSExp;
3168    IndexExpr = RHSExp;
3169    ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3170  } else if (RHSTy->isArrayType()) {
3171    // Same as previous, except for 123[f().a] case
3172    Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3173        RHSExp->getSourceRange();
3174    RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3175                               CK_ArrayToPointerDecay).take();
3176    RHSTy = RHSExp->getType();
3177
3178    BaseExpr = RHSExp;
3179    IndexExpr = LHSExp;
3180    ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3181  } else {
3182    return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3183       << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3184  }
3185  // C99 6.5.2.1p1
3186  if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3187    return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3188                     << IndexExpr->getSourceRange());
3189
3190  if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3191       IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3192         && !IndexExpr->isTypeDependent())
3193    Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3194
3195  // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3196  // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3197  // type. Note that Functions are not objects, and that (in C99 parlance)
3198  // incomplete types are not object types.
3199  if (ResultType->isFunctionType()) {
3200    Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3201      << ResultType << BaseExpr->getSourceRange();
3202    return ExprError();
3203  }
3204
3205  if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3206    // GNU extension: subscripting on pointer to void
3207    Diag(LLoc, diag::ext_gnu_subscript_void_type)
3208      << BaseExpr->getSourceRange();
3209
3210    // C forbids expressions of unqualified void type from being l-values.
3211    // See IsCForbiddenLValueType.
3212    if (!ResultType.hasQualifiers()) VK = VK_RValue;
3213  } else if (!ResultType->isDependentType() &&
3214      RequireCompleteType(LLoc, ResultType,
3215                          PDiag(diag::err_subscript_incomplete_type)
3216                            << BaseExpr->getSourceRange()))
3217    return ExprError();
3218
3219  // Diagnose bad cases where we step over interface counts.
3220  if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
3221    Diag(LLoc, diag::err_subscript_nonfragile_interface)
3222      << ResultType << BaseExpr->getSourceRange();
3223    return ExprError();
3224  }
3225
3226  assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3227         !ResultType.isCForbiddenLValueType());
3228
3229  return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3230                                                ResultType, VK, OK, RLoc));
3231}
3232
3233ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3234                                        FunctionDecl *FD,
3235                                        ParmVarDecl *Param) {
3236  if (Param->hasUnparsedDefaultArg()) {
3237    Diag(CallLoc,
3238         diag::err_use_of_default_argument_to_function_declared_later) <<
3239      FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3240    Diag(UnparsedDefaultArgLocs[Param],
3241         diag::note_default_argument_declared_here);
3242    return ExprError();
3243  }
3244
3245  if (Param->hasUninstantiatedDefaultArg()) {
3246    Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3247
3248    // Instantiate the expression.
3249    MultiLevelTemplateArgumentList ArgList
3250      = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
3251
3252    std::pair<const TemplateArgument *, unsigned> Innermost
3253      = ArgList.getInnermost();
3254    InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3255                               Innermost.second);
3256
3257    ExprResult Result;
3258    {
3259      // C++ [dcl.fct.default]p5:
3260      //   The names in the [default argument] expression are bound, and
3261      //   the semantic constraints are checked, at the point where the
3262      //   default argument expression appears.
3263      ContextRAII SavedContext(*this, FD);
3264      Result = SubstExpr(UninstExpr, ArgList);
3265    }
3266    if (Result.isInvalid())
3267      return ExprError();
3268
3269    // Check the expression as an initializer for the parameter.
3270    InitializedEntity Entity
3271      = InitializedEntity::InitializeParameter(Context, Param);
3272    InitializationKind Kind
3273      = InitializationKind::CreateCopy(Param->getLocation(),
3274             /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3275    Expr *ResultE = Result.takeAs<Expr>();
3276
3277    InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3278    Result = InitSeq.Perform(*this, Entity, Kind,
3279                             MultiExprArg(*this, &ResultE, 1));
3280    if (Result.isInvalid())
3281      return ExprError();
3282
3283    // Build the default argument expression.
3284    return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3285                                           Result.takeAs<Expr>()));
3286  }
3287
3288  // If the default expression creates temporaries, we need to
3289  // push them to the current stack of expression temporaries so they'll
3290  // be properly destroyed.
3291  // FIXME: We should really be rebuilding the default argument with new
3292  // bound temporaries; see the comment in PR5810.
3293  for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3294    CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3295    MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
3296                    const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3297    ExprTemporaries.push_back(Temporary);
3298    ExprNeedsCleanups = true;
3299  }
3300
3301  // We already type-checked the argument, so we know it works.
3302  // Just mark all of the declarations in this potentially-evaluated expression
3303  // as being "referenced".
3304  MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
3305  return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
3306}
3307
3308/// ConvertArgumentsForCall - Converts the arguments specified in
3309/// Args/NumArgs to the parameter types of the function FDecl with
3310/// function prototype Proto. Call is the call expression itself, and
3311/// Fn is the function expression. For a C++ member function, this
3312/// routine does not attempt to convert the object argument. Returns
3313/// true if the call is ill-formed.
3314bool
3315Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3316                              FunctionDecl *FDecl,
3317                              const FunctionProtoType *Proto,
3318                              Expr **Args, unsigned NumArgs,
3319                              SourceLocation RParenLoc,
3320                              bool IsExecConfig) {
3321  // Bail out early if calling a builtin with custom typechecking.
3322  // We don't need to do this in the
3323  if (FDecl)
3324    if (unsigned ID = FDecl->getBuiltinID())
3325      if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3326        return false;
3327
3328  // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
3329  // assignment, to the types of the corresponding parameter, ...
3330  unsigned NumArgsInProto = Proto->getNumArgs();
3331  bool Invalid = false;
3332  unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
3333  unsigned FnKind = Fn->getType()->isBlockPointerType()
3334                       ? 1 /* block */
3335                       : (IsExecConfig ? 3 /* kernel function (exec config) */
3336                                       : 0 /* function */);
3337
3338  // If too few arguments are available (and we don't have default
3339  // arguments for the remaining parameters), don't make the call.
3340  if (NumArgs < NumArgsInProto) {
3341    if (NumArgs < MinArgs) {
3342      Diag(RParenLoc, MinArgs == NumArgsInProto
3343                        ? diag::err_typecheck_call_too_few_args
3344                        : diag::err_typecheck_call_too_few_args_at_least)
3345        << FnKind
3346        << MinArgs << NumArgs << Fn->getSourceRange();
3347
3348      // Emit the location of the prototype.
3349      if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
3350        Diag(FDecl->getLocStart(), diag::note_callee_decl)
3351          << FDecl;
3352
3353      return true;
3354    }
3355    Call->setNumArgs(Context, NumArgsInProto);
3356  }
3357
3358  // If too many are passed and not variadic, error on the extras and drop
3359  // them.
3360  if (NumArgs > NumArgsInProto) {
3361    if (!Proto->isVariadic()) {
3362      Diag(Args[NumArgsInProto]->getLocStart(),
3363           MinArgs == NumArgsInProto
3364             ? diag::err_typecheck_call_too_many_args
3365             : diag::err_typecheck_call_too_many_args_at_most)
3366        << FnKind
3367        << NumArgsInProto << NumArgs << Fn->getSourceRange()
3368        << SourceRange(Args[NumArgsInProto]->getLocStart(),
3369                       Args[NumArgs-1]->getLocEnd());
3370
3371      // Emit the location of the prototype.
3372      if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
3373        Diag(FDecl->getLocStart(), diag::note_callee_decl)
3374          << FDecl;
3375
3376      // This deletes the extra arguments.
3377      Call->setNumArgs(Context, NumArgsInProto);
3378      return true;
3379    }
3380  }
3381  SmallVector<Expr *, 8> AllArgs;
3382  VariadicCallType CallType =
3383    Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3384  if (Fn->getType()->isBlockPointerType())
3385    CallType = VariadicBlock; // Block
3386  else if (isa<MemberExpr>(Fn))
3387    CallType = VariadicMethod;
3388  Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
3389                                   Proto, 0, Args, NumArgs, AllArgs, CallType);
3390  if (Invalid)
3391    return true;
3392  unsigned TotalNumArgs = AllArgs.size();
3393  for (unsigned i = 0; i < TotalNumArgs; ++i)
3394    Call->setArg(i, AllArgs[i]);
3395
3396  return false;
3397}
3398
3399bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3400                                  FunctionDecl *FDecl,
3401                                  const FunctionProtoType *Proto,
3402                                  unsigned FirstProtoArg,
3403                                  Expr **Args, unsigned NumArgs,
3404                                  SmallVector<Expr *, 8> &AllArgs,
3405                                  VariadicCallType CallType) {
3406  unsigned NumArgsInProto = Proto->getNumArgs();
3407  unsigned NumArgsToCheck = NumArgs;
3408  bool Invalid = false;
3409  if (NumArgs != NumArgsInProto)
3410    // Use default arguments for missing arguments
3411    NumArgsToCheck = NumArgsInProto;
3412  unsigned ArgIx = 0;
3413  // Continue to check argument types (even if we have too few/many args).
3414  for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
3415    QualType ProtoArgType = Proto->getArgType(i);
3416
3417    Expr *Arg;
3418    ParmVarDecl *Param;
3419    if (ArgIx < NumArgs) {
3420      Arg = Args[ArgIx++];
3421
3422      if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3423                              ProtoArgType,
3424                              PDiag(diag::err_call_incomplete_argument)
3425                              << Arg->getSourceRange()))
3426        return true;
3427
3428      // Pass the argument
3429      Param = 0;
3430      if (FDecl && i < FDecl->getNumParams())
3431        Param = FDecl->getParamDecl(i);
3432
3433      // Strip the unbridged-cast placeholder expression off, if applicable.
3434      if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3435          FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3436          (!Param || !Param->hasAttr<CFConsumedAttr>()))
3437        Arg = stripARCUnbridgedCast(Arg);
3438
3439      InitializedEntity Entity =
3440        Param? InitializedEntity::InitializeParameter(Context, Param)
3441             : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3442                                                      Proto->isArgConsumed(i));
3443      ExprResult ArgE = PerformCopyInitialization(Entity,
3444                                                  SourceLocation(),
3445                                                  Owned(Arg));
3446      if (ArgE.isInvalid())
3447        return true;
3448
3449      Arg = ArgE.takeAs<Expr>();
3450    } else {
3451      Param = FDecl->getParamDecl(i);
3452
3453      ExprResult ArgExpr =
3454        BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
3455      if (ArgExpr.isInvalid())
3456        return true;
3457
3458      Arg = ArgExpr.takeAs<Expr>();
3459    }
3460
3461    // Check for array bounds violations for each argument to the call. This
3462    // check only triggers warnings when the argument isn't a more complex Expr
3463    // with its own checking, such as a BinaryOperator.
3464    CheckArrayAccess(Arg);
3465
3466    // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3467    CheckStaticArrayArgument(CallLoc, Param, Arg);
3468
3469    AllArgs.push_back(Arg);
3470  }
3471
3472  // If this is a variadic call, handle args passed through "...".
3473  if (CallType != VariadicDoesNotApply) {
3474
3475    // Assume that extern "C" functions with variadic arguments that
3476    // return __unknown_anytype aren't *really* variadic.
3477    if (Proto->getResultType() == Context.UnknownAnyTy &&
3478        FDecl && FDecl->isExternC()) {
3479      for (unsigned i = ArgIx; i != NumArgs; ++i) {
3480        ExprResult arg;
3481        if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3482          arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3483        else
3484          arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3485        Invalid |= arg.isInvalid();
3486        AllArgs.push_back(arg.take());
3487      }
3488
3489    // Otherwise do argument promotion, (C99 6.5.2.2p7).
3490    } else {
3491      for (unsigned i = ArgIx; i != NumArgs; ++i) {
3492        ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3493                                                          FDecl);
3494        Invalid |= Arg.isInvalid();
3495        AllArgs.push_back(Arg.take());
3496      }
3497    }
3498
3499    // Check for array bounds violations.
3500    for (unsigned i = ArgIx; i != NumArgs; ++i)
3501      CheckArrayAccess(Args[i]);
3502  }
3503  return Invalid;
3504}
3505
3506static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3507  TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3508  if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3509    S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3510      << ATL->getLocalSourceRange();
3511}
3512
3513/// CheckStaticArrayArgument - If the given argument corresponds to a static
3514/// array parameter, check that it is non-null, and that if it is formed by
3515/// array-to-pointer decay, the underlying array is sufficiently large.
3516///
3517/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3518/// array type derivation, then for each call to the function, the value of the
3519/// corresponding actual argument shall provide access to the first element of
3520/// an array with at least as many elements as specified by the size expression.
3521void
3522Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3523                               ParmVarDecl *Param,
3524                               const Expr *ArgExpr) {
3525  // Static array parameters are not supported in C++.
3526  if (!Param || getLangOptions().CPlusPlus)
3527    return;
3528
3529  QualType OrigTy = Param->getOriginalType();
3530
3531  const ArrayType *AT = Context.getAsArrayType(OrigTy);
3532  if (!AT || AT->getSizeModifier() != ArrayType::Static)
3533    return;
3534
3535  if (ArgExpr->isNullPointerConstant(Context,
3536                                     Expr::NPC_NeverValueDependent)) {
3537    Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3538    DiagnoseCalleeStaticArrayParam(*this, Param);
3539    return;
3540  }
3541
3542  const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3543  if (!CAT)
3544    return;
3545
3546  const ConstantArrayType *ArgCAT =
3547    Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3548  if (!ArgCAT)
3549    return;
3550
3551  if (ArgCAT->getSize().ult(CAT->getSize())) {
3552    Diag(CallLoc, diag::warn_static_array_too_small)
3553      << ArgExpr->getSourceRange()
3554      << (unsigned) ArgCAT->getSize().getZExtValue()
3555      << (unsigned) CAT->getSize().getZExtValue();
3556    DiagnoseCalleeStaticArrayParam(*this, Param);
3557  }
3558}
3559
3560/// Given a function expression of unknown-any type, try to rebuild it
3561/// to have a function type.
3562static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3563
3564/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
3565/// This provides the location of the left/right parens and a list of comma
3566/// locations.
3567ExprResult
3568Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
3569                    MultiExprArg ArgExprs, SourceLocation RParenLoc,
3570                    Expr *ExecConfig, bool IsExecConfig) {
3571  unsigned NumArgs = ArgExprs.size();
3572
3573  // Since this might be a postfix expression, get rid of ParenListExprs.
3574  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
3575  if (Result.isInvalid()) return ExprError();
3576  Fn = Result.take();
3577
3578  Expr **Args = ArgExprs.release();
3579
3580  if (getLangOptions().CPlusPlus) {
3581    // If this is a pseudo-destructor expression, build the call immediately.
3582    if (isa<CXXPseudoDestructorExpr>(Fn)) {
3583      if (NumArgs > 0) {
3584        // Pseudo-destructor calls should not have any arguments.
3585        Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3586          << FixItHint::CreateRemoval(
3587                                    SourceRange(Args[0]->getLocStart(),
3588                                                Args[NumArgs-1]->getLocEnd()));
3589
3590        NumArgs = 0;
3591      }
3592
3593      return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3594                                          VK_RValue, RParenLoc));
3595    }
3596
3597    // Determine whether this is a dependent call inside a C++ template,
3598    // in which case we won't do any semantic analysis now.
3599    // FIXME: Will need to cache the results of name lookup (including ADL) in
3600    // Fn.
3601    bool Dependent = false;
3602    if (Fn->isTypeDependent())
3603      Dependent = true;
3604    else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3605      Dependent = true;
3606
3607    if (Dependent) {
3608      if (ExecConfig) {
3609        return Owned(new (Context) CUDAKernelCallExpr(
3610            Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3611            Context.DependentTy, VK_RValue, RParenLoc));
3612      } else {
3613        return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3614                                            Context.DependentTy, VK_RValue,
3615                                            RParenLoc));
3616      }
3617    }
3618
3619    // Determine whether this is a call to an object (C++ [over.call.object]).
3620    if (Fn->getType()->isRecordType())
3621      return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3622                                                RParenLoc));
3623
3624    if (Fn->getType() == Context.UnknownAnyTy) {
3625      ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3626      if (result.isInvalid()) return ExprError();
3627      Fn = result.take();
3628    }
3629
3630    if (Fn->getType() == Context.BoundMemberTy) {
3631      return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3632                                       RParenLoc);
3633    }
3634  }
3635
3636  // Check for overloaded calls.  This can happen even in C due to extensions.
3637  if (Fn->getType() == Context.OverloadTy) {
3638    OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3639
3640    // We aren't supposed to apply this logic for if there's an '&' involved.
3641    if (!find.HasFormOfMemberPointer) {
3642      OverloadExpr *ovl = find.Expression;
3643      if (isa<UnresolvedLookupExpr>(ovl)) {
3644        UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3645        return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3646                                       RParenLoc, ExecConfig);
3647      } else {
3648        return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3649                                         RParenLoc);
3650      }
3651    }
3652  }
3653
3654  // If we're directly calling a function, get the appropriate declaration.
3655
3656  Expr *NakedFn = Fn->IgnoreParens();
3657
3658  NamedDecl *NDecl = 0;
3659  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3660    if (UnOp->getOpcode() == UO_AddrOf)
3661      NakedFn = UnOp->getSubExpr()->IgnoreParens();
3662
3663  if (isa<DeclRefExpr>(NakedFn))
3664    NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3665  else if (isa<MemberExpr>(NakedFn))
3666    NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
3667
3668  return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
3669                               ExecConfig, IsExecConfig);
3670}
3671
3672ExprResult
3673Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3674                              MultiExprArg ExecConfig, SourceLocation GGGLoc) {
3675  FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3676  if (!ConfigDecl)
3677    return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3678                          << "cudaConfigureCall");
3679  QualType ConfigQTy = ConfigDecl->getType();
3680
3681  DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3682      ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3683
3684  return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3685                       /*IsExecConfig=*/true);
3686}
3687
3688/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3689///
3690/// __builtin_astype( value, dst type )
3691///
3692ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
3693                                 SourceLocation BuiltinLoc,
3694                                 SourceLocation RParenLoc) {
3695  ExprValueKind VK = VK_RValue;
3696  ExprObjectKind OK = OK_Ordinary;
3697  QualType DstTy = GetTypeFromParser(ParsedDestTy);
3698  QualType SrcTy = E->getType();
3699  if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3700    return ExprError(Diag(BuiltinLoc,
3701                          diag::err_invalid_astype_of_different_size)
3702                     << DstTy
3703                     << SrcTy
3704                     << E->getSourceRange());
3705  return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
3706               RParenLoc));
3707}
3708
3709/// BuildResolvedCallExpr - Build a call to a resolved expression,
3710/// i.e. an expression not of \p OverloadTy.  The expression should
3711/// unary-convert to an expression of function-pointer or
3712/// block-pointer type.
3713///
3714/// \param NDecl the declaration being called, if available
3715ExprResult
3716Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3717                            SourceLocation LParenLoc,
3718                            Expr **Args, unsigned NumArgs,
3719                            SourceLocation RParenLoc,
3720                            Expr *Config, bool IsExecConfig) {
3721  FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3722
3723  // Promote the function operand.
3724  ExprResult Result = UsualUnaryConversions(Fn);
3725  if (Result.isInvalid())
3726    return ExprError();
3727  Fn = Result.take();
3728
3729  // Make the call expr early, before semantic checks.  This guarantees cleanup
3730  // of arguments and function on error.
3731  CallExpr *TheCall;
3732  if (Config) {
3733    TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3734                                               cast<CallExpr>(Config),
3735                                               Args, NumArgs,
3736                                               Context.BoolTy,
3737                                               VK_RValue,
3738                                               RParenLoc);
3739  } else {
3740    TheCall = new (Context) CallExpr(Context, Fn,
3741                                     Args, NumArgs,
3742                                     Context.BoolTy,
3743                                     VK_RValue,
3744                                     RParenLoc);
3745  }
3746
3747  unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3748
3749  // Bail out early if calling a builtin with custom typechecking.
3750  if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3751    return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3752
3753 retry:
3754  const FunctionType *FuncT;
3755  if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
3756    // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3757    // have type pointer to function".
3758    FuncT = PT->getPointeeType()->getAs<FunctionType>();
3759    if (FuncT == 0)
3760      return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3761                         << Fn->getType() << Fn->getSourceRange());
3762  } else if (const BlockPointerType *BPT =
3763               Fn->getType()->getAs<BlockPointerType>()) {
3764    FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3765  } else {
3766    // Handle calls to expressions of unknown-any type.
3767    if (Fn->getType() == Context.UnknownAnyTy) {
3768      ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
3769      if (rewrite.isInvalid()) return ExprError();
3770      Fn = rewrite.take();
3771      TheCall->setCallee(Fn);
3772      goto retry;
3773    }
3774
3775    return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3776      << Fn->getType() << Fn->getSourceRange());
3777  }
3778
3779  if (getLangOptions().CUDA) {
3780    if (Config) {
3781      // CUDA: Kernel calls must be to global functions
3782      if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3783        return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3784            << FDecl->getName() << Fn->getSourceRange());
3785
3786      // CUDA: Kernel function must have 'void' return type
3787      if (!FuncT->getResultType()->isVoidType())
3788        return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3789            << Fn->getType() << Fn->getSourceRange());
3790    } else {
3791      // CUDA: Calls to global functions must be configured
3792      if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
3793        return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
3794            << FDecl->getName() << Fn->getSourceRange());
3795    }
3796  }
3797
3798  // Check for a valid return type
3799  if (CheckCallReturnType(FuncT->getResultType(),
3800                          Fn->getSourceRange().getBegin(), TheCall,
3801                          FDecl))
3802    return ExprError();
3803
3804  // We know the result type of the call, set it.
3805  TheCall->setType(FuncT->getCallResultType(Context));
3806  TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
3807
3808  if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
3809    if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
3810                                RParenLoc, IsExecConfig))
3811      return ExprError();
3812  } else {
3813    assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
3814
3815    if (FDecl) {
3816      // Check if we have too few/too many template arguments, based
3817      // on our knowledge of the function definition.
3818      const FunctionDecl *Def = 0;
3819      if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
3820        const FunctionProtoType *Proto
3821          = Def->getType()->getAs<FunctionProtoType>();
3822        if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
3823          Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3824            << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3825      }
3826
3827      // If the function we're calling isn't a function prototype, but we have
3828      // a function prototype from a prior declaratiom, use that prototype.
3829      if (!FDecl->hasPrototype())
3830        Proto = FDecl->getType()->getAs<FunctionProtoType>();
3831    }
3832
3833    // Promote the arguments (C99 6.5.2.2p6).
3834    for (unsigned i = 0; i != NumArgs; i++) {
3835      Expr *Arg = Args[i];
3836
3837      if (Proto && i < Proto->getNumArgs()) {
3838        InitializedEntity Entity
3839          = InitializedEntity::InitializeParameter(Context,
3840                                                   Proto->getArgType(i),
3841                                                   Proto->isArgConsumed(i));
3842        ExprResult ArgE = PerformCopyInitialization(Entity,
3843                                                    SourceLocation(),
3844                                                    Owned(Arg));
3845        if (ArgE.isInvalid())
3846          return true;
3847
3848        Arg = ArgE.takeAs<Expr>();
3849
3850      } else {
3851        ExprResult ArgE = DefaultArgumentPromotion(Arg);
3852
3853        if (ArgE.isInvalid())
3854          return true;
3855
3856        Arg = ArgE.takeAs<Expr>();
3857      }
3858
3859      if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3860                              Arg->getType(),
3861                              PDiag(diag::err_call_incomplete_argument)
3862                                << Arg->getSourceRange()))
3863        return ExprError();
3864
3865      TheCall->setArg(i, Arg);
3866    }
3867  }
3868
3869  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3870    if (!Method->isStatic())
3871      return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3872        << Fn->getSourceRange());
3873
3874  // Check for sentinels
3875  if (NDecl)
3876    DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
3877
3878  // Do special checking on direct calls to functions.
3879  if (FDecl) {
3880    if (CheckFunctionCall(FDecl, TheCall))
3881      return ExprError();
3882
3883    if (BuiltinID)
3884      return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3885  } else if (NDecl) {
3886    if (CheckBlockCall(NDecl, TheCall))
3887      return ExprError();
3888  }
3889
3890  return MaybeBindToTemporary(TheCall);
3891}
3892
3893ExprResult
3894Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
3895                           SourceLocation RParenLoc, Expr *InitExpr) {
3896  assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
3897  // FIXME: put back this assert when initializers are worked out.
3898  //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
3899
3900  TypeSourceInfo *TInfo;
3901  QualType literalType = GetTypeFromParser(Ty, &TInfo);
3902  if (!TInfo)
3903    TInfo = Context.getTrivialTypeSourceInfo(literalType);
3904
3905  return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
3906}
3907
3908ExprResult
3909Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
3910                               SourceLocation RParenLoc, Expr *LiteralExpr) {
3911  QualType literalType = TInfo->getType();
3912
3913  if (literalType->isArrayType()) {
3914    if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3915             PDiag(diag::err_illegal_decl_array_incomplete_type)
3916               << SourceRange(LParenLoc,
3917                              LiteralExpr->getSourceRange().getEnd())))
3918      return ExprError();
3919    if (literalType->isVariableArrayType())
3920      return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3921        << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
3922  } else if (!literalType->isDependentType() &&
3923             RequireCompleteType(LParenLoc, literalType,
3924                      PDiag(diag::err_typecheck_decl_incomplete_type)
3925                        << SourceRange(LParenLoc,
3926                                       LiteralExpr->getSourceRange().getEnd())))
3927    return ExprError();
3928
3929  InitializedEntity Entity
3930    = InitializedEntity::InitializeTemporary(literalType);
3931  InitializationKind Kind
3932    = InitializationKind::CreateCStyleCast(LParenLoc,
3933                                           SourceRange(LParenLoc, RParenLoc));
3934  InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
3935  ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3936                                       MultiExprArg(*this, &LiteralExpr, 1),
3937                                            &literalType);
3938  if (Result.isInvalid())
3939    return ExprError();
3940  LiteralExpr = Result.get();
3941
3942  bool isFileScope = getCurFunctionOrMethodDecl() == 0;
3943  if (isFileScope) { // 6.5.2.5p3
3944    if (CheckForConstantInitializer(LiteralExpr, literalType))
3945      return ExprError();
3946  }
3947
3948  // In C, compound literals are l-values for some reason.
3949  ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3950
3951  return MaybeBindToTemporary(
3952           new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
3953                                             VK, LiteralExpr, isFileScope));
3954}
3955
3956ExprResult
3957Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
3958                    SourceLocation RBraceLoc) {
3959  unsigned NumInit = InitArgList.size();
3960  Expr **InitList = InitArgList.release();
3961
3962  // Immediately handle non-overload placeholders.  Overloads can be
3963  // resolved contextually, but everything else here can't.
3964  for (unsigned I = 0; I != NumInit; ++I) {
3965    if (const BuiltinType *pty
3966          = InitList[I]->getType()->getAsPlaceholderType()) {
3967      if (pty->getKind() == BuiltinType::Overload) continue;
3968
3969      ExprResult result = CheckPlaceholderExpr(InitList[I]);
3970
3971      // Ignore failures; dropping the entire initializer list because
3972      // of one failure would be terrible for indexing/etc.
3973      if (result.isInvalid()) continue;
3974
3975      InitList[I] = result.take();
3976    }
3977  }
3978
3979  // Semantic analysis for initializers is done by ActOnDeclarator() and
3980  // CheckInitializer() - it requires knowledge of the object being intialized.
3981
3982  InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3983                                               NumInit, RBraceLoc);
3984  E->setType(Context.VoidTy); // FIXME: just a place holder for now.
3985  return Owned(E);
3986}
3987
3988/// Do an explicit extend of the given block pointer if we're in ARC.
3989static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
3990  assert(E.get()->getType()->isBlockPointerType());
3991  assert(E.get()->isRValue());
3992
3993  // Only do this in an r-value context.
3994  if (!S.getLangOptions().ObjCAutoRefCount) return;
3995
3996  E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
3997                               CK_ARCExtendBlockObject, E.get(),
3998                               /*base path*/ 0, VK_RValue);
3999  S.ExprNeedsCleanups = true;
4000}
4001
4002/// Prepare a conversion of the given expression to an ObjC object
4003/// pointer type.
4004CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4005  QualType type = E.get()->getType();
4006  if (type->isObjCObjectPointerType()) {
4007    return CK_BitCast;
4008  } else if (type->isBlockPointerType()) {
4009    maybeExtendBlockObject(*this, E);
4010    return CK_BlockPointerToObjCPointerCast;
4011  } else {
4012    assert(type->isPointerType());
4013    return CK_CPointerToObjCPointerCast;
4014  }
4015}
4016
4017/// Prepares for a scalar cast, performing all the necessary stages
4018/// except the final cast and returning the kind required.
4019CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
4020  // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4021  // Also, callers should have filtered out the invalid cases with
4022  // pointers.  Everything else should be possible.
4023
4024  QualType SrcTy = Src.get()->getType();
4025  if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
4026    return CK_NoOp;
4027
4028  switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
4029  case Type::STK_MemberPointer:
4030    llvm_unreachable("member pointer type in C");
4031
4032  case Type::STK_CPointer:
4033  case Type::STK_BlockPointer:
4034  case Type::STK_ObjCObjectPointer:
4035    switch (DestTy->getScalarTypeKind()) {
4036    case Type::STK_CPointer:
4037      return CK_BitCast;
4038    case Type::STK_BlockPointer:
4039      return (SrcKind == Type::STK_BlockPointer
4040                ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4041    case Type::STK_ObjCObjectPointer:
4042      if (SrcKind == Type::STK_ObjCObjectPointer)
4043        return CK_BitCast;
4044      else if (SrcKind == Type::STK_CPointer)
4045        return CK_CPointerToObjCPointerCast;
4046      else {
4047        maybeExtendBlockObject(*this, Src);
4048        return CK_BlockPointerToObjCPointerCast;
4049      }
4050    case Type::STK_Bool:
4051      return CK_PointerToBoolean;
4052    case Type::STK_Integral:
4053      return CK_PointerToIntegral;
4054    case Type::STK_Floating:
4055    case Type::STK_FloatingComplex:
4056    case Type::STK_IntegralComplex:
4057    case Type::STK_MemberPointer:
4058      llvm_unreachable("illegal cast from pointer");
4059    }
4060    break;
4061
4062  case Type::STK_Bool: // casting from bool is like casting from an integer
4063  case Type::STK_Integral:
4064    switch (DestTy->getScalarTypeKind()) {
4065    case Type::STK_CPointer:
4066    case Type::STK_ObjCObjectPointer:
4067    case Type::STK_BlockPointer:
4068      if (Src.get()->isNullPointerConstant(Context,
4069                                           Expr::NPC_ValueDependentIsNull))
4070        return CK_NullToPointer;
4071      return CK_IntegralToPointer;
4072    case Type::STK_Bool:
4073      return CK_IntegralToBoolean;
4074    case Type::STK_Integral:
4075      return CK_IntegralCast;
4076    case Type::STK_Floating:
4077      return CK_IntegralToFloating;
4078    case Type::STK_IntegralComplex:
4079      Src = ImpCastExprToType(Src.take(),
4080                              DestTy->castAs<ComplexType>()->getElementType(),
4081                              CK_IntegralCast);
4082      return CK_IntegralRealToComplex;
4083    case Type::STK_FloatingComplex:
4084      Src = ImpCastExprToType(Src.take(),
4085                              DestTy->castAs<ComplexType>()->getElementType(),
4086                              CK_IntegralToFloating);
4087      return CK_FloatingRealToComplex;
4088    case Type::STK_MemberPointer:
4089      llvm_unreachable("member pointer type in C");
4090    }
4091    break;
4092
4093  case Type::STK_Floating:
4094    switch (DestTy->getScalarTypeKind()) {
4095    case Type::STK_Floating:
4096      return CK_FloatingCast;
4097    case Type::STK_Bool:
4098      return CK_FloatingToBoolean;
4099    case Type::STK_Integral:
4100      return CK_FloatingToIntegral;
4101    case Type::STK_FloatingComplex:
4102      Src = ImpCastExprToType(Src.take(),
4103                              DestTy->castAs<ComplexType>()->getElementType(),
4104                              CK_FloatingCast);
4105      return CK_FloatingRealToComplex;
4106    case Type::STK_IntegralComplex:
4107      Src = ImpCastExprToType(Src.take(),
4108                              DestTy->castAs<ComplexType>()->getElementType(),
4109                              CK_FloatingToIntegral);
4110      return CK_IntegralRealToComplex;
4111    case Type::STK_CPointer:
4112    case Type::STK_ObjCObjectPointer:
4113    case Type::STK_BlockPointer:
4114      llvm_unreachable("valid float->pointer cast?");
4115    case Type::STK_MemberPointer:
4116      llvm_unreachable("member pointer type in C");
4117    }
4118    break;
4119
4120  case Type::STK_FloatingComplex:
4121    switch (DestTy->getScalarTypeKind()) {
4122    case Type::STK_FloatingComplex:
4123      return CK_FloatingComplexCast;
4124    case Type::STK_IntegralComplex:
4125      return CK_FloatingComplexToIntegralComplex;
4126    case Type::STK_Floating: {
4127      QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4128      if (Context.hasSameType(ET, DestTy))
4129        return CK_FloatingComplexToReal;
4130      Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
4131      return CK_FloatingCast;
4132    }
4133    case Type::STK_Bool:
4134      return CK_FloatingComplexToBoolean;
4135    case Type::STK_Integral:
4136      Src = ImpCastExprToType(Src.take(),
4137                              SrcTy->castAs<ComplexType>()->getElementType(),
4138                              CK_FloatingComplexToReal);
4139      return CK_FloatingToIntegral;
4140    case Type::STK_CPointer:
4141    case Type::STK_ObjCObjectPointer:
4142    case Type::STK_BlockPointer:
4143      llvm_unreachable("valid complex float->pointer cast?");
4144    case Type::STK_MemberPointer:
4145      llvm_unreachable("member pointer type in C");
4146    }
4147    break;
4148
4149  case Type::STK_IntegralComplex:
4150    switch (DestTy->getScalarTypeKind()) {
4151    case Type::STK_FloatingComplex:
4152      return CK_IntegralComplexToFloatingComplex;
4153    case Type::STK_IntegralComplex:
4154      return CK_IntegralComplexCast;
4155    case Type::STK_Integral: {
4156      QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4157      if (Context.hasSameType(ET, DestTy))
4158        return CK_IntegralComplexToReal;
4159      Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
4160      return CK_IntegralCast;
4161    }
4162    case Type::STK_Bool:
4163      return CK_IntegralComplexToBoolean;
4164    case Type::STK_Floating:
4165      Src = ImpCastExprToType(Src.take(),
4166                              SrcTy->castAs<ComplexType>()->getElementType(),
4167                              CK_IntegralComplexToReal);
4168      return CK_IntegralToFloating;
4169    case Type::STK_CPointer:
4170    case Type::STK_ObjCObjectPointer:
4171    case Type::STK_BlockPointer:
4172      llvm_unreachable("valid complex int->pointer cast?");
4173    case Type::STK_MemberPointer:
4174      llvm_unreachable("member pointer type in C");
4175    }
4176    break;
4177  }
4178
4179  llvm_unreachable("Unhandled scalar cast");
4180}
4181
4182bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
4183                           CastKind &Kind) {
4184  assert(VectorTy->isVectorType() && "Not a vector type!");
4185
4186  if (Ty->isVectorType() || Ty->isIntegerType()) {
4187    if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
4188      return Diag(R.getBegin(),
4189                  Ty->isVectorType() ?
4190                  diag::err_invalid_conversion_between_vectors :
4191                  diag::err_invalid_conversion_between_vector_and_integer)
4192        << VectorTy << Ty << R;
4193  } else
4194    return Diag(R.getBegin(),
4195                diag::err_invalid_conversion_between_vector_and_scalar)
4196      << VectorTy << Ty << R;
4197
4198  Kind = CK_BitCast;
4199  return false;
4200}
4201
4202ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4203                                    Expr *CastExpr, CastKind &Kind) {
4204  assert(DestTy->isExtVectorType() && "Not an extended vector type!");
4205
4206  QualType SrcTy = CastExpr->getType();
4207
4208  // If SrcTy is a VectorType, the total size must match to explicitly cast to
4209  // an ExtVectorType.
4210  // In OpenCL, casts between vectors of different types are not allowed.
4211  // (See OpenCL 6.2).
4212  if (SrcTy->isVectorType()) {
4213    if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
4214        || (getLangOptions().OpenCL &&
4215            (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
4216      Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4217        << DestTy << SrcTy << R;
4218      return ExprError();
4219    }
4220    Kind = CK_BitCast;
4221    return Owned(CastExpr);
4222  }
4223
4224  // All non-pointer scalars can be cast to ExtVector type.  The appropriate
4225  // conversion will take place first from scalar to elt type, and then
4226  // splat from elt type to vector.
4227  if (SrcTy->isPointerType())
4228    return Diag(R.getBegin(),
4229                diag::err_invalid_conversion_between_vector_and_scalar)
4230      << DestTy << SrcTy << R;
4231
4232  QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4233  ExprResult CastExprRes = Owned(CastExpr);
4234  CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
4235  if (CastExprRes.isInvalid())
4236    return ExprError();
4237  CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
4238
4239  Kind = CK_VectorSplat;
4240  return Owned(CastExpr);
4241}
4242
4243ExprResult
4244Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4245                    Declarator &D, ParsedType &Ty,
4246                    SourceLocation RParenLoc, Expr *CastExpr) {
4247  assert(!D.isInvalidType() && (CastExpr != 0) &&
4248         "ActOnCastExpr(): missing type or expr");
4249
4250  TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
4251  if (D.isInvalidType())
4252    return ExprError();
4253
4254  if (getLangOptions().CPlusPlus) {
4255    // Check that there are no default arguments (C++ only).
4256    CheckExtraCXXDefaultArguments(D);
4257  }
4258
4259  checkUnusedDeclAttributes(D);
4260
4261  QualType castType = castTInfo->getType();
4262  Ty = CreateParsedType(castType, castTInfo);
4263
4264  bool isVectorLiteral = false;
4265
4266  // Check for an altivec or OpenCL literal,
4267  // i.e. all the elements are integer constants.
4268  ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4269  ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
4270  if ((getLangOptions().AltiVec || getLangOptions().OpenCL)
4271       && castType->isVectorType() && (PE || PLE)) {
4272    if (PLE && PLE->getNumExprs() == 0) {
4273      Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4274      return ExprError();
4275    }
4276    if (PE || PLE->getNumExprs() == 1) {
4277      Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4278      if (!E->getType()->isVectorType())
4279        isVectorLiteral = true;
4280    }
4281    else
4282      isVectorLiteral = true;
4283  }
4284
4285  // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4286  // then handle it as such.
4287  if (isVectorLiteral)
4288    return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
4289
4290  // If the Expr being casted is a ParenListExpr, handle it specially.
4291  // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4292  // sequence of BinOp comma operators.
4293  if (isa<ParenListExpr>(CastExpr)) {
4294    ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
4295    if (Result.isInvalid()) return ExprError();
4296    CastExpr = Result.take();
4297  }
4298
4299  return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
4300}
4301
4302ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4303                                    SourceLocation RParenLoc, Expr *E,
4304                                    TypeSourceInfo *TInfo) {
4305  assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4306         "Expected paren or paren list expression");
4307
4308  Expr **exprs;
4309  unsigned numExprs;
4310  Expr *subExpr;
4311  if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4312    exprs = PE->getExprs();
4313    numExprs = PE->getNumExprs();
4314  } else {
4315    subExpr = cast<ParenExpr>(E)->getSubExpr();
4316    exprs = &subExpr;
4317    numExprs = 1;
4318  }
4319
4320  QualType Ty = TInfo->getType();
4321  assert(Ty->isVectorType() && "Expected vector type");
4322
4323  SmallVector<Expr *, 8> initExprs;
4324  const VectorType *VTy = Ty->getAs<VectorType>();
4325  unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4326
4327  // '(...)' form of vector initialization in AltiVec: the number of
4328  // initializers must be one or must match the size of the vector.
4329  // If a single value is specified in the initializer then it will be
4330  // replicated to all the components of the vector
4331  if (VTy->getVectorKind() == VectorType::AltiVecVector) {
4332    // The number of initializers must be one or must match the size of the
4333    // vector. If a single value is specified in the initializer then it will
4334    // be replicated to all the components of the vector
4335    if (numExprs == 1) {
4336      QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4337      ExprResult Literal = Owned(exprs[0]);
4338      Literal = ImpCastExprToType(Literal.take(), ElemTy,
4339                                  PrepareScalarCast(Literal, ElemTy));
4340      return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4341    }
4342    else if (numExprs < numElems) {
4343      Diag(E->getExprLoc(),
4344           diag::err_incorrect_number_of_vector_initializers);
4345      return ExprError();
4346    }
4347    else
4348      for (unsigned i = 0, e = numExprs; i != e; ++i)
4349        initExprs.push_back(exprs[i]);
4350  }
4351  else {
4352    // For OpenCL, when the number of initializers is a single value,
4353    // it will be replicated to all components of the vector.
4354    if (getLangOptions().OpenCL &&
4355        VTy->getVectorKind() == VectorType::GenericVector &&
4356        numExprs == 1) {
4357        QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4358        ExprResult Literal = Owned(exprs[0]);
4359        Literal = ImpCastExprToType(Literal.take(), ElemTy,
4360                                    PrepareScalarCast(Literal, ElemTy));
4361        return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4362    }
4363
4364    for (unsigned i = 0, e = numExprs; i != e; ++i)
4365      initExprs.push_back(exprs[i]);
4366  }
4367  // FIXME: This means that pretty-printing the final AST will produce curly
4368  // braces instead of the original commas.
4369  InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4370                                                   &initExprs[0],
4371                                                   initExprs.size(), RParenLoc);
4372  initE->setType(Ty);
4373  return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4374}
4375
4376/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4377/// of comma binary operators.
4378ExprResult
4379Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4380  ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
4381  if (!E)
4382    return Owned(OrigExpr);
4383
4384  ExprResult Result(E->getExpr(0));
4385
4386  for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
4387    Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4388                        E->getExpr(i));
4389
4390  if (Result.isInvalid()) return ExprError();
4391
4392  return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
4393}
4394
4395ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
4396                                           SourceLocation R,
4397                                           MultiExprArg Val) {
4398  unsigned nexprs = Val.size();
4399  Expr **exprs = reinterpret_cast<Expr**>(Val.release());
4400  assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4401  Expr *expr;
4402  if (nexprs == 1)
4403    expr = new (Context) ParenExpr(L, R, exprs[0]);
4404  else
4405    expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4406                                       exprs[nexprs-1]->getType());
4407  return Owned(expr);
4408}
4409
4410/// \brief Emit a specialized diagnostic when one expression is a null pointer
4411/// constant and the other is not a pointer.  Returns true if a diagnostic is
4412/// emitted.
4413bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
4414                                      SourceLocation QuestionLoc) {
4415  Expr *NullExpr = LHSExpr;
4416  Expr *NonPointerExpr = RHSExpr;
4417  Expr::NullPointerConstantKind NullKind =
4418      NullExpr->isNullPointerConstant(Context,
4419                                      Expr::NPC_ValueDependentIsNotNull);
4420
4421  if (NullKind == Expr::NPCK_NotNull) {
4422    NullExpr = RHSExpr;
4423    NonPointerExpr = LHSExpr;
4424    NullKind =
4425        NullExpr->isNullPointerConstant(Context,
4426                                        Expr::NPC_ValueDependentIsNotNull);
4427  }
4428
4429  if (NullKind == Expr::NPCK_NotNull)
4430    return false;
4431
4432  if (NullKind == Expr::NPCK_ZeroInteger) {
4433    // In this case, check to make sure that we got here from a "NULL"
4434    // string in the source code.
4435    NullExpr = NullExpr->IgnoreParenImpCasts();
4436    SourceLocation loc = NullExpr->getExprLoc();
4437    if (!findMacroSpelling(loc, "NULL"))
4438      return false;
4439  }
4440
4441  int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4442  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4443      << NonPointerExpr->getType() << DiagType
4444      << NonPointerExpr->getSourceRange();
4445  return true;
4446}
4447
4448/// \brief Return false if the condition expression is valid, true otherwise.
4449static bool checkCondition(Sema &S, Expr *Cond) {
4450  QualType CondTy = Cond->getType();
4451
4452  // C99 6.5.15p2
4453  if (CondTy->isScalarType()) return false;
4454
4455  // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4456  if (S.getLangOptions().OpenCL && CondTy->isVectorType())
4457    return false;
4458
4459  // Emit the proper error message.
4460  S.Diag(Cond->getLocStart(), S.getLangOptions().OpenCL ?
4461                              diag::err_typecheck_cond_expect_scalar :
4462                              diag::err_typecheck_cond_expect_scalar_or_vector)
4463    << CondTy;
4464  return true;
4465}
4466
4467/// \brief Return false if the two expressions can be converted to a vector,
4468/// true otherwise
4469static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4470                                                    ExprResult &RHS,
4471                                                    QualType CondTy) {
4472  // Both operands should be of scalar type.
4473  if (!LHS.get()->getType()->isScalarType()) {
4474    S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4475      << CondTy;
4476    return true;
4477  }
4478  if (!RHS.get()->getType()->isScalarType()) {
4479    S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4480      << CondTy;
4481    return true;
4482  }
4483
4484  // Implicity convert these scalars to the type of the condition.
4485  LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4486  RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4487  return false;
4488}
4489
4490/// \brief Handle when one or both operands are void type.
4491static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4492                                         ExprResult &RHS) {
4493    Expr *LHSExpr = LHS.get();
4494    Expr *RHSExpr = RHS.get();
4495
4496    if (!LHSExpr->getType()->isVoidType())
4497      S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4498        << RHSExpr->getSourceRange();
4499    if (!RHSExpr->getType()->isVoidType())
4500      S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4501        << LHSExpr->getSourceRange();
4502    LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4503    RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4504    return S.Context.VoidTy;
4505}
4506
4507/// \brief Return false if the NullExpr can be promoted to PointerTy,
4508/// true otherwise.
4509static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4510                                        QualType PointerTy) {
4511  if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4512      !NullExpr.get()->isNullPointerConstant(S.Context,
4513                                            Expr::NPC_ValueDependentIsNull))
4514    return true;
4515
4516  NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4517  return false;
4518}
4519
4520/// \brief Checks compatibility between two pointers and return the resulting
4521/// type.
4522static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4523                                                     ExprResult &RHS,
4524                                                     SourceLocation Loc) {
4525  QualType LHSTy = LHS.get()->getType();
4526  QualType RHSTy = RHS.get()->getType();
4527
4528  if (S.Context.hasSameType(LHSTy, RHSTy)) {
4529    // Two identical pointers types are always compatible.
4530    return LHSTy;
4531  }
4532
4533  QualType lhptee, rhptee;
4534
4535  // Get the pointee types.
4536  if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4537    lhptee = LHSBTy->getPointeeType();
4538    rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
4539  } else {
4540    lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4541    rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
4542  }
4543
4544  if (!S.Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4545                                    rhptee.getUnqualifiedType())) {
4546    S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4547      << LHSTy << RHSTy << LHS.get()->getSourceRange()
4548      << RHS.get()->getSourceRange();
4549    // In this situation, we assume void* type. No especially good
4550    // reason, but this is what gcc does, and we do have to pick
4551    // to get a consistent AST.
4552    QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4553    LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4554    RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4555    return incompatTy;
4556  }
4557
4558  // The pointer types are compatible.
4559  // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4560  // differently qualified versions of compatible types, the result type is
4561  // a pointer to an appropriately qualified version of the *composite*
4562  // type.
4563  // FIXME: Need to calculate the composite type.
4564  // FIXME: Need to add qualifiers
4565
4566  LHS = S.ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4567  RHS = S.ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
4568  return LHSTy;
4569}
4570
4571/// \brief Return the resulting type when the operands are both block pointers.
4572static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4573                                                          ExprResult &LHS,
4574                                                          ExprResult &RHS,
4575                                                          SourceLocation Loc) {
4576  QualType LHSTy = LHS.get()->getType();
4577  QualType RHSTy = RHS.get()->getType();
4578
4579  if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4580    if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4581      QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4582      LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4583      RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4584      return destType;
4585    }
4586    S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4587      << LHSTy << RHSTy << LHS.get()->getSourceRange()
4588      << RHS.get()->getSourceRange();
4589    return QualType();
4590  }
4591
4592  // We have 2 block pointer types.
4593  return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4594}
4595
4596/// \brief Return the resulting type when the operands are both pointers.
4597static QualType
4598checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4599                                            ExprResult &RHS,
4600                                            SourceLocation Loc) {
4601  // get the pointer types
4602  QualType LHSTy = LHS.get()->getType();
4603  QualType RHSTy = RHS.get()->getType();
4604
4605  // get the "pointed to" types
4606  QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4607  QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4608
4609  // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4610  if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4611    // Figure out necessary qualifiers (C99 6.5.15p6)
4612    QualType destPointee
4613      = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4614    QualType destType = S.Context.getPointerType(destPointee);
4615    // Add qualifiers if necessary.
4616    LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4617    // Promote to void*.
4618    RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4619    return destType;
4620  }
4621  if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4622    QualType destPointee
4623      = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4624    QualType destType = S.Context.getPointerType(destPointee);
4625    // Add qualifiers if necessary.
4626    RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4627    // Promote to void*.
4628    LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4629    return destType;
4630  }
4631
4632  return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4633}
4634
4635/// \brief Return false if the first expression is not an integer and the second
4636/// expression is not a pointer, true otherwise.
4637static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4638                                        Expr* PointerExpr, SourceLocation Loc,
4639                                        bool IsIntFirstExpr) {
4640  if (!PointerExpr->getType()->isPointerType() ||
4641      !Int.get()->getType()->isIntegerType())
4642    return false;
4643
4644  Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4645  Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
4646
4647  S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4648    << Expr1->getType() << Expr2->getType()
4649    << Expr1->getSourceRange() << Expr2->getSourceRange();
4650  Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4651                            CK_IntegralToPointer);
4652  return true;
4653}
4654
4655/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4656/// In that case, LHS = cond.
4657/// C99 6.5.15
4658QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4659                                        ExprResult &RHS, ExprValueKind &VK,
4660                                        ExprObjectKind &OK,
4661                                        SourceLocation QuestionLoc) {
4662
4663  ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4664  if (!LHSResult.isUsable()) return QualType();
4665  LHS = move(LHSResult);
4666
4667  ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4668  if (!RHSResult.isUsable()) return QualType();
4669  RHS = move(RHSResult);
4670
4671  // C++ is sufficiently different to merit its own checker.
4672  if (getLangOptions().CPlusPlus)
4673    return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
4674
4675  VK = VK_RValue;
4676  OK = OK_Ordinary;
4677
4678  Cond = UsualUnaryConversions(Cond.take());
4679  if (Cond.isInvalid())
4680    return QualType();
4681  LHS = UsualUnaryConversions(LHS.take());
4682  if (LHS.isInvalid())
4683    return QualType();
4684  RHS = UsualUnaryConversions(RHS.take());
4685  if (RHS.isInvalid())
4686    return QualType();
4687
4688  QualType CondTy = Cond.get()->getType();
4689  QualType LHSTy = LHS.get()->getType();
4690  QualType RHSTy = RHS.get()->getType();
4691
4692  // first, check the condition.
4693  if (checkCondition(*this, Cond.get()))
4694    return QualType();
4695
4696  // Now check the two expressions.
4697  if (LHSTy->isVectorType() || RHSTy->isVectorType())
4698    return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
4699
4700  // OpenCL: If the condition is a vector, and both operands are scalar,
4701  // attempt to implicity convert them to the vector type to act like the
4702  // built in select.
4703  if (getLangOptions().OpenCL && CondTy->isVectorType())
4704    if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
4705      return QualType();
4706
4707  // If both operands have arithmetic type, do the usual arithmetic conversions
4708  // to find a common type: C99 6.5.15p3,5.
4709  if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4710    UsualArithmeticConversions(LHS, RHS);
4711    if (LHS.isInvalid() || RHS.isInvalid())
4712      return QualType();
4713    return LHS.get()->getType();
4714  }
4715
4716  // If both operands are the same structure or union type, the result is that
4717  // type.
4718  if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
4719    if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
4720      if (LHSRT->getDecl() == RHSRT->getDecl())
4721        // "If both the operands have structure or union type, the result has
4722        // that type."  This implies that CV qualifiers are dropped.
4723        return LHSTy.getUnqualifiedType();
4724    // FIXME: Type of conditional expression must be complete in C mode.
4725  }
4726
4727  // C99 6.5.15p5: "If both operands have void type, the result has void type."
4728  // The following || allows only one side to be void (a GCC-ism).
4729  if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4730    return checkConditionalVoidType(*this, LHS, RHS);
4731  }
4732
4733  // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4734  // the type of the other operand."
4735  if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4736  if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
4737
4738  // All objective-c pointer type analysis is done here.
4739  QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4740                                                        QuestionLoc);
4741  if (LHS.isInvalid() || RHS.isInvalid())
4742    return QualType();
4743  if (!compositeType.isNull())
4744    return compositeType;
4745
4746
4747  // Handle block pointer types.
4748  if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4749    return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4750                                                     QuestionLoc);
4751
4752  // Check constraints for C object pointers types (C99 6.5.15p3,6).
4753  if (LHSTy->isPointerType() && RHSTy->isPointerType())
4754    return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4755                                                       QuestionLoc);
4756
4757  // GCC compatibility: soften pointer/integer mismatch.  Note that
4758  // null pointers have been filtered out by this point.
4759  if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4760      /*isIntFirstExpr=*/true))
4761    return RHSTy;
4762  if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4763      /*isIntFirstExpr=*/false))
4764    return LHSTy;
4765
4766  // Emit a better diagnostic if one of the expressions is a null pointer
4767  // constant and the other is not a pointer type. In this case, the user most
4768  // likely forgot to take the address of the other expression.
4769  if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
4770    return QualType();
4771
4772  // Otherwise, the operands are not compatible.
4773  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4774    << LHSTy << RHSTy << LHS.get()->getSourceRange()
4775    << RHS.get()->getSourceRange();
4776  return QualType();
4777}
4778
4779/// FindCompositeObjCPointerType - Helper method to find composite type of
4780/// two objective-c pointer types of the two input expressions.
4781QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
4782                                            SourceLocation QuestionLoc) {
4783  QualType LHSTy = LHS.get()->getType();
4784  QualType RHSTy = RHS.get()->getType();
4785
4786  // Handle things like Class and struct objc_class*.  Here we case the result
4787  // to the pseudo-builtin, because that will be implicitly cast back to the
4788  // redefinition type if an attempt is made to access its fields.
4789  if (LHSTy->isObjCClassType() &&
4790      (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
4791    RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
4792    return LHSTy;
4793  }
4794  if (RHSTy->isObjCClassType() &&
4795      (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
4796    LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
4797    return RHSTy;
4798  }
4799  // And the same for struct objc_object* / id
4800  if (LHSTy->isObjCIdType() &&
4801      (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
4802    RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
4803    return LHSTy;
4804  }
4805  if (RHSTy->isObjCIdType() &&
4806      (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
4807    LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
4808    return RHSTy;
4809  }
4810  // And the same for struct objc_selector* / SEL
4811  if (Context.isObjCSelType(LHSTy) &&
4812      (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
4813    RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
4814    return LHSTy;
4815  }
4816  if (Context.isObjCSelType(RHSTy) &&
4817      (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
4818    LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
4819    return RHSTy;
4820  }
4821  // Check constraints for Objective-C object pointers types.
4822  if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
4823
4824    if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4825      // Two identical object pointer types are always compatible.
4826      return LHSTy;
4827    }
4828    const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
4829    const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
4830    QualType compositeType = LHSTy;
4831
4832    // If both operands are interfaces and either operand can be
4833    // assigned to the other, use that type as the composite
4834    // type. This allows
4835    //   xxx ? (A*) a : (B*) b
4836    // where B is a subclass of A.
4837    //
4838    // Additionally, as for assignment, if either type is 'id'
4839    // allow silent coercion. Finally, if the types are
4840    // incompatible then make sure to use 'id' as the composite
4841    // type so the result is acceptable for sending messages to.
4842
4843    // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4844    // It could return the composite type.
4845    if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4846      compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4847    } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4848      compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4849    } else if ((LHSTy->isObjCQualifiedIdType() ||
4850                RHSTy->isObjCQualifiedIdType()) &&
4851               Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4852      // Need to handle "id<xx>" explicitly.
4853      // GCC allows qualified id and any Objective-C type to devolve to
4854      // id. Currently localizing to here until clear this should be
4855      // part of ObjCQualifiedIdTypesAreCompatible.
4856      compositeType = Context.getObjCIdType();
4857    } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4858      compositeType = Context.getObjCIdType();
4859    } else if (!(compositeType =
4860                 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4861      ;
4862    else {
4863      Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4864      << LHSTy << RHSTy
4865      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4866      QualType incompatTy = Context.getObjCIdType();
4867      LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4868      RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4869      return incompatTy;
4870    }
4871    // The object pointer types are compatible.
4872    LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4873    RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
4874    return compositeType;
4875  }
4876  // Check Objective-C object pointer types and 'void *'
4877  if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4878    QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4879    QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4880    QualType destPointee
4881    = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4882    QualType destType = Context.getPointerType(destPointee);
4883    // Add qualifiers if necessary.
4884    LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4885    // Promote to void*.
4886    RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4887    return destType;
4888  }
4889  if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4890    QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4891    QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4892    QualType destPointee
4893    = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4894    QualType destType = Context.getPointerType(destPointee);
4895    // Add qualifiers if necessary.
4896    RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4897    // Promote to void*.
4898    LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4899    return destType;
4900  }
4901  return QualType();
4902}
4903
4904/// SuggestParentheses - Emit a note with a fixit hint that wraps
4905/// ParenRange in parentheses.
4906static void SuggestParentheses(Sema &Self, SourceLocation Loc,
4907                               const PartialDiagnostic &Note,
4908                               SourceRange ParenRange) {
4909  SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4910  if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4911      EndLoc.isValid()) {
4912    Self.Diag(Loc, Note)
4913      << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4914      << FixItHint::CreateInsertion(EndLoc, ")");
4915  } else {
4916    // We can't display the parentheses, so just show the bare note.
4917    Self.Diag(Loc, Note) << ParenRange;
4918  }
4919}
4920
4921static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4922  return Opc >= BO_Mul && Opc <= BO_Shr;
4923}
4924
4925/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4926/// expression, either using a built-in or overloaded operator,
4927/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
4928/// expression.
4929static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
4930                                   Expr **RHSExprs) {
4931  // Don't strip parenthesis: we should not warn if E is in parenthesis.
4932  E = E->IgnoreImpCasts();
4933  E = E->IgnoreConversionOperator();
4934  E = E->IgnoreImpCasts();
4935
4936  // Built-in binary operator.
4937  if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4938    if (IsArithmeticOp(OP->getOpcode())) {
4939      *Opcode = OP->getOpcode();
4940      *RHSExprs = OP->getRHS();
4941      return true;
4942    }
4943  }
4944
4945  // Overloaded operator.
4946  if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
4947    if (Call->getNumArgs() != 2)
4948      return false;
4949
4950    // Make sure this is really a binary operator that is safe to pass into
4951    // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
4952    OverloadedOperatorKind OO = Call->getOperator();
4953    if (OO < OO_Plus || OO > OO_Arrow)
4954      return false;
4955
4956    BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
4957    if (IsArithmeticOp(OpKind)) {
4958      *Opcode = OpKind;
4959      *RHSExprs = Call->getArg(1);
4960      return true;
4961    }
4962  }
4963
4964  return false;
4965}
4966
4967static bool IsLogicOp(BinaryOperatorKind Opc) {
4968  return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
4969}
4970
4971/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
4972/// or is a logical expression such as (x==y) which has int type, but is
4973/// commonly interpreted as boolean.
4974static bool ExprLooksBoolean(Expr *E) {
4975  E = E->IgnoreParenImpCasts();
4976
4977  if (E->getType()->isBooleanType())
4978    return true;
4979  if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
4980    return IsLogicOp(OP->getOpcode());
4981  if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
4982    return OP->getOpcode() == UO_LNot;
4983
4984  return false;
4985}
4986
4987/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
4988/// and binary operator are mixed in a way that suggests the programmer assumed
4989/// the conditional operator has higher precedence, for example:
4990/// "int x = a + someBinaryCondition ? 1 : 2".
4991static void DiagnoseConditionalPrecedence(Sema &Self,
4992                                          SourceLocation OpLoc,
4993                                          Expr *Condition,
4994                                          Expr *LHSExpr,
4995                                          Expr *RHSExpr) {
4996  BinaryOperatorKind CondOpcode;
4997  Expr *CondRHS;
4998
4999  if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
5000    return;
5001  if (!ExprLooksBoolean(CondRHS))
5002    return;
5003
5004  // The condition is an arithmetic binary expression, with a right-
5005  // hand side that looks boolean, so warn.
5006
5007  Self.Diag(OpLoc, diag::warn_precedence_conditional)
5008      << Condition->getSourceRange()
5009      << BinaryOperator::getOpcodeStr(CondOpcode);
5010
5011  SuggestParentheses(Self, OpLoc,
5012    Self.PDiag(diag::note_precedence_conditional_silence)
5013      << BinaryOperator::getOpcodeStr(CondOpcode),
5014    SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
5015
5016  SuggestParentheses(Self, OpLoc,
5017    Self.PDiag(diag::note_precedence_conditional_first),
5018    SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
5019}
5020
5021/// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
5022/// in the case of a the GNU conditional expr extension.
5023ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
5024                                    SourceLocation ColonLoc,
5025                                    Expr *CondExpr, Expr *LHSExpr,
5026                                    Expr *RHSExpr) {
5027  // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5028  // was the condition.
5029  OpaqueValueExpr *opaqueValue = 0;
5030  Expr *commonExpr = 0;
5031  if (LHSExpr == 0) {
5032    commonExpr = CondExpr;
5033
5034    // We usually want to apply unary conversions *before* saving, except
5035    // in the special case of a C++ l-value conditional.
5036    if (!(getLangOptions().CPlusPlus
5037          && !commonExpr->isTypeDependent()
5038          && commonExpr->getValueKind() == RHSExpr->getValueKind()
5039          && commonExpr->isGLValue()
5040          && commonExpr->isOrdinaryOrBitFieldObject()
5041          && RHSExpr->isOrdinaryOrBitFieldObject()
5042          && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5043      ExprResult commonRes = UsualUnaryConversions(commonExpr);
5044      if (commonRes.isInvalid())
5045        return ExprError();
5046      commonExpr = commonRes.take();
5047    }
5048
5049    opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5050                                                commonExpr->getType(),
5051                                                commonExpr->getValueKind(),
5052                                                commonExpr->getObjectKind());
5053    LHSExpr = CondExpr = opaqueValue;
5054  }
5055
5056  ExprValueKind VK = VK_RValue;
5057  ExprObjectKind OK = OK_Ordinary;
5058  ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5059  QualType result = CheckConditionalOperands(Cond, LHS, RHS,
5060                                             VK, OK, QuestionLoc);
5061  if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5062      RHS.isInvalid())
5063    return ExprError();
5064
5065  DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5066                                RHS.get());
5067
5068  if (!commonExpr)
5069    return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5070                                                   LHS.take(), ColonLoc,
5071                                                   RHS.take(), result, VK, OK));
5072
5073  return Owned(new (Context)
5074    BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
5075                              RHS.take(), QuestionLoc, ColonLoc, result, VK,
5076                              OK));
5077}
5078
5079// checkPointerTypesForAssignment - This is a very tricky routine (despite
5080// being closely modeled after the C99 spec:-). The odd characteristic of this
5081// routine is it effectively iqnores the qualifiers on the top level pointee.
5082// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5083// FIXME: add a couple examples in this comment.
5084static Sema::AssignConvertType
5085checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5086  assert(LHSType.isCanonical() && "LHS not canonicalized!");
5087  assert(RHSType.isCanonical() && "RHS not canonicalized!");
5088
5089  // get the "pointed to" type (ignoring qualifiers at the top level)
5090  const Type *lhptee, *rhptee;
5091  Qualifiers lhq, rhq;
5092  llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5093  llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
5094
5095  Sema::AssignConvertType ConvTy = Sema::Compatible;
5096
5097  // C99 6.5.16.1p1: This following citation is common to constraints
5098  // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5099  // qualifiers of the type *pointed to* by the right;
5100  Qualifiers lq;
5101
5102  // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5103  if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5104      lhq.compatiblyIncludesObjCLifetime(rhq)) {
5105    // Ignore lifetime for further calculation.
5106    lhq.removeObjCLifetime();
5107    rhq.removeObjCLifetime();
5108  }
5109
5110  if (!lhq.compatiblyIncludes(rhq)) {
5111    // Treat address-space mismatches as fatal.  TODO: address subspaces
5112    if (lhq.getAddressSpace() != rhq.getAddressSpace())
5113      ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5114
5115    // It's okay to add or remove GC or lifetime qualifiers when converting to
5116    // and from void*.
5117    else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
5118                        .compatiblyIncludes(
5119                                rhq.withoutObjCGCAttr().withoutObjCGLifetime())
5120             && (lhptee->isVoidType() || rhptee->isVoidType()))
5121      ; // keep old
5122
5123    // Treat lifetime mismatches as fatal.
5124    else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5125      ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5126
5127    // For GCC compatibility, other qualifier mismatches are treated
5128    // as still compatible in C.
5129    else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5130  }
5131
5132  // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5133  // incomplete type and the other is a pointer to a qualified or unqualified
5134  // version of void...
5135  if (lhptee->isVoidType()) {
5136    if (rhptee->isIncompleteOrObjectType())
5137      return ConvTy;
5138
5139    // As an extension, we allow cast to/from void* to function pointer.
5140    assert(rhptee->isFunctionType());
5141    return Sema::FunctionVoidPointer;
5142  }
5143
5144  if (rhptee->isVoidType()) {
5145    if (lhptee->isIncompleteOrObjectType())
5146      return ConvTy;
5147
5148    // As an extension, we allow cast to/from void* to function pointer.
5149    assert(lhptee->isFunctionType());
5150    return Sema::FunctionVoidPointer;
5151  }
5152
5153  // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
5154  // unqualified versions of compatible types, ...
5155  QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5156  if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
5157    // Check if the pointee types are compatible ignoring the sign.
5158    // We explicitly check for char so that we catch "char" vs
5159    // "unsigned char" on systems where "char" is unsigned.
5160    if (lhptee->isCharType())
5161      ltrans = S.Context.UnsignedCharTy;
5162    else if (lhptee->hasSignedIntegerRepresentation())
5163      ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
5164
5165    if (rhptee->isCharType())
5166      rtrans = S.Context.UnsignedCharTy;
5167    else if (rhptee->hasSignedIntegerRepresentation())
5168      rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
5169
5170    if (ltrans == rtrans) {
5171      // Types are compatible ignoring the sign. Qualifier incompatibility
5172      // takes priority over sign incompatibility because the sign
5173      // warning can be disabled.
5174      if (ConvTy != Sema::Compatible)
5175        return ConvTy;
5176
5177      return Sema::IncompatiblePointerSign;
5178    }
5179
5180    // If we are a multi-level pointer, it's possible that our issue is simply
5181    // one of qualification - e.g. char ** -> const char ** is not allowed. If
5182    // the eventual target type is the same and the pointers have the same
5183    // level of indirection, this must be the issue.
5184    if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
5185      do {
5186        lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5187        rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
5188      } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
5189
5190      if (lhptee == rhptee)
5191        return Sema::IncompatibleNestedPointerQualifiers;
5192    }
5193
5194    // General pointer incompatibility takes priority over qualifiers.
5195    return Sema::IncompatiblePointer;
5196  }
5197  if (!S.getLangOptions().CPlusPlus &&
5198      S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5199    return Sema::IncompatiblePointer;
5200  return ConvTy;
5201}
5202
5203/// checkBlockPointerTypesForAssignment - This routine determines whether two
5204/// block pointer types are compatible or whether a block and normal pointer
5205/// are compatible. It is more restrict than comparing two function pointer
5206// types.
5207static Sema::AssignConvertType
5208checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5209                                    QualType RHSType) {
5210  assert(LHSType.isCanonical() && "LHS not canonicalized!");
5211  assert(RHSType.isCanonical() && "RHS not canonicalized!");
5212
5213  QualType lhptee, rhptee;
5214
5215  // get the "pointed to" type (ignoring qualifiers at the top level)
5216  lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5217  rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
5218
5219  // In C++, the types have to match exactly.
5220  if (S.getLangOptions().CPlusPlus)
5221    return Sema::IncompatibleBlockPointer;
5222
5223  Sema::AssignConvertType ConvTy = Sema::Compatible;
5224
5225  // For blocks we enforce that qualifiers are identical.
5226  if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5227    ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5228
5229  if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
5230    return Sema::IncompatibleBlockPointer;
5231
5232  return ConvTy;
5233}
5234
5235/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
5236/// for assignment compatibility.
5237static Sema::AssignConvertType
5238checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5239                                   QualType RHSType) {
5240  assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5241  assert(RHSType.isCanonical() && "RHS was not canonicalized!");
5242
5243  if (LHSType->isObjCBuiltinType()) {
5244    // Class is not compatible with ObjC object pointers.
5245    if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5246        !RHSType->isObjCQualifiedClassType())
5247      return Sema::IncompatiblePointer;
5248    return Sema::Compatible;
5249  }
5250  if (RHSType->isObjCBuiltinType()) {
5251    if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5252        !LHSType->isObjCQualifiedClassType())
5253      return Sema::IncompatiblePointer;
5254    return Sema::Compatible;
5255  }
5256  QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5257  QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5258
5259  if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5260    return Sema::CompatiblePointerDiscardsQualifiers;
5261
5262  if (S.Context.typesAreCompatible(LHSType, RHSType))
5263    return Sema::Compatible;
5264  if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
5265    return Sema::IncompatibleObjCQualifiedId;
5266  return Sema::IncompatiblePointer;
5267}
5268
5269Sema::AssignConvertType
5270Sema::CheckAssignmentConstraints(SourceLocation Loc,
5271                                 QualType LHSType, QualType RHSType) {
5272  // Fake up an opaque expression.  We don't actually care about what
5273  // cast operations are required, so if CheckAssignmentConstraints
5274  // adds casts to this they'll be wasted, but fortunately that doesn't
5275  // usually happen on valid code.
5276  OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5277  ExprResult RHSPtr = &RHSExpr;
5278  CastKind K = CK_Invalid;
5279
5280  return CheckAssignmentConstraints(LHSType, RHSPtr, K);
5281}
5282
5283/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5284/// has code to accommodate several GCC extensions when type checking
5285/// pointers. Here are some objectionable examples that GCC considers warnings:
5286///
5287///  int a, *pint;
5288///  short *pshort;
5289///  struct foo *pfoo;
5290///
5291///  pint = pshort; // warning: assignment from incompatible pointer type
5292///  a = pint; // warning: assignment makes integer from pointer without a cast
5293///  pint = a; // warning: assignment makes pointer from integer without a cast
5294///  pint = pfoo; // warning: assignment from incompatible pointer type
5295///
5296/// As a result, the code for dealing with pointers is more complex than the
5297/// C99 spec dictates.
5298///
5299/// Sets 'Kind' for any result kind except Incompatible.
5300Sema::AssignConvertType
5301Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5302                                 CastKind &Kind) {
5303  QualType RHSType = RHS.get()->getType();
5304  QualType OrigLHSType = LHSType;
5305
5306  // Get canonical types.  We're not formatting these types, just comparing
5307  // them.
5308  LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5309  RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
5310
5311  // We can't do assignment from/to atomics yet.
5312  if (LHSType->isAtomicType())
5313    return Incompatible;
5314
5315  // Common case: no conversion required.
5316  if (LHSType == RHSType) {
5317    Kind = CK_NoOp;
5318    return Compatible;
5319  }
5320
5321  // If the left-hand side is a reference type, then we are in a
5322  // (rare!) case where we've allowed the use of references in C,
5323  // e.g., as a parameter type in a built-in function. In this case,
5324  // just make sure that the type referenced is compatible with the
5325  // right-hand side type. The caller is responsible for adjusting
5326  // LHSType so that the resulting expression does not have reference
5327  // type.
5328  if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5329    if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
5330      Kind = CK_LValueBitCast;
5331      return Compatible;
5332    }
5333    return Incompatible;
5334  }
5335
5336  // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5337  // to the same ExtVector type.
5338  if (LHSType->isExtVectorType()) {
5339    if (RHSType->isExtVectorType())
5340      return Incompatible;
5341    if (RHSType->isArithmeticType()) {
5342      // CK_VectorSplat does T -> vector T, so first cast to the
5343      // element type.
5344      QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5345      if (elType != RHSType) {
5346        Kind = PrepareScalarCast(RHS, elType);
5347        RHS = ImpCastExprToType(RHS.take(), elType, Kind);
5348      }
5349      Kind = CK_VectorSplat;
5350      return Compatible;
5351    }
5352  }
5353
5354  // Conversions to or from vector type.
5355  if (LHSType->isVectorType() || RHSType->isVectorType()) {
5356    if (LHSType->isVectorType() && RHSType->isVectorType()) {
5357      // Allow assignments of an AltiVec vector type to an equivalent GCC
5358      // vector type and vice versa
5359      if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5360        Kind = CK_BitCast;
5361        return Compatible;
5362      }
5363
5364      // If we are allowing lax vector conversions, and LHS and RHS are both
5365      // vectors, the total size only needs to be the same. This is a bitcast;
5366      // no bits are changed but the result type is different.
5367      if (getLangOptions().LaxVectorConversions &&
5368          (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
5369        Kind = CK_BitCast;
5370        return IncompatibleVectors;
5371      }
5372    }
5373    return Incompatible;
5374  }
5375
5376  // Arithmetic conversions.
5377  if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
5378      !(getLangOptions().CPlusPlus && LHSType->isEnumeralType())) {
5379    Kind = PrepareScalarCast(RHS, LHSType);
5380    return Compatible;
5381  }
5382
5383  // Conversions to normal pointers.
5384  if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
5385    // U* -> T*
5386    if (isa<PointerType>(RHSType)) {
5387      Kind = CK_BitCast;
5388      return checkPointerTypesForAssignment(*this, LHSType, RHSType);
5389    }
5390
5391    // int -> T*
5392    if (RHSType->isIntegerType()) {
5393      Kind = CK_IntegralToPointer; // FIXME: null?
5394      return IntToPointer;
5395    }
5396
5397    // C pointers are not compatible with ObjC object pointers,
5398    // with two exceptions:
5399    if (isa<ObjCObjectPointerType>(RHSType)) {
5400      //  - conversions to void*
5401      if (LHSPointer->getPointeeType()->isVoidType()) {
5402        Kind = CK_BitCast;
5403        return Compatible;
5404      }
5405
5406      //  - conversions from 'Class' to the redefinition type
5407      if (RHSType->isObjCClassType() &&
5408          Context.hasSameType(LHSType,
5409                              Context.getObjCClassRedefinitionType())) {
5410        Kind = CK_BitCast;
5411        return Compatible;
5412      }
5413
5414      Kind = CK_BitCast;
5415      return IncompatiblePointer;
5416    }
5417
5418    // U^ -> void*
5419    if (RHSType->getAs<BlockPointerType>()) {
5420      if (LHSPointer->getPointeeType()->isVoidType()) {
5421        Kind = CK_BitCast;
5422        return Compatible;
5423      }
5424    }
5425
5426    return Incompatible;
5427  }
5428
5429  // Conversions to block pointers.
5430  if (isa<BlockPointerType>(LHSType)) {
5431    // U^ -> T^
5432    if (RHSType->isBlockPointerType()) {
5433      Kind = CK_BitCast;
5434      return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
5435    }
5436
5437    // int or null -> T^
5438    if (RHSType->isIntegerType()) {
5439      Kind = CK_IntegralToPointer; // FIXME: null
5440      return IntToBlockPointer;
5441    }
5442
5443    // id -> T^
5444    if (getLangOptions().ObjC1 && RHSType->isObjCIdType()) {
5445      Kind = CK_AnyPointerToBlockPointerCast;
5446      return Compatible;
5447    }
5448
5449    // void* -> T^
5450    if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
5451      if (RHSPT->getPointeeType()->isVoidType()) {
5452        Kind = CK_AnyPointerToBlockPointerCast;
5453        return Compatible;
5454      }
5455
5456    return Incompatible;
5457  }
5458
5459  // Conversions to Objective-C pointers.
5460  if (isa<ObjCObjectPointerType>(LHSType)) {
5461    // A* -> B*
5462    if (RHSType->isObjCObjectPointerType()) {
5463      Kind = CK_BitCast;
5464      Sema::AssignConvertType result =
5465        checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
5466      if (getLangOptions().ObjCAutoRefCount &&
5467          result == Compatible &&
5468          !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
5469        result = IncompatibleObjCWeakRef;
5470      return result;
5471    }
5472
5473    // int or null -> A*
5474    if (RHSType->isIntegerType()) {
5475      Kind = CK_IntegralToPointer; // FIXME: null
5476      return IntToPointer;
5477    }
5478
5479    // In general, C pointers are not compatible with ObjC object pointers,
5480    // with two exceptions:
5481    if (isa<PointerType>(RHSType)) {
5482      Kind = CK_CPointerToObjCPointerCast;
5483
5484      //  - conversions from 'void*'
5485      if (RHSType->isVoidPointerType()) {
5486        return Compatible;
5487      }
5488
5489      //  - conversions to 'Class' from its redefinition type
5490      if (LHSType->isObjCClassType() &&
5491          Context.hasSameType(RHSType,
5492                              Context.getObjCClassRedefinitionType())) {
5493        return Compatible;
5494      }
5495
5496      return IncompatiblePointer;
5497    }
5498
5499    // T^ -> A*
5500    if (RHSType->isBlockPointerType()) {
5501      maybeExtendBlockObject(*this, RHS);
5502      Kind = CK_BlockPointerToObjCPointerCast;
5503      return Compatible;
5504    }
5505
5506    return Incompatible;
5507  }
5508
5509  // Conversions from pointers that are not covered by the above.
5510  if (isa<PointerType>(RHSType)) {
5511    // T* -> _Bool
5512    if (LHSType == Context.BoolTy) {
5513      Kind = CK_PointerToBoolean;
5514      return Compatible;
5515    }
5516
5517    // T* -> int
5518    if (LHSType->isIntegerType()) {
5519      Kind = CK_PointerToIntegral;
5520      return PointerToInt;
5521    }
5522
5523    return Incompatible;
5524  }
5525
5526  // Conversions from Objective-C pointers that are not covered by the above.
5527  if (isa<ObjCObjectPointerType>(RHSType)) {
5528    // T* -> _Bool
5529    if (LHSType == Context.BoolTy) {
5530      Kind = CK_PointerToBoolean;
5531      return Compatible;
5532    }
5533
5534    // T* -> int
5535    if (LHSType->isIntegerType()) {
5536      Kind = CK_PointerToIntegral;
5537      return PointerToInt;
5538    }
5539
5540    return Incompatible;
5541  }
5542
5543  // struct A -> struct B
5544  if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5545    if (Context.typesAreCompatible(LHSType, RHSType)) {
5546      Kind = CK_NoOp;
5547      return Compatible;
5548    }
5549  }
5550
5551  return Incompatible;
5552}
5553
5554/// \brief Constructs a transparent union from an expression that is
5555/// used to initialize the transparent union.
5556static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5557                                      ExprResult &EResult, QualType UnionType,
5558                                      FieldDecl *Field) {
5559  // Build an initializer list that designates the appropriate member
5560  // of the transparent union.
5561  Expr *E = EResult.take();
5562  InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
5563                                                   &E, 1,
5564                                                   SourceLocation());
5565  Initializer->setType(UnionType);
5566  Initializer->setInitializedFieldInUnion(Field);
5567
5568  // Build a compound literal constructing a value of the transparent
5569  // union type from this initializer list.
5570  TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
5571  EResult = S.Owned(
5572    new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5573                                VK_RValue, Initializer, false));
5574}
5575
5576Sema::AssignConvertType
5577Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
5578                                               ExprResult &RHS) {
5579  QualType RHSType = RHS.get()->getType();
5580
5581  // If the ArgType is a Union type, we want to handle a potential
5582  // transparent_union GCC extension.
5583  const RecordType *UT = ArgType->getAsUnionType();
5584  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
5585    return Incompatible;
5586
5587  // The field to initialize within the transparent union.
5588  RecordDecl *UD = UT->getDecl();
5589  FieldDecl *InitField = 0;
5590  // It's compatible if the expression matches any of the fields.
5591  for (RecordDecl::field_iterator it = UD->field_begin(),
5592         itend = UD->field_end();
5593       it != itend; ++it) {
5594    if (it->getType()->isPointerType()) {
5595      // If the transparent union contains a pointer type, we allow:
5596      // 1) void pointer
5597      // 2) null pointer constant
5598      if (RHSType->isPointerType())
5599        if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
5600          RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
5601          InitField = *it;
5602          break;
5603        }
5604
5605      if (RHS.get()->isNullPointerConstant(Context,
5606                                           Expr::NPC_ValueDependentIsNull)) {
5607        RHS = ImpCastExprToType(RHS.take(), it->getType(),
5608                                CK_NullToPointer);
5609        InitField = *it;
5610        break;
5611      }
5612    }
5613
5614    CastKind Kind = CK_Invalid;
5615    if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
5616          == Compatible) {
5617      RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
5618      InitField = *it;
5619      break;
5620    }
5621  }
5622
5623  if (!InitField)
5624    return Incompatible;
5625
5626  ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
5627  return Compatible;
5628}
5629
5630Sema::AssignConvertType
5631Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5632                                       bool Diagnose) {
5633  if (getLangOptions().CPlusPlus) {
5634    if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
5635      // C++ 5.17p3: If the left operand is not of class type, the
5636      // expression is implicitly converted (C++ 4) to the
5637      // cv-unqualified type of the left operand.
5638      ExprResult Res;
5639      if (Diagnose) {
5640        Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5641                                        AA_Assigning);
5642      } else {
5643        ImplicitConversionSequence ICS =
5644            TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5645                                  /*SuppressUserConversions=*/false,
5646                                  /*AllowExplicit=*/false,
5647                                  /*InOverloadResolution=*/false,
5648                                  /*CStyle=*/false,
5649                                  /*AllowObjCWritebackConversion=*/false);
5650        if (ICS.isFailure())
5651          return Incompatible;
5652        Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5653                                        ICS, AA_Assigning);
5654      }
5655      if (Res.isInvalid())
5656        return Incompatible;
5657      Sema::AssignConvertType result = Compatible;
5658      if (getLangOptions().ObjCAutoRefCount &&
5659          !CheckObjCARCUnavailableWeakConversion(LHSType,
5660                                                 RHS.get()->getType()))
5661        result = IncompatibleObjCWeakRef;
5662      RHS = move(Res);
5663      return result;
5664    }
5665
5666    // FIXME: Currently, we fall through and treat C++ classes like C
5667    // structures.
5668    // FIXME: We also fall through for atomics; not sure what should
5669    // happen there, though.
5670  }
5671
5672  // C99 6.5.16.1p1: the left operand is a pointer and the right is
5673  // a null pointer constant.
5674  if ((LHSType->isPointerType() ||
5675       LHSType->isObjCObjectPointerType() ||
5676       LHSType->isBlockPointerType())
5677      && RHS.get()->isNullPointerConstant(Context,
5678                                          Expr::NPC_ValueDependentIsNull)) {
5679    RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
5680    return Compatible;
5681  }
5682
5683  // This check seems unnatural, however it is necessary to ensure the proper
5684  // conversion of functions/arrays. If the conversion were done for all
5685  // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
5686  // expressions that suppress this implicit conversion (&, sizeof).
5687  //
5688  // Suppress this for references: C++ 8.5.3p5.
5689  if (!LHSType->isReferenceType()) {
5690    RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5691    if (RHS.isInvalid())
5692      return Incompatible;
5693  }
5694
5695  CastKind Kind = CK_Invalid;
5696  Sema::AssignConvertType result =
5697    CheckAssignmentConstraints(LHSType, RHS, Kind);
5698
5699  // C99 6.5.16.1p2: The value of the right operand is converted to the
5700  // type of the assignment expression.
5701  // CheckAssignmentConstraints allows the left-hand side to be a reference,
5702  // so that we can use references in built-in functions even in C.
5703  // The getNonReferenceType() call makes sure that the resulting expression
5704  // does not have reference type.
5705  if (result != Incompatible && RHS.get()->getType() != LHSType)
5706    RHS = ImpCastExprToType(RHS.take(),
5707                            LHSType.getNonLValueExprType(Context), Kind);
5708  return result;
5709}
5710
5711QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5712                               ExprResult &RHS) {
5713  Diag(Loc, diag::err_typecheck_invalid_operands)
5714    << LHS.get()->getType() << RHS.get()->getType()
5715    << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5716  return QualType();
5717}
5718
5719QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
5720                                   SourceLocation Loc, bool IsCompAssign) {
5721  // For conversion purposes, we ignore any qualifiers.
5722  // For example, "const float" and "float" are equivalent.
5723  QualType LHSType =
5724    Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5725  QualType RHSType =
5726    Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
5727
5728  // If the vector types are identical, return.
5729  if (LHSType == RHSType)
5730    return LHSType;
5731
5732  // Handle the case of equivalent AltiVec and GCC vector types
5733  if (LHSType->isVectorType() && RHSType->isVectorType() &&
5734      Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5735    if (LHSType->isExtVectorType()) {
5736      RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5737      return LHSType;
5738    }
5739
5740    if (!IsCompAssign)
5741      LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
5742    return RHSType;
5743  }
5744
5745  if (getLangOptions().LaxVectorConversions &&
5746      Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
5747    // If we are allowing lax vector conversions, and LHS and RHS are both
5748    // vectors, the total size only needs to be the same. This is a
5749    // bitcast; no bits are changed but the result type is different.
5750    // FIXME: Should we really be allowing this?
5751    RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5752    return LHSType;
5753  }
5754
5755  // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5756  // swap back (so that we don't reverse the inputs to a subtract, for instance.
5757  bool swapped = false;
5758  if (RHSType->isExtVectorType() && !IsCompAssign) {
5759    swapped = true;
5760    std::swap(RHS, LHS);
5761    std::swap(RHSType, LHSType);
5762  }
5763
5764  // Handle the case of an ext vector and scalar.
5765  if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
5766    QualType EltTy = LV->getElementType();
5767    if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
5768      int order = Context.getIntegerTypeOrder(EltTy, RHSType);
5769      if (order > 0)
5770        RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
5771      if (order >= 0) {
5772        RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5773        if (swapped) std::swap(RHS, LHS);
5774        return LHSType;
5775      }
5776    }
5777    if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
5778        RHSType->isRealFloatingType()) {
5779      int order = Context.getFloatingTypeOrder(EltTy, RHSType);
5780      if (order > 0)
5781        RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
5782      if (order >= 0) {
5783        RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5784        if (swapped) std::swap(RHS, LHS);
5785        return LHSType;
5786      }
5787    }
5788  }
5789
5790  // Vectors of different size or scalar and non-ext-vector are errors.
5791  if (swapped) std::swap(RHS, LHS);
5792  Diag(Loc, diag::err_typecheck_vector_not_convertable)
5793    << LHS.get()->getType() << RHS.get()->getType()
5794    << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5795  return QualType();
5796}
5797
5798// checkArithmeticNull - Detect when a NULL constant is used improperly in an
5799// expression.  These are mainly cases where the null pointer is used as an
5800// integer instead of a pointer.
5801static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
5802                                SourceLocation Loc, bool IsCompare) {
5803  // The canonical way to check for a GNU null is with isNullPointerConstant,
5804  // but we use a bit of a hack here for speed; this is a relatively
5805  // hot path, and isNullPointerConstant is slow.
5806  bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
5807  bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
5808
5809  QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
5810
5811  // Avoid analyzing cases where the result will either be invalid (and
5812  // diagnosed as such) or entirely valid and not something to warn about.
5813  if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
5814      NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
5815    return;
5816
5817  // Comparison operations would not make sense with a null pointer no matter
5818  // what the other expression is.
5819  if (!IsCompare) {
5820    S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
5821        << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
5822        << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
5823    return;
5824  }
5825
5826  // The rest of the operations only make sense with a null pointer
5827  // if the other expression is a pointer.
5828  if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
5829      NonNullType->canDecayToPointerType())
5830    return;
5831
5832  S.Diag(Loc, diag::warn_null_in_comparison_operation)
5833      << LHSNull /* LHS is NULL */ << NonNullType
5834      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5835}
5836
5837QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
5838                                           SourceLocation Loc,
5839                                           bool IsCompAssign, bool IsDiv) {
5840  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5841
5842  if (LHS.get()->getType()->isVectorType() ||
5843      RHS.get()->getType()->isVectorType())
5844    return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
5845
5846  QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
5847  if (LHS.isInvalid() || RHS.isInvalid())
5848    return QualType();
5849
5850  if (!LHS.get()->getType()->isArithmeticType() ||
5851      !RHS.get()->getType()->isArithmeticType())
5852    return InvalidOperands(Loc, LHS, RHS);
5853
5854  // Check for division by zero.
5855  if (IsDiv &&
5856      RHS.get()->isNullPointerConstant(Context,
5857                                       Expr::NPC_ValueDependentIsNotNull))
5858    DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
5859                                          << RHS.get()->getSourceRange());
5860
5861  return compType;
5862}
5863
5864QualType Sema::CheckRemainderOperands(
5865  ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
5866  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5867
5868  if (LHS.get()->getType()->isVectorType() ||
5869      RHS.get()->getType()->isVectorType()) {
5870    if (LHS.get()->getType()->hasIntegerRepresentation() &&
5871        RHS.get()->getType()->hasIntegerRepresentation())
5872      return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
5873    return InvalidOperands(Loc, LHS, RHS);
5874  }
5875
5876  QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
5877  if (LHS.isInvalid() || RHS.isInvalid())
5878    return QualType();
5879
5880  if (!LHS.get()->getType()->isIntegerType() ||
5881      !RHS.get()->getType()->isIntegerType())
5882    return InvalidOperands(Loc, LHS, RHS);
5883
5884  // Check for remainder by zero.
5885  if (RHS.get()->isNullPointerConstant(Context,
5886                                       Expr::NPC_ValueDependentIsNotNull))
5887    DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
5888                                 << RHS.get()->getSourceRange());
5889
5890  return compType;
5891}
5892
5893/// \brief Diagnose invalid arithmetic on two void pointers.
5894static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
5895                                                Expr *LHSExpr, Expr *RHSExpr) {
5896  S.Diag(Loc, S.getLangOptions().CPlusPlus
5897                ? diag::err_typecheck_pointer_arith_void_type
5898                : diag::ext_gnu_void_ptr)
5899    << 1 /* two pointers */ << LHSExpr->getSourceRange()
5900                            << RHSExpr->getSourceRange();
5901}
5902
5903/// \brief Diagnose invalid arithmetic on a void pointer.
5904static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5905                                            Expr *Pointer) {
5906  S.Diag(Loc, S.getLangOptions().CPlusPlus
5907                ? diag::err_typecheck_pointer_arith_void_type
5908                : diag::ext_gnu_void_ptr)
5909    << 0 /* one pointer */ << Pointer->getSourceRange();
5910}
5911
5912/// \brief Diagnose invalid arithmetic on two function pointers.
5913static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5914                                                    Expr *LHS, Expr *RHS) {
5915  assert(LHS->getType()->isAnyPointerType());
5916  assert(RHS->getType()->isAnyPointerType());
5917  S.Diag(Loc, S.getLangOptions().CPlusPlus
5918                ? diag::err_typecheck_pointer_arith_function_type
5919                : diag::ext_gnu_ptr_func_arith)
5920    << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5921    // We only show the second type if it differs from the first.
5922    << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5923                                                   RHS->getType())
5924    << RHS->getType()->getPointeeType()
5925    << LHS->getSourceRange() << RHS->getSourceRange();
5926}
5927
5928/// \brief Diagnose invalid arithmetic on a function pointer.
5929static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5930                                                Expr *Pointer) {
5931  assert(Pointer->getType()->isAnyPointerType());
5932  S.Diag(Loc, S.getLangOptions().CPlusPlus
5933                ? diag::err_typecheck_pointer_arith_function_type
5934                : diag::ext_gnu_ptr_func_arith)
5935    << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
5936    << 0 /* one pointer, so only one type */
5937    << Pointer->getSourceRange();
5938}
5939
5940/// \brief Emit error if Operand is incomplete pointer type
5941///
5942/// \returns True if pointer has incomplete type
5943static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
5944                                                 Expr *Operand) {
5945  if ((Operand->getType()->isPointerType() &&
5946       !Operand->getType()->isDependentType()) ||
5947      Operand->getType()->isObjCObjectPointerType()) {
5948    QualType PointeeTy = Operand->getType()->getPointeeType();
5949    if (S.RequireCompleteType(
5950          Loc, PointeeTy,
5951          S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5952            << PointeeTy << Operand->getSourceRange()))
5953      return true;
5954  }
5955  return false;
5956}
5957
5958/// \brief Check the validity of an arithmetic pointer operand.
5959///
5960/// If the operand has pointer type, this code will check for pointer types
5961/// which are invalid in arithmetic operations. These will be diagnosed
5962/// appropriately, including whether or not the use is supported as an
5963/// extension.
5964///
5965/// \returns True when the operand is valid to use (even if as an extension).
5966static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
5967                                            Expr *Operand) {
5968  if (!Operand->getType()->isAnyPointerType()) return true;
5969
5970  QualType PointeeTy = Operand->getType()->getPointeeType();
5971  if (PointeeTy->isVoidType()) {
5972    diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
5973    return !S.getLangOptions().CPlusPlus;
5974  }
5975  if (PointeeTy->isFunctionType()) {
5976    diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
5977    return !S.getLangOptions().CPlusPlus;
5978  }
5979
5980  if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
5981
5982  return true;
5983}
5984
5985/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
5986/// operands.
5987///
5988/// This routine will diagnose any invalid arithmetic on pointer operands much
5989/// like \see checkArithmeticOpPointerOperand. However, it has special logic
5990/// for emitting a single diagnostic even for operations where both LHS and RHS
5991/// are (potentially problematic) pointers.
5992///
5993/// \returns True when the operand is valid to use (even if as an extension).
5994static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
5995                                                Expr *LHSExpr, Expr *RHSExpr) {
5996  bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
5997  bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
5998  if (!isLHSPointer && !isRHSPointer) return true;
5999
6000  QualType LHSPointeeTy, RHSPointeeTy;
6001  if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6002  if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
6003
6004  // Check for arithmetic on pointers to incomplete types.
6005  bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6006  bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6007  if (isLHSVoidPtr || isRHSVoidPtr) {
6008    if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6009    else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6010    else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
6011
6012    return !S.getLangOptions().CPlusPlus;
6013  }
6014
6015  bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6016  bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6017  if (isLHSFuncPtr || isRHSFuncPtr) {
6018    if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6019    else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6020                                                                RHSExpr);
6021    else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
6022
6023    return !S.getLangOptions().CPlusPlus;
6024  }
6025
6026  if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false;
6027  if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false;
6028
6029  return true;
6030}
6031
6032/// \brief Check bad cases where we step over interface counts.
6033static bool checkArithmethicPointerOnNonFragileABI(Sema &S,
6034                                                   SourceLocation OpLoc,
6035                                                   Expr *Op) {
6036  assert(Op->getType()->isAnyPointerType());
6037  QualType PointeeTy = Op->getType()->getPointeeType();
6038  if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI)
6039    return true;
6040
6041  S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
6042    << PointeeTy << Op->getSourceRange();
6043  return false;
6044}
6045
6046/// \brief Emit error when two pointers are incompatible.
6047static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
6048                                           Expr *LHSExpr, Expr *RHSExpr) {
6049  assert(LHSExpr->getType()->isAnyPointerType());
6050  assert(RHSExpr->getType()->isAnyPointerType());
6051  S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6052    << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6053    << RHSExpr->getSourceRange();
6054}
6055
6056QualType Sema::CheckAdditionOperands( // C99 6.5.6
6057  ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy) {
6058  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6059
6060  if (LHS.get()->getType()->isVectorType() ||
6061      RHS.get()->getType()->isVectorType()) {
6062    QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
6063    if (CompLHSTy) *CompLHSTy = compType;
6064    return compType;
6065  }
6066
6067  QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6068  if (LHS.isInvalid() || RHS.isInvalid())
6069    return QualType();
6070
6071  // handle the common case first (both operands are arithmetic).
6072  if (LHS.get()->getType()->isArithmeticType() &&
6073      RHS.get()->getType()->isArithmeticType()) {
6074    if (CompLHSTy) *CompLHSTy = compType;
6075    return compType;
6076  }
6077
6078  // Put any potential pointer into PExp
6079  Expr* PExp = LHS.get(), *IExp = RHS.get();
6080  if (IExp->getType()->isAnyPointerType())
6081    std::swap(PExp, IExp);
6082
6083  if (!PExp->getType()->isAnyPointerType())
6084    return InvalidOperands(Loc, LHS, RHS);
6085
6086  if (!IExp->getType()->isIntegerType())
6087    return InvalidOperands(Loc, LHS, RHS);
6088
6089  if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6090    return QualType();
6091
6092  // Diagnose bad cases where we step over interface counts.
6093  if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp))
6094    return QualType();
6095
6096  // Check array bounds for pointer arithemtic
6097  CheckArrayAccess(PExp, IExp);
6098
6099  if (CompLHSTy) {
6100    QualType LHSTy = Context.isPromotableBitField(LHS.get());
6101    if (LHSTy.isNull()) {
6102      LHSTy = LHS.get()->getType();
6103      if (LHSTy->isPromotableIntegerType())
6104        LHSTy = Context.getPromotedIntegerType(LHSTy);
6105    }
6106    *CompLHSTy = LHSTy;
6107  }
6108
6109  return PExp->getType();
6110}
6111
6112// C99 6.5.6
6113QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
6114                                        SourceLocation Loc,
6115                                        QualType* CompLHSTy) {
6116  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6117
6118  if (LHS.get()->getType()->isVectorType() ||
6119      RHS.get()->getType()->isVectorType()) {
6120    QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
6121    if (CompLHSTy) *CompLHSTy = compType;
6122    return compType;
6123  }
6124
6125  QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6126  if (LHS.isInvalid() || RHS.isInvalid())
6127    return QualType();
6128
6129  // Enforce type constraints: C99 6.5.6p3.
6130
6131  // Handle the common case first (both operands are arithmetic).
6132  if (LHS.get()->getType()->isArithmeticType() &&
6133      RHS.get()->getType()->isArithmeticType()) {
6134    if (CompLHSTy) *CompLHSTy = compType;
6135    return compType;
6136  }
6137
6138  // Either ptr - int   or   ptr - ptr.
6139  if (LHS.get()->getType()->isAnyPointerType()) {
6140    QualType lpointee = LHS.get()->getType()->getPointeeType();
6141
6142    // Diagnose bad cases where we step over interface counts.
6143    if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get()))
6144      return QualType();
6145
6146    // The result type of a pointer-int computation is the pointer type.
6147    if (RHS.get()->getType()->isIntegerType()) {
6148      if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
6149        return QualType();
6150
6151      Expr *IExpr = RHS.get()->IgnoreParenCasts();
6152      UnaryOperator negRex(IExpr, UO_Minus, IExpr->getType(), VK_RValue,
6153                           OK_Ordinary, IExpr->getExprLoc());
6154      // Check array bounds for pointer arithemtic
6155      CheckArrayAccess(LHS.get()->IgnoreParenCasts(), &negRex);
6156
6157      if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6158      return LHS.get()->getType();
6159    }
6160
6161    // Handle pointer-pointer subtractions.
6162    if (const PointerType *RHSPTy
6163          = RHS.get()->getType()->getAs<PointerType>()) {
6164      QualType rpointee = RHSPTy->getPointeeType();
6165
6166      if (getLangOptions().CPlusPlus) {
6167        // Pointee types must be the same: C++ [expr.add]
6168        if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6169          diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
6170        }
6171      } else {
6172        // Pointee types must be compatible C99 6.5.6p3
6173        if (!Context.typesAreCompatible(
6174                Context.getCanonicalType(lpointee).getUnqualifiedType(),
6175                Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6176          diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
6177          return QualType();
6178        }
6179      }
6180
6181      if (!checkArithmeticBinOpPointerOperands(*this, Loc,
6182                                               LHS.get(), RHS.get()))
6183        return QualType();
6184
6185      if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6186      return Context.getPointerDiffType();
6187    }
6188  }
6189
6190  return InvalidOperands(Loc, LHS, RHS);
6191}
6192
6193static bool isScopedEnumerationType(QualType T) {
6194  if (const EnumType *ET = dyn_cast<EnumType>(T))
6195    return ET->getDecl()->isScoped();
6196  return false;
6197}
6198
6199static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
6200                                   SourceLocation Loc, unsigned Opc,
6201                                   QualType LHSType) {
6202  llvm::APSInt Right;
6203  // Check right/shifter operand
6204  if (RHS.get()->isValueDependent() ||
6205      !RHS.get()->isIntegerConstantExpr(Right, S.Context))
6206    return;
6207
6208  if (Right.isNegative()) {
6209    S.DiagRuntimeBehavior(Loc, RHS.get(),
6210                          S.PDiag(diag::warn_shift_negative)
6211                            << RHS.get()->getSourceRange());
6212    return;
6213  }
6214  llvm::APInt LeftBits(Right.getBitWidth(),
6215                       S.Context.getTypeSize(LHS.get()->getType()));
6216  if (Right.uge(LeftBits)) {
6217    S.DiagRuntimeBehavior(Loc, RHS.get(),
6218                          S.PDiag(diag::warn_shift_gt_typewidth)
6219                            << RHS.get()->getSourceRange());
6220    return;
6221  }
6222  if (Opc != BO_Shl)
6223    return;
6224
6225  // When left shifting an ICE which is signed, we can check for overflow which
6226  // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6227  // integers have defined behavior modulo one more than the maximum value
6228  // representable in the result type, so never warn for those.
6229  llvm::APSInt Left;
6230  if (LHS.get()->isValueDependent() ||
6231      !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6232      LHSType->hasUnsignedIntegerRepresentation())
6233    return;
6234  llvm::APInt ResultBits =
6235      static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6236  if (LeftBits.uge(ResultBits))
6237    return;
6238  llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6239  Result = Result.shl(Right);
6240
6241  // Print the bit representation of the signed integer as an unsigned
6242  // hexadecimal number.
6243  llvm::SmallString<40> HexResult;
6244  Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6245
6246  // If we are only missing a sign bit, this is less likely to result in actual
6247  // bugs -- if the result is cast back to an unsigned type, it will have the
6248  // expected value. Thus we place this behind a different warning that can be
6249  // turned off separately if needed.
6250  if (LeftBits == ResultBits - 1) {
6251    S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
6252        << HexResult.str() << LHSType
6253        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6254    return;
6255  }
6256
6257  S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
6258    << HexResult.str() << Result.getMinSignedBits() << LHSType
6259    << Left.getBitWidth() << LHS.get()->getSourceRange()
6260    << RHS.get()->getSourceRange();
6261}
6262
6263// C99 6.5.7
6264QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
6265                                  SourceLocation Loc, unsigned Opc,
6266                                  bool IsCompAssign) {
6267  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6268
6269  // C99 6.5.7p2: Each of the operands shall have integer type.
6270  if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6271      !RHS.get()->getType()->hasIntegerRepresentation())
6272    return InvalidOperands(Loc, LHS, RHS);
6273
6274  // C++0x: Don't allow scoped enums. FIXME: Use something better than
6275  // hasIntegerRepresentation() above instead of this.
6276  if (isScopedEnumerationType(LHS.get()->getType()) ||
6277      isScopedEnumerationType(RHS.get()->getType())) {
6278    return InvalidOperands(Loc, LHS, RHS);
6279  }
6280
6281  // Vector shifts promote their scalar inputs to vector type.
6282  if (LHS.get()->getType()->isVectorType() ||
6283      RHS.get()->getType()->isVectorType())
6284    return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6285
6286  // Shifts don't perform usual arithmetic conversions, they just do integer
6287  // promotions on each operand. C99 6.5.7p3
6288
6289  // For the LHS, do usual unary conversions, but then reset them away
6290  // if this is a compound assignment.
6291  ExprResult OldLHS = LHS;
6292  LHS = UsualUnaryConversions(LHS.take());
6293  if (LHS.isInvalid())
6294    return QualType();
6295  QualType LHSType = LHS.get()->getType();
6296  if (IsCompAssign) LHS = OldLHS;
6297
6298  // The RHS is simpler.
6299  RHS = UsualUnaryConversions(RHS.take());
6300  if (RHS.isInvalid())
6301    return QualType();
6302
6303  // Sanity-check shift operands
6304  DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
6305
6306  // "The type of the result is that of the promoted left operand."
6307  return LHSType;
6308}
6309
6310static bool IsWithinTemplateSpecialization(Decl *D) {
6311  if (DeclContext *DC = D->getDeclContext()) {
6312    if (isa<ClassTemplateSpecializationDecl>(DC))
6313      return true;
6314    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6315      return FD->isFunctionTemplateSpecialization();
6316  }
6317  return false;
6318}
6319
6320/// If two different enums are compared, raise a warning.
6321static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6322                                ExprResult &RHS) {
6323  QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6324  QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
6325
6326  const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6327  if (!LHSEnumType)
6328    return;
6329  const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6330  if (!RHSEnumType)
6331    return;
6332
6333  // Ignore anonymous enums.
6334  if (!LHSEnumType->getDecl()->getIdentifier())
6335    return;
6336  if (!RHSEnumType->getDecl()->getIdentifier())
6337    return;
6338
6339  if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6340    return;
6341
6342  S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6343      << LHSStrippedType << RHSStrippedType
6344      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6345}
6346
6347/// \brief Diagnose bad pointer comparisons.
6348static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
6349                                              ExprResult &LHS, ExprResult &RHS,
6350                                              bool IsError) {
6351  S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
6352                      : diag::ext_typecheck_comparison_of_distinct_pointers)
6353    << LHS.get()->getType() << RHS.get()->getType()
6354    << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6355}
6356
6357/// \brief Returns false if the pointers are converted to a composite type,
6358/// true otherwise.
6359static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
6360                                           ExprResult &LHS, ExprResult &RHS) {
6361  // C++ [expr.rel]p2:
6362  //   [...] Pointer conversions (4.10) and qualification
6363  //   conversions (4.4) are performed on pointer operands (or on
6364  //   a pointer operand and a null pointer constant) to bring
6365  //   them to their composite pointer type. [...]
6366  //
6367  // C++ [expr.eq]p1 uses the same notion for (in)equality
6368  // comparisons of pointers.
6369
6370  // C++ [expr.eq]p2:
6371  //   In addition, pointers to members can be compared, or a pointer to
6372  //   member and a null pointer constant. Pointer to member conversions
6373  //   (4.11) and qualification conversions (4.4) are performed to bring
6374  //   them to a common type. If one operand is a null pointer constant,
6375  //   the common type is the type of the other operand. Otherwise, the
6376  //   common type is a pointer to member type similar (4.4) to the type
6377  //   of one of the operands, with a cv-qualification signature (4.4)
6378  //   that is the union of the cv-qualification signatures of the operand
6379  //   types.
6380
6381  QualType LHSType = LHS.get()->getType();
6382  QualType RHSType = RHS.get()->getType();
6383  assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6384         (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
6385
6386  bool NonStandardCompositeType = false;
6387  bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
6388  QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
6389  if (T.isNull()) {
6390    diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
6391    return true;
6392  }
6393
6394  if (NonStandardCompositeType)
6395    S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
6396      << LHSType << RHSType << T << LHS.get()->getSourceRange()
6397      << RHS.get()->getSourceRange();
6398
6399  LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6400  RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
6401  return false;
6402}
6403
6404static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
6405                                                    ExprResult &LHS,
6406                                                    ExprResult &RHS,
6407                                                    bool IsError) {
6408  S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6409                      : diag::ext_typecheck_comparison_of_fptr_to_void)
6410    << LHS.get()->getType() << RHS.get()->getType()
6411    << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6412}
6413
6414// C99 6.5.8, C++ [expr.rel]
6415QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
6416                                    SourceLocation Loc, unsigned OpaqueOpc,
6417                                    bool IsRelational) {
6418  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6419
6420  BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
6421
6422  // Handle vector comparisons separately.
6423  if (LHS.get()->getType()->isVectorType() ||
6424      RHS.get()->getType()->isVectorType())
6425    return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
6426
6427  QualType LHSType = LHS.get()->getType();
6428  QualType RHSType = RHS.get()->getType();
6429
6430  Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6431  Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
6432
6433  checkEnumComparison(*this, Loc, LHS, RHS);
6434
6435  if (!LHSType->hasFloatingRepresentation() &&
6436      !(LHSType->isBlockPointerType() && IsRelational) &&
6437      !LHS.get()->getLocStart().isMacroID() &&
6438      !RHS.get()->getLocStart().isMacroID()) {
6439    // For non-floating point types, check for self-comparisons of the form
6440    // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
6441    // often indicate logic errors in the program.
6442    //
6443    // NOTE: Don't warn about comparison expressions resulting from macro
6444    // expansion. Also don't warn about comparisons which are only self
6445    // comparisons within a template specialization. The warnings should catch
6446    // obvious cases in the definition of the template anyways. The idea is to
6447    // warn when the typed comparison operator will always evaluate to the same
6448    // result.
6449    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
6450      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
6451        if (DRL->getDecl() == DRR->getDecl() &&
6452            !IsWithinTemplateSpecialization(DRL->getDecl())) {
6453          DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
6454                              << 0 // self-
6455                              << (Opc == BO_EQ
6456                                  || Opc == BO_LE
6457                                  || Opc == BO_GE));
6458        } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
6459                   !DRL->getDecl()->getType()->isReferenceType() &&
6460                   !DRR->getDecl()->getType()->isReferenceType()) {
6461            // what is it always going to eval to?
6462            char always_evals_to;
6463            switch(Opc) {
6464            case BO_EQ: // e.g. array1 == array2
6465              always_evals_to = 0; // false
6466              break;
6467            case BO_NE: // e.g. array1 != array2
6468              always_evals_to = 1; // true
6469              break;
6470            default:
6471              // best we can say is 'a constant'
6472              always_evals_to = 2; // e.g. array1 <= array2
6473              break;
6474            }
6475            DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
6476                                << 1 // array
6477                                << always_evals_to);
6478        }
6479      }
6480    }
6481
6482    if (isa<CastExpr>(LHSStripped))
6483      LHSStripped = LHSStripped->IgnoreParenCasts();
6484    if (isa<CastExpr>(RHSStripped))
6485      RHSStripped = RHSStripped->IgnoreParenCasts();
6486
6487    // Warn about comparisons against a string constant (unless the other
6488    // operand is null), the user probably wants strcmp.
6489    Expr *literalString = 0;
6490    Expr *literalStringStripped = 0;
6491    if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
6492        !RHSStripped->isNullPointerConstant(Context,
6493                                            Expr::NPC_ValueDependentIsNull)) {
6494      literalString = LHS.get();
6495      literalStringStripped = LHSStripped;
6496    } else if ((isa<StringLiteral>(RHSStripped) ||
6497                isa<ObjCEncodeExpr>(RHSStripped)) &&
6498               !LHSStripped->isNullPointerConstant(Context,
6499                                            Expr::NPC_ValueDependentIsNull)) {
6500      literalString = RHS.get();
6501      literalStringStripped = RHSStripped;
6502    }
6503
6504    if (literalString) {
6505      std::string resultComparison;
6506      switch (Opc) {
6507      case BO_LT: resultComparison = ") < 0"; break;
6508      case BO_GT: resultComparison = ") > 0"; break;
6509      case BO_LE: resultComparison = ") <= 0"; break;
6510      case BO_GE: resultComparison = ") >= 0"; break;
6511      case BO_EQ: resultComparison = ") == 0"; break;
6512      case BO_NE: resultComparison = ") != 0"; break;
6513      default: llvm_unreachable("Invalid comparison operator");
6514      }
6515
6516      DiagRuntimeBehavior(Loc, 0,
6517        PDiag(diag::warn_stringcompare)
6518          << isa<ObjCEncodeExpr>(literalStringStripped)
6519          << literalString->getSourceRange());
6520    }
6521  }
6522
6523  // C99 6.5.8p3 / C99 6.5.9p4
6524  if (LHS.get()->getType()->isArithmeticType() &&
6525      RHS.get()->getType()->isArithmeticType()) {
6526    UsualArithmeticConversions(LHS, RHS);
6527    if (LHS.isInvalid() || RHS.isInvalid())
6528      return QualType();
6529  }
6530  else {
6531    LHS = UsualUnaryConversions(LHS.take());
6532    if (LHS.isInvalid())
6533      return QualType();
6534
6535    RHS = UsualUnaryConversions(RHS.take());
6536    if (RHS.isInvalid())
6537      return QualType();
6538  }
6539
6540  LHSType = LHS.get()->getType();
6541  RHSType = RHS.get()->getType();
6542
6543  // The result of comparisons is 'bool' in C++, 'int' in C.
6544  QualType ResultTy = Context.getLogicalOperationType();
6545
6546  if (IsRelational) {
6547    if (LHSType->isRealType() && RHSType->isRealType())
6548      return ResultTy;
6549  } else {
6550    // Check for comparisons of floating point operands using != and ==.
6551    if (LHSType->hasFloatingRepresentation())
6552      CheckFloatComparison(Loc, LHS.get(), RHS.get());
6553
6554    if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
6555      return ResultTy;
6556  }
6557
6558  bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
6559                                              Expr::NPC_ValueDependentIsNull);
6560  bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
6561                                              Expr::NPC_ValueDependentIsNull);
6562
6563  // All of the following pointer-related warnings are GCC extensions, except
6564  // when handling null pointer constants.
6565  if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
6566    QualType LCanPointeeTy =
6567      LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
6568    QualType RCanPointeeTy =
6569      RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
6570
6571    if (getLangOptions().CPlusPlus) {
6572      if (LCanPointeeTy == RCanPointeeTy)
6573        return ResultTy;
6574      if (!IsRelational &&
6575          (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6576        // Valid unless comparison between non-null pointer and function pointer
6577        // This is a gcc extension compatibility comparison.
6578        // In a SFINAE context, we treat this as a hard error to maintain
6579        // conformance with the C++ standard.
6580        if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6581            && !LHSIsNull && !RHSIsNull) {
6582          diagnoseFunctionPointerToVoidComparison(
6583              *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
6584
6585          if (isSFINAEContext())
6586            return QualType();
6587
6588          RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6589          return ResultTy;
6590        }
6591      }
6592
6593      if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
6594        return QualType();
6595      else
6596        return ResultTy;
6597    }
6598    // C99 6.5.9p2 and C99 6.5.8p2
6599    if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6600                                   RCanPointeeTy.getUnqualifiedType())) {
6601      // Valid unless a relational comparison of function pointers
6602      if (IsRelational && LCanPointeeTy->isFunctionType()) {
6603        Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
6604          << LHSType << RHSType << LHS.get()->getSourceRange()
6605          << RHS.get()->getSourceRange();
6606      }
6607    } else if (!IsRelational &&
6608               (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6609      // Valid unless comparison between non-null pointer and function pointer
6610      if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6611          && !LHSIsNull && !RHSIsNull)
6612        diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
6613                                                /*isError*/false);
6614    } else {
6615      // Invalid
6616      diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
6617    }
6618    if (LCanPointeeTy != RCanPointeeTy) {
6619      if (LHSIsNull && !RHSIsNull)
6620        LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6621      else
6622        RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6623    }
6624    return ResultTy;
6625  }
6626
6627  if (getLangOptions().CPlusPlus) {
6628    // Comparison of nullptr_t with itself.
6629    if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
6630      return ResultTy;
6631
6632    // Comparison of pointers with null pointer constants and equality
6633    // comparisons of member pointers to null pointer constants.
6634    if (RHSIsNull &&
6635        ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
6636         (!IsRelational &&
6637          (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
6638      RHS = ImpCastExprToType(RHS.take(), LHSType,
6639                        LHSType->isMemberPointerType()
6640                          ? CK_NullToMemberPointer
6641                          : CK_NullToPointer);
6642      return ResultTy;
6643    }
6644    if (LHSIsNull &&
6645        ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
6646         (!IsRelational &&
6647          (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
6648      LHS = ImpCastExprToType(LHS.take(), RHSType,
6649                        RHSType->isMemberPointerType()
6650                          ? CK_NullToMemberPointer
6651                          : CK_NullToPointer);
6652      return ResultTy;
6653    }
6654
6655    // Comparison of member pointers.
6656    if (!IsRelational &&
6657        LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
6658      if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
6659        return QualType();
6660      else
6661        return ResultTy;
6662    }
6663
6664    // Handle scoped enumeration types specifically, since they don't promote
6665    // to integers.
6666    if (LHS.get()->getType()->isEnumeralType() &&
6667        Context.hasSameUnqualifiedType(LHS.get()->getType(),
6668                                       RHS.get()->getType()))
6669      return ResultTy;
6670  }
6671
6672  // Handle block pointer types.
6673  if (!IsRelational && LHSType->isBlockPointerType() &&
6674      RHSType->isBlockPointerType()) {
6675    QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
6676    QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
6677
6678    if (!LHSIsNull && !RHSIsNull &&
6679        !Context.typesAreCompatible(lpointee, rpointee)) {
6680      Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
6681        << LHSType << RHSType << LHS.get()->getSourceRange()
6682        << RHS.get()->getSourceRange();
6683    }
6684    RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6685    return ResultTy;
6686  }
6687
6688  // Allow block pointers to be compared with null pointer constants.
6689  if (!IsRelational
6690      && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
6691          || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
6692    if (!LHSIsNull && !RHSIsNull) {
6693      if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
6694             ->getPointeeType()->isVoidType())
6695            || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
6696                ->getPointeeType()->isVoidType())))
6697        Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
6698          << LHSType << RHSType << LHS.get()->getSourceRange()
6699          << RHS.get()->getSourceRange();
6700    }
6701    if (LHSIsNull && !RHSIsNull)
6702      LHS = ImpCastExprToType(LHS.take(), RHSType,
6703                              RHSType->isPointerType() ? CK_BitCast
6704                                : CK_AnyPointerToBlockPointerCast);
6705    else
6706      RHS = ImpCastExprToType(RHS.take(), LHSType,
6707                              LHSType->isPointerType() ? CK_BitCast
6708                                : CK_AnyPointerToBlockPointerCast);
6709    return ResultTy;
6710  }
6711
6712  if (LHSType->isObjCObjectPointerType() ||
6713      RHSType->isObjCObjectPointerType()) {
6714    const PointerType *LPT = LHSType->getAs<PointerType>();
6715    const PointerType *RPT = RHSType->getAs<PointerType>();
6716    if (LPT || RPT) {
6717      bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6718      bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
6719
6720      if (!LPtrToVoid && !RPtrToVoid &&
6721          !Context.typesAreCompatible(LHSType, RHSType)) {
6722        diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
6723                                          /*isError*/false);
6724      }
6725      if (LHSIsNull && !RHSIsNull)
6726        LHS = ImpCastExprToType(LHS.take(), RHSType,
6727                                RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
6728      else
6729        RHS = ImpCastExprToType(RHS.take(), LHSType,
6730                                LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
6731      return ResultTy;
6732    }
6733    if (LHSType->isObjCObjectPointerType() &&
6734        RHSType->isObjCObjectPointerType()) {
6735      if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
6736        diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
6737                                          /*isError*/false);
6738      if (LHSIsNull && !RHSIsNull)
6739        LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6740      else
6741        RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6742      return ResultTy;
6743    }
6744  }
6745  if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
6746      (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
6747    unsigned DiagID = 0;
6748    bool isError = false;
6749    if ((LHSIsNull && LHSType->isIntegerType()) ||
6750        (RHSIsNull && RHSType->isIntegerType())) {
6751      if (IsRelational && !getLangOptions().CPlusPlus)
6752        DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
6753    } else if (IsRelational && !getLangOptions().CPlusPlus)
6754      DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
6755    else if (getLangOptions().CPlusPlus) {
6756      DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6757      isError = true;
6758    } else
6759      DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
6760
6761    if (DiagID) {
6762      Diag(Loc, DiagID)
6763        << LHSType << RHSType << LHS.get()->getSourceRange()
6764        << RHS.get()->getSourceRange();
6765      if (isError)
6766        return QualType();
6767    }
6768
6769    if (LHSType->isIntegerType())
6770      LHS = ImpCastExprToType(LHS.take(), RHSType,
6771                        LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
6772    else
6773      RHS = ImpCastExprToType(RHS.take(), LHSType,
6774                        RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
6775    return ResultTy;
6776  }
6777
6778  // Handle block pointers.
6779  if (!IsRelational && RHSIsNull
6780      && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
6781    RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
6782    return ResultTy;
6783  }
6784  if (!IsRelational && LHSIsNull
6785      && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
6786    LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
6787    return ResultTy;
6788  }
6789
6790  return InvalidOperands(Loc, LHS, RHS);
6791}
6792
6793/// CheckVectorCompareOperands - vector comparisons are a clang extension that
6794/// operates on extended vector types.  Instead of producing an IntTy result,
6795/// like a scalar comparison, a vector comparison produces a vector of integer
6796/// types.
6797QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
6798                                          SourceLocation Loc,
6799                                          bool IsRelational) {
6800  // Check to make sure we're operating on vectors of the same type and width,
6801  // Allowing one side to be a scalar of element type.
6802  QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
6803  if (vType.isNull())
6804    return vType;
6805
6806  QualType LHSType = LHS.get()->getType();
6807  QualType RHSType = RHS.get()->getType();
6808
6809  // If AltiVec, the comparison results in a numeric type, i.e.
6810  // bool for C++, int for C
6811  if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
6812    return Context.getLogicalOperationType();
6813
6814  // For non-floating point types, check for self-comparisons of the form
6815  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
6816  // often indicate logic errors in the program.
6817  if (!LHSType->hasFloatingRepresentation()) {
6818    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
6819      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParens()))
6820        if (DRL->getDecl() == DRR->getDecl())
6821          DiagRuntimeBehavior(Loc, 0,
6822                              PDiag(diag::warn_comparison_always)
6823                                << 0 // self-
6824                                << 2 // "a constant"
6825                              );
6826  }
6827
6828  // Check for comparisons of floating point operands using != and ==.
6829  if (!IsRelational && LHSType->hasFloatingRepresentation()) {
6830    assert (RHSType->hasFloatingRepresentation());
6831    CheckFloatComparison(Loc, LHS.get(), RHS.get());
6832  }
6833
6834  // Return a signed type that is of identical size and number of elements.
6835  // For floating point vectors, return an integer type of identical size
6836  // and number of elements.
6837  const VectorType *VTy = LHSType->getAs<VectorType>();
6838  unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
6839  if (TypeSize == Context.getTypeSize(Context.CharTy))
6840    return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
6841  else if (TypeSize == Context.getTypeSize(Context.ShortTy))
6842    return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
6843  else if (TypeSize == Context.getTypeSize(Context.IntTy))
6844    return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
6845  else if (TypeSize == Context.getTypeSize(Context.LongTy))
6846    return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6847  assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
6848         "Unhandled vector element size in vector compare");
6849  return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6850}
6851
6852inline QualType Sema::CheckBitwiseOperands(
6853  ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
6854  checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6855
6856  if (LHS.get()->getType()->isVectorType() ||
6857      RHS.get()->getType()->isVectorType()) {
6858    if (LHS.get()->getType()->hasIntegerRepresentation() &&
6859        RHS.get()->getType()->hasIntegerRepresentation())
6860      return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6861
6862    return InvalidOperands(Loc, LHS, RHS);
6863  }
6864
6865  ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
6866  QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
6867                                                 IsCompAssign);
6868  if (LHSResult.isInvalid() || RHSResult.isInvalid())
6869    return QualType();
6870  LHS = LHSResult.take();
6871  RHS = RHSResult.take();
6872
6873  if (LHS.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6874      RHS.get()->getType()->isIntegralOrUnscopedEnumerationType())
6875    return compType;
6876  return InvalidOperands(Loc, LHS, RHS);
6877}
6878
6879inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
6880  ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
6881
6882  // Diagnose cases where the user write a logical and/or but probably meant a
6883  // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
6884  // is a constant.
6885  if (LHS.get()->getType()->isIntegerType() &&
6886      !LHS.get()->getType()->isBooleanType() &&
6887      RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
6888      // Don't warn in macros or template instantiations.
6889      !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
6890    // If the RHS can be constant folded, and if it constant folds to something
6891    // that isn't 0 or 1 (which indicate a potential logical operation that
6892    // happened to fold to true/false) then warn.
6893    // Parens on the RHS are ignored.
6894    llvm::APSInt Result;
6895    if (RHS.get()->EvaluateAsInt(Result, Context))
6896      if ((getLangOptions().Bool && !RHS.get()->getType()->isBooleanType()) ||
6897          (Result != 0 && Result != 1)) {
6898        Diag(Loc, diag::warn_logical_instead_of_bitwise)
6899          << RHS.get()->getSourceRange()
6900          << (Opc == BO_LAnd ? "&&" : "||");
6901        // Suggest replacing the logical operator with the bitwise version
6902        Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
6903            << (Opc == BO_LAnd ? "&" : "|")
6904            << FixItHint::CreateReplacement(SourceRange(
6905                Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
6906                                                getLangOptions())),
6907                                            Opc == BO_LAnd ? "&" : "|");
6908        if (Opc == BO_LAnd)
6909          // Suggest replacing "Foo() && kNonZero" with "Foo()"
6910          Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
6911              << FixItHint::CreateRemoval(
6912                  SourceRange(
6913                      Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
6914                                                 0, getSourceManager(),
6915                                                 getLangOptions()),
6916                      RHS.get()->getLocEnd()));
6917      }
6918  }
6919
6920  if (!Context.getLangOptions().CPlusPlus) {
6921    LHS = UsualUnaryConversions(LHS.take());
6922    if (LHS.isInvalid())
6923      return QualType();
6924
6925    RHS = UsualUnaryConversions(RHS.take());
6926    if (RHS.isInvalid())
6927      return QualType();
6928
6929    if (!LHS.get()->getType()->isScalarType() ||
6930        !RHS.get()->getType()->isScalarType())
6931      return InvalidOperands(Loc, LHS, RHS);
6932
6933    return Context.IntTy;
6934  }
6935
6936  // The following is safe because we only use this method for
6937  // non-overloadable operands.
6938
6939  // C++ [expr.log.and]p1
6940  // C++ [expr.log.or]p1
6941  // The operands are both contextually converted to type bool.
6942  ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
6943  if (LHSRes.isInvalid())
6944    return InvalidOperands(Loc, LHS, RHS);
6945  LHS = move(LHSRes);
6946
6947  ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
6948  if (RHSRes.isInvalid())
6949    return InvalidOperands(Loc, LHS, RHS);
6950  RHS = move(RHSRes);
6951
6952  // C++ [expr.log.and]p2
6953  // C++ [expr.log.or]p2
6954  // The result is a bool.
6955  return Context.BoolTy;
6956}
6957
6958/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6959/// is a read-only property; return true if so. A readonly property expression
6960/// depends on various declarations and thus must be treated specially.
6961///
6962static bool IsReadonlyProperty(Expr *E, Sema &S) {
6963  const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
6964  if (!PropExpr) return false;
6965  if (PropExpr->isImplicitProperty()) return false;
6966
6967  ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6968  QualType BaseType = PropExpr->isSuperReceiver() ?
6969                            PropExpr->getSuperReceiverType() :
6970                            PropExpr->getBase()->getType();
6971
6972  if (const ObjCObjectPointerType *OPT =
6973      BaseType->getAsObjCInterfacePointerType())
6974    if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6975      if (S.isPropertyReadonly(PDecl, IFace))
6976        return true;
6977  return false;
6978}
6979
6980static bool IsConstProperty(Expr *E, Sema &S) {
6981  const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
6982  if (!PropExpr) return false;
6983  if (PropExpr->isImplicitProperty()) return false;
6984
6985  ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6986  QualType T = PDecl->getType().getNonReferenceType();
6987  return T.isConstQualified();
6988}
6989
6990static bool IsReadonlyMessage(Expr *E, Sema &S) {
6991  const MemberExpr *ME = dyn_cast<MemberExpr>(E);
6992  if (!ME) return false;
6993  if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
6994  ObjCMessageExpr *Base =
6995    dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
6996  if (!Base) return false;
6997  return Base->getMethodDecl() != 0;
6998}
6999
7000/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
7001/// emit an error and return true.  If so, return false.
7002static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
7003  SourceLocation OrigLoc = Loc;
7004  Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
7005                                                              &Loc);
7006  if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7007    IsLV = Expr::MLV_ReadonlyProperty;
7008  else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
7009    IsLV = Expr::MLV_Valid;
7010  else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7011    IsLV = Expr::MLV_InvalidMessageExpression;
7012  if (IsLV == Expr::MLV_Valid)
7013    return false;
7014
7015  unsigned Diag = 0;
7016  bool NeedType = false;
7017  switch (IsLV) { // C99 6.5.16p2
7018  case Expr::MLV_ConstQualified:
7019    Diag = diag::err_typecheck_assign_const;
7020
7021    // In ARC, use some specialized diagnostics for occasions where we
7022    // infer 'const'.  These are always pseudo-strong variables.
7023    if (S.getLangOptions().ObjCAutoRefCount) {
7024      DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7025      if (declRef && isa<VarDecl>(declRef->getDecl())) {
7026        VarDecl *var = cast<VarDecl>(declRef->getDecl());
7027
7028        // Use the normal diagnostic if it's pseudo-__strong but the
7029        // user actually wrote 'const'.
7030        if (var->isARCPseudoStrong() &&
7031            (!var->getTypeSourceInfo() ||
7032             !var->getTypeSourceInfo()->getType().isConstQualified())) {
7033          // There are two pseudo-strong cases:
7034          //  - self
7035          ObjCMethodDecl *method = S.getCurMethodDecl();
7036          if (method && var == method->getSelfDecl())
7037            Diag = diag::err_typecheck_arr_assign_self;
7038
7039          //  - fast enumeration variables
7040          else
7041            Diag = diag::err_typecheck_arr_assign_enumeration;
7042
7043          SourceRange Assign;
7044          if (Loc != OrigLoc)
7045            Assign = SourceRange(OrigLoc, OrigLoc);
7046          S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7047          // We need to preserve the AST regardless, so migration tool
7048          // can do its job.
7049          return false;
7050        }
7051      }
7052    }
7053
7054    break;
7055  case Expr::MLV_ArrayType:
7056    Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7057    NeedType = true;
7058    break;
7059  case Expr::MLV_NotObjectType:
7060    Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7061    NeedType = true;
7062    break;
7063  case Expr::MLV_LValueCast:
7064    Diag = diag::err_typecheck_lvalue_casts_not_supported;
7065    break;
7066  case Expr::MLV_Valid:
7067    llvm_unreachable("did not take early return for MLV_Valid");
7068  case Expr::MLV_InvalidExpression:
7069  case Expr::MLV_MemberFunction:
7070  case Expr::MLV_ClassTemporary:
7071    Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7072    break;
7073  case Expr::MLV_IncompleteType:
7074  case Expr::MLV_IncompleteVoidType:
7075    return S.RequireCompleteType(Loc, E->getType(),
7076              S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
7077                  << E->getSourceRange());
7078  case Expr::MLV_DuplicateVectorComponents:
7079    Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7080    break;
7081  case Expr::MLV_NotBlockQualified:
7082    Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7083    break;
7084  case Expr::MLV_ReadonlyProperty:
7085  case Expr::MLV_NoSetterProperty:
7086    llvm_unreachable("readonly properties should be processed differently");
7087    break;
7088  case Expr::MLV_InvalidMessageExpression:
7089    Diag = diag::error_readonly_message_assignment;
7090    break;
7091  case Expr::MLV_SubObjCPropertySetting:
7092    Diag = diag::error_no_subobject_property_setting;
7093    break;
7094  }
7095
7096  SourceRange Assign;
7097  if (Loc != OrigLoc)
7098    Assign = SourceRange(OrigLoc, OrigLoc);
7099  if (NeedType)
7100    S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
7101  else
7102    S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7103  return true;
7104}
7105
7106
7107
7108// C99 6.5.16.1
7109QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
7110                                       SourceLocation Loc,
7111                                       QualType CompoundType) {
7112  assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7113
7114  // Verify that LHS is a modifiable lvalue, and emit error if not.
7115  if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
7116    return QualType();
7117
7118  QualType LHSType = LHSExpr->getType();
7119  QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7120                                             CompoundType;
7121  AssignConvertType ConvTy;
7122  if (CompoundType.isNull()) {
7123    QualType LHSTy(LHSType);
7124    ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
7125    if (RHS.isInvalid())
7126      return QualType();
7127    // Special case of NSObject attributes on c-style pointer types.
7128    if (ConvTy == IncompatiblePointer &&
7129        ((Context.isObjCNSObjectType(LHSType) &&
7130          RHSType->isObjCObjectPointerType()) ||
7131         (Context.isObjCNSObjectType(RHSType) &&
7132          LHSType->isObjCObjectPointerType())))
7133      ConvTy = Compatible;
7134
7135    if (ConvTy == Compatible &&
7136        getLangOptions().ObjCNonFragileABI &&
7137        LHSType->isObjCObjectType())
7138      Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7139        << LHSType;
7140
7141    // If the RHS is a unary plus or minus, check to see if they = and + are
7142    // right next to each other.  If so, the user may have typo'd "x =+ 4"
7143    // instead of "x += 4".
7144    Expr *RHSCheck = RHS.get();
7145    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7146      RHSCheck = ICE->getSubExpr();
7147    if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
7148      if ((UO->getOpcode() == UO_Plus ||
7149           UO->getOpcode() == UO_Minus) &&
7150          Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
7151          // Only if the two operators are exactly adjacent.
7152          Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
7153          // And there is a space or other character before the subexpr of the
7154          // unary +/-.  We don't want to warn on "x=-1".
7155          Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7156          UO->getSubExpr()->getLocStart().isFileID()) {
7157        Diag(Loc, diag::warn_not_compound_assign)
7158          << (UO->getOpcode() == UO_Plus ? "+" : "-")
7159          << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
7160      }
7161    }
7162
7163    if (ConvTy == Compatible) {
7164      if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
7165        checkRetainCycles(LHSExpr, RHS.get());
7166      else if (getLangOptions().ObjCAutoRefCount)
7167        checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
7168    }
7169  } else {
7170    // Compound assignment "x += y"
7171    ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
7172  }
7173
7174  if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
7175                               RHS.get(), AA_Assigning))
7176    return QualType();
7177
7178  CheckForNullPointerDereference(*this, LHSExpr);
7179
7180  // C99 6.5.16p3: The type of an assignment expression is the type of the
7181  // left operand unless the left operand has qualified type, in which case
7182  // it is the unqualified version of the type of the left operand.
7183  // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7184  // is converted to the type of the assignment expression (above).
7185  // C++ 5.17p1: the type of the assignment expression is that of its left
7186  // operand.
7187  return (getLangOptions().CPlusPlus
7188          ? LHSType : LHSType.getUnqualifiedType());
7189}
7190
7191// C99 6.5.17
7192static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
7193                                   SourceLocation Loc) {
7194  S.DiagnoseUnusedExprResult(LHS.get());
7195
7196  LHS = S.CheckPlaceholderExpr(LHS.take());
7197  RHS = S.CheckPlaceholderExpr(RHS.take());
7198  if (LHS.isInvalid() || RHS.isInvalid())
7199    return QualType();
7200
7201  // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7202  // operands, but not unary promotions.
7203  // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
7204
7205  // So we treat the LHS as a ignored value, and in C++ we allow the
7206  // containing site to determine what should be done with the RHS.
7207  LHS = S.IgnoredValueConversions(LHS.take());
7208  if (LHS.isInvalid())
7209    return QualType();
7210
7211  if (!S.getLangOptions().CPlusPlus) {
7212    RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7213    if (RHS.isInvalid())
7214      return QualType();
7215    if (!RHS.get()->getType()->isVoidType())
7216      S.RequireCompleteType(Loc, RHS.get()->getType(),
7217                            diag::err_incomplete_type);
7218  }
7219
7220  return RHS.get()->getType();
7221}
7222
7223/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7224/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
7225static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7226                                               ExprValueKind &VK,
7227                                               SourceLocation OpLoc,
7228                                               bool IsInc, bool IsPrefix) {
7229  if (Op->isTypeDependent())
7230    return S.Context.DependentTy;
7231
7232  QualType ResType = Op->getType();
7233  assert(!ResType.isNull() && "no type for increment/decrement expression");
7234
7235  if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
7236    // Decrement of bool is not allowed.
7237    if (!IsInc) {
7238      S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
7239      return QualType();
7240    }
7241    // Increment of bool sets it to true, but is deprecated.
7242    S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
7243  } else if (ResType->isRealType()) {
7244    // OK!
7245  } else if (ResType->isAnyPointerType()) {
7246    // C99 6.5.2.4p2, 6.5.6p2
7247    if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
7248      return QualType();
7249
7250    // Diagnose bad cases where we step over interface counts.
7251    else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op))
7252      return QualType();
7253  } else if (ResType->isAnyComplexType()) {
7254    // C99 does not support ++/-- on complex types, we allow as an extension.
7255    S.Diag(OpLoc, diag::ext_integer_increment_complex)
7256      << ResType << Op->getSourceRange();
7257  } else if (ResType->isPlaceholderType()) {
7258    ExprResult PR = S.CheckPlaceholderExpr(Op);
7259    if (PR.isInvalid()) return QualType();
7260    return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7261                                          IsInc, IsPrefix);
7262  } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7263    // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
7264  } else {
7265    S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
7266      << ResType << int(IsInc) << Op->getSourceRange();
7267    return QualType();
7268  }
7269  // At this point, we know we have a real, complex or pointer type.
7270  // Now make sure the operand is a modifiable lvalue.
7271  if (CheckForModifiableLvalue(Op, OpLoc, S))
7272    return QualType();
7273  // In C++, a prefix increment is the same type as the operand. Otherwise
7274  // (in C or with postfix), the increment is the unqualified type of the
7275  // operand.
7276  if (IsPrefix && S.getLangOptions().CPlusPlus) {
7277    VK = VK_LValue;
7278    return ResType;
7279  } else {
7280    VK = VK_RValue;
7281    return ResType.getUnqualifiedType();
7282  }
7283}
7284
7285
7286/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
7287/// This routine allows us to typecheck complex/recursive expressions
7288/// where the declaration is needed for type checking. We only need to
7289/// handle cases when the expression references a function designator
7290/// or is an lvalue. Here are some examples:
7291///  - &(x) => x
7292///  - &*****f => f for f a function designator.
7293///  - &s.xx => s
7294///  - &s.zz[1].yy -> s, if zz is an array
7295///  - *(x + 1) -> x, if x is an array
7296///  - &"123"[2] -> 0
7297///  - & __real__ x -> x
7298static ValueDecl *getPrimaryDecl(Expr *E) {
7299  switch (E->getStmtClass()) {
7300  case Stmt::DeclRefExprClass:
7301    return cast<DeclRefExpr>(E)->getDecl();
7302  case Stmt::MemberExprClass:
7303    // If this is an arrow operator, the address is an offset from
7304    // the base's value, so the object the base refers to is
7305    // irrelevant.
7306    if (cast<MemberExpr>(E)->isArrow())
7307      return 0;
7308    // Otherwise, the expression refers to a part of the base
7309    return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
7310  case Stmt::ArraySubscriptExprClass: {
7311    // FIXME: This code shouldn't be necessary!  We should catch the implicit
7312    // promotion of register arrays earlier.
7313    Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7314    if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7315      if (ICE->getSubExpr()->getType()->isArrayType())
7316        return getPrimaryDecl(ICE->getSubExpr());
7317    }
7318    return 0;
7319  }
7320  case Stmt::UnaryOperatorClass: {
7321    UnaryOperator *UO = cast<UnaryOperator>(E);
7322
7323    switch(UO->getOpcode()) {
7324    case UO_Real:
7325    case UO_Imag:
7326    case UO_Extension:
7327      return getPrimaryDecl(UO->getSubExpr());
7328    default:
7329      return 0;
7330    }
7331  }
7332  case Stmt::ParenExprClass:
7333    return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
7334  case Stmt::ImplicitCastExprClass:
7335    // If the result of an implicit cast is an l-value, we care about
7336    // the sub-expression; otherwise, the result here doesn't matter.
7337    return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
7338  default:
7339    return 0;
7340  }
7341}
7342
7343namespace {
7344  enum {
7345    AO_Bit_Field = 0,
7346    AO_Vector_Element = 1,
7347    AO_Property_Expansion = 2,
7348    AO_Register_Variable = 3,
7349    AO_No_Error = 4
7350  };
7351}
7352/// \brief Diagnose invalid operand for address of operations.
7353///
7354/// \param Type The type of operand which cannot have its address taken.
7355static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7356                                         Expr *E, unsigned Type) {
7357  S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7358}
7359
7360/// CheckAddressOfOperand - The operand of & must be either a function
7361/// designator or an lvalue designating an object. If it is an lvalue, the
7362/// object cannot be declared with storage class register or be a bit field.
7363/// Note: The usual conversions are *not* applied to the operand of the &
7364/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
7365/// In C++, the operand might be an overloaded function name, in which case
7366/// we allow the '&' but retain the overloaded-function type.
7367static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
7368                                      SourceLocation OpLoc) {
7369  if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7370    if (PTy->getKind() == BuiltinType::Overload) {
7371      if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7372        S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7373          << OrigOp.get()->getSourceRange();
7374        return QualType();
7375      }
7376
7377      return S.Context.OverloadTy;
7378    }
7379
7380    if (PTy->getKind() == BuiltinType::UnknownAny)
7381      return S.Context.UnknownAnyTy;
7382
7383    if (PTy->getKind() == BuiltinType::BoundMember) {
7384      S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7385        << OrigOp.get()->getSourceRange();
7386      return QualType();
7387    }
7388
7389    OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
7390    if (OrigOp.isInvalid()) return QualType();
7391  }
7392
7393  if (OrigOp.get()->isTypeDependent())
7394    return S.Context.DependentTy;
7395
7396  assert(!OrigOp.get()->getType()->isPlaceholderType());
7397
7398  // Make sure to ignore parentheses in subsequent checks
7399  Expr *op = OrigOp.get()->IgnoreParens();
7400
7401  if (S.getLangOptions().C99) {
7402    // Implement C99-only parts of addressof rules.
7403    if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
7404      if (uOp->getOpcode() == UO_Deref)
7405        // Per C99 6.5.3.2, the address of a deref always returns a valid result
7406        // (assuming the deref expression is valid).
7407        return uOp->getSubExpr()->getType();
7408    }
7409    // Technically, there should be a check for array subscript
7410    // expressions here, but the result of one is always an lvalue anyway.
7411  }
7412  ValueDecl *dcl = getPrimaryDecl(op);
7413  Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
7414  unsigned AddressOfError = AO_No_Error;
7415
7416  if (lval == Expr::LV_ClassTemporary) {
7417    bool sfinae = S.isSFINAEContext();
7418    S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7419                         : diag::ext_typecheck_addrof_class_temporary)
7420      << op->getType() << op->getSourceRange();
7421    if (sfinae)
7422      return QualType();
7423  } else if (isa<ObjCSelectorExpr>(op)) {
7424    return S.Context.getPointerType(op->getType());
7425  } else if (lval == Expr::LV_MemberFunction) {
7426    // If it's an instance method, make a member pointer.
7427    // The expression must have exactly the form &A::foo.
7428
7429    // If the underlying expression isn't a decl ref, give up.
7430    if (!isa<DeclRefExpr>(op)) {
7431      S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7432        << OrigOp.get()->getSourceRange();
7433      return QualType();
7434    }
7435    DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7436    CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7437
7438    // The id-expression was parenthesized.
7439    if (OrigOp.get() != DRE) {
7440      S.Diag(OpLoc, diag::err_parens_pointer_member_function)
7441        << OrigOp.get()->getSourceRange();
7442
7443    // The method was named without a qualifier.
7444    } else if (!DRE->getQualifier()) {
7445      S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
7446        << op->getSourceRange();
7447    }
7448
7449    return S.Context.getMemberPointerType(op->getType(),
7450              S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
7451  } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
7452    // C99 6.5.3.2p1
7453    // The operand must be either an l-value or a function designator
7454    if (!op->getType()->isFunctionType()) {
7455      // Use a special diagnostic for loads from property references.
7456      if (isa<ObjCPropertyRefExpr>(op->IgnoreImplicit()->IgnoreParens())) {
7457        AddressOfError = AO_Property_Expansion;
7458      } else {
7459        // FIXME: emit more specific diag...
7460        S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7461          << op->getSourceRange();
7462        return QualType();
7463      }
7464    }
7465  } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
7466    // The operand cannot be a bit-field
7467    AddressOfError = AO_Bit_Field;
7468  } else if (op->getObjectKind() == OK_VectorComponent) {
7469    // The operand cannot be an element of a vector
7470    AddressOfError = AO_Vector_Element;
7471  } else if (op->getObjectKind() == OK_ObjCProperty) {
7472    // cannot take address of a property expression.
7473    AddressOfError = AO_Property_Expansion;
7474  } else if (dcl) { // C99 6.5.3.2p1
7475    // We have an lvalue with a decl. Make sure the decl is not declared
7476    // with the register storage-class specifier.
7477    if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
7478      // in C++ it is not error to take address of a register
7479      // variable (c++03 7.1.1P3)
7480      if (vd->getStorageClass() == SC_Register &&
7481          !S.getLangOptions().CPlusPlus) {
7482        AddressOfError = AO_Register_Variable;
7483      }
7484    } else if (isa<FunctionTemplateDecl>(dcl)) {
7485      return S.Context.OverloadTy;
7486    } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
7487      // Okay: we can take the address of a field.
7488      // Could be a pointer to member, though, if there is an explicit
7489      // scope qualifier for the class.
7490      if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
7491        DeclContext *Ctx = dcl->getDeclContext();
7492        if (Ctx && Ctx->isRecord()) {
7493          if (dcl->getType()->isReferenceType()) {
7494            S.Diag(OpLoc,
7495                   diag::err_cannot_form_pointer_to_member_of_reference_type)
7496              << dcl->getDeclName() << dcl->getType();
7497            return QualType();
7498          }
7499
7500          while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7501            Ctx = Ctx->getParent();
7502          return S.Context.getMemberPointerType(op->getType(),
7503                S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
7504        }
7505      }
7506    } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
7507      llvm_unreachable("Unknown/unexpected decl type");
7508  }
7509
7510  if (AddressOfError != AO_No_Error) {
7511    diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
7512    return QualType();
7513  }
7514
7515  if (lval == Expr::LV_IncompleteVoidType) {
7516    // Taking the address of a void variable is technically illegal, but we
7517    // allow it in cases which are otherwise valid.
7518    // Example: "extern void x; void* y = &x;".
7519    S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
7520  }
7521
7522  // If the operand has type "type", the result has type "pointer to type".
7523  if (op->getType()->isObjCObjectType())
7524    return S.Context.getObjCObjectPointerType(op->getType());
7525  return S.Context.getPointerType(op->getType());
7526}
7527
7528/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
7529static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7530                                        SourceLocation OpLoc) {
7531  if (Op->isTypeDependent())
7532    return S.Context.DependentTy;
7533
7534  ExprResult ConvResult = S.UsualUnaryConversions(Op);
7535  if (ConvResult.isInvalid())
7536    return QualType();
7537  Op = ConvResult.take();
7538  QualType OpTy = Op->getType();
7539  QualType Result;
7540
7541  if (isa<CXXReinterpretCastExpr>(Op)) {
7542    QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7543    S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7544                                     Op->getSourceRange());
7545  }
7546
7547  // Note that per both C89 and C99, indirection is always legal, even if OpTy
7548  // is an incomplete type or void.  It would be possible to warn about
7549  // dereferencing a void pointer, but it's completely well-defined, and such a
7550  // warning is unlikely to catch any mistakes.
7551  if (const PointerType *PT = OpTy->getAs<PointerType>())
7552    Result = PT->getPointeeType();
7553  else if (const ObjCObjectPointerType *OPT =
7554             OpTy->getAs<ObjCObjectPointerType>())
7555    Result = OPT->getPointeeType();
7556  else {
7557    ExprResult PR = S.CheckPlaceholderExpr(Op);
7558    if (PR.isInvalid()) return QualType();
7559    if (PR.take() != Op)
7560      return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
7561  }
7562
7563  if (Result.isNull()) {
7564    S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
7565      << OpTy << Op->getSourceRange();
7566    return QualType();
7567  }
7568
7569  // Dereferences are usually l-values...
7570  VK = VK_LValue;
7571
7572  // ...except that certain expressions are never l-values in C.
7573  if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
7574    VK = VK_RValue;
7575
7576  return Result;
7577}
7578
7579static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
7580  tok::TokenKind Kind) {
7581  BinaryOperatorKind Opc;
7582  switch (Kind) {
7583  default: llvm_unreachable("Unknown binop!");
7584  case tok::periodstar:           Opc = BO_PtrMemD; break;
7585  case tok::arrowstar:            Opc = BO_PtrMemI; break;
7586  case tok::star:                 Opc = BO_Mul; break;
7587  case tok::slash:                Opc = BO_Div; break;
7588  case tok::percent:              Opc = BO_Rem; break;
7589  case tok::plus:                 Opc = BO_Add; break;
7590  case tok::minus:                Opc = BO_Sub; break;
7591  case tok::lessless:             Opc = BO_Shl; break;
7592  case tok::greatergreater:       Opc = BO_Shr; break;
7593  case tok::lessequal:            Opc = BO_LE; break;
7594  case tok::less:                 Opc = BO_LT; break;
7595  case tok::greaterequal:         Opc = BO_GE; break;
7596  case tok::greater:              Opc = BO_GT; break;
7597  case tok::exclaimequal:         Opc = BO_NE; break;
7598  case tok::equalequal:           Opc = BO_EQ; break;
7599  case tok::amp:                  Opc = BO_And; break;
7600  case tok::caret:                Opc = BO_Xor; break;
7601  case tok::pipe:                 Opc = BO_Or; break;
7602  case tok::ampamp:               Opc = BO_LAnd; break;
7603  case tok::pipepipe:             Opc = BO_LOr; break;
7604  case tok::equal:                Opc = BO_Assign; break;
7605  case tok::starequal:            Opc = BO_MulAssign; break;
7606  case tok::slashequal:           Opc = BO_DivAssign; break;
7607  case tok::percentequal:         Opc = BO_RemAssign; break;
7608  case tok::plusequal:            Opc = BO_AddAssign; break;
7609  case tok::minusequal:           Opc = BO_SubAssign; break;
7610  case tok::lesslessequal:        Opc = BO_ShlAssign; break;
7611  case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
7612  case tok::ampequal:             Opc = BO_AndAssign; break;
7613  case tok::caretequal:           Opc = BO_XorAssign; break;
7614  case tok::pipeequal:            Opc = BO_OrAssign; break;
7615  case tok::comma:                Opc = BO_Comma; break;
7616  }
7617  return Opc;
7618}
7619
7620static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
7621  tok::TokenKind Kind) {
7622  UnaryOperatorKind Opc;
7623  switch (Kind) {
7624  default: llvm_unreachable("Unknown unary op!");
7625  case tok::plusplus:     Opc = UO_PreInc; break;
7626  case tok::minusminus:   Opc = UO_PreDec; break;
7627  case tok::amp:          Opc = UO_AddrOf; break;
7628  case tok::star:         Opc = UO_Deref; break;
7629  case tok::plus:         Opc = UO_Plus; break;
7630  case tok::minus:        Opc = UO_Minus; break;
7631  case tok::tilde:        Opc = UO_Not; break;
7632  case tok::exclaim:      Opc = UO_LNot; break;
7633  case tok::kw___real:    Opc = UO_Real; break;
7634  case tok::kw___imag:    Opc = UO_Imag; break;
7635  case tok::kw___extension__: Opc = UO_Extension; break;
7636  }
7637  return Opc;
7638}
7639
7640/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7641/// This warning is only emitted for builtin assignment operations. It is also
7642/// suppressed in the event of macro expansions.
7643static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
7644                                   SourceLocation OpLoc) {
7645  if (!S.ActiveTemplateInstantiations.empty())
7646    return;
7647  if (OpLoc.isInvalid() || OpLoc.isMacroID())
7648    return;
7649  LHSExpr = LHSExpr->IgnoreParenImpCasts();
7650  RHSExpr = RHSExpr->IgnoreParenImpCasts();
7651  const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
7652  const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
7653  if (!LHSDeclRef || !RHSDeclRef ||
7654      LHSDeclRef->getLocation().isMacroID() ||
7655      RHSDeclRef->getLocation().isMacroID())
7656    return;
7657  const ValueDecl *LHSDecl =
7658    cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
7659  const ValueDecl *RHSDecl =
7660    cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
7661  if (LHSDecl != RHSDecl)
7662    return;
7663  if (LHSDecl->getType().isVolatileQualified())
7664    return;
7665  if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
7666    if (RefTy->getPointeeType().isVolatileQualified())
7667      return;
7668
7669  S.Diag(OpLoc, diag::warn_self_assignment)
7670      << LHSDeclRef->getType()
7671      << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
7672}
7673
7674/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7675/// operator @p Opc at location @c TokLoc. This routine only supports
7676/// built-in operations; ActOnBinOp handles overloaded operators.
7677ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
7678                                    BinaryOperatorKind Opc,
7679                                    Expr *LHSExpr, Expr *RHSExpr) {
7680  ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
7681  QualType ResultTy;     // Result type of the binary operator.
7682  // The following two variables are used for compound assignment operators
7683  QualType CompLHSTy;    // Type of LHS after promotions for computation
7684  QualType CompResultTy; // Type of computation result
7685  ExprValueKind VK = VK_RValue;
7686  ExprObjectKind OK = OK_Ordinary;
7687
7688  switch (Opc) {
7689  case BO_Assign:
7690    ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
7691    if (getLangOptions().CPlusPlus &&
7692        LHS.get()->getObjectKind() != OK_ObjCProperty) {
7693      VK = LHS.get()->getValueKind();
7694      OK = LHS.get()->getObjectKind();
7695    }
7696    if (!ResultTy.isNull())
7697      DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
7698    break;
7699  case BO_PtrMemD:
7700  case BO_PtrMemI:
7701    ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
7702                                            Opc == BO_PtrMemI);
7703    break;
7704  case BO_Mul:
7705  case BO_Div:
7706    ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
7707                                           Opc == BO_Div);
7708    break;
7709  case BO_Rem:
7710    ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
7711    break;
7712  case BO_Add:
7713    ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc);
7714    break;
7715  case BO_Sub:
7716    ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
7717    break;
7718  case BO_Shl:
7719  case BO_Shr:
7720    ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
7721    break;
7722  case BO_LE:
7723  case BO_LT:
7724  case BO_GE:
7725  case BO_GT:
7726    ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
7727    break;
7728  case BO_EQ:
7729  case BO_NE:
7730    ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
7731    break;
7732  case BO_And:
7733  case BO_Xor:
7734  case BO_Or:
7735    ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
7736    break;
7737  case BO_LAnd:
7738  case BO_LOr:
7739    ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
7740    break;
7741  case BO_MulAssign:
7742  case BO_DivAssign:
7743    CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
7744                                               Opc == BO_DivAssign);
7745    CompLHSTy = CompResultTy;
7746    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7747      ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
7748    break;
7749  case BO_RemAssign:
7750    CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
7751    CompLHSTy = CompResultTy;
7752    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7753      ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
7754    break;
7755  case BO_AddAssign:
7756    CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7757    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7758      ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
7759    break;
7760  case BO_SubAssign:
7761    CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7762    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7763      ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
7764    break;
7765  case BO_ShlAssign:
7766  case BO_ShrAssign:
7767    CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
7768    CompLHSTy = CompResultTy;
7769    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7770      ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
7771    break;
7772  case BO_AndAssign:
7773  case BO_XorAssign:
7774  case BO_OrAssign:
7775    CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
7776    CompLHSTy = CompResultTy;
7777    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7778      ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
7779    break;
7780  case BO_Comma:
7781    ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
7782    if (getLangOptions().CPlusPlus && !RHS.isInvalid()) {
7783      VK = RHS.get()->getValueKind();
7784      OK = RHS.get()->getObjectKind();
7785    }
7786    break;
7787  }
7788  if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
7789    return ExprError();
7790
7791  // Check for array bounds violations for both sides of the BinaryOperator
7792  CheckArrayAccess(LHS.get());
7793  CheckArrayAccess(RHS.get());
7794
7795  if (CompResultTy.isNull())
7796    return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
7797                                              ResultTy, VK, OK, OpLoc));
7798  if (getLangOptions().CPlusPlus && LHS.get()->getObjectKind() !=
7799      OK_ObjCProperty) {
7800    VK = VK_LValue;
7801    OK = LHS.get()->getObjectKind();
7802  }
7803  return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
7804                                                    ResultTy, VK, OK, CompLHSTy,
7805                                                    CompResultTy, OpLoc));
7806}
7807
7808/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7809/// operators are mixed in a way that suggests that the programmer forgot that
7810/// comparison operators have higher precedence. The most typical example of
7811/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
7812static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
7813                                      SourceLocation OpLoc, Expr *LHSExpr,
7814                                      Expr *RHSExpr) {
7815  typedef BinaryOperator BinOp;
7816  BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
7817                RHSopc = static_cast<BinOp::Opcode>(-1);
7818  if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
7819    LHSopc = BO->getOpcode();
7820  if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
7821    RHSopc = BO->getOpcode();
7822
7823  // Subs are not binary operators.
7824  if (LHSopc == -1 && RHSopc == -1)
7825    return;
7826
7827  // Bitwise operations are sometimes used as eager logical ops.
7828  // Don't diagnose this.
7829  if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
7830      (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
7831    return;
7832
7833  bool isLeftComp = BinOp::isComparisonOp(LHSopc);
7834  bool isRightComp = BinOp::isComparisonOp(RHSopc);
7835  if (!isLeftComp && !isRightComp) return;
7836
7837  SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
7838                                                   OpLoc)
7839                                     : SourceRange(OpLoc, RHSExpr->getLocEnd());
7840  std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
7841                                 : BinOp::getOpcodeStr(RHSopc);
7842  SourceRange ParensRange = isLeftComp ?
7843      SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
7844                  RHSExpr->getLocEnd())
7845    : SourceRange(LHSExpr->getLocStart(),
7846                  cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
7847
7848  Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7849    << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
7850  SuggestParentheses(Self, OpLoc,
7851    Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
7852    RHSExpr->getSourceRange());
7853  SuggestParentheses(Self, OpLoc,
7854    Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
7855    ParensRange);
7856}
7857
7858/// \brief It accepts a '&' expr that is inside a '|' one.
7859/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
7860/// in parentheses.
7861static void
7862EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
7863                                       BinaryOperator *Bop) {
7864  assert(Bop->getOpcode() == BO_And);
7865  Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
7866      << Bop->getSourceRange() << OpLoc;
7867  SuggestParentheses(Self, Bop->getOperatorLoc(),
7868    Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
7869    Bop->getSourceRange());
7870}
7871
7872/// \brief It accepts a '&&' expr that is inside a '||' one.
7873/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7874/// in parentheses.
7875static void
7876EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
7877                                       BinaryOperator *Bop) {
7878  assert(Bop->getOpcode() == BO_LAnd);
7879  Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
7880      << Bop->getSourceRange() << OpLoc;
7881  SuggestParentheses(Self, Bop->getOperatorLoc(),
7882    Self.PDiag(diag::note_logical_and_in_logical_or_silence),
7883    Bop->getSourceRange());
7884}
7885
7886/// \brief Returns true if the given expression can be evaluated as a constant
7887/// 'true'.
7888static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7889  bool Res;
7890  return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7891}
7892
7893/// \brief Returns true if the given expression can be evaluated as a constant
7894/// 'false'.
7895static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7896  bool Res;
7897  return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7898}
7899
7900/// \brief Look for '&&' in the left hand of a '||' expr.
7901static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
7902                                             Expr *LHSExpr, Expr *RHSExpr) {
7903  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
7904    if (Bop->getOpcode() == BO_LAnd) {
7905      // If it's "a && b || 0" don't warn since the precedence doesn't matter.
7906      if (EvaluatesAsFalse(S, RHSExpr))
7907        return;
7908      // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7909      if (!EvaluatesAsTrue(S, Bop->getLHS()))
7910        return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7911    } else if (Bop->getOpcode() == BO_LOr) {
7912      if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7913        // If it's "a || b && 1 || c" we didn't warn earlier for
7914        // "a || b && 1", but warn now.
7915        if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7916          return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7917      }
7918    }
7919  }
7920}
7921
7922/// \brief Look for '&&' in the right hand of a '||' expr.
7923static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
7924                                             Expr *LHSExpr, Expr *RHSExpr) {
7925  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
7926    if (Bop->getOpcode() == BO_LAnd) {
7927      // If it's "0 || a && b" don't warn since the precedence doesn't matter.
7928      if (EvaluatesAsFalse(S, LHSExpr))
7929        return;
7930      // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7931      if (!EvaluatesAsTrue(S, Bop->getRHS()))
7932        return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7933    }
7934  }
7935}
7936
7937/// \brief Look for '&' in the left or right hand of a '|' expr.
7938static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
7939                                             Expr *OrArg) {
7940  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
7941    if (Bop->getOpcode() == BO_And)
7942      return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
7943  }
7944}
7945
7946/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
7947/// precedence.
7948static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
7949                                    SourceLocation OpLoc, Expr *LHSExpr,
7950                                    Expr *RHSExpr){
7951  // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
7952  if (BinaryOperator::isBitwiseOp(Opc))
7953    DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
7954
7955  // Diagnose "arg1 & arg2 | arg3"
7956  if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
7957    DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
7958    DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
7959  }
7960
7961  // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
7962  // We don't warn for 'assert(a || b && "bad")' since this is safe.
7963  if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
7964    DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
7965    DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
7966  }
7967}
7968
7969// Binary Operators.  'Tok' is the token for the operator.
7970ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
7971                            tok::TokenKind Kind,
7972                            Expr *LHSExpr, Expr *RHSExpr) {
7973  BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
7974  assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
7975  assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
7976
7977  // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
7978  DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
7979
7980  return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
7981}
7982
7983/// Build an overloaded binary operator expression in the given scope.
7984static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
7985                                       BinaryOperatorKind Opc,
7986                                       Expr *LHS, Expr *RHS) {
7987  // Find all of the overloaded operators visible from this
7988  // point. We perform both an operator-name lookup from the local
7989  // scope and an argument-dependent lookup based on the types of
7990  // the arguments.
7991  UnresolvedSet<16> Functions;
7992  OverloadedOperatorKind OverOp
7993    = BinaryOperator::getOverloadedOperator(Opc);
7994  if (Sc && OverOp != OO_None)
7995    S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
7996                                   RHS->getType(), Functions);
7997
7998  // Build the (potentially-overloaded, potentially-dependent)
7999  // binary operation.
8000  return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8001}
8002
8003ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
8004                            BinaryOperatorKind Opc,
8005                            Expr *LHSExpr, Expr *RHSExpr) {
8006  // Handle pseudo-objects in the LHS.
8007  if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8008    // Assignments with a pseudo-object l-value need special analysis.
8009    if (pty->getKind() == BuiltinType::PseudoObject &&
8010        BinaryOperator::isAssignmentOp(Opc))
8011      return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8012
8013    // Don't resolve overloads if the other type is overloadable.
8014    if (pty->getKind() == BuiltinType::Overload) {
8015      // We can't actually test that if we still have a placeholder,
8016      // though.  Fortunately, none of the exceptions we see in that
8017      // code below are valid when the LHS is an overload set.
8018      ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8019      if (resolvedRHS.isInvalid()) return ExprError();
8020      RHSExpr = resolvedRHS.take();
8021
8022      if (RHSExpr->getType()->isOverloadableType())
8023        return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8024    }
8025
8026    ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8027    if (LHS.isInvalid()) return ExprError();
8028    LHSExpr = LHS.take();
8029  }
8030
8031  // Handle pseudo-objects in the RHS.
8032  if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8033    // An overload in the RHS can potentially be resolved by the type
8034    // being assigned to.
8035    if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload)
8036      return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
8037
8038    // Don't resolve overloads if the other type is overloadable.
8039    if (pty->getKind() == BuiltinType::Overload &&
8040        LHSExpr->getType()->isOverloadableType())
8041      return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8042
8043    ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8044    if (!resolvedRHS.isUsable()) return ExprError();
8045    RHSExpr = resolvedRHS.take();
8046  }
8047
8048  if (getLangOptions().CPlusPlus) {
8049    bool UseBuiltinOperator;
8050
8051    if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) {
8052      UseBuiltinOperator = false;
8053    } else {
8054      UseBuiltinOperator = !LHSExpr->getType()->isOverloadableType() &&
8055                           !RHSExpr->getType()->isOverloadableType();
8056    }
8057
8058    if (!UseBuiltinOperator)
8059      return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8060  }
8061
8062  // Build a built-in binary operation.
8063  return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
8064}
8065
8066ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
8067                                      UnaryOperatorKind Opc,
8068                                      Expr *InputExpr) {
8069  ExprResult Input = Owned(InputExpr);
8070  ExprValueKind VK = VK_RValue;
8071  ExprObjectKind OK = OK_Ordinary;
8072  QualType resultType;
8073  switch (Opc) {
8074  case UO_PreInc:
8075  case UO_PreDec:
8076  case UO_PostInc:
8077  case UO_PostDec:
8078    resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
8079                                                Opc == UO_PreInc ||
8080                                                Opc == UO_PostInc,
8081                                                Opc == UO_PreInc ||
8082                                                Opc == UO_PreDec);
8083    break;
8084  case UO_AddrOf:
8085    resultType = CheckAddressOfOperand(*this, Input, OpLoc);
8086    break;
8087  case UO_Deref: {
8088    Input = DefaultFunctionArrayLvalueConversion(Input.take());
8089    resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
8090    break;
8091  }
8092  case UO_Plus:
8093  case UO_Minus:
8094    Input = UsualUnaryConversions(Input.take());
8095    if (Input.isInvalid()) return ExprError();
8096    resultType = Input.get()->getType();
8097    if (resultType->isDependentType())
8098      break;
8099    if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8100        resultType->isVectorType())
8101      break;
8102    else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8103             resultType->isEnumeralType())
8104      break;
8105    else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
8106             Opc == UO_Plus &&
8107             resultType->isPointerType())
8108      break;
8109
8110    return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8111      << resultType << Input.get()->getSourceRange());
8112
8113  case UO_Not: // bitwise complement
8114    Input = UsualUnaryConversions(Input.take());
8115    if (Input.isInvalid()) return ExprError();
8116    resultType = Input.get()->getType();
8117    if (resultType->isDependentType())
8118      break;
8119    // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8120    if (resultType->isComplexType() || resultType->isComplexIntegerType())
8121      // C99 does not support '~' for complex conjugation.
8122      Diag(OpLoc, diag::ext_integer_complement_complex)
8123        << resultType << Input.get()->getSourceRange();
8124    else if (resultType->hasIntegerRepresentation())
8125      break;
8126    else {
8127      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8128        << resultType << Input.get()->getSourceRange());
8129    }
8130    break;
8131
8132  case UO_LNot: // logical negation
8133    // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
8134    Input = DefaultFunctionArrayLvalueConversion(Input.take());
8135    if (Input.isInvalid()) return ExprError();
8136    resultType = Input.get()->getType();
8137
8138    // Though we still have to promote half FP to float...
8139    if (resultType->isHalfType()) {
8140      Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8141      resultType = Context.FloatTy;
8142    }
8143
8144    if (resultType->isDependentType())
8145      break;
8146    if (resultType->isScalarType()) {
8147      // C99 6.5.3.3p1: ok, fallthrough;
8148      if (Context.getLangOptions().CPlusPlus) {
8149        // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8150        // operand contextually converted to bool.
8151        Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8152                                  ScalarTypeToBooleanCastKind(resultType));
8153      }
8154    } else {
8155      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8156        << resultType << Input.get()->getSourceRange());
8157    }
8158
8159    // LNot always has type int. C99 6.5.3.3p5.
8160    // In C++, it's bool. C++ 5.3.1p8
8161    resultType = Context.getLogicalOperationType();
8162    break;
8163  case UO_Real:
8164  case UO_Imag:
8165    resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
8166    // _Real and _Imag map ordinary l-values into ordinary l-values.
8167    if (Input.isInvalid()) return ExprError();
8168    if (Input.get()->getValueKind() != VK_RValue &&
8169        Input.get()->getObjectKind() == OK_Ordinary)
8170      VK = Input.get()->getValueKind();
8171    break;
8172  case UO_Extension:
8173    resultType = Input.get()->getType();
8174    VK = Input.get()->getValueKind();
8175    OK = Input.get()->getObjectKind();
8176    break;
8177  }
8178  if (resultType.isNull() || Input.isInvalid())
8179    return ExprError();
8180
8181  // Check for array bounds violations in the operand of the UnaryOperator,
8182  // except for the '*' and '&' operators that have to be handled specially
8183  // by CheckArrayAccess (as there are special cases like &array[arraysize]
8184  // that are explicitly defined as valid by the standard).
8185  if (Opc != UO_AddrOf && Opc != UO_Deref)
8186    CheckArrayAccess(Input.get());
8187
8188  return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
8189                                           VK, OK, OpLoc));
8190}
8191
8192ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
8193                              UnaryOperatorKind Opc, Expr *Input) {
8194  // First things first: handle placeholders so that the
8195  // overloaded-operator check considers the right type.
8196  if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8197    // Increment and decrement of pseudo-object references.
8198    if (pty->getKind() == BuiltinType::PseudoObject &&
8199        UnaryOperator::isIncrementDecrementOp(Opc))
8200      return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8201
8202    // extension is always a builtin operator.
8203    if (Opc == UO_Extension)
8204      return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8205
8206    // & gets special logic for several kinds of placeholder.
8207    // The builtin code knows what to do.
8208    if (Opc == UO_AddrOf &&
8209        (pty->getKind() == BuiltinType::Overload ||
8210         pty->getKind() == BuiltinType::UnknownAny ||
8211         pty->getKind() == BuiltinType::BoundMember))
8212      return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8213
8214    // Anything else needs to be handled now.
8215    ExprResult Result = CheckPlaceholderExpr(Input);
8216    if (Result.isInvalid()) return ExprError();
8217    Input = Result.take();
8218  }
8219
8220  if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
8221      UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
8222    // Find all of the overloaded operators visible from this
8223    // point. We perform both an operator-name lookup from the local
8224    // scope and an argument-dependent lookup based on the types of
8225    // the arguments.
8226    UnresolvedSet<16> Functions;
8227    OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
8228    if (S && OverOp != OO_None)
8229      LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8230                                   Functions);
8231
8232    return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
8233  }
8234
8235  return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8236}
8237
8238// Unary Operators.  'Tok' is the token for the operator.
8239ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
8240                              tok::TokenKind Op, Expr *Input) {
8241  return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
8242}
8243
8244/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
8245ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
8246                                LabelDecl *TheDecl) {
8247  TheDecl->setUsed();
8248  // Create the AST node.  The address of a label always has type 'void*'.
8249  return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
8250                                       Context.getPointerType(Context.VoidTy)));
8251}
8252
8253/// Given the last statement in a statement-expression, check whether
8254/// the result is a producing expression (like a call to an
8255/// ns_returns_retained function) and, if so, rebuild it to hoist the
8256/// release out of the full-expression.  Otherwise, return null.
8257/// Cannot fail.
8258static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
8259  // Should always be wrapped with one of these.
8260  ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
8261  if (!cleanups) return 0;
8262
8263  ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
8264  if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
8265    return 0;
8266
8267  // Splice out the cast.  This shouldn't modify any interesting
8268  // features of the statement.
8269  Expr *producer = cast->getSubExpr();
8270  assert(producer->getType() == cast->getType());
8271  assert(producer->getValueKind() == cast->getValueKind());
8272  cleanups->setSubExpr(producer);
8273  return cleanups;
8274}
8275
8276ExprResult
8277Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
8278                    SourceLocation RPLoc) { // "({..})"
8279  assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8280  CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8281
8282  bool isFileScope
8283    = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
8284  if (isFileScope)
8285    return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
8286
8287  // FIXME: there are a variety of strange constraints to enforce here, for
8288  // example, it is not possible to goto into a stmt expression apparently.
8289  // More semantic analysis is needed.
8290
8291  // If there are sub stmts in the compound stmt, take the type of the last one
8292  // as the type of the stmtexpr.
8293  QualType Ty = Context.VoidTy;
8294  bool StmtExprMayBindToTemp = false;
8295  if (!Compound->body_empty()) {
8296    Stmt *LastStmt = Compound->body_back();
8297    LabelStmt *LastLabelStmt = 0;
8298    // If LastStmt is a label, skip down through into the body.
8299    while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8300      LastLabelStmt = Label;
8301      LastStmt = Label->getSubStmt();
8302    }
8303
8304    if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
8305      // Do function/array conversion on the last expression, but not
8306      // lvalue-to-rvalue.  However, initialize an unqualified type.
8307      ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8308      if (LastExpr.isInvalid())
8309        return ExprError();
8310      Ty = LastExpr.get()->getType().getUnqualifiedType();
8311
8312      if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
8313        // In ARC, if the final expression ends in a consume, splice
8314        // the consume out and bind it later.  In the alternate case
8315        // (when dealing with a retainable type), the result
8316        // initialization will create a produce.  In both cases the
8317        // result will be +1, and we'll need to balance that out with
8318        // a bind.
8319        if (Expr *rebuiltLastStmt
8320              = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8321          LastExpr = rebuiltLastStmt;
8322        } else {
8323          LastExpr = PerformCopyInitialization(
8324                            InitializedEntity::InitializeResult(LPLoc,
8325                                                                Ty,
8326                                                                false),
8327                                                   SourceLocation(),
8328                                               LastExpr);
8329        }
8330
8331        if (LastExpr.isInvalid())
8332          return ExprError();
8333        if (LastExpr.get() != 0) {
8334          if (!LastLabelStmt)
8335            Compound->setLastStmt(LastExpr.take());
8336          else
8337            LastLabelStmt->setSubStmt(LastExpr.take());
8338          StmtExprMayBindToTemp = true;
8339        }
8340      }
8341    }
8342  }
8343
8344  // FIXME: Check that expression type is complete/non-abstract; statement
8345  // expressions are not lvalues.
8346  Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8347  if (StmtExprMayBindToTemp)
8348    return MaybeBindToTemporary(ResStmtExpr);
8349  return Owned(ResStmtExpr);
8350}
8351
8352ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
8353                                      TypeSourceInfo *TInfo,
8354                                      OffsetOfComponent *CompPtr,
8355                                      unsigned NumComponents,
8356                                      SourceLocation RParenLoc) {
8357  QualType ArgTy = TInfo->getType();
8358  bool Dependent = ArgTy->isDependentType();
8359  SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
8360
8361  // We must have at least one component that refers to the type, and the first
8362  // one is known to be a field designator.  Verify that the ArgTy represents
8363  // a struct/union/class.
8364  if (!Dependent && !ArgTy->isRecordType())
8365    return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8366                       << ArgTy << TypeRange);
8367
8368  // Type must be complete per C99 7.17p3 because a declaring a variable
8369  // with an incomplete type would be ill-formed.
8370  if (!Dependent
8371      && RequireCompleteType(BuiltinLoc, ArgTy,
8372                             PDiag(diag::err_offsetof_incomplete_type)
8373                               << TypeRange))
8374    return ExprError();
8375
8376  // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8377  // GCC extension, diagnose them.
8378  // FIXME: This diagnostic isn't actually visible because the location is in
8379  // a system header!
8380  if (NumComponents != 1)
8381    Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8382      << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
8383
8384  bool DidWarnAboutNonPOD = false;
8385  QualType CurrentType = ArgTy;
8386  typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
8387  SmallVector<OffsetOfNode, 4> Comps;
8388  SmallVector<Expr*, 4> Exprs;
8389  for (unsigned i = 0; i != NumComponents; ++i) {
8390    const OffsetOfComponent &OC = CompPtr[i];
8391    if (OC.isBrackets) {
8392      // Offset of an array sub-field.  TODO: Should we allow vector elements?
8393      if (!CurrentType->isDependentType()) {
8394        const ArrayType *AT = Context.getAsArrayType(CurrentType);
8395        if(!AT)
8396          return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8397                           << CurrentType);
8398        CurrentType = AT->getElementType();
8399      } else
8400        CurrentType = Context.DependentTy;
8401
8402      ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
8403      if (IdxRval.isInvalid())
8404        return ExprError();
8405      Expr *Idx = IdxRval.take();
8406
8407      // The expression must be an integral expression.
8408      // FIXME: An integral constant expression?
8409      if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8410          !Idx->getType()->isIntegerType())
8411        return ExprError(Diag(Idx->getLocStart(),
8412                              diag::err_typecheck_subscript_not_integer)
8413                         << Idx->getSourceRange());
8414
8415      // Record this array index.
8416      Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8417      Exprs.push_back(Idx);
8418      continue;
8419    }
8420
8421    // Offset of a field.
8422    if (CurrentType->isDependentType()) {
8423      // We have the offset of a field, but we can't look into the dependent
8424      // type. Just record the identifier of the field.
8425      Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8426      CurrentType = Context.DependentTy;
8427      continue;
8428    }
8429
8430    // We need to have a complete type to look into.
8431    if (RequireCompleteType(OC.LocStart, CurrentType,
8432                            diag::err_offsetof_incomplete_type))
8433      return ExprError();
8434
8435    // Look for the designated field.
8436    const RecordType *RC = CurrentType->getAs<RecordType>();
8437    if (!RC)
8438      return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8439                       << CurrentType);
8440    RecordDecl *RD = RC->getDecl();
8441
8442    // C++ [lib.support.types]p5:
8443    //   The macro offsetof accepts a restricted set of type arguments in this
8444    //   International Standard. type shall be a POD structure or a POD union
8445    //   (clause 9).
8446    if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8447      if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
8448          DiagRuntimeBehavior(BuiltinLoc, 0,
8449                              PDiag(diag::warn_offsetof_non_pod_type)
8450                              << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8451                              << CurrentType))
8452        DidWarnAboutNonPOD = true;
8453    }
8454
8455    // Look for the field.
8456    LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8457    LookupQualifiedName(R, RD);
8458    FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
8459    IndirectFieldDecl *IndirectMemberDecl = 0;
8460    if (!MemberDecl) {
8461      if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
8462        MemberDecl = IndirectMemberDecl->getAnonField();
8463    }
8464
8465    if (!MemberDecl)
8466      return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8467                       << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8468                                                              OC.LocEnd));
8469
8470    // C99 7.17p3:
8471    //   (If the specified member is a bit-field, the behavior is undefined.)
8472    //
8473    // We diagnose this as an error.
8474    if (MemberDecl->isBitField()) {
8475      Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8476        << MemberDecl->getDeclName()
8477        << SourceRange(BuiltinLoc, RParenLoc);
8478      Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8479      return ExprError();
8480    }
8481
8482    RecordDecl *Parent = MemberDecl->getParent();
8483    if (IndirectMemberDecl)
8484      Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
8485
8486    // If the member was found in a base class, introduce OffsetOfNodes for
8487    // the base class indirections.
8488    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8489                       /*DetectVirtual=*/false);
8490    if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
8491      CXXBasePath &Path = Paths.front();
8492      for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8493           B != BEnd; ++B)
8494        Comps.push_back(OffsetOfNode(B->Base));
8495    }
8496
8497    if (IndirectMemberDecl) {
8498      for (IndirectFieldDecl::chain_iterator FI =
8499           IndirectMemberDecl->chain_begin(),
8500           FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8501        assert(isa<FieldDecl>(*FI));
8502        Comps.push_back(OffsetOfNode(OC.LocStart,
8503                                     cast<FieldDecl>(*FI), OC.LocEnd));
8504      }
8505    } else
8506      Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
8507
8508    CurrentType = MemberDecl->getType().getNonReferenceType();
8509  }
8510
8511  return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8512                                    TInfo, Comps.data(), Comps.size(),
8513                                    Exprs.data(), Exprs.size(), RParenLoc));
8514}
8515
8516ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
8517                                      SourceLocation BuiltinLoc,
8518                                      SourceLocation TypeLoc,
8519                                      ParsedType ParsedArgTy,
8520                                      OffsetOfComponent *CompPtr,
8521                                      unsigned NumComponents,
8522                                      SourceLocation RParenLoc) {
8523
8524  TypeSourceInfo *ArgTInfo;
8525  QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
8526  if (ArgTy.isNull())
8527    return ExprError();
8528
8529  if (!ArgTInfo)
8530    ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8531
8532  return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8533                              RParenLoc);
8534}
8535
8536
8537ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
8538                                 Expr *CondExpr,
8539                                 Expr *LHSExpr, Expr *RHSExpr,
8540                                 SourceLocation RPLoc) {
8541  assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8542
8543  ExprValueKind VK = VK_RValue;
8544  ExprObjectKind OK = OK_Ordinary;
8545  QualType resType;
8546  bool ValueDependent = false;
8547  if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
8548    resType = Context.DependentTy;
8549    ValueDependent = true;
8550  } else {
8551    // The conditional expression is required to be a constant expression.
8552    llvm::APSInt condEval(32);
8553    SourceLocation ExpLoc;
8554    if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
8555      return ExprError(Diag(ExpLoc,
8556                       diag::err_typecheck_choose_expr_requires_constant)
8557        << CondExpr->getSourceRange());
8558
8559    // If the condition is > zero, then the AST type is the same as the LSHExpr.
8560    Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8561
8562    resType = ActiveExpr->getType();
8563    ValueDependent = ActiveExpr->isValueDependent();
8564    VK = ActiveExpr->getValueKind();
8565    OK = ActiveExpr->getObjectKind();
8566  }
8567
8568  return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
8569                                        resType, VK, OK, RPLoc,
8570                                        resType->isDependentType(),
8571                                        ValueDependent));
8572}
8573
8574//===----------------------------------------------------------------------===//
8575// Clang Extensions.
8576//===----------------------------------------------------------------------===//
8577
8578/// ActOnBlockStart - This callback is invoked when a block literal is started.
8579void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
8580  BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8581  PushBlockScope(CurScope, Block);
8582  CurContext->addDecl(Block);
8583  if (CurScope)
8584    PushDeclContext(CurScope, Block);
8585  else
8586    CurContext = Block;
8587}
8588
8589void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
8590  assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
8591  assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
8592  BlockScopeInfo *CurBlock = getCurBlock();
8593
8594  TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
8595  QualType T = Sig->getType();
8596
8597  // GetTypeForDeclarator always produces a function type for a block
8598  // literal signature.  Furthermore, it is always a FunctionProtoType
8599  // unless the function was written with a typedef.
8600  assert(T->isFunctionType() &&
8601         "GetTypeForDeclarator made a non-function block signature");
8602
8603  // Look for an explicit signature in that function type.
8604  FunctionProtoTypeLoc ExplicitSignature;
8605
8606  TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8607  if (isa<FunctionProtoTypeLoc>(tmp)) {
8608    ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8609
8610    // Check whether that explicit signature was synthesized by
8611    // GetTypeForDeclarator.  If so, don't save that as part of the
8612    // written signature.
8613    if (ExplicitSignature.getLocalRangeBegin() ==
8614        ExplicitSignature.getLocalRangeEnd()) {
8615      // This would be much cheaper if we stored TypeLocs instead of
8616      // TypeSourceInfos.
8617      TypeLoc Result = ExplicitSignature.getResultLoc();
8618      unsigned Size = Result.getFullDataSize();
8619      Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8620      Sig->getTypeLoc().initializeFullCopy(Result, Size);
8621
8622      ExplicitSignature = FunctionProtoTypeLoc();
8623    }
8624  }
8625
8626  CurBlock->TheDecl->setSignatureAsWritten(Sig);
8627  CurBlock->FunctionType = T;
8628
8629  const FunctionType *Fn = T->getAs<FunctionType>();
8630  QualType RetTy = Fn->getResultType();
8631  bool isVariadic =
8632    (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8633
8634  CurBlock->TheDecl->setIsVariadic(isVariadic);
8635
8636  // Don't allow returning a objc interface by value.
8637  if (RetTy->isObjCObjectType()) {
8638    Diag(ParamInfo.getSourceRange().getBegin(),
8639         diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8640    return;
8641  }
8642
8643  // Context.DependentTy is used as a placeholder for a missing block
8644  // return type.  TODO:  what should we do with declarators like:
8645  //   ^ * { ... }
8646  // If the answer is "apply template argument deduction"....
8647  if (RetTy != Context.DependentTy)
8648    CurBlock->ReturnType = RetTy;
8649
8650  // Push block parameters from the declarator if we had them.
8651  SmallVector<ParmVarDecl*, 8> Params;
8652  if (ExplicitSignature) {
8653    for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8654      ParmVarDecl *Param = ExplicitSignature.getArg(I);
8655      if (Param->getIdentifier() == 0 &&
8656          !Param->isImplicit() &&
8657          !Param->isInvalidDecl() &&
8658          !getLangOptions().CPlusPlus)
8659        Diag(Param->getLocation(), diag::err_parameter_name_omitted);
8660      Params.push_back(Param);
8661    }
8662
8663  // Fake up parameter variables if we have a typedef, like
8664  //   ^ fntype { ... }
8665  } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8666    for (FunctionProtoType::arg_type_iterator
8667           I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8668      ParmVarDecl *Param =
8669        BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8670                                   ParamInfo.getSourceRange().getBegin(),
8671                                   *I);
8672      Params.push_back(Param);
8673    }
8674  }
8675
8676  // Set the parameters on the block decl.
8677  if (!Params.empty()) {
8678    CurBlock->TheDecl->setParams(Params);
8679    CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8680                             CurBlock->TheDecl->param_end(),
8681                             /*CheckParameterNames=*/false);
8682  }
8683
8684  // Finally we can process decl attributes.
8685  ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
8686
8687  if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
8688    Diag(ParamInfo.getAttributes()->getLoc(),
8689         diag::warn_attribute_sentinel_not_variadic) << 1;
8690    // FIXME: remove the attribute.
8691  }
8692
8693  // Put the parameter variables in scope.  We can bail out immediately
8694  // if we don't have any.
8695  if (Params.empty())
8696    return;
8697
8698  for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
8699         E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8700    (*AI)->setOwningFunction(CurBlock->TheDecl);
8701
8702    // If this has an identifier, add it to the scope stack.
8703    if ((*AI)->getIdentifier()) {
8704      CheckShadow(CurBlock->TheScope, *AI);
8705
8706      PushOnScopeChains(*AI, CurBlock->TheScope);
8707    }
8708  }
8709}
8710
8711/// ActOnBlockError - If there is an error parsing a block, this callback
8712/// is invoked to pop the information about the block from the action impl.
8713void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
8714  // Pop off CurBlock, handle nested blocks.
8715  PopDeclContext();
8716  PopFunctionOrBlockScope();
8717}
8718
8719/// ActOnBlockStmtExpr - This is called when the body of a block statement
8720/// literal was successfully completed.  ^(int x){...}
8721ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
8722                                    Stmt *Body, Scope *CurScope) {
8723  // If blocks are disabled, emit an error.
8724  if (!LangOpts.Blocks)
8725    Diag(CaretLoc, diag::err_blocks_disable);
8726
8727  BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
8728
8729  PopDeclContext();
8730
8731  QualType RetTy = Context.VoidTy;
8732  if (!BSI->ReturnType.isNull())
8733    RetTy = BSI->ReturnType;
8734
8735  bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
8736  QualType BlockTy;
8737
8738  // Set the captured variables on the block.
8739  BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8740                            BSI->CapturesCXXThis);
8741
8742  // If the user wrote a function type in some form, try to use that.
8743  if (!BSI->FunctionType.isNull()) {
8744    const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8745
8746    FunctionType::ExtInfo Ext = FTy->getExtInfo();
8747    if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8748
8749    // Turn protoless block types into nullary block types.
8750    if (isa<FunctionNoProtoType>(FTy)) {
8751      FunctionProtoType::ExtProtoInfo EPI;
8752      EPI.ExtInfo = Ext;
8753      BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
8754
8755    // Otherwise, if we don't need to change anything about the function type,
8756    // preserve its sugar structure.
8757    } else if (FTy->getResultType() == RetTy &&
8758               (!NoReturn || FTy->getNoReturnAttr())) {
8759      BlockTy = BSI->FunctionType;
8760
8761    // Otherwise, make the minimal modifications to the function type.
8762    } else {
8763      const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
8764      FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8765      EPI.TypeQuals = 0; // FIXME: silently?
8766      EPI.ExtInfo = Ext;
8767      BlockTy = Context.getFunctionType(RetTy,
8768                                        FPT->arg_type_begin(),
8769                                        FPT->getNumArgs(),
8770                                        EPI);
8771    }
8772
8773  // If we don't have a function type, just build one from nothing.
8774  } else {
8775    FunctionProtoType::ExtProtoInfo EPI;
8776    EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
8777    BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
8778  }
8779
8780  DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8781                           BSI->TheDecl->param_end());
8782  BlockTy = Context.getBlockPointerType(BlockTy);
8783
8784  // If needed, diagnose invalid gotos and switches in the block.
8785  if (getCurFunction()->NeedsScopeChecking() &&
8786      !hasAnyUnrecoverableErrorsInThisFunction())
8787    DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
8788
8789  BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
8790
8791  for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8792       ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8793    const VarDecl *variable = ci->getVariable();
8794    QualType T = variable->getType();
8795    QualType::DestructionKind destructKind = T.isDestructedType();
8796    if (destructKind != QualType::DK_none)
8797      getCurFunction()->setHasBranchProtectedScope();
8798  }
8799
8800  computeNRVO(Body, getCurBlock());
8801
8802  BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8803  const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8804  PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
8805
8806  return Owned(Result);
8807}
8808
8809ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
8810                                        Expr *E, ParsedType Ty,
8811                                        SourceLocation RPLoc) {
8812  TypeSourceInfo *TInfo;
8813  GetTypeFromParser(Ty, &TInfo);
8814  return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
8815}
8816
8817ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
8818                                Expr *E, TypeSourceInfo *TInfo,
8819                                SourceLocation RPLoc) {
8820  Expr *OrigExpr = E;
8821
8822  // Get the va_list type
8823  QualType VaListType = Context.getBuiltinVaListType();
8824  if (VaListType->isArrayType()) {
8825    // Deal with implicit array decay; for example, on x86-64,
8826    // va_list is an array, but it's supposed to decay to
8827    // a pointer for va_arg.
8828    VaListType = Context.getArrayDecayedType(VaListType);
8829    // Make sure the input expression also decays appropriately.
8830    ExprResult Result = UsualUnaryConversions(E);
8831    if (Result.isInvalid())
8832      return ExprError();
8833    E = Result.take();
8834  } else {
8835    // Otherwise, the va_list argument must be an l-value because
8836    // it is modified by va_arg.
8837    if (!E->isTypeDependent() &&
8838        CheckForModifiableLvalue(E, BuiltinLoc, *this))
8839      return ExprError();
8840  }
8841
8842  if (!E->isTypeDependent() &&
8843      !Context.hasSameType(VaListType, E->getType())) {
8844    return ExprError(Diag(E->getLocStart(),
8845                         diag::err_first_argument_to_va_arg_not_of_type_va_list)
8846      << OrigExpr->getType() << E->getSourceRange());
8847  }
8848
8849  if (!TInfo->getType()->isDependentType()) {
8850    if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8851          PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8852          << TInfo->getTypeLoc().getSourceRange()))
8853      return ExprError();
8854
8855    if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8856          TInfo->getType(),
8857          PDiag(diag::err_second_parameter_to_va_arg_abstract)
8858          << TInfo->getTypeLoc().getSourceRange()))
8859      return ExprError();
8860
8861    if (!TInfo->getType().isPODType(Context)) {
8862      Diag(TInfo->getTypeLoc().getBeginLoc(),
8863           TInfo->getType()->isObjCLifetimeType()
8864             ? diag::warn_second_parameter_to_va_arg_ownership_qualified
8865             : diag::warn_second_parameter_to_va_arg_not_pod)
8866        << TInfo->getType()
8867        << TInfo->getTypeLoc().getSourceRange();
8868    }
8869
8870    // Check for va_arg where arguments of the given type will be promoted
8871    // (i.e. this va_arg is guaranteed to have undefined behavior).
8872    QualType PromoteType;
8873    if (TInfo->getType()->isPromotableIntegerType()) {
8874      PromoteType = Context.getPromotedIntegerType(TInfo->getType());
8875      if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
8876        PromoteType = QualType();
8877    }
8878    if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
8879      PromoteType = Context.DoubleTy;
8880    if (!PromoteType.isNull())
8881      Diag(TInfo->getTypeLoc().getBeginLoc(),
8882          diag::warn_second_parameter_to_va_arg_never_compatible)
8883        << TInfo->getType()
8884        << PromoteType
8885        << TInfo->getTypeLoc().getSourceRange();
8886  }
8887
8888  QualType T = TInfo->getType().getNonLValueExprType(Context);
8889  return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
8890}
8891
8892ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
8893  // The type of __null will be int or long, depending on the size of
8894  // pointers on the target.
8895  QualType Ty;
8896  unsigned pw = Context.getTargetInfo().getPointerWidth(0);
8897  if (pw == Context.getTargetInfo().getIntWidth())
8898    Ty = Context.IntTy;
8899  else if (pw == Context.getTargetInfo().getLongWidth())
8900    Ty = Context.LongTy;
8901  else if (pw == Context.getTargetInfo().getLongLongWidth())
8902    Ty = Context.LongLongTy;
8903  else {
8904    llvm_unreachable("I don't know size of pointer!");
8905  }
8906
8907  return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
8908}
8909
8910static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
8911                                           Expr *SrcExpr, FixItHint &Hint) {
8912  if (!SemaRef.getLangOptions().ObjC1)
8913    return;
8914
8915  const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8916  if (!PT)
8917    return;
8918
8919  // Check if the destination is of type 'id'.
8920  if (!PT->isObjCIdType()) {
8921    // Check if the destination is the 'NSString' interface.
8922    const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8923    if (!ID || !ID->getIdentifier()->isStr("NSString"))
8924      return;
8925  }
8926
8927  // Strip off any parens and casts.
8928  StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
8929  if (!SL || !SL->isAscii())
8930    return;
8931
8932  Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
8933}
8934
8935bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8936                                    SourceLocation Loc,
8937                                    QualType DstType, QualType SrcType,
8938                                    Expr *SrcExpr, AssignmentAction Action,
8939                                    bool *Complained) {
8940  if (Complained)
8941    *Complained = false;
8942
8943  // Decode the result (notice that AST's are still created for extensions).
8944  bool CheckInferredResultType = false;
8945  bool isInvalid = false;
8946  unsigned DiagKind;
8947  FixItHint Hint;
8948  ConversionFixItGenerator ConvHints;
8949  bool MayHaveConvFixit = false;
8950
8951  switch (ConvTy) {
8952  default: llvm_unreachable("Unknown conversion type");
8953  case Compatible: return false;
8954  case PointerToInt:
8955    DiagKind = diag::ext_typecheck_convert_pointer_int;
8956    ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8957    MayHaveConvFixit = true;
8958    break;
8959  case IntToPointer:
8960    DiagKind = diag::ext_typecheck_convert_int_pointer;
8961    ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8962    MayHaveConvFixit = true;
8963    break;
8964  case IncompatiblePointer:
8965    MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
8966    DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
8967    CheckInferredResultType = DstType->isObjCObjectPointerType() &&
8968      SrcType->isObjCObjectPointerType();
8969    if (Hint.isNull() && !CheckInferredResultType) {
8970      ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8971    }
8972    MayHaveConvFixit = true;
8973    break;
8974  case IncompatiblePointerSign:
8975    DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8976    break;
8977  case FunctionVoidPointer:
8978    DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8979    break;
8980  case IncompatiblePointerDiscardsQualifiers: {
8981    // Perform array-to-pointer decay if necessary.
8982    if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
8983
8984    Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
8985    Qualifiers rhq = DstType->getPointeeType().getQualifiers();
8986    if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
8987      DiagKind = diag::err_typecheck_incompatible_address_space;
8988      break;
8989
8990
8991    } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
8992      DiagKind = diag::err_typecheck_incompatible_ownership;
8993      break;
8994    }
8995
8996    llvm_unreachable("unknown error case for discarding qualifiers!");
8997    // fallthrough
8998  }
8999  case CompatiblePointerDiscardsQualifiers:
9000    // If the qualifiers lost were because we were applying the
9001    // (deprecated) C++ conversion from a string literal to a char*
9002    // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
9003    // Ideally, this check would be performed in
9004    // checkPointerTypesForAssignment. However, that would require a
9005    // bit of refactoring (so that the second argument is an
9006    // expression, rather than a type), which should be done as part
9007    // of a larger effort to fix checkPointerTypesForAssignment for
9008    // C++ semantics.
9009    if (getLangOptions().CPlusPlus &&
9010        IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9011      return false;
9012    DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9013    break;
9014  case IncompatibleNestedPointerQualifiers:
9015    DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
9016    break;
9017  case IntToBlockPointer:
9018    DiagKind = diag::err_int_to_block_pointer;
9019    break;
9020  case IncompatibleBlockPointer:
9021    DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
9022    break;
9023  case IncompatibleObjCQualifiedId:
9024    // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
9025    // it can give a more specific diagnostic.
9026    DiagKind = diag::warn_incompatible_qualified_id;
9027    break;
9028  case IncompatibleVectors:
9029    DiagKind = diag::warn_incompatible_vectors;
9030    break;
9031  case IncompatibleObjCWeakRef:
9032    DiagKind = diag::err_arc_weak_unavailable_assign;
9033    break;
9034  case Incompatible:
9035    DiagKind = diag::err_typecheck_convert_incompatible;
9036    ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9037    MayHaveConvFixit = true;
9038    isInvalid = true;
9039    break;
9040  }
9041
9042  QualType FirstType, SecondType;
9043  switch (Action) {
9044  case AA_Assigning:
9045  case AA_Initializing:
9046    // The destination type comes first.
9047    FirstType = DstType;
9048    SecondType = SrcType;
9049    break;
9050
9051  case AA_Returning:
9052  case AA_Passing:
9053  case AA_Converting:
9054  case AA_Sending:
9055  case AA_Casting:
9056    // The source type comes first.
9057    FirstType = SrcType;
9058    SecondType = DstType;
9059    break;
9060  }
9061
9062  PartialDiagnostic FDiag = PDiag(DiagKind);
9063  FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9064
9065  // If we can fix the conversion, suggest the FixIts.
9066  assert(ConvHints.isNull() || Hint.isNull());
9067  if (!ConvHints.isNull()) {
9068    for (llvm::SmallVector<FixItHint, 1>::iterator
9069        HI = ConvHints.Hints.begin(), HE = ConvHints.Hints.end();
9070        HI != HE; ++HI)
9071      FDiag << *HI;
9072  } else {
9073    FDiag << Hint;
9074  }
9075  if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9076
9077  Diag(Loc, FDiag);
9078
9079  if (CheckInferredResultType)
9080    EmitRelatedResultTypeNote(SrcExpr);
9081
9082  if (Complained)
9083    *Complained = true;
9084  return isInvalid;
9085}
9086
9087bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
9088  llvm::APSInt ICEResult;
9089  if (E->isIntegerConstantExpr(ICEResult, Context)) {
9090    if (Result)
9091      *Result = ICEResult;
9092    return false;
9093  }
9094
9095  Expr::EvalResult EvalResult;
9096
9097  if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
9098      EvalResult.HasSideEffects) {
9099    Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9100
9101    if (EvalResult.Diag) {
9102      // We only show the note if it's not the usual "invalid subexpression"
9103      // or if it's actually in a subexpression.
9104      if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9105          E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9106        Diag(EvalResult.DiagLoc, EvalResult.Diag);
9107    }
9108
9109    return true;
9110  }
9111
9112  Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9113    E->getSourceRange();
9114
9115  if (EvalResult.Diag &&
9116      Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9117          != DiagnosticsEngine::Ignored)
9118    Diag(EvalResult.DiagLoc, EvalResult.Diag);
9119
9120  if (Result)
9121    *Result = EvalResult.Val.getInt();
9122  return false;
9123}
9124
9125void
9126Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
9127  ExprEvalContexts.push_back(
9128             ExpressionEvaluationContextRecord(NewContext,
9129                                               ExprTemporaries.size(),
9130                                               ExprNeedsCleanups));
9131  ExprNeedsCleanups = false;
9132}
9133
9134void Sema::PopExpressionEvaluationContext() {
9135  // Pop the current expression evaluation context off the stack.
9136  ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9137  ExprEvalContexts.pop_back();
9138
9139  if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9140    if (Rec.PotentiallyReferenced) {
9141      // Mark any remaining declarations in the current position of the stack
9142      // as "referenced". If they were not meant to be referenced, semantic
9143      // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
9144      for (PotentiallyReferencedDecls::iterator
9145             I = Rec.PotentiallyReferenced->begin(),
9146             IEnd = Rec.PotentiallyReferenced->end();
9147           I != IEnd; ++I)
9148        MarkDeclarationReferenced(I->first, I->second);
9149    }
9150
9151    if (Rec.PotentiallyDiagnosed) {
9152      // Emit any pending diagnostics.
9153      for (PotentiallyEmittedDiagnostics::iterator
9154                I = Rec.PotentiallyDiagnosed->begin(),
9155             IEnd = Rec.PotentiallyDiagnosed->end();
9156           I != IEnd; ++I)
9157        Diag(I->first, I->second);
9158    }
9159  }
9160
9161  // When are coming out of an unevaluated context, clear out any
9162  // temporaries that we may have created as part of the evaluation of
9163  // the expression in that context: they aren't relevant because they
9164  // will never be constructed.
9165  if (Rec.Context == Unevaluated) {
9166    ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9167                          ExprTemporaries.end());
9168    ExprNeedsCleanups = Rec.ParentNeedsCleanups;
9169
9170  // Otherwise, merge the contexts together.
9171  } else {
9172    ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
9173  }
9174
9175  // Destroy the popped expression evaluation record.
9176  Rec.Destroy();
9177}
9178
9179void Sema::DiscardCleanupsInEvaluationContext() {
9180  ExprTemporaries.erase(
9181              ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
9182              ExprTemporaries.end());
9183  ExprNeedsCleanups = false;
9184}
9185
9186/// \brief Note that the given declaration was referenced in the source code.
9187///
9188/// This routine should be invoke whenever a given declaration is referenced
9189/// in the source code, and where that reference occurred. If this declaration
9190/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9191/// C99 6.9p3), then the declaration will be marked as used.
9192///
9193/// \param Loc the location where the declaration was referenced.
9194///
9195/// \param D the declaration that has been referenced by the source code.
9196void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9197  assert(D && "No declaration?");
9198
9199  D->setReferenced();
9200
9201  if (D->isUsed(false))
9202    return;
9203
9204  // Mark a parameter or variable declaration "used", regardless of whether
9205  // we're in a template or not. The reason for this is that unevaluated
9206  // expressions (e.g. (void)sizeof()) constitute a use for warning purposes
9207  // (-Wunused-variables and -Wunused-parameters)
9208  if (isa<ParmVarDecl>(D) ||
9209      (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
9210    D->setUsed();
9211    return;
9212  }
9213
9214  if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9215    return;
9216
9217  // Do not mark anything as "used" within a dependent context; wait for
9218  // an instantiation.
9219  if (CurContext->isDependentContext())
9220    return;
9221
9222  switch (ExprEvalContexts.back().Context) {
9223    case Unevaluated:
9224      // We are in an expression that is not potentially evaluated; do nothing.
9225      return;
9226
9227    case PotentiallyEvaluated:
9228      // We are in a potentially-evaluated expression, so this declaration is
9229      // "used"; handle this below.
9230      break;
9231
9232    case PotentiallyPotentiallyEvaluated:
9233      // We are in an expression that may be potentially evaluated; queue this
9234      // declaration reference until we know whether the expression is
9235      // potentially evaluated.
9236      ExprEvalContexts.back().addReferencedDecl(Loc, D);
9237      return;
9238
9239    case PotentiallyEvaluatedIfUsed:
9240      // Referenced declarations will only be used if the construct in the
9241      // containing expression is used.
9242      return;
9243  }
9244
9245  // Note that this declaration has been used.
9246  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
9247    if (Constructor->isDefaulted()) {
9248      if (Constructor->isDefaultConstructor()) {
9249        if (Constructor->isTrivial())
9250          return;
9251        if (!Constructor->isUsed(false))
9252          DefineImplicitDefaultConstructor(Loc, Constructor);
9253      } else if (Constructor->isCopyConstructor()) {
9254        if (!Constructor->isUsed(false))
9255          DefineImplicitCopyConstructor(Loc, Constructor);
9256      } else if (Constructor->isMoveConstructor()) {
9257        if (!Constructor->isUsed(false))
9258          DefineImplicitMoveConstructor(Loc, Constructor);
9259      }
9260    }
9261
9262    MarkVTableUsed(Loc, Constructor->getParent());
9263  } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
9264    if (Destructor->isDefaulted() && !Destructor->isUsed(false))
9265      DefineImplicitDestructor(Loc, Destructor);
9266    if (Destructor->isVirtual())
9267      MarkVTableUsed(Loc, Destructor->getParent());
9268  } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
9269    if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
9270        MethodDecl->getOverloadedOperator() == OO_Equal) {
9271      if (!MethodDecl->isUsed(false)) {
9272        if (MethodDecl->isCopyAssignmentOperator())
9273          DefineImplicitCopyAssignment(Loc, MethodDecl);
9274        else
9275          DefineImplicitMoveAssignment(Loc, MethodDecl);
9276      }
9277    } else if (MethodDecl->isVirtual())
9278      MarkVTableUsed(Loc, MethodDecl->getParent());
9279  }
9280  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
9281    // Recursive functions should be marked when used from another function.
9282    if (CurContext == Function) return;
9283
9284    // Implicit instantiation of function templates and member functions of
9285    // class templates.
9286    if (Function->isImplicitlyInstantiable()) {
9287      bool AlreadyInstantiated = false;
9288      if (FunctionTemplateSpecializationInfo *SpecInfo
9289                                = Function->getTemplateSpecializationInfo()) {
9290        if (SpecInfo->getPointOfInstantiation().isInvalid())
9291          SpecInfo->setPointOfInstantiation(Loc);
9292        else if (SpecInfo->getTemplateSpecializationKind()
9293                   == TSK_ImplicitInstantiation)
9294          AlreadyInstantiated = true;
9295      } else if (MemberSpecializationInfo *MSInfo
9296                                  = Function->getMemberSpecializationInfo()) {
9297        if (MSInfo->getPointOfInstantiation().isInvalid())
9298          MSInfo->setPointOfInstantiation(Loc);
9299        else if (MSInfo->getTemplateSpecializationKind()
9300                   == TSK_ImplicitInstantiation)
9301          AlreadyInstantiated = true;
9302      }
9303
9304      if (!AlreadyInstantiated) {
9305        if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9306            cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9307          PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9308                                                                      Loc));
9309        else
9310          PendingInstantiations.push_back(std::make_pair(Function, Loc));
9311      }
9312    } else {
9313      // Walk redefinitions, as some of them may be instantiable.
9314      for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9315           e(Function->redecls_end()); i != e; ++i) {
9316        if (!i->isUsed(false) && i->isImplicitlyInstantiable())
9317          MarkDeclarationReferenced(Loc, *i);
9318      }
9319    }
9320
9321    // Keep track of used but undefined functions.
9322    if (!Function->isPure() && !Function->hasBody() &&
9323        Function->getLinkage() != ExternalLinkage) {
9324      SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9325      if (old.isInvalid()) old = Loc;
9326    }
9327
9328    Function->setUsed(true);
9329    return;
9330  }
9331
9332  if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
9333    // Implicit instantiation of static data members of class templates.
9334    if (Var->isStaticDataMember() &&
9335        Var->getInstantiatedFromStaticDataMember()) {
9336      MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9337      assert(MSInfo && "Missing member specialization information?");
9338      if (MSInfo->getPointOfInstantiation().isInvalid() &&
9339          MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9340        MSInfo->setPointOfInstantiation(Loc);
9341        // This is a modification of an existing AST node. Notify listeners.
9342        if (ASTMutationListener *L = getASTMutationListener())
9343          L->StaticDataMemberInstantiated(Var);
9344        PendingInstantiations.push_back(std::make_pair(Var, Loc));
9345      }
9346    }
9347
9348    // Keep track of used but undefined variables.  We make a hole in
9349    // the warning for static const data members with in-line
9350    // initializers.
9351    if (Var->hasDefinition() == VarDecl::DeclarationOnly
9352        && Var->getLinkage() != ExternalLinkage
9353        && !(Var->isStaticDataMember() && Var->hasInit())) {
9354      SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9355      if (old.isInvalid()) old = Loc;
9356    }
9357
9358    D->setUsed(true);
9359    return;
9360  }
9361}
9362
9363namespace {
9364  // Mark all of the declarations referenced
9365  // FIXME: Not fully implemented yet! We need to have a better understanding
9366  // of when we're entering
9367  class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9368    Sema &S;
9369    SourceLocation Loc;
9370
9371  public:
9372    typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
9373
9374    MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
9375
9376    bool TraverseTemplateArgument(const TemplateArgument &Arg);
9377    bool TraverseRecordType(RecordType *T);
9378  };
9379}
9380
9381bool MarkReferencedDecls::TraverseTemplateArgument(
9382  const TemplateArgument &Arg) {
9383  if (Arg.getKind() == TemplateArgument::Declaration) {
9384    S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9385  }
9386
9387  return Inherited::TraverseTemplateArgument(Arg);
9388}
9389
9390bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
9391  if (ClassTemplateSpecializationDecl *Spec
9392                  = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9393    const TemplateArgumentList &Args = Spec->getTemplateArgs();
9394    return TraverseTemplateArguments(Args.data(), Args.size());
9395  }
9396
9397  return true;
9398}
9399
9400void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9401  MarkReferencedDecls Marker(*this, Loc);
9402  Marker.TraverseType(Context.getCanonicalType(T));
9403}
9404
9405namespace {
9406  /// \brief Helper class that marks all of the declarations referenced by
9407  /// potentially-evaluated subexpressions as "referenced".
9408  class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9409    Sema &S;
9410
9411  public:
9412    typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9413
9414    explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9415
9416    void VisitDeclRefExpr(DeclRefExpr *E) {
9417      S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9418    }
9419
9420    void VisitMemberExpr(MemberExpr *E) {
9421      S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
9422      Inherited::VisitMemberExpr(E);
9423    }
9424
9425    void VisitCXXNewExpr(CXXNewExpr *E) {
9426      if (E->getConstructor())
9427        S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9428      if (E->getOperatorNew())
9429        S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9430      if (E->getOperatorDelete())
9431        S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
9432      Inherited::VisitCXXNewExpr(E);
9433    }
9434
9435    void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9436      if (E->getOperatorDelete())
9437        S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
9438      QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9439      if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9440        CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9441        S.MarkDeclarationReferenced(E->getLocStart(),
9442                                    S.LookupDestructor(Record));
9443      }
9444
9445      Inherited::VisitCXXDeleteExpr(E);
9446    }
9447
9448    void VisitCXXConstructExpr(CXXConstructExpr *E) {
9449      S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9450      Inherited::VisitCXXConstructExpr(E);
9451    }
9452
9453    void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9454      S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9455    }
9456
9457    void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9458      Visit(E->getExpr());
9459    }
9460  };
9461}
9462
9463/// \brief Mark any declarations that appear within this expression or any
9464/// potentially-evaluated subexpressions as "referenced".
9465void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9466  EvaluatedExprMarker(*this).Visit(E);
9467}
9468
9469/// \brief Emit a diagnostic that describes an effect on the run-time behavior
9470/// of the program being compiled.
9471///
9472/// This routine emits the given diagnostic when the code currently being
9473/// type-checked is "potentially evaluated", meaning that there is a
9474/// possibility that the code will actually be executable. Code in sizeof()
9475/// expressions, code used only during overload resolution, etc., are not
9476/// potentially evaluated. This routine will suppress such diagnostics or,
9477/// in the absolutely nutty case of potentially potentially evaluated
9478/// expressions (C++ typeid), queue the diagnostic to potentially emit it
9479/// later.
9480///
9481/// This routine should be used for all diagnostics that describe the run-time
9482/// behavior of a program, such as passing a non-POD value through an ellipsis.
9483/// Failure to do so will likely result in spurious diagnostics or failures
9484/// during overload resolution or within sizeof/alignof/typeof/typeid.
9485bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
9486                               const PartialDiagnostic &PD) {
9487  switch (ExprEvalContexts.back().Context) {
9488  case Unevaluated:
9489    // The argument will never be evaluated, so don't complain.
9490    break;
9491
9492  case PotentiallyEvaluated:
9493  case PotentiallyEvaluatedIfUsed:
9494    if (Statement && getCurFunctionOrMethodDecl()) {
9495      FunctionScopes.back()->PossiblyUnreachableDiags.
9496        push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
9497    }
9498    else
9499      Diag(Loc, PD);
9500
9501    return true;
9502
9503  case PotentiallyPotentiallyEvaluated:
9504    ExprEvalContexts.back().addDiagnostic(Loc, PD);
9505    break;
9506  }
9507
9508  return false;
9509}
9510
9511bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9512                               CallExpr *CE, FunctionDecl *FD) {
9513  if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9514    return false;
9515
9516  PartialDiagnostic Note =
9517    FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9518    << FD->getDeclName() : PDiag();
9519  SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
9520
9521  if (RequireCompleteType(Loc, ReturnType,
9522                          FD ?
9523                          PDiag(diag::err_call_function_incomplete_return)
9524                            << CE->getSourceRange() << FD->getDeclName() :
9525                          PDiag(diag::err_call_incomplete_return)
9526                            << CE->getSourceRange(),
9527                          std::make_pair(NoteLoc, Note)))
9528    return true;
9529
9530  return false;
9531}
9532
9533// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
9534// will prevent this condition from triggering, which is what we want.
9535void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9536  SourceLocation Loc;
9537
9538  unsigned diagnostic = diag::warn_condition_is_assignment;
9539  bool IsOrAssign = false;
9540
9541  if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
9542    if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
9543      return;
9544
9545    IsOrAssign = Op->getOpcode() == BO_OrAssign;
9546
9547    // Greylist some idioms by putting them into a warning subcategory.
9548    if (ObjCMessageExpr *ME
9549          = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9550      Selector Sel = ME->getSelector();
9551
9552      // self = [<foo> init...]
9553      if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
9554        diagnostic = diag::warn_condition_is_idiomatic_assignment;
9555
9556      // <foo> = [<bar> nextObject]
9557      else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
9558        diagnostic = diag::warn_condition_is_idiomatic_assignment;
9559    }
9560
9561    Loc = Op->getOperatorLoc();
9562  } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
9563    if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
9564      return;
9565
9566    IsOrAssign = Op->getOperator() == OO_PipeEqual;
9567    Loc = Op->getOperatorLoc();
9568  } else {
9569    // Not an assignment.
9570    return;
9571  }
9572
9573  Diag(Loc, diagnostic) << E->getSourceRange();
9574
9575  SourceLocation Open = E->getSourceRange().getBegin();
9576  SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9577  Diag(Loc, diag::note_condition_assign_silence)
9578        << FixItHint::CreateInsertion(Open, "(")
9579        << FixItHint::CreateInsertion(Close, ")");
9580
9581  if (IsOrAssign)
9582    Diag(Loc, diag::note_condition_or_assign_to_comparison)
9583      << FixItHint::CreateReplacement(Loc, "!=");
9584  else
9585    Diag(Loc, diag::note_condition_assign_to_comparison)
9586      << FixItHint::CreateReplacement(Loc, "==");
9587}
9588
9589/// \brief Redundant parentheses over an equality comparison can indicate
9590/// that the user intended an assignment used as condition.
9591void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
9592  // Don't warn if the parens came from a macro.
9593  SourceLocation parenLoc = ParenE->getLocStart();
9594  if (parenLoc.isInvalid() || parenLoc.isMacroID())
9595    return;
9596  // Don't warn for dependent expressions.
9597  if (ParenE->isTypeDependent())
9598    return;
9599
9600  Expr *E = ParenE->IgnoreParens();
9601
9602  if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
9603    if (opE->getOpcode() == BO_EQ &&
9604        opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9605                                                           == Expr::MLV_Valid) {
9606      SourceLocation Loc = opE->getOperatorLoc();
9607
9608      Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
9609      Diag(Loc, diag::note_equality_comparison_silence)
9610        << FixItHint::CreateRemoval(ParenE->getSourceRange().getBegin())
9611        << FixItHint::CreateRemoval(ParenE->getSourceRange().getEnd());
9612      Diag(Loc, diag::note_equality_comparison_to_assign)
9613        << FixItHint::CreateReplacement(Loc, "=");
9614    }
9615}
9616
9617ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
9618  DiagnoseAssignmentAsCondition(E);
9619  if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9620    DiagnoseEqualityWithExtraParens(parenE);
9621
9622  ExprResult result = CheckPlaceholderExpr(E);
9623  if (result.isInvalid()) return ExprError();
9624  E = result.take();
9625
9626  if (!E->isTypeDependent()) {
9627    if (getLangOptions().CPlusPlus)
9628      return CheckCXXBooleanCondition(E); // C++ 6.4p4
9629
9630    ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9631    if (ERes.isInvalid())
9632      return ExprError();
9633    E = ERes.take();
9634
9635    QualType T = E->getType();
9636    if (!T->isScalarType()) { // C99 6.8.4.1p1
9637      Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9638        << T << E->getSourceRange();
9639      return ExprError();
9640    }
9641  }
9642
9643  return Owned(E);
9644}
9645
9646ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9647                                       Expr *SubExpr) {
9648  if (!SubExpr)
9649    return ExprError();
9650
9651  return CheckBooleanCondition(SubExpr, Loc);
9652}
9653
9654namespace {
9655  /// A visitor for rebuilding a call to an __unknown_any expression
9656  /// to have an appropriate type.
9657  struct RebuildUnknownAnyFunction
9658    : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9659
9660    Sema &S;
9661
9662    RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9663
9664    ExprResult VisitStmt(Stmt *S) {
9665      llvm_unreachable("unexpected statement!");
9666      return ExprError();
9667    }
9668
9669    ExprResult VisitExpr(Expr *E) {
9670      S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
9671        << E->getSourceRange();
9672      return ExprError();
9673    }
9674
9675    /// Rebuild an expression which simply semantically wraps another
9676    /// expression which it shares the type and value kind of.
9677    template <class T> ExprResult rebuildSugarExpr(T *E) {
9678      ExprResult SubResult = Visit(E->getSubExpr());
9679      if (SubResult.isInvalid()) return ExprError();
9680
9681      Expr *SubExpr = SubResult.take();
9682      E->setSubExpr(SubExpr);
9683      E->setType(SubExpr->getType());
9684      E->setValueKind(SubExpr->getValueKind());
9685      assert(E->getObjectKind() == OK_Ordinary);
9686      return E;
9687    }
9688
9689    ExprResult VisitParenExpr(ParenExpr *E) {
9690      return rebuildSugarExpr(E);
9691    }
9692
9693    ExprResult VisitUnaryExtension(UnaryOperator *E) {
9694      return rebuildSugarExpr(E);
9695    }
9696
9697    ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
9698      ExprResult SubResult = Visit(E->getSubExpr());
9699      if (SubResult.isInvalid()) return ExprError();
9700
9701      Expr *SubExpr = SubResult.take();
9702      E->setSubExpr(SubExpr);
9703      E->setType(S.Context.getPointerType(SubExpr->getType()));
9704      assert(E->getValueKind() == VK_RValue);
9705      assert(E->getObjectKind() == OK_Ordinary);
9706      return E;
9707    }
9708
9709    ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
9710      if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
9711
9712      E->setType(VD->getType());
9713
9714      assert(E->getValueKind() == VK_RValue);
9715      if (S.getLangOptions().CPlusPlus &&
9716          !(isa<CXXMethodDecl>(VD) &&
9717            cast<CXXMethodDecl>(VD)->isInstance()))
9718        E->setValueKind(VK_LValue);
9719
9720      return E;
9721    }
9722
9723    ExprResult VisitMemberExpr(MemberExpr *E) {
9724      return resolveDecl(E, E->getMemberDecl());
9725    }
9726
9727    ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
9728      return resolveDecl(E, E->getDecl());
9729    }
9730  };
9731}
9732
9733/// Given a function expression of unknown-any type, try to rebuild it
9734/// to have a function type.
9735static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
9736  ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
9737  if (Result.isInvalid()) return ExprError();
9738  return S.DefaultFunctionArrayConversion(Result.take());
9739}
9740
9741namespace {
9742  /// A visitor for rebuilding an expression of type __unknown_anytype
9743  /// into one which resolves the type directly on the referring
9744  /// expression.  Strict preservation of the original source
9745  /// structure is not a goal.
9746  struct RebuildUnknownAnyExpr
9747    : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
9748
9749    Sema &S;
9750
9751    /// The current destination type.
9752    QualType DestType;
9753
9754    RebuildUnknownAnyExpr(Sema &S, QualType CastType)
9755      : S(S), DestType(CastType) {}
9756
9757    ExprResult VisitStmt(Stmt *S) {
9758      llvm_unreachable("unexpected statement!");
9759      return ExprError();
9760    }
9761
9762    ExprResult VisitExpr(Expr *E) {
9763      S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9764        << E->getSourceRange();
9765      return ExprError();
9766    }
9767
9768    ExprResult VisitCallExpr(CallExpr *E);
9769    ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
9770
9771    /// Rebuild an expression which simply semantically wraps another
9772    /// expression which it shares the type and value kind of.
9773    template <class T> ExprResult rebuildSugarExpr(T *E) {
9774      ExprResult SubResult = Visit(E->getSubExpr());
9775      if (SubResult.isInvalid()) return ExprError();
9776      Expr *SubExpr = SubResult.take();
9777      E->setSubExpr(SubExpr);
9778      E->setType(SubExpr->getType());
9779      E->setValueKind(SubExpr->getValueKind());
9780      assert(E->getObjectKind() == OK_Ordinary);
9781      return E;
9782    }
9783
9784    ExprResult VisitParenExpr(ParenExpr *E) {
9785      return rebuildSugarExpr(E);
9786    }
9787
9788    ExprResult VisitUnaryExtension(UnaryOperator *E) {
9789      return rebuildSugarExpr(E);
9790    }
9791
9792    ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
9793      const PointerType *Ptr = DestType->getAs<PointerType>();
9794      if (!Ptr) {
9795        S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
9796          << E->getSourceRange();
9797        return ExprError();
9798      }
9799      assert(E->getValueKind() == VK_RValue);
9800      assert(E->getObjectKind() == OK_Ordinary);
9801      E->setType(DestType);
9802
9803      // Build the sub-expression as if it were an object of the pointee type.
9804      DestType = Ptr->getPointeeType();
9805      ExprResult SubResult = Visit(E->getSubExpr());
9806      if (SubResult.isInvalid()) return ExprError();
9807      E->setSubExpr(SubResult.take());
9808      return E;
9809    }
9810
9811    ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
9812
9813    ExprResult resolveDecl(Expr *E, ValueDecl *VD);
9814
9815    ExprResult VisitMemberExpr(MemberExpr *E) {
9816      return resolveDecl(E, E->getMemberDecl());
9817    }
9818
9819    ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
9820      return resolveDecl(E, E->getDecl());
9821    }
9822  };
9823}
9824
9825/// Rebuilds a call expression which yielded __unknown_anytype.
9826ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
9827  Expr *CalleeExpr = E->getCallee();
9828
9829  enum FnKind {
9830    FK_MemberFunction,
9831    FK_FunctionPointer,
9832    FK_BlockPointer
9833  };
9834
9835  FnKind Kind;
9836  QualType CalleeType = CalleeExpr->getType();
9837  if (CalleeType == S.Context.BoundMemberTy) {
9838    assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
9839    Kind = FK_MemberFunction;
9840    CalleeType = Expr::findBoundMemberType(CalleeExpr);
9841  } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
9842    CalleeType = Ptr->getPointeeType();
9843    Kind = FK_FunctionPointer;
9844  } else {
9845    CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
9846    Kind = FK_BlockPointer;
9847  }
9848  const FunctionType *FnType = CalleeType->castAs<FunctionType>();
9849
9850  // Verify that this is a legal result type of a function.
9851  if (DestType->isArrayType() || DestType->isFunctionType()) {
9852    unsigned diagID = diag::err_func_returning_array_function;
9853    if (Kind == FK_BlockPointer)
9854      diagID = diag::err_block_returning_array_function;
9855
9856    S.Diag(E->getExprLoc(), diagID)
9857      << DestType->isFunctionType() << DestType;
9858    return ExprError();
9859  }
9860
9861  // Otherwise, go ahead and set DestType as the call's result.
9862  E->setType(DestType.getNonLValueExprType(S.Context));
9863  E->setValueKind(Expr::getValueKindForType(DestType));
9864  assert(E->getObjectKind() == OK_Ordinary);
9865
9866  // Rebuild the function type, replacing the result type with DestType.
9867  if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
9868    DestType = S.Context.getFunctionType(DestType,
9869                                         Proto->arg_type_begin(),
9870                                         Proto->getNumArgs(),
9871                                         Proto->getExtProtoInfo());
9872  else
9873    DestType = S.Context.getFunctionNoProtoType(DestType,
9874                                                FnType->getExtInfo());
9875
9876  // Rebuild the appropriate pointer-to-function type.
9877  switch (Kind) {
9878  case FK_MemberFunction:
9879    // Nothing to do.
9880    break;
9881
9882  case FK_FunctionPointer:
9883    DestType = S.Context.getPointerType(DestType);
9884    break;
9885
9886  case FK_BlockPointer:
9887    DestType = S.Context.getBlockPointerType(DestType);
9888    break;
9889  }
9890
9891  // Finally, we can recurse.
9892  ExprResult CalleeResult = Visit(CalleeExpr);
9893  if (!CalleeResult.isUsable()) return ExprError();
9894  E->setCallee(CalleeResult.take());
9895
9896  // Bind a temporary if necessary.
9897  return S.MaybeBindToTemporary(E);
9898}
9899
9900ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
9901  // Verify that this is a legal result type of a call.
9902  if (DestType->isArrayType() || DestType->isFunctionType()) {
9903    S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
9904      << DestType->isFunctionType() << DestType;
9905    return ExprError();
9906  }
9907
9908  // Rewrite the method result type if available.
9909  if (ObjCMethodDecl *Method = E->getMethodDecl()) {
9910    assert(Method->getResultType() == S.Context.UnknownAnyTy);
9911    Method->setResultType(DestType);
9912  }
9913
9914  // Change the type of the message.
9915  E->setType(DestType.getNonReferenceType());
9916  E->setValueKind(Expr::getValueKindForType(DestType));
9917
9918  return S.MaybeBindToTemporary(E);
9919}
9920
9921ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
9922  // The only case we should ever see here is a function-to-pointer decay.
9923  assert(E->getCastKind() == CK_FunctionToPointerDecay);
9924  assert(E->getValueKind() == VK_RValue);
9925  assert(E->getObjectKind() == OK_Ordinary);
9926
9927  E->setType(DestType);
9928
9929  // Rebuild the sub-expression as the pointee (function) type.
9930  DestType = DestType->castAs<PointerType>()->getPointeeType();
9931
9932  ExprResult Result = Visit(E->getSubExpr());
9933  if (!Result.isUsable()) return ExprError();
9934
9935  E->setSubExpr(Result.take());
9936  return S.Owned(E);
9937}
9938
9939ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
9940  ExprValueKind ValueKind = VK_LValue;
9941  QualType Type = DestType;
9942
9943  // We know how to make this work for certain kinds of decls:
9944
9945  //  - functions
9946  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
9947    if (const PointerType *Ptr = Type->getAs<PointerType>()) {
9948      DestType = Ptr->getPointeeType();
9949      ExprResult Result = resolveDecl(E, VD);
9950      if (Result.isInvalid()) return ExprError();
9951      return S.ImpCastExprToType(Result.take(), Type,
9952                                 CK_FunctionToPointerDecay, VK_RValue);
9953    }
9954
9955    if (!Type->isFunctionType()) {
9956      S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
9957        << VD << E->getSourceRange();
9958      return ExprError();
9959    }
9960
9961    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
9962      if (MD->isInstance()) {
9963        ValueKind = VK_RValue;
9964        Type = S.Context.BoundMemberTy;
9965      }
9966
9967    // Function references aren't l-values in C.
9968    if (!S.getLangOptions().CPlusPlus)
9969      ValueKind = VK_RValue;
9970
9971  //  - variables
9972  } else if (isa<VarDecl>(VD)) {
9973    if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
9974      Type = RefTy->getPointeeType();
9975    } else if (Type->isFunctionType()) {
9976      S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
9977        << VD << E->getSourceRange();
9978      return ExprError();
9979    }
9980
9981  //  - nothing else
9982  } else {
9983    S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
9984      << VD << E->getSourceRange();
9985    return ExprError();
9986  }
9987
9988  VD->setType(DestType);
9989  E->setType(Type);
9990  E->setValueKind(ValueKind);
9991  return S.Owned(E);
9992}
9993
9994/// Check a cast of an unknown-any type.  We intentionally only
9995/// trigger this for C-style casts.
9996ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
9997                                     Expr *CastExpr, CastKind &CastKind,
9998                                     ExprValueKind &VK, CXXCastPath &Path) {
9999  // Rewrite the casted expression from scratch.
10000  ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
10001  if (!result.isUsable()) return ExprError();
10002
10003  CastExpr = result.take();
10004  VK = CastExpr->getValueKind();
10005  CastKind = CK_NoOp;
10006
10007  return CastExpr;
10008}
10009
10010static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
10011  Expr *orig = E;
10012  unsigned diagID = diag::err_uncasted_use_of_unknown_any;
10013  while (true) {
10014    E = E->IgnoreParenImpCasts();
10015    if (CallExpr *call = dyn_cast<CallExpr>(E)) {
10016      E = call->getCallee();
10017      diagID = diag::err_uncasted_call_of_unknown_any;
10018    } else {
10019      break;
10020    }
10021  }
10022
10023  SourceLocation loc;
10024  NamedDecl *d;
10025  if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
10026    loc = ref->getLocation();
10027    d = ref->getDecl();
10028  } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
10029    loc = mem->getMemberLoc();
10030    d = mem->getMemberDecl();
10031  } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
10032    diagID = diag::err_uncasted_call_of_unknown_any;
10033    loc = msg->getSelectorStartLoc();
10034    d = msg->getMethodDecl();
10035    if (!d) {
10036      S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
10037        << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
10038        << orig->getSourceRange();
10039      return ExprError();
10040    }
10041  } else {
10042    S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10043      << E->getSourceRange();
10044    return ExprError();
10045  }
10046
10047  S.Diag(loc, diagID) << d << orig->getSourceRange();
10048
10049  // Never recoverable.
10050  return ExprError();
10051}
10052
10053/// Check for operands with placeholder types and complain if found.
10054/// Returns true if there was an error and no recovery was possible.
10055ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
10056  const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
10057  if (!placeholderType) return Owned(E);
10058
10059  switch (placeholderType->getKind()) {
10060
10061  // Overloaded expressions.
10062  case BuiltinType::Overload: {
10063    // Try to resolve a single function template specialization.
10064    // This is obligatory.
10065    ExprResult result = Owned(E);
10066    if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
10067      return result;
10068
10069    // If that failed, try to recover with a call.
10070    } else {
10071      tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
10072                           /*complain*/ true);
10073      return result;
10074    }
10075  }
10076
10077  // Bound member functions.
10078  case BuiltinType::BoundMember: {
10079    ExprResult result = Owned(E);
10080    tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
10081                         /*complain*/ true);
10082    return result;
10083  }
10084
10085  // ARC unbridged casts.
10086  case BuiltinType::ARCUnbridgedCast: {
10087    Expr *realCast = stripARCUnbridgedCast(E);
10088    diagnoseARCUnbridgedCast(realCast);
10089    return Owned(realCast);
10090  }
10091
10092  // Expressions of unknown type.
10093  case BuiltinType::UnknownAny:
10094    return diagnoseUnknownAnyExpr(*this, E);
10095
10096  // Pseudo-objects.
10097  case BuiltinType::PseudoObject:
10098    return checkPseudoObjectRValue(E);
10099
10100  // Everything else should be impossible.
10101#define BUILTIN_TYPE(Id, SingletonId) \
10102  case BuiltinType::Id:
10103#define PLACEHOLDER_TYPE(Id, SingletonId)
10104#include "clang/AST/BuiltinTypes.def"
10105    break;
10106  }
10107
10108  llvm_unreachable("invalid placeholder type!");
10109}
10110
10111bool Sema::CheckCaseExpression(Expr *E) {
10112  if (E->isTypeDependent())
10113    return true;
10114  if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
10115    return E->getType()->isIntegralOrEnumerationType();
10116  return false;
10117}
10118