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

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

Work on the pipeline algorithms.

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