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