source: icGREP/icgrep-devel/icgrep/kernels/kernel.h @ 5398

Last change on this file since 5398 was 5398, checked in by nmedfort, 2 years ago

Continued work on processing stdin input. Partial integration of ParabixDriver? methods into icgrep and editd. Object cache does not currently work for recursive REs.

File size: 15.8 KB
Line 
1/*
2 *  Copyright (c) 2016 International Characters.
3 *  This software is licensed to the public under the Open Software License 3.0.
4 */
5
6#ifndef KERNEL_BUILDER_H
7#define KERNEL_BUILDER_H
8
9#include <string>           // for string
10#include <memory>           // for unique_ptr
11#include "interface.h"      // for KernelInterface
12#include <boost/container/flat_map.hpp>
13#include <IR_Gen/idisa_builder.h>
14
15//namespace llvm { class ConstantInt; }
16#include <llvm/IR/Constants.h>
17namespace llvm { class Function; }
18namespace llvm { class IntegerType; }
19namespace llvm { class LoadInst; }
20namespace llvm { class Type; }
21namespace llvm { class Value; }
22namespace parabix { class StreamSetBuffer; }
23
24namespace kernel {
25   
26class KernelBuilder : public KernelInterface {
27protected:
28    using KernelMap = boost::container::flat_map<std::string, unsigned>;
29    enum class Port { Input, Output };
30    using StreamPort = std::pair<Port, unsigned>;
31    using StreamMap = boost::container::flat_map<std::string, StreamPort>;
32public:
33   
34    // Kernel Signatures and Module IDs
35    //
36    // A kernel signature uniquely identifies a kernel and its full functionality.
37    // In the event that a particular kernel instance is to be generated and compiled
38    // to produce object code, and we have a cached kernel object code instance with
39    // the same signature and targetting the same IDISA architecture, then the cached
40    // object code may safely be used to avoid recompilation.
41    //
42    // A kernel signature is a byte string of arbitrary length.
43    //
44    // Kernel developers should take responsibility for designing appropriate signature
45    // mechanisms that are short, inexpensive to compute and guarantee uniqueness
46    // based on the semantics of the kernel. 
47    //
48    // If no other mechanism is available, the default generateKernelSignature() method
49    // uses the full LLVM IR (before optimization) of the kernel instance.
50    //
51    // A kernel Module ID is short string that is used as a name for a particular kernel
52    // instance.  Kernel Module IDs are used to look up and retrieve cached kernel instances
53    // and so should be highly likely to uniquely identify a kernel instance.
54    //
55    // The ideal case is that a kernel Module ID serves as a full kernel signature thus
56    // guaranteeing uniqueness.  In this case, the moduleIDisUnique() method
57    // should return true.
58    //
59   
60    // Can the module ID itself serve as the unique signature?
61    virtual bool moduleIDisSignature() {/* default */  return false;}
62   
63    virtual void generateKernelSignature(std::string & signature);
64   
65    // Create a module stub for the kernel, populated only with its Module ID.     
66    //
67    std::unique_ptr<llvm::Module> createKernelStub();
68   
69    // Create a module for the kernel, including the kernel state type declaration and
70    // the full implementation of all required methods.     
71    //
72    std::unique_ptr<llvm::Module> createKernelModule(const std::vector<parabix::StreamSetBuffer *> & inputs, const std::vector<parabix::StreamSetBuffer *> & outputs);
73   
74    void setCallParameters(const std::vector<parabix::StreamSetBuffer *> & inputs, const std::vector<parabix::StreamSetBuffer *> & outputs);
75
76    // Generate the Kernel to the current module (iBuilder->getModule()).
77    void generateKernel();
78    void generateKernel(const std::vector<parabix::StreamSetBuffer *> & inputs, const std::vector<parabix::StreamSetBuffer *> & outputs);
79   
80    void createInstance() override;
81
82    llvm::Value * getProducedItemCount(llvm::Value * instance, const std::string & name, llvm::Value * doFinal = nullptr) const final;
83
84    void setProducedItemCount(llvm::Value * instance, const std::string & name, llvm::Value * value) const final;
85
86    llvm::Value * getProcessedItemCount(llvm::Value * instance, const std::string & name) const final;
87
88    void setProcessedItemCount(llvm::Value * instance, const std::string & name, llvm::Value * value) const final;
89
90    bool hasNoTerminateAttribute() { return mNoTerminateAttribute;}
91   
92    llvm::Value * getTerminationSignal(llvm::Value * instance) const final;
93
94    void setTerminationSignal(llvm::Value * instance) const final;
95
96    // Get the value of a scalar field for a given instance.
97    llvm::Value * getScalarField(llvm::Value * instance, const std::string & fieldName) const;
98
99    llvm::Value * getScalarField(llvm::Value * instance, llvm::Value * index) const;
100
101    // Set the value of a scalar field for a given instance.
102    void setScalarField(llvm::Value *instance, const std::string & fieldName, llvm::Value * value) const;
103
104    void setScalarField(llvm::Value * instance, llvm::Value * index, llvm::Value * value) const;
105
106    // Synchronization actions for executing a kernel for a particular logical segment.
107    //
108    // Before the segment is processed, acquireLogicalSegmentNo must be used to load
109    // the segment number of the kernel state to ensure that the previous segment is
110    // complete (by checking that the acquired segment number is equal to the desired segment
111    // number).
112    // After all segment processing actions for the kernel are complete, and any necessary
113    // data has been extracted from the kernel for further pipeline processing, the
114    // segment number must be incremented and stored using releaseLogicalSegmentNo.
115    llvm::LoadInst * acquireLogicalSegmentNo(llvm::Value * instance) const;
116
117    void releaseLogicalSegmentNo(llvm::Value * instance, llvm::Value * newFieldVal) const;
118
119    // Get a parameter by name.
120    llvm::Argument * getParameter(llvm::Function * f, const std::string & name) const;
121
122    inline llvm::IntegerType * getSizeTy() const {
123        return getBuilder()->getSizeTy();
124    }
125
126    inline llvm::Type * getStreamTy(const unsigned FieldWidth = 1) {
127        return getBuilder()->getStreamTy(FieldWidth);
128    }
129   
130    inline llvm::Type * getStreamSetTy(const unsigned NumElements = 1, const unsigned FieldWidth = 1) {
131        return getBuilder()->getStreamSetTy(NumElements, FieldWidth);
132    }
133   
134    virtual ~KernelBuilder() = 0;
135   
136    const std::vector<const parabix::StreamSetBuffer *> & getStreamSetInputBuffers() const { return mStreamSetInputBuffers; }
137
138    const std::vector<const parabix::StreamSetBuffer *> & getStreamSetOutputBuffers() const { return mStreamSetOutputBuffers; }
139
140    llvm::Value * createDoSegmentCall(const std::vector<llvm::Value *> & args) const;
141
142    llvm::Value * createGetAccumulatorCall(llvm::Value * self, const std::string & accumName) const;
143
144protected:
145
146    // Constructor
147    KernelBuilder(IDISA::IDISA_Builder * builder,
148                    std::string && kernelName,
149                    std::vector<Binding> && stream_inputs,
150                    std::vector<Binding> && stream_outputs,
151                    std::vector<Binding> && scalar_parameters,
152                    std::vector<Binding> && scalar_outputs,
153                    std::vector<Binding> && internal_scalars);
154
155    //
156    // Kernel builder subtypes define their logic of kernel construction
157    // in terms of 3 virtual methods for
158    // (a) preparing the Kernel state data structure
159    // (b) defining the logic of the doBlock function, and
160    // (c) defining the logic of the finalBlock function.
161    //
162    // Note: the kernel state data structure must only be finalized after
163    // all scalar fields have been added.   If there are no fields to
164    // be added, the default method for preparing kernel state may be used.
165   
166    void setNoTerminateAttribute(const bool noTerminate = true) {
167        mNoTerminateAttribute = noTerminate;
168    }
169
170    void prepareStreamSetNameMap();
171
172    virtual void prepareKernel();
173
174    virtual void generateInitMethod() { }
175   
176    virtual void generateDoSegmentMethod(llvm::Value * doFinal, const std::vector<llvm::Value *> & producerPos) = 0;
177
178    // Add an additional scalar field to the KernelState struct.
179    // Must occur before any call to addKernelDeclarations or createKernelModule.
180    unsigned addScalar(llvm::Type * type, const std::string & name);
181
182    unsigned addUnnamedScalar(llvm::Type * type);
183
184    unsigned getScalarCount() const;
185
186    // Run-time access of Kernel State and parameters of methods for
187    // use in implementing kernels.
188   
189    // Get the index of a named scalar field within the kernel state struct.
190    llvm::ConstantInt * getScalarIndex(const std::string & name) const;
191
192    // Get the value of a scalar field for a given instance.
193    llvm::Value * getScalarField(const std::string & fieldName) const {
194        return getScalarField(getSelf(), fieldName);
195    }
196
197    llvm::Value * getScalarField(llvm::Value * index) const {
198        return getScalarField(getSelf(), index);
199    }
200
201    // Set the value of a scalar field for a given instance.
202    void setScalarField(const std::string & fieldName, llvm::Value * value) const {
203        return setScalarField(getSelf(), fieldName, value);
204    }
205
206    void setScalarField(llvm::Value * index, llvm::Value * value) const {
207        return setScalarField(getSelf(), index, value);
208    }
209
210    llvm::Value * getInputStreamBlockPtr(const std::string & name, llvm::Value * streamIndex) const;
211
212    llvm::Value * loadInputStreamBlock(const std::string & name, llvm::Value * streamIndex) const;
213   
214    llvm::Value * getInputStreamPackPtr(const std::string & name, llvm::Value * streamIndex, llvm::Value * packIndex) const;
215   
216    llvm::Value * loadInputStreamPack(const std::string & name, llvm::Value * streamIndex, llvm::Value * packIndex) const;
217   
218    llvm::Value * getInputStreamSetCount(const std::string & name) const;
219
220    llvm::Value * getOutputStreamBlockPtr(const std::string & name, llvm::Value * streamIndex) const;
221   
222    void storeOutputStreamBlock(const std::string & name, llvm::Value * streamIndex, llvm::Value * toStore) const;
223   
224    llvm::Value * getOutputStreamPackPtr(const std::string & name, llvm::Value * streamIndex, llvm::Value * packIndex) const;
225   
226    void storeOutputStreamPack(const std::string & name, llvm::Value * streamIndex, llvm::Value * packIndex, llvm::Value * toStore) const;
227
228    llvm::Value * getOutputStreamSetCount(const std::string & name) const;
229
230    llvm::Value * getAdjustedInputStreamBlockPtr(llvm::Value * blockAdjustment, const std::string & name, llvm::Value * streamIndex) const;
231
232    llvm::Value * getRawInputPointer(const std::string & name, llvm::Value * streamIndex, llvm::Value * absolutePosition) const;
233
234    llvm::Value * getRawOutputPointer(const std::string & name, llvm::Value * streamIndex, llvm::Value * absolutePosition) const;
235
236    void setBaseAddress(const std::string & name, llvm::Value * addr) const;
237
238    llvm::Value * getBufferedSize(const std::string & name) const;
239
240    void setBufferedSize(const std::string & name, llvm::Value * size) const;
241
242    void reserveBytes(const std::string & name, llvm::Value * requested) const;
243
244    llvm::Value * getScalarFieldPtr(const std::string & name) const {
245        return getScalarFieldPtr(getSelf(), name);
246    }
247
248    llvm::Value * getScalarFieldPtr(llvm::Value * index) const {
249        return getScalarFieldPtr(getSelf(), index);
250    }
251
252    inline llvm::Value * getProducedItemCount(const std::string & name) const {
253        return getProducedItemCount(getSelf(), name);
254    }
255
256    inline void setProducedItemCount(const std::string & name, llvm::Value * value) const {
257        setProducedItemCount(getSelf(), name, value);
258    }
259
260    inline llvm::Value * getProcessedItemCount(const std::string & name) const {
261        return getProcessedItemCount(getSelf(), name);
262    }
263
264    inline void setProcessedItemCount(const std::string & name, llvm::Value * value) const {
265        setProcessedItemCount(getSelf(), name, value);
266    }
267
268    llvm::Value * getTerminationSignal() const {
269        return getTerminationSignal(getSelf());
270    }
271
272    void setTerminationSignal() const {
273        return setTerminationSignal(getSelf());
274    }
275
276    llvm::Value * getSelf() const {
277        return mSelf;
278    }
279
280    llvm::BasicBlock * CreateBasicBlock(std::string && name) const;
281
282    // Stream set helpers.
283
284    llvm::Value * getStreamSetBufferPtr(const std::string & name) const;
285
286    llvm::Value * getScalarFieldPtr(llvm::Value * instance, const std::string & name) const;
287
288    llvm::Value * getScalarFieldPtr(llvm::Value * instance, llvm::Value * index) const;
289
290    StreamPort getStreamPort(const std::string & name) const;
291
292    const parabix::StreamSetBuffer * getInputStreamSetBuffer(const std::string & name) const {
293        const auto port = getStreamPort(name);
294        assert (port.first == Port::Input);
295        assert (port.second < mStreamSetInputBuffers.size());
296        return mStreamSetInputBuffers[port.second];
297    }
298
299    const parabix::StreamSetBuffer * getOutputStreamSetBuffer(const std::string & name) const {
300        const auto port = getStreamPort(name);
301        assert (port.first == Port::Output);
302        assert (port.second < mStreamSetOutputBuffers.size());
303        return mStreamSetOutputBuffers[port.second];
304    }
305
306    void callGenerateInitMethod();
307
308    void callGenerateDoSegmentMethod();
309
310private:
311
312    llvm::Value * computeBlockIndex(const std::vector<Binding> & binding, const std::string & name, llvm::Value * itemCount) const;
313
314protected:
315
316    llvm::Value *                                   mSelf;
317    llvm::Function *                                mCurrentMethod;
318
319    std::vector<llvm::Type *>                       mKernelFields;
320    KernelMap                                       mKernelMap;
321    StreamMap                                       mStreamMap;
322    std::vector<const parabix::StreamSetBuffer *>   mStreamSetInputBuffers;
323    std::vector<const parabix::StreamSetBuffer *>   mStreamSetOutputBuffers;
324    bool                                            mNoTerminateAttribute;
325    bool                                            mIsGenerated;
326
327};
328
329class SegmentOrientedKernel : public KernelBuilder {
330protected:
331
332    SegmentOrientedKernel(IDISA::IDISA_Builder * builder,
333                          std::string && kernelName,
334                          std::vector<Binding> && stream_inputs,
335                          std::vector<Binding> && stream_outputs,
336                          std::vector<Binding> && scalar_parameters,
337                          std::vector<Binding> && scalar_outputs,
338                          std::vector<Binding> && internal_scalars);
339
340    virtual ~SegmentOrientedKernel() { }
341
342};
343
344class BlockOrientedKernel : public KernelBuilder {
345protected:
346
347    void CreateDoBlockMethodCall();
348
349    // Each kernel builder subtype must provide its own logic for generating
350    // doBlock calls.
351    virtual void generateDoBlockMethod() = 0;
352
353    // Each kernel builder subtypre must also specify the logic for processing the
354    // final block of stream data, if there is any special processing required
355    // beyond simply calling the doBlock function.   In the case that the final block
356    // processing may be trivially implemented by dispatching to the doBlock method
357    // without additional preparation, the default generateFinalBlockMethod need
358    // not be overridden.
359
360    virtual void generateFinalBlockMethod(llvm::Value * remainingItems);
361
362    void generateDoSegmentMethod(llvm::Value * doFinal, const std::vector<llvm::Value *> & producerPos) override final;
363
364    BlockOrientedKernel(IDISA::IDISA_Builder * builder,
365                        std::string && kernelName,
366                        std::vector<Binding> && stream_inputs,
367                        std::vector<Binding> && stream_outputs,
368                        std::vector<Binding> && scalar_parameters,
369                        std::vector<Binding> && scalar_outputs,
370                        std::vector<Binding> && internal_scalars);
371
372    virtual ~BlockOrientedKernel() { }
373
374private:
375
376    bool useIndirectBr() const {
377        return iBuilder->supportsIndirectBr();
378    }
379
380    void writeDoBlockMethod();
381
382    void writeFinalBlockMethod(llvm::Value * remainingItems);
383
384private:
385
386    llvm::Function *        mDoBlockMethod;
387    llvm::BasicBlock *      mStrideLoopBody;
388    llvm::IndirectBrInst *  mStrideLoopBranch;
389    llvm::PHINode *         mStrideLoopTarget;
390};
391
392
393}
394#endif
Note: See TracBrowser for help on using the repository browser.