Ownership.h revision 686775deca8b8685eb90801495880e3abdd844c2
1//===--- Ownership.h - Parser ownership helpers -----------------*- C++ -*-===//
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 contains classes for managing ownership of Stmt and Expr nodes.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SEMA_OWNERSHIP_H
15#define LLVM_CLANG_SEMA_OWNERSHIP_H
16
17#include "clang/Basic/LLVM.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/PointerIntPair.h"
20
21//===----------------------------------------------------------------------===//
22// OpaquePtr
23//===----------------------------------------------------------------------===//
24
25namespace clang {
26  class Attr;
27  class CXXCtorInitializer;
28  class CXXBaseSpecifier;
29  class Decl;
30  class DeclGroupRef;
31  class Expr;
32  class NestedNameSpecifier;
33  class QualType;
34  class Sema;
35  class Stmt;
36  class TemplateName;
37  class TemplateParameterList;
38
39  /// OpaquePtr - This is a very simple POD type that wraps a pointer that the
40  /// Parser doesn't know about but that Sema or another client does.  The UID
41  /// template argument is used to make sure that "Decl" pointers are not
42  /// compatible with "Type" pointers for example.
43  template <class PtrTy>
44  class OpaquePtr {
45    void *Ptr;
46    explicit OpaquePtr(void *Ptr) : Ptr(Ptr) {}
47
48    typedef llvm::PointerLikeTypeTraits<PtrTy> Traits;
49
50  public:
51    OpaquePtr() : Ptr(0) {}
52
53    static OpaquePtr make(PtrTy P) { OpaquePtr OP; OP.set(P); return OP; }
54
55    template <typename T> T* getAs() const {
56      return get();
57    }
58
59    template <typename T> T getAsVal() const {
60      return get();
61    }
62
63    PtrTy get() const {
64      return Traits::getFromVoidPointer(Ptr);
65    }
66
67    void set(PtrTy P) {
68      Ptr = Traits::getAsVoidPointer(P);
69    }
70
71    operator bool() const { return Ptr != 0; }
72
73    void *getAsOpaquePtr() const { return Ptr; }
74    static OpaquePtr getFromOpaquePtr(void *P) { return OpaquePtr(P); }
75  };
76
77  /// UnionOpaquePtr - A version of OpaquePtr suitable for membership
78  /// in a union.
79  template <class T> struct UnionOpaquePtr {
80    void *Ptr;
81
82    static UnionOpaquePtr make(OpaquePtr<T> P) {
83      UnionOpaquePtr OP = { P.getAsOpaquePtr() };
84      return OP;
85    }
86
87    OpaquePtr<T> get() const { return OpaquePtr<T>::getFromOpaquePtr(Ptr); }
88    operator OpaquePtr<T>() const { return get(); }
89
90    UnionOpaquePtr &operator=(OpaquePtr<T> P) {
91      Ptr = P.getAsOpaquePtr();
92      return *this;
93    }
94  };
95}
96
97namespace llvm {
98  template <class T>
99  class PointerLikeTypeTraits<clang::OpaquePtr<T> > {
100  public:
101    static inline void *getAsVoidPointer(clang::OpaquePtr<T> P) {
102      // FIXME: Doesn't work? return P.getAs< void >();
103      return P.getAsOpaquePtr();
104    }
105    static inline clang::OpaquePtr<T> getFromVoidPointer(void *P) {
106      return clang::OpaquePtr<T>::getFromOpaquePtr(P);
107    }
108    enum { NumLowBitsAvailable = 0 };
109  };
110
111  template <class T>
112  struct isPodLike<clang::OpaquePtr<T> > { static const bool value = true; };
113}
114
115
116
117// -------------------------- About Move Emulation -------------------------- //
118// The smart pointer classes in this file attempt to emulate move semantics
119// as they appear in C++0x with rvalue references. Since C++03 doesn't have
120// rvalue references, some tricks are needed to get similar results.
121// Move semantics in C++0x have the following properties:
122// 1) "Moving" means transferring the value of an object to another object,
123//    similar to copying, but without caring what happens to the old object.
124//    In particular, this means that the new object can steal the old object's
125//    resources instead of creating a copy.
126// 2) Since moving can modify the source object, it must either be explicitly
127//    requested by the user, or the modifications must be unnoticeable.
128// 3) As such, C++0x moving is only allowed in three contexts:
129//    * By explicitly using std::move() to request it.
130//    * From a temporary object, since that object cannot be accessed
131//      afterwards anyway, thus making the state unobservable.
132//    * On function return, since the object is not observable afterwards.
133//
134// To sum up: moving from a named object should only be possible with an
135// explicit std::move(), or on function return. Moving from a temporary should
136// be implicitly done. Moving from a const object is forbidden.
137//
138// The emulation is not perfect, and has the following shortcomings:
139// * move() is not in namespace std.
140// * move() is required on function return.
141// * There are difficulties with implicit conversions.
142// * Microsoft's compiler must be given the /Za switch to successfully compile.
143//
144// -------------------------- Implementation -------------------------------- //
145// The move emulation relies on the peculiar reference binding semantics of
146// C++03: as a rule, a non-const reference may not bind to a temporary object,
147// except for the implicit object parameter in a member function call, which
148// can refer to a temporary even when not being const.
149// The moveable object has five important functions to facilitate moving:
150// * A private, unimplemented constructor taking a non-const reference to its
151//   own class. This constructor serves a two-fold purpose.
152//   - It prevents the creation of a copy constructor that takes a const
153//     reference. Temporaries would be able to bind to the argument of such a
154//     constructor, and that would be bad.
155//   - Named objects will bind to the non-const reference, but since it's
156//     private, this will fail to compile. This prevents implicit moving from
157//     named objects.
158//   There's also a copy assignment operator for the same purpose.
159// * An implicit, non-const conversion operator to a special mover type. This
160//   type represents the rvalue reference of C++0x. Being a non-const member,
161//   its implicit this parameter can bind to temporaries.
162// * A constructor that takes an object of this mover type. This constructor
163//   performs the actual move operation. There is an equivalent assignment
164//   operator.
165// There is also a free move() function that takes a non-const reference to
166// an object and returns a temporary. Internally, this function uses explicit
167// constructor calls to move the value from the referenced object to the return
168// value.
169//
170// There are now three possible scenarios of use.
171// * Copying from a const object. Constructor overload resolution will find the
172//   non-const copy constructor, and the move constructor. The first is not
173//   viable because the const object cannot be bound to the non-const reference.
174//   The second fails because the conversion to the mover object is non-const.
175//   Moving from a const object fails as intended.
176// * Copying from a named object. Constructor overload resolution will select
177//   the non-const copy constructor, but fail as intended, because this
178//   constructor is private.
179// * Copying from a temporary. Constructor overload resolution cannot select
180//   the non-const copy constructor, because the temporary cannot be bound to
181//   the non-const reference. It thus selects the move constructor. The
182//   temporary can be bound to the implicit this parameter of the conversion
183//   operator, because of the special binding rule. Construction succeeds.
184//   Note that the Microsoft compiler, as an extension, allows binding
185//   temporaries against non-const references. The compiler thus selects the
186//   non-const copy constructor and fails, because the constructor is private.
187//   Passing /Za (disable extensions) disables this behaviour.
188// The free move() function is used to move from a named object.
189//
190// Note that when passing an object of a different type (the classes below
191// have OwningResult and OwningPtr, which should be mixable), you get a problem.
192// Argument passing and function return use copy initialization rules. The
193// effect of this is that, when the source object is not already of the target
194// type, the compiler will first seek a way to convert the source object to the
195// target type, and only then attempt to copy the resulting object. This means
196// that when passing an OwningResult where an OwningPtr is expected, the
197// compiler will first seek a conversion from OwningResult to OwningPtr, then
198// copy the OwningPtr. The resulting conversion sequence is:
199// OwningResult object -> ResultMover -> OwningResult argument to
200// OwningPtr(OwningResult) -> OwningPtr -> PtrMover -> final OwningPtr
201// This conversion sequence is too complex to be allowed. Thus the special
202// move_* functions, which help the compiler out with some explicit
203// conversions.
204
205namespace clang {
206  // Basic
207  class DiagnosticBuilder;
208
209  // Determines whether the low bit of the result pointer for the
210  // given UID is always zero. If so, ActionResult will use that bit
211  // for it's "invalid" flag.
212  template<class Ptr>
213  struct IsResultPtrLowBitFree {
214    static const bool value = false;
215  };
216
217  /// ActionResult - This structure is used while parsing/acting on
218  /// expressions, stmts, etc.  It encapsulates both the object returned by
219  /// the action, plus a sense of whether or not it is valid.
220  /// When CompressInvalid is true, the "invalid" flag will be
221  /// stored in the low bit of the Val pointer.
222  template<class PtrTy,
223           bool CompressInvalid = IsResultPtrLowBitFree<PtrTy>::value>
224  class ActionResult {
225    PtrTy Val;
226    bool Invalid;
227
228  public:
229    ActionResult(bool Invalid = false)
230      : Val(PtrTy()), Invalid(Invalid) {}
231    ActionResult(PtrTy val) : Val(val), Invalid(false) {}
232    ActionResult(const DiagnosticBuilder &) : Val(PtrTy()), Invalid(true) {}
233
234    // These two overloads prevent void* -> bool conversions.
235    ActionResult(const void *);
236    ActionResult(volatile void *);
237
238    bool isInvalid() const { return Invalid; }
239    bool isUsable() const { return !Invalid && Val; }
240
241    PtrTy get() const { return Val; }
242    PtrTy release() const { return Val; }
243    PtrTy take() const { return Val; }
244    template <typename T> T *takeAs() { return static_cast<T*>(get()); }
245
246    void set(PtrTy V) { Val = V; }
247
248    const ActionResult &operator=(PtrTy RHS) {
249      Val = RHS;
250      Invalid = false;
251      return *this;
252    }
253  };
254
255  // This ActionResult partial specialization places the "invalid"
256  // flag into the low bit of the pointer.
257  template<typename PtrTy>
258  class ActionResult<PtrTy, true> {
259    // A pointer whose low bit is 1 if this result is invalid, 0
260    // otherwise.
261    uintptr_t PtrWithInvalid;
262    typedef llvm::PointerLikeTypeTraits<PtrTy> PtrTraits;
263  public:
264    ActionResult(bool Invalid = false)
265      : PtrWithInvalid(static_cast<uintptr_t>(Invalid)) { }
266
267    ActionResult(PtrTy V) {
268      void *VP = PtrTraits::getAsVoidPointer(V);
269      PtrWithInvalid = reinterpret_cast<uintptr_t>(VP);
270      assert((PtrWithInvalid & 0x01) == 0 && "Badly aligned pointer");
271    }
272    ActionResult(const DiagnosticBuilder &) : PtrWithInvalid(0x01) { }
273
274    // These two overloads prevent void* -> bool conversions.
275    ActionResult(const void *);
276    ActionResult(volatile void *);
277
278    bool isInvalid() const { return PtrWithInvalid & 0x01; }
279    bool isUsable() const { return PtrWithInvalid > 0x01; }
280
281    PtrTy get() const {
282      void *VP = reinterpret_cast<void *>(PtrWithInvalid & ~0x01);
283      return PtrTraits::getFromVoidPointer(VP);
284    }
285    PtrTy take() const { return get(); }
286    PtrTy release() const { return get(); }
287    template <typename T> T *takeAs() { return static_cast<T*>(get()); }
288
289    void set(PtrTy V) {
290      void *VP = PtrTraits::getAsVoidPointer(V);
291      PtrWithInvalid = reinterpret_cast<uintptr_t>(VP);
292      assert((PtrWithInvalid & 0x01) == 0 && "Badly aligned pointer");
293    }
294
295    const ActionResult &operator=(PtrTy RHS) {
296      void *VP = PtrTraits::getAsVoidPointer(RHS);
297      PtrWithInvalid = reinterpret_cast<uintptr_t>(VP);
298      assert((PtrWithInvalid & 0x01) == 0 && "Badly aligned pointer");
299      return *this;
300    }
301  };
302
303  /// ASTMultiPtr - A moveable smart pointer to multiple AST nodes. Only owns
304  /// the individual pointers, not the array holding them.
305  template <typename PtrTy> class ASTMultiPtr;
306
307  template <class PtrTy>
308  class ASTMultiPtr {
309    PtrTy *Nodes;
310    unsigned Count;
311
312  public:
313    // Normal copying implicitly defined
314    ASTMultiPtr() : Nodes(0), Count(0) {}
315    explicit ASTMultiPtr(Sema &) : Nodes(0), Count(0) {}
316    ASTMultiPtr(Sema &, PtrTy *nodes, unsigned count)
317      : Nodes(nodes), Count(count) {}
318    // Fake mover in Parse/AstGuard.h needs this:
319    ASTMultiPtr(PtrTy *nodes, unsigned count) : Nodes(nodes), Count(count) {}
320
321    /// Access to the raw pointers.
322    PtrTy *get() const { return Nodes; }
323
324    /// Access to the count.
325    unsigned size() const { return Count; }
326
327    PtrTy *release() {
328      return Nodes;
329    }
330  };
331
332  class ParsedTemplateArgument;
333
334  class ASTTemplateArgsPtr {
335    ParsedTemplateArgument *Args;
336    mutable unsigned Count;
337
338  public:
339    ASTTemplateArgsPtr(Sema &actions, ParsedTemplateArgument *args,
340                       unsigned count) :
341      Args(args), Count(count) { }
342
343    // FIXME: Lame, not-fully-type-safe emulation of 'move semantics'.
344    ASTTemplateArgsPtr(ASTTemplateArgsPtr &Other) :
345      Args(Other.Args), Count(Other.Count) {
346    }
347
348    // FIXME: Lame, not-fully-type-safe emulation of 'move semantics'.
349    ASTTemplateArgsPtr& operator=(ASTTemplateArgsPtr &Other)  {
350      Args = Other.Args;
351      Count = Other.Count;
352      return *this;
353    }
354
355    ParsedTemplateArgument *getArgs() const { return Args; }
356    unsigned size() const { return Count; }
357
358    void reset(ParsedTemplateArgument *args, unsigned count) {
359      Args = args;
360      Count = count;
361    }
362
363    const ParsedTemplateArgument &operator[](unsigned Arg) const;
364
365    ParsedTemplateArgument *release() const {
366      return Args;
367    }
368  };
369
370  /// \brief A small vector that owns a set of AST nodes.
371  template <class PtrTy, unsigned N = 8>
372  class ASTOwningVector : public SmallVector<PtrTy, N> {
373    ASTOwningVector(ASTOwningVector &); // do not implement
374    ASTOwningVector &operator=(ASTOwningVector &); // do not implement
375
376  public:
377    explicit ASTOwningVector(Sema &Actions)
378    { }
379
380    PtrTy *take() {
381      return &this->front();
382    }
383
384    template<typename T> T **takeAs() { return reinterpret_cast<T**>(take()); }
385  };
386
387  /// An opaque type for threading parsed type information through the
388  /// parser.
389  typedef OpaquePtr<QualType> ParsedType;
390  typedef UnionOpaquePtr<QualType> UnionParsedType;
391
392  /// A SmallVector of statements, with stack size 32 (as that is the only one
393  /// used.)
394  typedef ASTOwningVector<Stmt*, 32> StmtVector;
395  /// A SmallVector of expressions, with stack size 12 (the maximum used.)
396  typedef ASTOwningVector<Expr*, 12> ExprVector;
397  /// A SmallVector of types.
398  typedef ASTOwningVector<ParsedType, 12> TypeVector;
399
400  template <class T, unsigned N> inline
401  ASTMultiPtr<T> move_arg(ASTOwningVector<T, N> &vec) {
402    return ASTMultiPtr<T>(vec.take(), vec.size());
403  }
404
405  // These versions are hopefully no-ops.
406  template <class T, bool C>
407  inline ActionResult<T,C> move(ActionResult<T,C> &ptr) {
408    return ptr;
409  }
410
411  template <class T> inline
412  ASTMultiPtr<T>& move(ASTMultiPtr<T> &ptr) {
413    return ptr;
414  }
415
416  // We can re-use the low bit of expression, statement, base, and
417  // member-initializer pointers for the "invalid" flag of
418  // ActionResult.
419  template<> struct IsResultPtrLowBitFree<Expr*> {
420    static const bool value = true;
421  };
422  template<> struct IsResultPtrLowBitFree<Stmt*> {
423    static const bool value = true;
424  };
425  template<> struct IsResultPtrLowBitFree<CXXBaseSpecifier*> {
426    static const bool value = true;
427  };
428  template<> struct IsResultPtrLowBitFree<CXXCtorInitializer*> {
429    static const bool value = true;
430  };
431
432  typedef ActionResult<Expr*> ExprResult;
433  typedef ActionResult<Stmt*> StmtResult;
434  typedef ActionResult<ParsedType> TypeResult;
435  typedef ActionResult<CXXBaseSpecifier*> BaseResult;
436  typedef ActionResult<CXXCtorInitializer*> MemInitResult;
437
438  typedef ActionResult<Decl*> DeclResult;
439  typedef OpaquePtr<TemplateName> ParsedTemplateTy;
440
441  inline Expr *move(Expr *E) { return E; }
442  inline Stmt *move(Stmt *S) { return S; }
443
444  typedef ASTMultiPtr<Expr*> MultiExprArg;
445  typedef ASTMultiPtr<Stmt*> MultiStmtArg;
446  typedef ASTMultiPtr<ParsedType> MultiTypeArg;
447  typedef ASTMultiPtr<TemplateParameterList*> MultiTemplateParamsArg;
448
449  inline ExprResult ExprError() { return ExprResult(true); }
450  inline StmtResult StmtError() { return StmtResult(true); }
451
452  inline ExprResult ExprError(const DiagnosticBuilder&) { return ExprError(); }
453  inline StmtResult StmtError(const DiagnosticBuilder&) { return StmtError(); }
454
455  inline ExprResult ExprEmpty() { return ExprResult(false); }
456  inline StmtResult StmtEmpty() { return StmtResult(false); }
457
458  inline Expr *AssertSuccess(ExprResult R) {
459    assert(!R.isInvalid() && "operation was asserted to never fail!");
460    return R.get();
461  }
462
463  inline Stmt *AssertSuccess(StmtResult R) {
464    assert(!R.isInvalid() && "operation was asserted to never fail!");
465    return R.get();
466  }
467}
468
469#endif
470