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