835a001091553c5f0e946861f585b669c722396f
[oota-llvm.git] / include / llvm / ADT / Tree.h
1 //===- llvm/ADT/Tree.h - Generic n-way tree structure -----------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This class defines a generic N way tree node structure.  The tree structure
11 // is immutable after creation, but the payload contained within it is not.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_ADT_TREE_H
16 #define LLVM_ADT_TREE_H
17
18 #include <vector>
19
20 namespace llvm {
21
22 template<class ConcreteTreeNode, class Payload>
23 class Tree {
24   std::vector<ConcreteTreeNode*> Children;        // This nodes children, if any
25   ConcreteTreeNode              *Parent;          // Parent of this node...
26   Payload                        Data;            // Data held in this node...
27
28 protected:
29   void setChildren(const std::vector<ConcreteTreeNode*> &children) {
30     Children = children;
31   }
32 public:
33   inline Tree(ConcreteTreeNode *parent) : Parent(parent) {}
34   inline Tree(const std::vector<ConcreteTreeNode*> &children,
35               ConcreteTreeNode *par) : Children(children), Parent(par) {}
36
37   inline Tree(const std::vector<ConcreteTreeNode*> &children,
38               ConcreteTreeNode *par, const Payload &data)
39     : Children(children), Parent(par), Data(data) {}
40
41   // Tree dtor - Free all children
42   inline ~Tree() {
43     for (unsigned i = Children.size(); i > 0; --i)
44       delete Children[i-1];
45   }
46
47   // Tree manipulation/walking routines...
48   inline ConcreteTreeNode *getParent() const { return Parent; }
49   inline unsigned getNumChildren() const { return Children.size(); }
50   inline ConcreteTreeNode *getChild(unsigned i) const {
51     assert(i < Children.size() && "Tree::getChild with index out of range!");
52     return Children[i];
53   }
54
55   // Payload access...
56   inline Payload &getTreeData() { return Data; }
57   inline const Payload &getTreeData() const { return Data; }
58 };
59
60 } // End llvm namespace
61
62 #endif