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

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

First attempt to allow Kernels to wait for consumers to finish processing before performing a realloc.

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