llvm.org GIT mirror llvm / 5eca075
Rename some GC classes so that their roll will hopefully be clearer. In particular, Collector was confusing to implementors. Several thought that this compile-time class was the place to implement their runtime GC heap. Of course, it doesn't even exist at runtime. Specifically, the renames are: Collector -> GCStrategy CollectorMetadata -> GCFunctionInfo CollectorModuleMetadata -> GCModuleInfo CollectorRegistry -> GCRegistry Function::getCollector -> getGC (setGC, hasGC, clearGC) Several accessors and nested types have also been renamed to be consistent. These changes should be obvious. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@54899 91177308-0d34-0410-b5e6-96231b3b80d8 Gordon Henriksen 11 years ago
38 changed file(s) with 549 addition(s) and 703 deletion(s). Raw diff Collapse all Expand all
365365 external function_call_conv : llvalue -> int = "llvm_function_call_conv"
366366 external set_function_call_conv : int -> llvalue -> unit
367367 = "llvm_set_function_call_conv"
368 external collector : llvalue -> string option = "llvm_collector"
369 external set_collector : string option -> llvalue -> unit = "llvm_set_collector"
368 external gc : llvalue -> string option = "llvm_gc"
369 external set_gc : string option -> llvalue -> unit = "llvm_set_gc"
370370 external function_begin : llmodule -> (llmodule, llvalue) llpos
371371 = "llvm_function_begin"
372372 external function_succ : llvalue -> (llmodule, llvalue) llpos
920920 external set_function_call_conv : int -> llvalue -> unit
921921 = "llvm_set_function_call_conv"
922922
923 (** [collector f] returns [Some name] if the function [f] has a garbage
923 (** [gc f] returns [Some name] if the function [f] has a garbage
924924 collection algorithm specified and [None] otherwise.
925 See the method [llvm::Function::getCollector]. *)
926 external collector : llvalue -> string option = "llvm_collector"
927
928 (** [set_collector gc f] sets the collection algorithm for the function [f] to
929 [gc]. See the method [llvm::Function::setCollector]. *)
930 external set_collector : string option -> llvalue -> unit = "llvm_set_collector"
925 See the method [llvm::Function::getGC]. *)
926 external gc : llvalue -> string option = "llvm_gc"
927
928 (** [set_gc gc f] sets the collection algorithm for the function [f] to
929 [gc]. See the method [llvm::Function::setGC]. *)
930 external set_gc : string option -> llvalue -> unit = "llvm_set_gc"
931931
932932
933933 (** {7 Operations on params} *)
642642 }
643643
644644 /* llvalue -> string option */
645 CAMLprim value llvm_collector(LLVMValueRef Fn) {
646 const char *Collector;
645 CAMLprim value llvm_gc(LLVMValueRef Fn) {
646 const char *GC;
647647 CAMLparam0();
648648 CAMLlocal2(Name, Option);
649649
650 if ((Collector = LLVMGetCollector(Fn))) {
651 Name = copy_string(Collector);
650 if ((GC = LLVMGetGC(Fn))) {
651 Name = copy_string(GC);
652652
653653 Option = alloc(1, 0);
654654 Field(Option, 0) = Name;
659659 }
660660
661661 /* string option -> llvalue -> unit */
662 CAMLprim value llvm_set_collector(value GC, LLVMValueRef Fn) {
663 LLVMSetCollector(Fn, GC == Val_int(0)? 0 : String_val(Field(GC, 0)));
662 CAMLprim value llvm_set_gc(value GC, LLVMValueRef Fn) {
663 LLVMSetGC(Fn, GC == Val_int(0)? 0 : String_val(Field(GC, 0)));
664664 return Val_unit;
665665 }
666666
5959 /// MODULE_CODE_PURGEVALS: [numvals]
6060 MODULE_CODE_PURGEVALS = 10,
6161
62 MODULE_CODE_COLLECTORNAME = 11 // COLLECTORNAME: [strchr x N]
62 MODULE_CODE_GCNAME = 11 // GCNAME: [strchr x N]
6363 };
6464
6565 /// PARAMATTR blocks have code for defining a parameter attribute set.
2121 #include
2222
2323 namespace llvm {
24 class Collector;
24 class GCStrategy;
2525 class Constant;
2626 class ConstantArray;
2727 class GCMetadataPrinter;
5252 MachineModuleInfo *MMI;
5353
5454 // GCMetadataPrinters - The garbage collection metadata printer table.
55 typedef DenseMap<Collector*,GCMetadataPrinter*> gcp_map_type;
55 typedef DenseMap<GCStrategy*,GCMetadataPrinter*> gcp_map_type;
5656 typedef gcp_map_type::iterator gcp_iterator;
5757 gcp_map_type GCMetadataPrinters;
5858
365365 void EmitXXStructorList(Constant *List);
366366 void EmitConstantPool(unsigned Alignment, const char *Section,
367367 std::vector > &CP);
368 GCMetadataPrinter *GetOrCreateGCPrinter(Collector *C);
368 GCMetadataPrinter *GetOrCreateGCPrinter(GCStrategy *C);
369369 };
370370 }
371371
+0
-167
include/llvm/CodeGen/GCMedataPrinter.h less more
None //===-- llvm/CodeGen/Collector.h - Garbage collection -----------*- C++ -*-===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Collector records sufficient information about a machine function to enable
10 // accurate garbage collectors. Specifically:
11 //
12 // - Safe points
13 // Garbage collection is only possible at certain points in code. Code
14 // generators should record points:
15 //
16 // - At and after any call to a subroutine
17 // - Before returning from the current function
18 // - Before backwards branches (loops)
19 //
20 // - Roots
21 // When a reference to a GC-allocated object exists on the stack, it must be
22 // stored in an alloca registered with llvm.gcoot.
23 //
24 // This generic information should used by ABI-specific passes to emit support
25 // tables for the runtime garbage collector.
26 //
27 // MachineCodeAnalysis identifies the GC safe points in the machine code. (Roots
28 // are identified in SelectionDAGISel.)
29 //
30 //===----------------------------------------------------------------------===//
31
32 #ifndef LLVM_CODEGEN_COLLECTOR_H
33 #define LLVM_CODEGEN_COLLECTOR_H
34
35 #include "llvm/CodeGen/CollectorMetadata.h"
36 #include
37 #include
38
39 namespace llvm {
40
41 /// Collector describes a garbage collector's code generation requirements,
42 /// and provides overridable hooks for those needs which cannot be abstractly
43 /// described.
44 class Collector {
45 public:
46 typedef std::vector list_type;
47 typedef list_type::iterator iterator;
48
49 private:
50 friend class CollectorModuleMetadata;
51 const Module *M;
52 std::string Name;
53
54 list_type Functions;
55
56 protected:
57 unsigned NeededSafePoints; //< Bitmask of required safe points.
58 bool CustomReadBarriers; //< Default is to insert loads.
59 bool CustomWriteBarriers; //< Default is to insert stores.
60 bool CustomRoots; //< Default is to pass through to backend.
61 bool InitRoots; //< If set, roots are nulled during lowering.
62 bool UsesMetadata; //< If set, backend must emit metadata tables.
63
64 public:
65 Collector();
66
67 virtual ~Collector();
68
69
70 /// getName - The name of the collector, for debugging.
71 ///
72 const std::string &getName() const { return Name; }
73
74 /// getModule - The module upon which the collector is operating.
75 ///
76 const Module &getModule() const { return *M; }
77
78 /// True if this collector requires safe points of any kind. By default,
79 /// none are recorded.
80 bool needsSafePoints() const { return NeededSafePoints != 0; }
81
82 /// True if the collector requires the given kind of safe point. By default,
83 /// none are recorded.
84 bool needsSafePoint(GC::PointKind Kind) const {
85 return (NeededSafePoints & 1 << Kind) != 0;
86 }
87
88 /// By default, write barriers are replaced with simple store instructions.
89 /// If true, then addPassesToCustomLowerIntrinsics must instead process
90 /// them.
91 bool customWriteBarrier() const { return CustomWriteBarriers; }
92
93 /// By default, read barriers are replaced with simple load instructions.
94 /// If true, then addPassesToCustomLowerIntrinsics must instead process
95 /// them.
96 bool customReadBarrier() const { return CustomReadBarriers; }
97
98 /// By default, roots are left for the code generator. If Custom, then
99 /// addPassesToCustomLowerIntrinsics must add passes to delete them.
100 bool customRoots() const { return CustomRoots; }
101
102 /// If set, gcroot intrinsics should initialize their allocas to null. This
103 /// is necessary for most collectors.
104 bool initializeRoots() const { return InitRoots; }
105
106 /// If set, appropriate metadata tables must be emitted by the back-end
107 /// (assembler, JIT, or otherwise).
108 bool usesMetadata() const { return UsesMetadata; }
109
110 /// begin/end - Iterators for function metadata.
111 ///
112 iterator begin() { return Functions.begin(); }
113 iterator end() { return Functions.end(); }
114
115 /// insertFunctionMetadata - Creates metadata for a function.
116 ///
117 CollectorMetadata *insertFunctionMetadata(const Function &F);
118
119 /// initializeCustomLowering/performCustomLowering - If any of the actions
120 /// are set to custom, performCustomLowering must be overriden to create a
121 /// transform to lower those actions to LLVM IR. initializeCustomLowering
122 /// is optional to override. These are the only Collector methods through
123 /// which the LLVM IR can be modified.
124 virtual bool initializeCustomLowering(Module &F);
125 virtual bool performCustomLowering(Function &F);
126 };
127
128 // GCMetadataPrinter - Emits GC metadata as assembly code.
129 class GCMetadataPrinter {
130 public:
131 typedef Collector::list_type list_type;
132 typedef Collector::iterator iterator;
133
134 private:
135 Collector *Coll;
136
137 friend class AsmPrinter;
138
139 protected:
140 // May only be subclassed.
141 GCMetadataPrinter();
142
143 // Do not implement.
144 GCMetadataPrinter(const GCMetadataPrinter &);
145 GCMetadataPrinter &operator=(const GCMetadataPrinter &);
146
147 public:
148 Collector &getCollector() { return *Coll; }
149 const Module &getModule() const { return Coll->getModule(); }
150
151 iterator begin() { return Coll->begin(); }
152 iterator end() { return Coll->end(); }
153
154 /// beginAssembly/finishAssembly - Emit module metadata as assembly code.
155 virtual void beginAssembly(std::ostream &OS, AsmPrinter &AP,
156 const TargetAsmInfo &TAI);
157
158 virtual void finishAssembly(std::ostream &OS, AsmPrinter &AP,
159 const TargetAsmInfo &TAI);
160
161 virtual ~GCMetadataPrinter();
162 };
163
164 }
165
166 #endif
None //===-- CollectorMetadata.h - Garbage collector metadata ------------------===//
0 //===-- GCMetadata.h - Garbage collector metadata -------------------------===//
11 //
22 // The LLVM Compiler Infrastructure
33 //
66 //
77 //===----------------------------------------------------------------------===//
88 //
9 // This file declares the CollectorMetadata and CollectorModuleMetadata classes,
10 // which are used as a communication channel from the target code generator
11 // to the target garbage collectors. This interface allows code generators and
12 // garbage collectors to be developed independently.
9 // This file declares the GCFunctionInfo and GCModuleInfo classes, which are
10 // used as a communication channel from the target code generator to the target
11 // garbage collectors. This interface allows code generators and garbage
12 // collectors to be developed independently.
1313 //
14 // The CollectorMetadata class records the data necessary to build a type
15 // accurate stack map. Roots are specified in the LLVM IR using the llvm.gcroot
16 // intrinsic, which the code generator understands. The code generator records
17 // the stack offset for each GC root. Safe points are generated by the code
18 // generator according to the collector's declared needs (generally at function
19 // calls).
14 // The GCFunctionInfo class logs the data necessary to build a type accurate
15 // stack map. The code generator outputs:
16 //
17 // - Safe points as specified by the GCStrategy's NeededSafePoints.
18 // - Stack offsets for GC roots, as specified by calls to llvm.gcroot
2019 //
21 // Safe points and roots are sufficient to build type-accurate stack maps. As a
22 // refinement, liveness analysis calculates the set of live roots at each safe
23 // point. Liveness analysis is not presently performed, so all roots are assumed
24 // live.
20 // As a refinement, liveness analysis calculates the set of live roots at each
21 // safe point. Liveness analysis is not presently performed by the code
22 // generator, so all roots are assumed live.
2523 //
26 // CollectorModuleMetadata simply collects CollectorMetadata structures for each
27 // Function as it is compiled. This is necessary for collectors which must emit
28 // a stack map for the entire compilation unit. CollectorMetadata outlives the
29 // MachineFunction from which it is derived, so must not refer to any code
30 // generator data structures.
24 // GCModuleInfo simply collects GCFunctionInfo instances for each Function as
25 // they are compiled. This accretion is necessary for collectors which must emit
26 // a stack map for the compilation unit as a whole. Therefore, GCFunctionInfo
27 // outlives the MachineFunction from which it is derived and must not refer to
28 // any code generator data structures.
3129 //
3230 //===----------------------------------------------------------------------===//
3331
34 #ifndef LLVM_CODEGEN_COLLECTORMETADATA_H
35 #define LLVM_CODEGEN_COLLECTORMETADATA_H
32 #ifndef LLVM_CODEGEN_GCMETADATA_H
33 #define LLVM_CODEGEN_GCMETADATA_H
3634
3735 #include "llvm/Pass.h"
3836 #include "llvm/ADT/DenseMap.h"
4139 namespace llvm {
4240
4341 class AsmPrinter;
44 class Collector;
42 class GCStrategy;
4543 class Constant;
4644 class TargetAsmInfo;
4745
7775 };
7876
7977
80 /// CollectorMetadata - Garbage collection metadata for a function.
78 /// GCFunctionInfo - Garbage collection metadata for a single function.
8179 ///
82 class CollectorMetadata {
80 class GCFunctionInfo {
8381 public:
8482 typedef std::vector::iterator iterator;
8583 typedef std::vector::iterator roots_iterator;
8785
8886 private:
8987 const Function &F;
90 Collector &C;
88 GCStrategy &S;
9189 uint64_t FrameSize;
9290 std::vector Roots;
9391 std::vector SafePoints;
103101 // are live per safe point (1.5% on 64-bit hosts).
104102
105103 public:
106 CollectorMetadata(const Function &F, Collector &C);
107 ~CollectorMetadata();
104 GCFunctionInfo(const Function &F, GCStrategy &S);
105 ~GCFunctionInfo();
108106
109107 /// getFunction - Return the function to which this metadata applies.
110108 ///
111109 const Function &getFunction() const { return F; }
112110
113 /// getCollector - Return the collector for the function.
111 /// getStrategy - Return the GC strategy for the function.
114112 ///
115 Collector &getCollector() { return C; }
113 GCStrategy &getStrategy() { return S; }
116114
117115 /// addStackRoot - Registers a root that lives on the stack. Num is the
118 /// stack object ID for the alloca (if the code generator is using
119 /// MachineFrameInfo).
116 /// stack object ID for the alloca (if the code generator is
117 // using MachineFrameInfo).
120118 void addStackRoot(int Num, Constant *Metadata) {
121119 Roots.push_back(GCRoot(Num, Metadata));
122120 }
153151 };
154152
155153
156 /// CollectorModuleMetadata - Garbage collection metadata for a whole module.
154 /// GCModuleInfo - Garbage collection metadata for a whole module.
157155 ///
158 class CollectorModuleMetadata : public ImmutablePass {
159 typedef StringMap collector_map_type;
160 typedef std::vector list_type;
161 typedef DenseMap function_map_type;
156 class GCModuleInfo : public ImmutablePass {
157 typedef StringMap strategy_map_type;
158 typedef std::vector list_type;
159 typedef DenseMap finfo_map_type;
162160
163 collector_map_type NameMap;
164 list_type Collectors;
165 function_map_type Map;
161 strategy_map_type StrategyMap;
162 list_type StrategyList;
163 finfo_map_type FInfoMap;
166164
167 Collector *getOrCreateCollector(const Module *M, const std::string &Name);
165 GCStrategy *getOrCreateStrategy(const Module *M, const std::string &Name);
168166
169167 public:
170168 typedef list_type::const_iterator iterator;
171169
172170 static char ID;
173171
174 CollectorModuleMetadata();
175 ~CollectorModuleMetadata();
172 GCModuleInfo();
173 ~GCModuleInfo();
176174
177 /// clear - Used to delete module metadata. The metadata deleter pass calls
178 /// this.
175 /// clear - Resets the pass. The metadata deleter pass calls this.
176 ///
179177 void clear();
180178
181 /// begin/end - Iterators for collectors.
179 /// begin/end - Iterators for used strategies.
182180 ///
183 iterator begin() const { return Collectors.begin(); }
184 iterator end() const { return Collectors.end(); }
181 iterator begin() const { return StrategyList.begin(); }
182 iterator end() const { return StrategyList.end(); }
185183
186184 /// get - Look up function metadata.
187185 ///
188 CollectorMetadata &get(const Function &F);
186 GCFunctionInfo &getFunctionInfo(const Function &F);
189187 };
190188
191189 }
0 //===-- llvm/CodeGen/GCMetadataPrinter.h - Prints asm GC tables -*- C++ -*-===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // The abstract base class GCMetadataPrinter supports writing GC metadata tables
10 // as assembly code. This is a separate class from GCStrategy in order to allow
11 // users of the LLVM JIT to avoid linking with the AsmWriter.
12 //
13 // Subclasses of GCMetadataPrinter must be registered using the
14 // GCMetadataPrinterRegistry. This is separate from the GCStrategy itself
15 // because these subclasses are logically plugins for the AsmWriter.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #ifndef LLVM_CODEGEN_GCMETADATAPRINTER_H
20 #define LLVM_CODEGEN_GCMETADATAPRINTER_H
21
22 #include "llvm/CodeGen/GCMetadata.h"
23 #include "llvm/CodeGen/GCStrategy.h"
24 #include "llvm/Support/Registry.h"
25 #include
26 #include
27
28 namespace llvm {
29
30 class GCMetadataPrinter;
31
32 /// GCMetadataPrinterRegistry - The GC assembly printer registry uses all the
33 /// defaults from Registry.
34 typedef Registry GCMetadataPrinterRegistry;
35
36 /// GCMetadataPrinter - Emits GC metadata as assembly code.
37 ///
38 class GCMetadataPrinter {
39 public:
40 typedef GCStrategy::list_type list_type;
41 typedef GCStrategy::iterator iterator;
42
43 private:
44 GCStrategy *S;
45
46 friend class AsmPrinter;
47
48 protected:
49 // May only be subclassed.
50 GCMetadataPrinter();
51
52 // Do not implement.
53 GCMetadataPrinter(const GCMetadataPrinter &);
54 GCMetadataPrinter &operator=(const GCMetadataPrinter &);
55
56 public:
57 GCStrategy &getStrategy() { return *S; }
58 const Module &getModule() const { return S->getModule(); }
59
60 /// begin/end - Iterate over the collected function metadata.
61 iterator begin() { return S->begin(); }
62 iterator end() { return S->end(); }
63
64 /// beginAssembly/finishAssembly - Emit module metadata as assembly code.
65 virtual void beginAssembly(std::ostream &OS, AsmPrinter &AP,
66 const TargetAsmInfo &TAI);
67
68 virtual void finishAssembly(std::ostream &OS, AsmPrinter &AP,
69 const TargetAsmInfo &TAI);
70
71 virtual ~GCMetadataPrinter();
72 };
73
74 }
75
76 #endif
None //===-- llvm/CodeGen/Collector.h - Garbage collection -----------*- C++ -*-===//
0 //===-- llvm/CodeGen/GCStrategy.h - Garbage collection ----------*- C++ -*-===//
11 //
22 // The LLVM Compiler Infrastructure
33 //
66 //
77 //===----------------------------------------------------------------------===//
88 //
9 // Collector records sufficient information about a machine function to enable
10 // accurate garbage collectors. Specifically:
9 // GCStrategy coordinates code generation algorithms and implements some itself
10 // in order to generate code compatible with a target code generator as
11 // specified in a function's 'gc' attribute. Algorithms are enabled by setting
12 // flags in a subclass's constructor, and some virtual methods can be
13 // overridden.
14 //
15 // When requested, the GCStrategy will be populated with data about each
16 // function which uses it. Specifically:
1117 //
1218 // - Safe points
13 // Garbage collection is only possible at certain points in code. Code
14 // generators should record points:
19 // Garbage collection is generally only possible at certain points in code.
20 // GCStrategy can request that the collector insert such points:
1521 //
1622 // - At and after any call to a subroutine
1723 // - Before returning from the current function
2127 // When a reference to a GC-allocated object exists on the stack, it must be
2228 // stored in an alloca registered with llvm.gcoot.
2329 //
24 // This generic information should used by ABI-specific passes to emit support
25 // tables for the runtime garbage collector.
26 //
27 // MachineCodeAnalysis identifies the GC safe points in the machine code. (Roots
28 // are identified in SelectionDAGISel.)
30 // This information can used to emit the metadata tables which are required by
31 // the target garbage collector runtime.
2932 //
3033 //===----------------------------------------------------------------------===//
3134
32 #ifndef LLVM_CODEGEN_COLLECTOR_H
33 #define LLVM_CODEGEN_COLLECTOR_H
35 #ifndef LLVM_CODEGEN_GCSTRATEGY_H
36 #define LLVM_CODEGEN_GCSTRATEGY_H
3437
3538 #include "llvm/CodeGen/GCMetadata.h"
39 #include "llvm/Support/Registry.h"
3640 #include
3741 #include
3842
3943 namespace llvm {
4044
41 /// Collector describes a garbage collector's code generation requirements,
42 /// and provides overridable hooks for those needs which cannot be abstractly
43 /// described.
44 class Collector {
45 class GCStrategy;
46
47 /// The GC strategy registry uses all the defaults from Registry.
48 ///
49 typedef Registry GCRegistry;
50
51 /// GCStrategy describes a garbage collector algorithm's code generation
52 /// requirements, and provides overridable hooks for those needs which cannot
53 /// be abstractly described.
54 class GCStrategy {
4555 public:
46 typedef std::vector<CollectorMetadata*> list_type;
56 typedef std::vector<GCFunctionInfo*> list_type;
4757 typedef list_type::iterator iterator;
4858
4959 private:
50 friend class CollectorModuleMetadata;
60 friend class GCModuleInfo;
5161 const Module *M;
5262 std::string Name;
5363
6272 bool UsesMetadata; //< If set, backend must emit metadata tables.
6373
6474 public:
65 Collector();
75 GCStrategy();
6676
67 virtual ~Collector();
77 virtual ~GCStrategy();
6878
6979
70 /// getName - The name of the collector, for debugging.
80 /// getName - The name of the GC strategy, for debugging.
7181 ///
7282 const std::string &getName() const { return Name; }
7383
74 /// getModule - The module upon which the collector is operating.
84 /// getModule - The module within which the GC strategy is operating.
7585 ///
7686 const Module &getModule() const { return *M; }
7787
78 /// True if this collector requires safe points of any kind. By default,
79 /// none are recorded.
88 /// needsSafePoitns - True if safe points of any kind are required. By
89 // default, none are recorded.
8090 bool needsSafePoints() const { return NeededSafePoints != 0; }
8191
82 /// True if the collector requires the given kind of safe point. By default,
83 /// none are recorded.
92 /// needsSafePoint(Kind) - True if the given kind of safe point is
93 // required. By default, none are recorded.
8494 bool needsSafePoint(GC::PointKind Kind) const {
8595 return (NeededSafePoints & 1 << Kind) != 0;
8696 }
8797
88 /// By default, write barriers are replaced with simple store instructions.
89 /// If true, then addPassesToCustomLowerIntrinsics must instead process
90 /// them.
98 /// customWriteBarrier - By default, write barriers are replaced with simple
99 /// store instructions. If true, then
100 /// performCustomLowering must instead lower them.
91101 bool customWriteBarrier() const { return CustomWriteBarriers; }
92102
93 /// By default, read barriers are replaced with simple load instructions.
94 /// If true, then addPassesToCustomLowerIntrinsics must instead process
95 /// them.
103 /// customReadBarrier - By default, read barriers are replaced with simple
104 /// load instructions. If true, then
105 /// performCustomLowering must instead lower them.
96106 bool customReadBarrier() const { return CustomReadBarriers; }
97107
98 /// By default, roots are left for the code generator. If Custom, then
99 /// addPassesToCustomLowerIntrinsics must add passes to delete them.
108 /// customRoots - By default, roots are left for the code generator so it
109 /// can generate a stack map. If true, then
110 // performCustomLowering must delete them.
100111 bool customRoots() const { return CustomRoots; }
101112
102 /// If set, gcroot intrinsics should initialize their allocas to null. This
103 /// is necessary for most collectors.
113 /// initializeRoots - If set, gcroot intrinsics should initialize their
114 // allocas to null before the first use. This is
115 // necessary for most GCs and is enabled by default.
104116 bool initializeRoots() const { return InitRoots; }
105117
106 /// If set, appropriate metadata tables must be emitted by the back-end
107 /// (assembler, JIT, or otherwise).
118 /// usesMetadata - If set, appropriate metadata tables must be emitted by
119 /// the back-end (assembler, JIT, or otherwise).
108120 bool usesMetadata() const { return UsesMetadata; }
109121
110122 /// begin/end - Iterators for function metadata.
114126
115127 /// insertFunctionMetadata - Creates metadata for a function.
116128 ///
117 CollectorMetadata *insertFunctionMetadata(const Function &F);
129 GCFunctionInfo *insertFunctionInfo(const Function &F);
118130
119131 /// initializeCustomLowering/performCustomLowering - If any of the actions
120 /// are set to custom, performCustomLowering must be overriden to create a
121 /// transform to lower those actions to LLVM IR. initializeCustomLowering
122 /// is optional to override. These are the only Collector methods through
132 /// are set to custom, performCustomLowering must be overriden to transform
133 /// the corresponding actions to LLVM IR. initializeCustomLowering is
134 /// optional to override. These are the only GCStrategy methods through
123135 /// which the LLVM IR can be modified.
124136 virtual bool initializeCustomLowering(Module &F);
125137 virtual bool performCustomLowering(Function &F);
126138 };
127139
128 // GCMetadataPrinter - Emits GC metadata as assembly code.
129 class GCMetadataPrinter {
130 public:
131 typedef Collector::list_type list_type;
132 typedef Collector::iterator iterator;
133
134 private:
135 Collector *Coll;
136
137 friend class AsmPrinter;
138
139 protected:
140 // May only be subclassed.
141 GCMetadataPrinter();
142
143 // Do not implement.
144 GCMetadataPrinter(const GCMetadataPrinter &);
145 GCMetadataPrinter &operator=(const GCMetadataPrinter &);
146
147 public:
148 Collector &getCollector() { return *Coll; }
149 const Module &getModule() const { return Coll->getModule(); }
150
151 iterator begin() { return Coll->begin(); }
152 iterator end() { return Coll->end(); }
153
154 /// beginAssembly/finishAssembly - Emit module metadata as assembly code.
155 virtual void beginAssembly(std::ostream &OS, AsmPrinter &AP,
156 const TargetAsmInfo &TAI);
157
158 virtual void finishAssembly(std::ostream &OS, AsmPrinter &AP,
159 const TargetAsmInfo &TAI);
160
161 virtual ~GCMetadataPrinter();
162 };
163
164140 }
165141
166142 #endif
None //===-- Collectors.h - Garbage collector registry -------------------------===//
0 //===-- GCs.h - Garbage collector linkage hacks ---------------------------===//
11 //
22 // The LLVM Compiler Infrastructure
33 //
66 //
77 //===----------------------------------------------------------------------===//
88 //
9 // This file declares the CollectorRegistry class, which is used to discover
10 // pluggable garbage collectors.
9 // This file contains hack functions to force linking in the GC components.
1110 //
1211 //===----------------------------------------------------------------------===//
1312
1413 #ifndef LLVM_CODEGEN_GCS_H
1514 #define LLVM_CODEGEN_GCS_H
1615
17 #include "llvm/Support/Registry.h"
18
1916 namespace llvm {
20
21 class Collector;
17 class GCStrategy;
2218 class GCMetadataPrinter;
23
24 /// The collector registry uses all the defaults from Registry.
25 ///
26 typedef Registry CollectorRegistry;
27
28 /// The GC assembly printer registry uses all the defaults from Registry.
29 ///
30 typedef Registry GCMetadataPrinterRegistry;
3119
3220 /// FIXME: Collector instances are not useful on their own. These no longer
3321 /// serve any purpose except to link in the plugins.
3422
3523 /// Creates an ocaml-compatible garbage collector.
36 Collector *createOcamlCollector();
24 void linkOcamlGC();
3725
3826 /// Creates an ocaml-compatible metadata printer.
39 GCMetadataPrinter *createOcamlMetadataPrinter();
27 void linkOcamlGCPrinter();
4028
4129 /// Creates a shadow stack garbage collector. This collector requires no code
4230 /// generator support.
43 Collector *createShadowStackCollector();
31 void linkShadowStackGC();
4432 }
4533
4634 #endif
1919 namespace {
2020 struct ForceAsmWriterLinking {
2121 ForceAsmWriterLinking() {
22 // We must reference the passes in such a way that compilers will not
22 // We must reference the plug-ins in such a way that compilers will not
2323 // delete it all as dead code, even with whole program optimization,
2424 // yet is effectively a NO-OP. As the compiler isn't smart enough
2525 // to know that getenv() never returns -1, this will do the job.
2626 if (std::getenv("bar") != (char*) -1)
2727 return;
2828
29 (void) llvm::createOcamlMetadataPrinter();
29 llvm::linkOcamlGCPrinter();
3030
3131 }
3232 } ForceAsmWriterLinking; // Force link by creating a global definition.
3535
3636 (void) llvm::createSimpleRegisterCoalescer();
3737
38 (void) llvm::createOcamlCollector();
39 (void) llvm::createShadowStackCollector();
38 llvm::linkOcamlGC();
39 llvm::linkShadowStackGC();
4040
4141 (void) llvm::createBURRListDAGScheduler(NULL, NULL, NULL, false);
4242 (void) llvm::createTDRRListDAGScheduler(NULL, NULL, NULL, false);
151151 FunctionPass *getRegisterAllocator(TargetMachine &T);
152152
153153 /// IntrinsicLowering Pass - Performs target-independent LLVM IR
154 /// transformations for highly portable collectors.
154 /// transformations for highly portable strategies.
155155 FunctionPass *createGCLoweringPass();
156156
157157 /// MachineCodeAnalysis Pass - Target-independent pass to mark safe points in
160160 /// folding).
161161 FunctionPass *createGCMachineCodeAnalysisPass();
162162
163 /// Deleter Pass - Releases collector metadata.
163 /// Deleter Pass - Releases GC metadata.
164164 ///
165 FunctionPass *createCollectorMetadataDeleter();
165 FunctionPass *createGCInfoDeleter();
166166
167 /// Creates a pass to print collector metadata.
167 /// Creates a pass to print GC metadata.
168168 ///
169 FunctionPass *createCollectorMetadataPrinter(std::ostream &OS);
169 FunctionPass *createGCInfoPrinter(std::ostream &OS);
170170
171171 /// createMachineLICMPass - This pass performs LICM on machine instructions.
172172 ///
2828 class TargetLowering;
2929 class FunctionLoweringInfo;
3030 class HazardRecognizer;
31 class CollectorMetadata;
31 class GCFunctionInfo;
3232 class ScheduleDAG;
3333
3434 /// SelectionDAGISel - This is the common base class used for SelectionDAG-based
4040 SelectionDAG *CurDAG;
4141 MachineBasicBlock *BB;
4242 AliasAnalysis *AA;
43 CollectorMetadata *GCI;
43 GCFunctionInfo *GFI;
4444 bool Fast;
4545 std::vector TopOrder;
4646 static char ID;
4747
4848 explicit SelectionDAGISel(TargetLowering &tli, bool fast = false) :
49 FunctionPass((intptr_t)&ID), TLI(tli), GCI(0), Fast(fast), DAGSize(0) {}
49 FunctionPass((intptr_t)&ID), TLI(tli), GFI(), Fast(fast), DAGSize(0) {}
5050
5151 TargetLowering &getTargetLowering() { return TLI; }
5252
147147 ///
148148 void setParamAttrs(const PAListPtr &attrs) { ParamAttrs = attrs; }
149149
150 /// hasCollector/getCollector/setCollector/clearCollector - The name of the
151 /// garbage collection algorithm to use during code generation.
152 bool hasCollector() const;
153 const char *getCollector() const;
154 void setCollector(const char *Str);
155 void clearCollector();
150 /// hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm
151 /// to use during code generation.
152 bool hasGC() const;
153 const char *getGC() const;
154 void setGC(const char *Str);
155 void clearGC();
156156
157157 /// @brief Determine whether the function has the given attribute.
158158 bool paramHasAttr(unsigned i, ParameterAttributes attr) const {
410410 unsigned LLVMGetIntrinsicID(LLVMValueRef Fn);
411411 unsigned LLVMGetFunctionCallConv(LLVMValueRef Fn);
412412 void LLVMSetFunctionCallConv(LLVMValueRef Fn, unsigned CC);
413 const char *LLVMGetCollector(LLVMValueRef Fn);
414 void LLVMSetCollector(LLVMValueRef Fn, const char *Coll);
413 const char *LLVMGetGC(LLVMValueRef Fn);
414 void LLVMSetGC(LLVMValueRef Fn, const char *Name);
415415
416416 /* Operations on parameters */
417417 unsigned LLVMCountParams(LLVMValueRef Fn);
23922392 delete $8;
23932393 }
23942394 if ($10) {
2395 Fn->setCollector($10->c_str());
2395 Fn->setGC($10->c_str());
23962396 delete $10;
23972397 }
23982398
891891
892892 SmallVector Record;
893893 std::vector SectionTable;
894 std::vector CollectorTable;
894 std::vector GCTable;
895895
896896 // Read all the records for this module.
897897 while (!Stream.AtEndOfStream()) {
10181018 SectionTable.push_back(S);
10191019 break;
10201020 }
1021 case bitc::MODULE_CODE_COLLECTORNAME: { // SECTIONNAME: [strchr x N]
1021 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
10221022 std::string S;
10231023 if (ConvertToString(Record, 0, S))
1024 return Error("Invalid MODULE_CODE_COLLECTORNAME record");
1025 CollectorTable.push_back(S);
1024 return Error("Invalid MODULE_CODE_GCNAME record");
1025 GCTable.push_back(S);
10261026 break;
10271027 }
10281028 // GLOBALVAR: [pointer type, isconst, initid,
10691069 break;
10701070 }
10711071 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1072 // alignment, section, visibility, collector]
1072 // alignment, section, visibility, gc]
10731073 case bitc::MODULE_CODE_FUNCTION: {
10741074 if (Record.size() < 8)
10751075 return Error("Invalid MODULE_CODE_FUNCTION record");
10971097 }
10981098 Func->setVisibility(GetDecodedVisibility(Record[7]));
10991099 if (Record.size() > 8 && Record[8]) {
1100 if (Record[8]-1 > CollectorTable.size())
1101 return Error("Invalid collector ID");
1102 Func->setCollector(CollectorTable[Record[8]-1].c_str());
1100 if (Record[8]-1 > GCTable.size())
1101 return Error("Invalid GC ID");
1102 Func->setGC(GCTable[Record[8]-1].c_str());
11031103 }
11041104
11051105 ValueList.push_back(Func);
302302 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
303303 0/*TODO*/, Stream);
304304
305 // Emit information about sections and collectors, computing how many there
306 // are. Also compute the maximum alignment value.
305 // Emit information about sections and GC, computing how many there are. Also
306 // compute the maximum alignment value.
307307 std::map SectionMap;
308 std::map CollectorMap;
308 std::map GCMap;
309309 unsigned MaxAlignment = 0;
310310 unsigned MaxGlobalType = 0;
311311 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
332332 Entry = SectionMap.size();
333333 }
334334 }
335 if (F->hasCollector()) {
336 // Same for collector names.
337 unsigned &Entry = CollectorMap[F->getCollector()];
335 if (F->hasGC()) {
336 // Same for GC names.
337 unsigned &Entry = GCMap[F->getGC()];
338338 if (!Entry) {
339 WriteStringRecord(bitc::MODULE_CODE_COLLECTORNAME, F->getCollector(),
339 WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(),
340340 0/*TODO*/, Stream);
341 Entry = CollectorMap.size();
341 Entry = GCMap.size();
342342 }
343343 }
344344 }
400400 // Emit the function proto information.
401401 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
402402 // FUNCTION: [type, callingconv, isproto, paramattr,
403 // linkage, alignment, section, visibility, collector]
403 // linkage, alignment, section, visibility, gc]
404404 Vals.push_back(VE.getTypeID(F->getType()));
405405 Vals.push_back(F->getCallingConv());
406406 Vals.push_back(F->isDeclaration());
409409 Vals.push_back(Log2_32(F->getAlignment())+1);
410410 Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
411411 Vals.push_back(getEncodedVisibility(F));
412 Vals.push_back(F->hasCollector() ? CollectorMap[F->getCollector()] : 0);
412 Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0);
413413
414414 unsigned AbbrevToUse = 0;
415415 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
1515 #include "llvm/DerivedTypes.h"
1616 #include "llvm/Constants.h"
1717 #include "llvm/Module.h"
18 #include "llvm/CodeGen/GCStrategy.h"
19 #include "llvm/CodeGen/GCMetadata.h"
20 #include "llvm/CodeGen/GCs.h"
18 #include "llvm/CodeGen/GCMetadataPrinter.h"
2119 #include "llvm/CodeGen/MachineConstantPool.h"
2220 #include "llvm/CodeGen/MachineJumpTableInfo.h"
2321 #include "llvm/CodeGen/MachineModuleInfo.h"
109107
110108 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
111109 MachineFunctionPass::getAnalysisUsage(AU);
112 AU.addRequired<CollectorModuleMetadata>();
110 AU.addRequired<GCModuleInfo>();
113111 }
114112
115113 bool AsmPrinter::doInitialization(Module &M) {
116114 Mang = new Mangler(M, TAI->getGlobalPrefix());
117115
118 CollectorModuleMetadata *CMM = getAnalysisToUpdate();
119 assert(CMM && "AsmPrinter didn't require CollectorModuleMetadata?");
120 for (CollectorModuleMetadata::iterator I = CMM->begin(),
121 E = CMM->end(); I != E; ++I)
122 if (GCMetadataPrinter *GCP = GetOrCreateGCPrinter(*I))
123 GCP->beginAssembly(O, *this, *TAI);
116 GCModuleInfo *MI = getAnalysisToUpdate();
117 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
118 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
119 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
120 MP->beginAssembly(O, *this, *TAI);
124121
125122 if (!M.getModuleInlineAsm().empty())
126123 O << TAI->getCommentString() << " Start of file scope inline assembly\n"
191188 }
192189 }
193190
194 CollectorModuleMetadata *CMM = getAnalysisToUpdate();
195 assert(CMM && "AsmPrinter didn't require CollectorModuleMetadata?");
196 for (CollectorModuleMetadata::iterator I = CMM->end(),
197 E = CMM->begin(); I != E; )
198 if (GCMetadataPrinter *GCP = GetOrCreateGCPrinter(*--I))
199 GCP->finishAssembly(O, *this, *TAI);
191 GCModuleInfo *MI = getAnalysisToUpdate();
192 assert(MI && "AsmPrinter didn't require GCModuleInfo?");
193 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
194 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
195 MP->finishAssembly(O, *this, *TAI);
200196
201197 // If we don't have any trampolines, then we don't require stack memory
202198 // to be executable. Some targets have a directive to declare this.
14651461 }
14661462 }
14671463
1468 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(Collector *C) {
1469 if (!C->usesMetadata())
1464 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1465 if (!S->usesMetadata())
14701466 return 0;
14711467
1472 gcp_iterator GCPI = GCMetadataPrinters.find(C);
1468 gcp_iterator GCPI = GCMetadataPrinters.find(S);
14731469 if (GCPI != GCMetadataPrinters.end())
14741470 return GCPI->second;
14751471
1476 const char *Name = C->getName().c_str();
1472 const char *Name = S->getName().c_str();
14771473
14781474 for (GCMetadataPrinterRegistry::iterator
14791475 I = GCMetadataPrinterRegistry::begin(),
14801476 E = GCMetadataPrinterRegistry::end(); I != E; ++I)
14811477 if (strcmp(Name, I->getName()) == 0) {
1482 GCMetadataPrinter *GCP = I->instantiate();
1483 GCP->Coll = C;
1484 GCMetadataPrinters.insert(std::make_pair(C, GCP));
1485 return GCP;
1486 }
1487
1488 cerr << "no GCMetadataPrinter registered for collector: " << Name << "\n";
1478 GCMetadataPrinter *GMP = I->instantiate();
1479 GMP->S = S;
1480 GCMetadataPrinters.insert(std::make_pair(S, GMP));
1481 return GMP;
1482 }
1483
1484 cerr << "no GCMetadataPrinter registered for GC: " << Name << "\n";
14891485 abort();
14901486 }
None //===-- OcamlCollector.cpp - Ocaml frametable emitter ---------------------===//
0 //===-- OcamlGCPrinter.cpp - Ocaml frametable emitter ---------------------===//
11 //
22 // The LLVM Compiler Infrastructure
33 //
66 //
77 //===----------------------------------------------------------------------===//
88 //
9 // This file implements lowering for the llvm.gc* intrinsics compatible with
10 // Objective Caml 3.10.0, which uses a liveness-accurate static stack map.
9 // This file implements printing the assembly code for an Ocaml frametable.
1110 //
1211 //===----------------------------------------------------------------------===//
1312
1413 #include "llvm/CodeGen/GCs.h"
1514 #include "llvm/CodeGen/AsmPrinter.h"
15 #include "llvm/CodeGen/GCMetadataPrinter.h"
1616 #include "llvm/CodeGen/GCStrategy.h"
1717 #include "llvm/Module.h"
1818 #include "llvm/Target/TargetAsmInfo.h"
3737 static GCMetadataPrinterRegistry::Add
3838 Y("ocaml", "ocaml 3.10-compatible collector");
3939
40 GCMetadataPrinter *llvm::createOcamlMetadataPrinter() {
41 return new OcamlGCMetadataPrinter();
42 }
40 void llvm::linkOcamlGCPrinter() { }
4341
4442 static void EmitCamlGlobal(const Module &M, std::ostream &OS, AsmPrinter &AP,
4543 const TargetAsmInfo &TAI, const char *Id) {
8482 ///
8583 /// Note that this precludes programs from stack frames larger than 64K
8684 /// (FrameSize and LiveOffsets would overflow). FrameTablePrinter will abort if
87 /// either condition is detected in a function which uses the collector.
85 /// either condition is detected in a function which uses the GC.
8886 ///
8987 void OcamlGCMetadataPrinter::finishAssembly(std::ostream &OS, AsmPrinter &AP,
9088 const TargetAsmInfo &TAI) {
110108 AP.SwitchToDataSection(TAI.getDataSection());
111109 EmitCamlGlobal(getModule(), OS, AP, TAI, "frametable");
112110
113 for (iterator FI = begin(), FE = end(); FI != FE; ++FI) {
114 CollectorMetadata &MD = **FI;
111 for (iterator I = begin(), IE = end(); I != IE; ++I) {
112 GCFunctionInfo &FI = **I;
113
114 uint64_t FrameSize = FI.getFrameSize();
115 if (FrameSize >= 1<<16) {
116 cerr << "Function '" << FI.getFunction().getNameStart()
117 << "' is too large for the ocaml GC! "
118 << "Frame size " << FrameSize << " >= 65536.\n";
119 cerr << "(" << uintptr_t(&FI) << ")\n";
120 abort(); // Very rude!
121 }
115122
116123 OS << "\t" << TAI.getCommentString() << " live roots for "
117 << MD.getFunction().getNameStart() << "\n";
124 << FI.getFunction().getNameStart() << "\n";
118125
119 for (CollectorMetadata::iterator PI = MD.begin(),
120 PE = MD.end(); PI != PE; ++PI) {
121
122 uint64_t FrameSize = MD.getFrameSize();
123 if (FrameSize >= 1<<16) {
124 cerr << "Function '" << MD.getFunction().getNameStart()
125 << "' is too large for the ocaml collector! "
126 << "Frame size " << FrameSize << " >= 65536.\n";
127 abort(); // Very rude!
128 }
129
130 size_t LiveCount = MD.live_size(PI);
126 for (GCFunctionInfo::iterator J = FI.begin(), JE = FI.end(); J != JE; ++J) {
127 size_t LiveCount = FI.live_size(J);
131128 if (LiveCount >= 1<<16) {
132 cerr << "Function '" << MD.getFunction().getNameStart()
133 << "' is too large for the ocaml collector! "
129 cerr << "Function '" << FI.getFunction().getNameStart()
130 << "' is too large for the ocaml GC! "
134131 << "Live root count " << LiveCount << " >= 65536.\n";
135132 abort(); // Very rude!
136133 }
137134
138135 OS << AddressDirective
139 << TAI.getPrivateGlobalPrefix() << "label" << PI->Num;
136 << TAI.getPrivateGlobalPrefix() << "label" << J->Num;
140137 AP.EOL("call return address");
141138
142139 AP.EmitInt16(FrameSize);
145142 AP.EmitInt16(LiveCount);
146143 AP.EOL("live root count");
147144
148 for (CollectorMetadata::live_iterator LI = MD.live_begin(PI),
149 LE = MD.live_end(PI);
150 LI != LE; ++LI) {
151 assert(LI->StackOffset < 1<<16 &&
145 for (GCFunctionInfo::live_iterator K = FI.live_begin(J),
146 KE = FI.live_end(J); K != KE; ++K) {
147 assert(K->StackOffset < 1<<16 &&
152148 "GC root stack offset is outside of fixed stack frame and out "
153 "of range for Ocaml collector!");
149 "of range for ocaml GC!");
154150
155 OS << "\t.word\t" << LI->StackOffset;
151 OS << "\t.word\t" << K->StackOffset;
156152 AP.EOL("stack offset");
157153 }
158154
None //===-- CollectorMetadata.cpp - Garbage collector metadata ----------------===//
0 //===-- GCMetadata.cpp - Garbage collector metadata -----------------------===//
11 //
22 // The LLVM Compiler Infrastructure
33 //
66 //
77 //===----------------------------------------------------------------------===//
88 //
9 // This file implements the CollectorMetadata and CollectorModuleMetadata
10 // classes.
9 // This file implements the GCFunctionInfo class and GCModuleInfo pass.
1110 //
1211 //===----------------------------------------------------------------------===//
1312
1413 #include "llvm/CodeGen/GCMetadata.h"
1514 #include "llvm/CodeGen/GCStrategy.h"
16 #include "llvm/CodeGen/GCs.h"
1715 #include "llvm/CodeGen/MachineFrameInfo.h"
1816 #include "llvm/Pass.h"
1917 #include "llvm/CodeGen/Passes.h"
5250
5351 }
5452
55 static RegisterPass<CollectorModuleMetadata>
53 static RegisterPass<GCModuleInfo>
5654 X("collector-metadata", "Create Garbage Collector Module Metadata");
5755
5856 // -----------------------------------------------------------------------------
5957
60 CollectorMetadata::CollectorMetadata(const Function &F, Collector &C)
61 : F(F), C(C), FrameSize(~0LL) {}
62
63 CollectorMetadata::~CollectorMetadata() {}
64
65 // -----------------------------------------------------------------------------
66
67 char CollectorModuleMetadata::ID = 0;
68
69 CollectorModuleMetadata::CollectorModuleMetadata()
58 GCFunctionInfo::GCFunctionInfo(const Function &F, GCStrategy &S)
59 : F(F), S(S), FrameSize(~0LL) {}
60
61 GCFunctionInfo::~GCFunctionInfo() {}
62
63 // -----------------------------------------------------------------------------
64
65 char GCModuleInfo::ID = 0;
66
67 GCModuleInfo::GCModuleInfo()
7068 : ImmutablePass((intptr_t)&ID) {}
7169
72 CollectorModuleMetadata::~CollectorModuleMetadata() {
70 GCModuleInfo::~GCModuleInfo() {
7371 clear();
7472 }
7573
76 Collector *CollectorModuleMetadata::
77 getOrCreateCollector(const Module *M, const std::string &Name) {
74 GCStrategy *GCModuleInfo::getOrCreateStrategy(const Module *M,
75 const std::string &Name) {
7876 const char *Start = Name.c_str();
7977
80 collector_map_type::iterator NMI = NameMap.find(Start, Start + Name.size());
81 if (NMI != NameMap.end())
78 strategy_map_type::iterator NMI =
79 StrategyMap.find(Start, Start + Name.size());
80 if (NMI != StrategyMap.end())
8281 return NMI->getValue();
8382
84 for (CollectorRegistry::iterator I = CollectorRegistry::begin(),
85 E = CollectorRegistry::end(); I != E; ++I) {
83 for (GCRegistry::iterator I = GCRegistry::begin(),
84 E = GCRegistry::end(); I != E; ++I) {
8685 if (strcmp(Start, I->getName()) == 0) {
87 Collector *C = I->instantiate();
88 C->M = M;
89 C->Name = Name;
90 NameMap.GetOrCreateValue(Start, Start + Name.size()).setValue(C);
91 Collectors.push_back(C);
92 return C;
86 GCStrategy *S = I->instantiate();
87 S->M = M;
88 S->Name = Name;
89 StrategyMap.GetOrCreateValue(Start, Start + Name.size()).setValue(S);
90 StrategyList.push_back(S);
91 return S;
9392 }
9493 }
9594
96 cerr << "unsupported collector: " << Name << "\n";
95 cerr << "unsupported GC: " << Name << "\n";
9796 abort();
9897 }
9998
100 CollectorMetadata &CollectorModuleMetadata::get(const Function &F) {
99 GCFunctionInfo &GCModuleInfo::getFunctionInfo(const Function &F) {
101100 assert(!F.isDeclaration() && "Can only get GCFunctionInfo for a definition!");
102 assert(F.hasCollector());
103
104 function_map_type::iterator I = Map.find(&F);
105 if (I != Map.end())
101 assert(F.hasGC());
102
103 finfo_map_type::iterator I = FInfoMap.find(&F);
104 if (I != FInfoMap.end())
106105 return *I->second;
107
108 Collector *C = getOrCreateCollector(F.getParent(), F.getCollector());
109 CollectorMetadata *MD = C->insertFunctionMetadata(F);
110 Map[&F] = MD;
111 return *MD;
112 }
113
114 void CollectorModuleMetadata::clear() {
115 Map.clear();
116 NameMap.clear();
106
107 GCStrategy *S = getOrCreateStrategy(F.getParent(), F.getGC());
108 GCFunctionInfo *GFI = S->insertFunctionInfo(F);
109 FInfoMap[&F] = GFI;
110 return *GFI;
111 }
112
113 void GCModuleInfo::clear() {
114 FInfoMap.clear();
115 StrategyMap.clear();
117116
118117 for (iterator I = begin(), E = end(); I != E; ++I)
119118 delete *I;
120 Collectors.clear();
119 StrategyList.clear();
121120 }
122121
123122 // -----------------------------------------------------------------------------
124123
125124 char Printer::ID = 0;
126125
127 FunctionPass *llvm::createCollectorMetadataPrinter(std::ostream &OS) {
126 FunctionPass *llvm::createGCInfoPrinter(std::ostream &OS) {
128127 return new Printer(OS);
129128 }
130129
138137 void Printer::getAnalysisUsage(AnalysisUsage &AU) const {
139138 FunctionPass::getAnalysisUsage(AU);
140139 AU.setPreservesAll();
141 AU.addRequired<CollectorModuleMetadata>();
140 AU.addRequired<GCModuleInfo>();
142141 }
143142
144143 static const char *DescKind(GC::PointKind Kind) {
152151 }
153152
154153 bool Printer::runOnFunction(Function &F) {
155 if (F.hasCollector()) {
156 CollectorMetadata *FD = &getAnalysis().get(F);
154 if (!F.hasGC()) {
155 GCFunctionInfo *FD = &getAnalysis().getFunctionInfo(F);
157156
158157 OS << "GC roots for " << FD->getFunction().getNameStart() << ":\n";
159 for (CollectorMetadata::roots_iterator RI = FD->roots_begin(),
160 RE = FD->roots_end();
161 RI != RE; ++RI)
158 for (GCFunctionInfo::roots_iterator RI = FD->roots_begin(),
159 RE = FD->roots_end(); RI != RE; ++RI)
162160 OS << "\t" << RI->Num << "\t" << RI->StackOffset << "[sp]\n";
163161
164162 OS << "GC safe points for " << FD->getFunction().getNameStart() << ":\n";
165 for (CollectorMetadata::iterator PI = FD->begin(),
166 PE = FD->end(); PI != PE; ++PI) {
163 for (GCFunctionInfo::iterator PI = FD->begin(),
164 PE = FD->end(); PI != PE; ++PI) {
167165
168166 OS << "\tlabel " << PI->Num << ": " << DescKind(PI->Kind) << ", live = {";
169167
170 for (CollectorMetadata::live_iterator RI = FD->live_begin(PI),
171 RE = FD->live_end(PI);;) {
168 for (GCFunctionInfo::live_iterator RI = FD->live_begin(PI),
169 RE = FD->live_end(PI);;) {
172170 OS << " " << RI->Num;
173171 if (++RI == RE)
174172 break;
186184
187185 char Deleter::ID = 0;
188186
189 FunctionPass *llvm::createCollectorMetadataDeleter() {
187 FunctionPass *llvm::createGCInfoDeleter() {
190188 return new Deleter();
191189 }
192190
198196
199197 void Deleter::getAnalysisUsage(AnalysisUsage &AU) const {
200198 AU.setPreservesAll();
201 AU.addRequired<CollectorModuleMetadata>();
199 AU.addRequired<GCModuleInfo>();
202200 }
203201
204202 bool Deleter::runOnFunction(Function &MF) {
206204 }
207205
208206 bool Deleter::doFinalization(Module &M) {
209 CollectorModuleMetadata *CMM = getAnalysisToUpdate();
210 assert(CMM && "Deleter didn't require CollectorModuleMetadata?!");
211 CMM->clear();
207 GCModuleInfo *GMI = getAnalysisToUpdate();
208 assert(GMI && "Deleter didn't require GCModuleInfo?!");
209 GMI->clear();
212210 return false;
213211 }
None //===-- Collector.cpp - Garbage collection infrastructure -----------------===//
0 //===-- GCMetadataPrinter.cpp - Garbage collection infrastructure ---------===//
11 //
22 // The LLVM Compiler Infrastructure
33 //
66 //
77 //===----------------------------------------------------------------------===//
88 //
9 // This file implements target- and collector-independent garbage collection
10 // infrastructure.
9 // This file implements the abstract base class GCMetadataPrinter.
1110 //
1211 //===----------------------------------------------------------------------===//
1312
14 #include "llvm/CodeGen/GCStrategy.h"
13 #include "llvm/CodeGen/GCMetadataPrinter.h"
1514
1615 using namespace llvm;
16
17 // -----------------------------------------------------------------------------
18
19 template<> GCMetadataPrinterRegistry::node *GCMetadataPrinterRegistry::Head = 0;
20 template<> GCMetadataPrinterRegistry::node *GCMetadataPrinterRegistry::Tail = 0;
21 template<> GCMetadataPrinterRegistry::listener *
22 GCMetadataPrinterRegistry::ListenerHead = 0;
23 template<> GCMetadataPrinterRegistry::listener *
24 GCMetadataPrinterRegistry::ListenerTail = 0;
25
26 // -----------------------------------------------------------------------------
1727
1828 GCMetadataPrinter::GCMetadataPrinter() { }
1929
None //===-- Collector.cpp - Garbage collection infrastructure -----------------===//
0 //===-- GCStrategy.cpp - Garbage collection infrastructure -----------------===//
11 //
22 // The LLVM Compiler Infrastructure
33 //
88 //
99 // This file implements target- and collector-independent garbage collection
1010 // infrastructure.
11 //
12 // MachineCodeAnalysis identifies the GC safe points in the machine code. Roots
13 // are identified in SelectionDAGISel.
1114 //
1215 //===----------------------------------------------------------------------===//
1316
3033
3134 /// LowerIntrinsics - This pass rewrites calls to the llvm.gcread or
3235 /// llvm.gcwrite intrinsics, replacing them with simple loads and stores as
33 /// directed by the Collector. It also performs automatic root initialization
36 /// directed by the GCStrategy. It also performs automatic root initialization
3437 /// and custom intrinsic lowering.
3538 class VISIBILITY_HIDDEN LowerIntrinsics : public FunctionPass {
36 static bool NeedsDefaultLoweringPass(const Collector &C);
37 static bool NeedsCustomLoweringPass(const Collector &C);
39 static bool NeedsDefaultLoweringPass(const GCStrategy &C);
40 static bool NeedsCustomLoweringPass(const GCStrategy &C);
3841 static bool CouldBecomeSafePoint(Instruction *I);
39 bool PerformDefaultLowering(Function &F, Collector &Coll);
42 bool PerformDefaultLowering(Function &F, GCStrategy &Coll);
4043 static bool InsertRootInitializers(Function &F,
4144 AllocaInst **Roots, unsigned Count);
4245
5558 /// MachineCodeAnalysis - This is a target-independent pass over the machine
5659 /// function representation to identify safe points for the garbage collector
5760 /// in the machine code. It inserts labels at safe points and populates a
58 /// CollectorMetadata record for each function.
61 /// GCMetadata record for each function.
5962 class VISIBILITY_HIDDEN MachineCodeAnalysis : public MachineFunctionPass {
6063 const TargetMachine *TM;
61 CollectorMetadata *MD;
64 GCFunctionInfo *FI;
6265 MachineModuleInfo *MMI;
6366 const TargetInstrInfo *TII;
6467 MachineFrameInfo *MFI;
8487
8588 // -----------------------------------------------------------------------------
8689
87 Collector::Collector() :
90 template<> GCRegistry::node *GCRegistry::Head = 0;
91 template<> GCRegistry::node *GCRegistry::Tail = 0;
92 template<> GCRegistry::listener *GCRegistry::ListenerHead = 0;
93 template<> GCRegistry::listener *GCRegistry::ListenerTail = 0;
94
95 // -----------------------------------------------------------------------------
96
97 GCStrategy::GCStrategy() :
8898 NeededSafePoints(0),
8999 CustomReadBarriers(false),
90100 CustomWriteBarriers(false),
93103 UsesMetadata(false)
94104 {}
95105
96 Collector::~Collector() {
106 GCStrategy::~GCStrategy() {
97107 for (iterator I = begin(), E = end(); I != E; ++I)
98108 delete *I;
99109
100110 Functions.clear();
101111 }
102112
103 bool Collector::initializeCustomLowering(Module &M) { return false; }
113 bool GCStrategy::initializeCustomLowering(Module &M) { return false; }
104114
105 bool Collector::performCustomLowering(Function &F) {
115 bool GCStrategy::performCustomLowering(Function &F) {
106116 cerr << "gc " << getName() << " must override performCustomLowering.\n";
107117 abort();
108118 return 0;
109119 }
110
111 CollectorMetadata *Collector::insertFunctionMetadata(const Function &F) {
112 CollectorMetadata *CM = new CollectorMetadata(F, *this);
113 Functions.push_back(CM);
114 return CM;
115 }
120
121 GCFunctionInfo *GCStrategy::insertFunctionInfo(const Function &F) {
122 GCFunctionInfo *FI = new GCFunctionInfo(F, *this);
123 Functions.push_back(FI);
124 return FI;
125 }
116126
117127 // -----------------------------------------------------------------------------
118128
131141
132142 void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
133143 FunctionPass::getAnalysisUsage(AU);
134 AU.addRequired<CollectorModuleMetadata>();
144 AU.addRequired<GCModuleInfo>();
135145 }
136146
137147 /// doInitialization - If this module uses the GC intrinsics, find them now.
140150 // work against the entire module. But this cannot be done at
141151 // runFunction time (initializeCustomLowering likely needs to change
142152 // the module).
143 CollectorModuleMetadata *CMM = getAnalysisToUpdate();
144 assert(CMM && "LowerIntrinsics didn't require CollectorModuleMetadata!?");
153 GCModuleInfo *MI = getAnalysisToUpdate();
154 assert(MI && "LowerIntrinsics didn't require GCModuleInfo!?");
145155 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
146 if (!I->isDeclaration() && I->hasCollector())
147 CMM->get(*I); // Instantiate the Collector.
156 if (!I->isDeclaration() && I->hasGC())
157 MI->getFunctionInfo(*I); // Instantiate the GC strategy.
148158
149159 bool MadeChange = false;
150 for (CollectorModuleMetadata::iterator I = CMM->begin(),
151 E = CMM->end(); I != E; ++I)
160 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
152161 if (NeedsCustomLoweringPass(**I))
153162 if ((*I)->initializeCustomLowering(M))
154163 MadeChange = true;
184193 return MadeChange;
185194 }
186195
187 bool LowerIntrinsics::NeedsDefaultLoweringPass(const Collector &C) {
196 bool LowerIntrinsics::NeedsDefaultLoweringPass(const GCStrategy &C) {
188197 // Default lowering is necessary only if read or write barriers have a default
189198 // action. The default for roots is no action.
190199 return !C.customWriteBarrier()
192201 || C.initializeRoots();
193202 }
194203
195 bool LowerIntrinsics::NeedsCustomLoweringPass(const Collector &C) {
204 bool LowerIntrinsics::NeedsCustomLoweringPass(const GCStrategy &C) {
196205 // Custom lowering is only necessary if enabled for some action.
197206 return C.customWriteBarrier()
198207 || C.customReadBarrier()
231240 /// Leave gcroot intrinsics; the code generator needs to see those.
232241 bool LowerIntrinsics::runOnFunction(Function &F) {
233242 // Quick exit for functions that do not use GC.
234 if (!F.hasCollector()) return false;
235
236 CollectorMetadata &MD = getAnalysis().get(F);
237 Collector &Coll = MD.getCollector();
243 if (!F.hasGC())
244 return false;
245
246 GCFunctionInfo &FI = getAnalysis().getFunctionInfo(F);
247 GCStrategy &S = FI.getStrategy();
238248
239249 bool MadeChange = false;
240250
241 if (NeedsDefaultLoweringPass(Coll))
242 MadeChange |= PerformDefaultLowering(F, Coll);
243
244 if (NeedsCustomLoweringPass(Coll))
245 MadeChange |= Coll.performCustomLowering(F);
251 if (NeedsDefaultLoweringPass(S))
252 MadeChange |= PerformDefaultLowering(F, S);
253
254 if (NeedsCustomLoweringPass(S))
255 MadeChange |= S.performCustomLowering(F);
246256
247257 return MadeChange;
248258 }
249259
250 bool LowerIntrinsics::PerformDefaultLowering(Function &F, Collector &Coll) {
251 bool LowerWr = !Coll.customWriteBarrier();
252 bool LowerRd = !Coll.customReadBarrier();
253 bool InitRoots = Coll.initializeRoots();
260 bool LowerIntrinsics::PerformDefaultLowering(Function &F, GCStrategy &S) {
261 bool LowerWr = !S.customWriteBarrier();
262 bool LowerRd = !S.customReadBarrier();
263 bool InitRoots = S.initializeRoots();
254264
255265 SmallVector Roots;
256266
319329 MachineFunctionPass::getAnalysisUsage(AU);
320330 AU.setPreservesAll();
321331 AU.addRequired();
322 AU.addRequired<CollectorModuleMetadata>();
332 AU.addRequired<GCModuleInfo>();
323333 }
324334
325335 unsigned MachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB,
335345 MachineBasicBlock::iterator RAI = CI;
336346 ++RAI;
337347
338 if (MD->getCollector().needsSafePoint(GC::PreCall))
339 MD->addSafePoint(GC::PreCall, InsertLabel(*CI->getParent(), CI));
340
341 if (MD->getCollector().needsSafePoint(GC::PostCall))
342 MD->addSafePoint(GC::PostCall, InsertLabel(*CI->getParent(), RAI));
348 if (FI->getStrategy().needsSafePoint(GC::PreCall))
349 FI->addSafePoint(GC::PreCall, InsertLabel(*CI->getParent(), CI));
350
351 if (FI->getStrategy().needsSafePoint(GC::PostCall))
352 FI->addSafePoint(GC::PostCall, InsertLabel(*CI->getParent(), RAI));
343353 }
344354
345355 void MachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
356366 uint64_t OffsetAdjustment = MFI->getOffsetAdjustment();
357367 uint64_t OffsetOfLocalArea = TM->getFrameInfo()->getOffsetOfLocalArea();
358368
359 for (CollectorMetadata::roots_iterator RI = MD->roots_begin(),
360 RE = MD->roots_end(); RI != RE; ++RI)
369 for (GCFunctionInfo::roots_iterator RI = FI->roots_begin(),
370 RE = FI->roots_end(); RI != RE; ++RI)
361371 RI->StackOffset = MFI->getObjectOffset(RI->Num) + StackSize
362372 - OffsetOfLocalArea + OffsetAdjustment;
363373 }
364374
365375 bool MachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
366376 // Quick exit for functions that do not use GC.
367 if (!MF.getFunction()->hasCollector()) return false;
368
369 MD = &getAnalysis().get(*MF.getFunction());
370 if (!MD->getCollector().needsSafePoints())
377 if (!MF.getFunction()->hasGC())
378 return false;
379
380 FI = &getAnalysis().getFunctionInfo(*MF.getFunction());
381 if (!FI->getStrategy().needsSafePoints())
371382 return false;
372383
373384 TM = &MF.getTarget();
376387 MFI = MF.getFrameInfo();
377388
378389 // Find the size of the stack frame.
379 MD->setFrameSize(MFI->getStackSize());
390 FI->setFrameSize(MFI->getStackSize());
380391
381392 // Find all safe points.
382393 FindSafePoints(MF);
+0
-28
lib/CodeGen/GCs.cpp less more
None //===-- Collectors.cpp - Garbage collector registry -----------------------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the static data members of the CollectorRegistry class.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "llvm/CodeGen/GCs.h"
14
15 using namespace llvm;
16
17 template<> CollectorRegistry::node *CollectorRegistry::Head = 0;
18 template<> CollectorRegistry::node *CollectorRegistry::Tail = 0;
19 template<> CollectorRegistry::listener *CollectorRegistry::ListenerHead = 0;
20 template<> CollectorRegistry::listener *CollectorRegistry::ListenerTail = 0;
21
22 template<> GCMetadataPrinterRegistry::node *GCMetadataPrinterRegistry::Head = 0;
23 template<> GCMetadataPrinterRegistry::node *GCMetadataPrinterRegistry::Tail = 0;
24 template<> GCMetadataPrinterRegistry::listener *
25 GCMetadataPrinterRegistry::ListenerHead = 0;
26 template<> GCMetadataPrinterRegistry::listener *
27 GCMetadataPrinterRegistry::ListenerTail = 0;
132132 PM.add(createMachineFunctionPrinterPass(cerr));
133133
134134 if (PrintGCInfo)
135 PM.add(createCollectorMetadataPrinter(*cerr));
135 PM.add(createGCInfoPrinter(*cerr));
136136
137137 // Fold redundant debug labels.
138138 PM.add(createDebugLabelFoldingPass());
172172 if (MCE)
173173 addSimpleCodeEmitter(PM, Fast, PrintEmittedAsm, *MCE);
174174
175 PM.add(createCollectorMetadataDeleter());
175 PM.add(createGCInfoDeleter());
176176
177177 // Delete machine code for this function
178178 PM.add(createMachineCodeDeleter());
273273 PM.add(createMachineFunctionPrinterPass(cerr));
274274
275275 if (PrintGCInfo)
276 PM.add(createCollectorMetadataPrinter(*cerr));
276 PM.add(createGCInfoPrinter(*cerr));
277277
278278 if (addPreEmitPass(PM, Fast) && PrintMachineCode)
279279 PM.add(createMachineFunctionPrinterPass(cerr));
280280
281281 addCodeEmitter(PM, Fast, PrintEmittedAsm, MCE);
282282
283 PM.add(createCollectorMetadataDeleter());
283 PM.add(createGCInfoDeleter());
284284
285285 // Delete machine code for this function
286286 PM.add(createMachineCodeDeleter());
None //===-- OcamlCollector.cpp - Ocaml frametable emitter ---------------------===//
0 //===-- OcamlGC.cpp - Ocaml frametable GC strategy ------------------------===//
11 //
22 // The LLVM Compiler Infrastructure
33 //
88 //
99 // This file implements lowering for the llvm.gc* intrinsics compatible with
1010 // Objective Caml 3.10.0, which uses a liveness-accurate static stack map.
11 //
12 // The frametable emitter is in OcamlGCPrinter.cpp.
1113 //
1214 //===----------------------------------------------------------------------===//
1315
1416 #include "llvm/CodeGen/GCs.h"
15 #include "llvm/CodeGen/AsmPrinter.h"
1617 #include "llvm/CodeGen/GCStrategy.h"
17 #include "llvm/Module.h"
18 #include "llvm/Target/TargetAsmInfo.h"
19 #include "llvm/Target/TargetData.h"
20 #include "llvm/Target/TargetMachine.h"
2118
2219 using namespace llvm;
2320
2421 namespace {
25
26 class VISIBILITY_HIDDEN OcamlCollector : public Collector {
22 class VISIBILITY_HIDDEN OcamlGC : public GCStrategy {
2723 public:
28 OcamlCollector();
24 OcamlGC();
2925 };
30
3126 }
3227
33 static CollectorRegistry::Add
34 X("ocaml", "ocaml 3.10-compatible collector");
28 static GCRegistry::Add
29 X("ocaml", "ocaml 3.10-compatible GC");
3530
36 // -----------------------------------------------------------------------------
31 void llvm::linkOcamlGC() { }
3732
38 Collector *llvm::createOcamlCollector() {
39 return new OcamlCollector();
40 }
41
42 OcamlCollector::OcamlCollector() {
33 OcamlGC::OcamlGC() {
4334 NeededSafePoints = 1 << GC::PostCall;
4435 UsesMetadata = true;
4536 }
2626 #include "llvm/IntrinsicInst.h"
2727 #include "llvm/ParameterAttributes.h"
2828 #include "llvm/CodeGen/GCStrategy.h"
29 #include "llvm/CodeGen/GCMetadata.h"
2930 #include "llvm/CodeGen/MachineFunction.h"
3031 #include "llvm/CodeGen/MachineFrameInfo.h"
3132 #include "llvm/CodeGen/MachineInstrBuilder.h"
600601 ///
601602 FunctionLoweringInfo &FuncInfo;
602603
603 /// GCI - Garbage collection metadata for the function.
604 CollectorMetadata *GCI;
604 /// GFI - Garbage collection metadata for the function.
605 GCFunctionInfo *GFI;
605606
606607 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
607608 AliasAnalysis &aa,
608609 FunctionLoweringInfo &funcinfo,
609 CollectorMetadata *gci)
610 GCFunctionInfo *gfi)
610611 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa),
611 FuncInfo(funcinfo), GCI(gci) {
612 FuncInfo(funcinfo), GFI(gfi) {
612613 }
613614
614615 /// getRoot - Return the current virtual root of the Selection DAG,
34843485 }
34853486
34863487 case Intrinsic::gcroot:
3487 if (GCI) {
3488 if (GFI) {
34883489 Value *Alloca = I.getOperand(1);
34893490 Constant *TypeMap = cast(I.getOperand(2));
34903491
34913492 FrameIndexSDNode *FI = cast(getValue(Alloca).Val);
3492 GCI->addStackRoot(FI->getIndex(), TypeMap);
3493 GFI->addStackRoot(FI->getIndex(), TypeMap);
34933494 }
34943495 return 0;
34953496
34963497 case Intrinsic::gcread:
34973498 case Intrinsic::gcwrite:
3498 assert(0 && "Collector failed to lower gcread/gcwrite intrinsics!");
3499 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
34993500 return 0;
35003501
35013502 case Intrinsic::flt_rounds: {
48774878
48784879 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
48794880 AU.addRequired();
4880 AU.addRequired<CollectorModuleMetadata>();
4881 AU.addRequired<GCModuleInfo>();
48814882 AU.setPreservesAll();
48824883 }
48834884
48864887 AA = &getAnalysis();
48874888
48884889 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4889 if (MF.getFunction()->hasCollector())
4890 GCI = &getAnalysis().get(*MF.getFunction());
4890 if (MF.getFunction()->hasGC())
4891 GFI = &getAnalysis().getFunctionInfo(*MF.getFunction());
48914892 else
4892 GCI = 0;
4893 GFI = 0;
48934894 RegInfo = &MF.getRegInfo();
48944895 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
48954896
50885089 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
50895090 std::vector > &PHINodesToUpdate,
50905091 FunctionLoweringInfo &FuncInfo) {
5091 SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo, GCI);
5092 SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo, GFI);
50925093
50935094 // Lower any arguments needed in this block if this is the entry block.
50945095 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
55035504 getAnalysisToUpdate(),
55045505 NodeAllocator);
55055506 CurDAG = &HSDAG;
5506 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
5507 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GFI);
55075508 // Set the current basic block to the mbb we wish to insert the code into
55085509 BB = BitTestCases[i].Parent;
55095510 HSDL.setCurrentBasicBlock(BB);
55185519 getAnalysisToUpdate(),
55195520 NodeAllocator);
55205521 CurDAG = &BSDAG;
5521 SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo, GCI);
5522 SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo, GFI);
55225523 // Set the current basic block to the mbb we wish to insert the code into
55235524 BB = BitTestCases[i].Cases[j].ThisBB;
55245525 BSDL.setCurrentBasicBlock(BB);
55775578 getAnalysisToUpdate(),
55785579 NodeAllocator);
55795580 CurDAG = &HSDAG;
5580 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
5581 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GFI);
55815582 // Set the current basic block to the mbb we wish to insert the code into
55825583 BB = JTCases[i].first.HeaderBB;
55835584 HSDL.setCurrentBasicBlock(BB);
55915592 getAnalysisToUpdate(),
55925593 NodeAllocator);
55935594 CurDAG = &JSDAG;
5594 SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo, GCI);
5595 SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo, GFI);
55955596 // Set the current basic block to the mbb we wish to insert the code into
55965597 BB = JTCases[i].second.MBB;
55975598 JSDL.setCurrentBasicBlock(BB);
56415642 getAnalysisToUpdate(),
56425643 NodeAllocator);
56435644 CurDAG = &SDAG;
5644 SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo, GCI);
5645 SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo, GFI);
56455646
56465647 // Set the current basic block to the mbb we wish to insert the code into
56475648 BB = SwitchCases[i].ThisBB;
None //===-- ShadowStackCollector.cpp - GC support for uncooperative targets ---===//
0 //===-- ShadowStackGC.cpp - GC support for uncooperative targets ----------===//
11 //
22 // The LLVM Compiler Infrastructure
33 //
88 //
99 // This file implements lowering for the llvm.gc* intrinsics for targets that do
1010 // not natively support them (which includes the C backend). Note that the code
11 // generated is not quite as efficient as collectors which generate stack maps
11 // generated is not quite as efficient as algorithms which generate stack maps
1212 // to identify roots.
1313 //
1414 // This pass implements the code transformation described in this paper:
1616 // Fergus Henderson, ISMM, 2002
1717 //
1818 // In runtime/GC/SemiSpace.cpp is a prototype runtime which is compatible with
19 // this collector.
19 // ShadowStackGC.
2020 //
2121 // In order to support this particular transformation, all stack roots are
2222 // coallocated in the stack. This allows a fully target-independent stack map
3636
3737 namespace {
3838
39 class VISIBILITY_HIDDEN ShadowStackCollector : public Collector {
39 class VISIBILITY_HIDDEN ShadowStackGC : public GCStrategy {
4040 /// RootChain - This is the global linked-list that contains the chain of GC
4141 /// roots.
4242 GlobalVariable *Head;
5050 std::vector > Roots;
5151
5252 public:
53 ShadowStackCollector();
53 ShadowStackGC();
5454
5555 bool initializeCustomLowering(Module &M);
5656 bool performCustomLowering(Function &F);
6868
6969 }
7070
71 static CollectorRegistry::Add
72 Y("shadow-stack",
73 "Very portable collector for uncooperative code generators");
71 static GCRegistry::Add
72 X("shadow-stack", "Very portable GC for uncooperative code generators");
7473
7574 namespace {
7675 /// EscapeEnumerator - This is a little algorithm to find all escape points
172171 }
173172 }
174173 };
175
176174 }
177175
178176 // -----------------------------------------------------------------------------
179177
180 Collector *llvm::createShadowStackCollector() {
181 return new ShadowStackCollector();
182 }
183
184 ShadowStackCollector::ShadowStackCollector() : Head(0), StackEntryTy(0) {
178 void llvm::linkShadowStackGC() { }
179
180 ShadowStackGC::ShadowStackGC() : Head(0), StackEntryTy(0) {
185181 InitRoots = true;
186182 CustomRoots = true;
187183 }
188184
189 Constant *ShadowStackCollector::GetFrameMap(Function &F) {
185 Constant *ShadowStackGC::GetFrameMap(Function &F) {
190186 // doInitialization creates the abstract type of this value.
191187
192188 Type *VoidPtr = PointerType::getUnqual(Type::Int8Ty);
241237 return ConstantExpr::getGetElementPtr(GV, GEPIndices, 2);
242238 }
243239
244 const Type* ShadowStackCollector::GetConcreteStackEntryType(Function &F) {
240 const Type* ShadowStackGC::GetConcreteStackEntryType(Function &F) {
245241 // doInitialization creates the generic version of this type.
246242 std::vector EltTys;
247243 EltTys.push_back(StackEntryTy);
258254
259255 /// doInitialization - If this module uses the GC intrinsics, find them now. If
260256 /// not, exit fast.
261 bool ShadowStackCollector::initializeCustomLowering(Module &M) {
257 bool ShadowStackGC::initializeCustomLowering(Module &M) {
262258 // struct FrameMap {
263259 // int32_t NumRoots; // Number of roots in stack frame.
264260 // int32_t NumMeta; // Number of metadata descriptors. May be < NumRoots.
306302 return true;
307303 }
308304
309 bool ShadowStackCollector::IsNullValue(Value *V) {
305 bool ShadowStackGC::IsNullValue(Value *V) {
310306 if (Constant *C = dyn_cast(V))
311307 return C->isNullValue();
312308 return false;
313309 }
314310
315 void ShadowStackCollector::CollectRoots(Function &F) {
311 void ShadowStackGC::CollectRoots(Function &F) {
316312 // FIXME: Account for original alignment. Could fragment the root array.
317313 // Approach 1: Null initialize empty slots at runtime. Yuck.
318314 // Approach 2: Emit a map of the array instead of just a count.
340336 }
341337
342338 GetElementPtrInst *
343 ShadowStackCollector::CreateGEP(IRBuilder<> &B, Value *BasePtr,
344 int Idx, int Idx2, const char *Name) {
339 ShadowStackGC::CreateGEP(IRBuilder<> &B, Value *BasePtr,
340 int Idx, int Idx2, const char *Name) {
345341 Value *Indices[] = { ConstantInt::get(Type::Int32Ty, 0),
346342 ConstantInt::get(Type::Int32Ty, Idx),
347343 ConstantInt::get(Type::Int32Ty, Idx2) };
353349 }
354350
355351 GetElementPtrInst *
356 ShadowStackCollector::CreateGEP(IRBuilder<> &B, Value *BasePtr,
357 int Idx, const char *Name) {
352 ShadowStackGC::CreateGEP(IRBuilder<> &B, Value *BasePtr,
353 int Idx, const char *Name) {
358354 Value *Indices[] = { ConstantInt::get(Type::Int32Ty, 0),
359355 ConstantInt::get(Type::Int32Ty, Idx) };
360356 Value *Val = B.CreateGEP(BasePtr, Indices, Indices + 2, Name);
365361 }
366362
367363 /// runOnFunction - Insert code to maintain the shadow stack.
368 bool ShadowStackCollector::performCustomLowering(Function &F) {
364 bool ShadowStackGC::performCustomLowering(Function &F) {
369365 // Find calls to llvm.gcroot.
370366 CollectRoots(F);
371367
404400 OriginalAlloca->replaceAllUsesWith(SlotPtr);
405401 }
406402
407 // Move past the original stores inserted by Collector::InitRoots. This isn't
408 // really necessary (the collector would never see the intermediate state),
409 // but it's nicer not to push the half-initialized entry onto the stack.
403 // Move past the original stores inserted by GCStrategy::InitRoots. This isn't
404 // really necessary (the collector would never see the intermediate state at
405 // runtime), but it's nicer not to push the half-initialized entry onto the
406 // shadow stack.
410407 while (isa(IP)) ++IP;
411408 AtEntry.SetInsertPoint(IP->getParent(), IP);
412409
33853385 PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
33863386 PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
33873387 PM.add(new CWriter(o));
3388 PM.add(createCollectorMetadataDeleter());
3388 PM.add(createGCInfoDeleter());
33893389 return false;
33903390 }
16021602 Out << ");";
16031603 nl(Out);
16041604 }
1605 if (F->hasCollector()) {
1605 if (F->hasGC()) {
16061606 printCppName(F);
1607 Out << "->setCollector(\"" << F->getCollector() << "\");";
1607 Out << "->setGC(\"" << F->getGC() << "\");";
16081608 nl(Out);
16091609 }
16101610 if (is_inline) {
16591659 PM.add(createCFGSimplificationPass());
16601660 PM.add(new MSILModule(Writer->UsedTypes,Writer->TD));
16611661 PM.add(Writer);
1662 PM.add(createCollectorMetadataDeleter());
1662 PM.add(createGCInfoDeleter());
16631663 return false;
16641664 }
207207 // 1. If the caller has no GC, then the callee's GC must be propagated to the
208208 // caller.
209209 // 2. If the caller has a differing GC, it is invalid to inline.
210 if (CalledFunc->hasCollector()) {
211 if (!Caller->hasCollector())
212 Caller->setCollector(CalledFunc->getCollector());
213 else if (CalledFunc->getCollector() != Caller->getCollector())
210 if (CalledFunc->hasGC()) {
211 if (!Caller->hasGC())
212 Caller->setGC(CalledFunc->getGC());
213 else if (CalledFunc->getGC() != Caller->getGC())
214214 return false;
215215 }
216216
11831183 Out << " section \"" << F->getSection() << '"';
11841184 if (F->getAlignment())
11851185 Out << " align " << F->getAlignment();
1186 if (F->hasCollector())
1187 Out << " gc \"" << F->getCollector() << '"';
1186 if (F->hasGC())
1187 Out << " gc \"" << F->getGC() << '"';
11881188
11891189 if (F->isDeclaration()) {
11901190 Out << "\n";
718718 return unwrap(Fn)->setCallingConv(CC);
719719 }
720720
721 const char *LLVMGetCollector(LLVMValueRef Fn) {
721 const char *LLVMGetGC(LLVMValueRef Fn) {
722722 Function *F = unwrap(Fn);
723 return F->hasCollector()? F->getCollector() : 0;
724 }
725
726 void LLVMSetCollector(LLVMValueRef Fn, const char *Coll) {
723 return F->hasGC()? F->getGC() : 0;
724 }
725
726 void LLVMSetGC(LLVMValueRef Fn, const char *GC) {
727727 Function *F = unwrap(Fn);
728 if (Coll)
729 F->setCollector(Coll);
728 if (GC)
729 F->setGC(GC);
730730 else
731 F->clearCollector();
731 F->clearGC();
732732 }
733733
734734 /*--.. Operations on parameters ............................................--*/
181181 ArgumentList.clear();
182182 delete SymTab;
183183
184 // Remove the function from the on-the-side collector table.
185 clearCollector();
184 // Remove the function from the on-the-side GC table.
185 clearGC();
186186 }
187187
188188 void Function::BuildLazyArguments() const {
239239 setParamAttrs(PAL);
240240 }
241241
242 // Maintain the collector name for each function in an on-the-side table. This
243 // saves allocating an additional word in Function for programs which do not use
244 // GC (i.e., most programs) at the cost of increased overhead for clients which
245 // do use GC.
246 static DenseMap *CollectorNames;
247 static StringPool *CollectorNamePool;
248
249 bool Function::hasCollector() const {
250 return CollectorNames && CollectorNames->count(this);
251 }
252
253 const char *Function::getCollector() const {
254 assert(hasCollector() && "Function has no collector");
255 return *(*CollectorNames)[this];
256 }
257
258 void Function::setCollector(const char *Str) {
259 if (!CollectorNamePool)
260 CollectorNamePool = new StringPool();
261 if (!CollectorNames)
262 CollectorNames = new DenseMap();
263 (*CollectorNames)[this] = CollectorNamePool->intern(Str);
264 }
265
266 void Function::clearCollector() {
267 if (CollectorNames) {
268 CollectorNames->erase(this);
269 if (CollectorNames->empty()) {
270 delete CollectorNames;
271 CollectorNames = 0;
272 if (CollectorNamePool->empty()) {
273 delete CollectorNamePool;
274 CollectorNamePool = 0;
242 // Maintain the GC name for each function in an on-the-side table. This saves
243 // allocating an additional word in Function for programs which do not use GC
244 // (i.e., most programs) at the cost of increased overhead for clients which do
245 // use GC.
246 static DenseMap *GCNames;
247 static StringPool *GCNamePool;
248
249 bool Function::hasGC() const {
250 return GCNames && GCNames->count(this);
251 }
252
253 const char *Function::getGC() const {
254 assert(hasGC() && "Function has no collector");
255 return *(*GCNames)[this];
256 }
257
258 void Function::setGC(const char *Str) {
259 if (!GCNamePool)
260 GCNamePool = new StringPool();
261 if (!GCNames)
262 GCNames = new DenseMap();
263 (*GCNames)[this] = GCNamePool->intern(Str);
264 }
265
266 void Function::clearGC() {
267 if (GCNames) {
268 GCNames->erase(this);
269 if (GCNames->empty()) {
270 delete GCNames;
271 GCNames = 0;
272 if (GCNamePool->empty()) {
273 delete GCNamePool;
274 GCNamePool = 0;
275275 }
276276 }
277277 }
285285 const Function *SrcF = cast(Src);
286286 setCallingConv(SrcF->getCallingConv());
287287 setParamAttrs(SrcF->getParamAttrs());
288 if (SrcF->hasCollector())
289 setCollector(SrcF->getCollector());
288 if (SrcF->hasGC())
289 setGC(SrcF->getGC());
290 else
291 clearGC();
290292 }
291293
292294 /// getIntrinsicID - This method returns the ID number of the specified
13071307 break;
13081308 }
13091309
1310 Assert1(CI.getParent()->getParent()->hasCollector(),
1311 "Enclosing function does not specify a collector algorithm.",
1310 Assert1(CI.getParent()->getParent()->hasGC(),
1311 "Enclosing function does not use GC.",
13121312 &CI);
13131313 } break;
13141314 case Intrinsic::init_trampoline:
568568 insist (CallConv.fast = function_call_conv fn);
569569 ignore (build_unreachable (builder_at_end (entry_block fn)));
570570
571 begin group "collector";
571 begin group "gc";
572572 (* RUN: grep {Fn6.*gc.*shadowstack} < %t.ll
573573 *)
574574 let fn = define_function "Fn6" ty m in
575 insist (None = collector fn);
576 set_collector (Some "ocaml") fn;
577 insist (Some "ocaml" = collector fn);
578 set_collector None fn;
579 insist (None = collector fn);
580 set_collector (Some "shadowstack") fn;
575 insist (None = gc fn);
576 set_gc (Some "ocaml") fn;
577 insist (Some "ocaml" = gc fn);
578 set_gc None fn;
579 insist (None = gc fn);
580 set_gc (Some "shadowstack") fn;
581581 ignore (build_unreachable (builder_at_end (entry_block fn)));
582582 end;
583583