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

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

partial refactoring check in with change for Linda.

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