1 //===-- Support/Casting.h - Allow flexible, checked, casts -------*- C++ -*--=//
3 // This file defines the isa<X>(), cast<X>(), dyn_cast<X>(), cast_or_null<X>(),
4 // and dyn_cast_or_null<X>() templates.
6 //===----------------------------------------------------------------------===//
8 #ifndef SUPPORT_CASTING_H
9 #define SUPPORT_CASTING_H
11 // real_type - Provide a macro to get the real type of a value that might be
12 // a use. This provides a typedef 'Type' that is the argument type for all
13 // non UseTy types, and is the contained pointer type of the use if it is a
16 template <class X> class real_type { typedef X Type; };
18 //===----------------------------------------------------------------------===//
19 // Type Checking Templates
20 //===----------------------------------------------------------------------===//
22 // isa<X> - Return true if the parameter to the template is an instance of the
23 // template type argument. Used like this:
25 // if (isa<Type>(myVal)) { ... }
27 template <class X, class Y>
28 inline bool isa(Y Val) {
29 assert(Val && "isa<Ty>(NULL) invoked!");
30 return X::classof(Val);
34 // cast<X> - Return the argument parameter cast to the specified type. This
35 // casting operator asserts that the type is correct, so it does not return null
36 // on failure. But it will correctly return NULL when the input is NULL.
39 // cast< Instruction>(myVal)->getParent()
40 // cast<const Instruction>(myVal)->getParent()
42 template <class X, class Y>
43 inline X *cast(Y Val) {
44 assert(isa<X>(Val) && "cast<Ty>() argument of uncompatible type!");
45 return (X*)(real_type<Y>::Type)Val;
48 // cast_or_null<X> - Functionally identical to cast, except that a null value is
51 template <class X, class Y>
52 inline X *cast_or_null(Y Val) {
53 assert((Val == 0 || isa<X>(Val)) &&
54 "cast_or_null<Ty>() argument of uncompatible type!");
55 return (X*)(real_type<Y>::Type)Val;
59 // dyn_cast<X> - Return the argument parameter cast to the specified type. This
60 // casting operator returns null if the argument is of the wrong type, so it can
61 // be used to test for a type as well as cast if successful. This should be
62 // used in the context of an if statement like this:
64 // if (const Instruction *I = dyn_cast<const Instruction>(myVal)) { ... }
67 template <class X, class Y>
68 inline X *dyn_cast(Y Val) {
69 return isa<X>(Val) ? cast<X>(Val) : 0;
72 // dyn_cast_or_null<X> - Functionally identical to dyn_cast, except that a null
75 template <class X, class Y>
76 inline X *dyn_cast_or_null(Y Val) {
77 return (Val && isa<X>(Val)) ? cast<X>(Val) : 0;