source: icGREP/icgrep-devel/icgrep/kernels/kernel.cpp @ 5341

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

Added a simple CreateAssert? function in CBuilder and ReadOnly? flag for getStreamSetBufferPtr method to prevent expanding input stream sets. Begun work on CarryManager? to preallocate variable-length carry data slots.

File size: 29.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#include "kernel.h"
7#include <toolchain.h>
8#include <kernels/streamset.h>
9#include <llvm/IR/Constants.h>
10#include <llvm/IR/Function.h>
11#include <llvm/IR/Instructions.h>
12#include <llvm/IR/Module.h>
13#include <llvm/Support/raw_ostream.h>
14#include <llvm/IR/LegacyPassManager.h>
15#include <llvm/Transforms/Scalar.h>
16#ifndef NDEBUG
17#include <llvm/IR/Verifier.h>
18#endif
19
20static const auto DO_BLOCK_SUFFIX = "_DoBlock";
21
22static const auto FINAL_BLOCK_SUFFIX = "_FinalBlock";
23
24static const auto LOGICAL_SEGMENT_NO_SCALAR = "logicalSegNo";
25
26static const auto PROCESSED_ITEM_COUNT_SUFFIX = "_processedItemCount";
27
28static const auto PRODUCED_ITEM_COUNT_SUFFIX = "_producedItemCount";
29
30static const auto TERMINATION_SIGNAL = "terminationSignal";
31
32static const auto BUFFER_PTR_SUFFIX = "_bufferPtr";
33
34static const auto BLOCK_MASK_SUFFIX = "_blkMask";
35
36using namespace llvm;
37using namespace kernel;
38using namespace parabix;
39using namespace llvm::legacy;
40
41unsigned KernelBuilder::addScalar(Type * const type, const std::string & name) {
42    if (LLVM_UNLIKELY(mKernelStateType != nullptr)) {
43        report_fatal_error("Cannot add field " + name + " to " + getName() + " after kernel state finalized");
44    }
45    if (LLVM_UNLIKELY(mKernelMap.count(name))) {
46        report_fatal_error(getName() + " already contains scalar field " + name);
47    }
48    const auto index = mKernelFields.size();
49    mKernelMap.emplace(name, index);
50    mKernelFields.push_back(type);
51    return index;
52}
53
54unsigned KernelBuilder::addUnnamedScalar(Type * const type) {
55    if (LLVM_UNLIKELY(mKernelStateType != nullptr)) {
56        report_fatal_error("Cannot add unnamed kernel field after kernel state finalized");
57    }
58    const auto index = mKernelFields.size();
59    mKernelFields.push_back(type);
60    return index;
61}
62
63void KernelBuilder::prepareKernelSignature() {
64    for (unsigned i = 0; i < mStreamSetInputs.size(); i++) {
65        mStreamSetNameMap.emplace(mStreamSetInputs[i].name, i);
66    }
67    for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
68        mStreamSetNameMap.emplace(mStreamSetOutputs[i].name, i);
69    }
70}
71   
72void KernelBuilder::prepareKernel() {
73    if (LLVM_UNLIKELY(mKernelStateType != nullptr)) {
74        report_fatal_error("Cannot prepare kernel after kernel state finalized");
75    }
76    if (mStreamSetInputs.size() != mStreamSetInputBuffers.size()) {
77        std::string tmp;
78        raw_string_ostream out(tmp);
79        out << "kernel contains " << mStreamSetInputBuffers.size() << " input buffers for "
80            << mStreamSetInputs.size() << " input stream sets.";
81        report_fatal_error(out.str());
82    }
83    if (mStreamSetOutputs.size() != mStreamSetOutputBuffers.size()) {
84        std::string tmp;
85        raw_string_ostream out(tmp);
86        out << "kernel contains " << mStreamSetOutputBuffers.size() << " output buffers for "
87            << mStreamSetOutputs.size() << " output stream sets.";
88        report_fatal_error(out.str());
89    }
90    const auto blockSize = iBuilder->getBitBlockWidth();
91    for (unsigned i = 0; i < mStreamSetInputs.size(); i++) {
92        if ((mStreamSetInputBuffers[i]->getBufferBlocks() > 0) && (mStreamSetInputBuffers[i]->getBufferBlocks() < codegen::SegmentSize + (blockSize + mLookAheadPositions - 1)/blockSize)) {
93            report_fatal_error("Kernel preparation: Buffer size too small " + mStreamSetInputs[i].name);
94        }
95        mScalarInputs.emplace_back(mStreamSetInputBuffers[i]->getPointerType(), mStreamSetInputs[i].name + BUFFER_PTR_SUFFIX);
96        if ((i == 0) || !mStreamSetInputs[i].rate.isExact()) {
97            addScalar(iBuilder->getSizeTy(), mStreamSetInputs[i].name + PROCESSED_ITEM_COUNT_SUFFIX);
98        }
99       
100    }
101    for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
102        mScalarInputs.emplace_back(mStreamSetOutputBuffers[i]->getPointerType(), mStreamSetOutputs[i].name + BUFFER_PTR_SUFFIX);
103        if ((mStreamSetInputs.empty() && (i == 0)) || !mStreamSetOutputs[i].rate.isExact()) {
104            addScalar(iBuilder->getSizeTy(), mStreamSetOutputs[i].name + PRODUCED_ITEM_COUNT_SUFFIX);
105        }
106    }
107    for (const auto binding : mScalarInputs) {
108        addScalar(binding.type, binding.name);
109    }
110    for (const auto binding : mScalarOutputs) {
111        addScalar(binding.type, binding.name);
112    }
113    if (mStreamSetNameMap.empty()) {
114        prepareKernelSignature();
115    }
116    for (auto binding : mInternalScalars) {
117        addScalar(binding.type, binding.name);
118    }
119    addScalar(iBuilder->getSizeTy(), LOGICAL_SEGMENT_NO_SCALAR);
120    addScalar(iBuilder->getInt1Ty(), TERMINATION_SIGNAL);
121    mKernelStateType = StructType::create(iBuilder->getContext(), mKernelFields, getName());
122}
123
124std::unique_ptr<Module> KernelBuilder::createKernelModule(const std::vector<StreamSetBuffer *> & inputs, const std::vector<StreamSetBuffer *> & outputs) {
125    auto saveModule = iBuilder->getModule();
126    auto savePoint = iBuilder->saveIP();
127    auto module = make_unique<Module>(getName() + "_" + iBuilder->getBitBlockTypeName(), iBuilder->getContext());
128    iBuilder->setModule(module.get());
129    generateKernel(inputs, outputs);
130    iBuilder->setModule(saveModule);
131    iBuilder->restoreIP(savePoint);
132    return module;
133}
134
135void KernelBuilder::generateKernel(const std::vector<StreamSetBuffer *> & inputs, const std::vector<StreamSetBuffer *> & outputs) {
136
137    mStreamSetInputBuffers.assign(inputs.begin(), inputs.end());
138    for (unsigned i = 0; i < mStreamSetInputBuffers.size(); ++i) {
139        if (LLVM_UNLIKELY(mStreamSetInputBuffers[i] == nullptr)) {
140            report_fatal_error(getName() + ": input stream set " + std::to_string(i)
141                               + " cannot be null when calling generateKernel()");
142        }
143    }
144    if (LLVM_UNLIKELY(mStreamSetInputs.size() != mStreamSetInputBuffers.size())) {
145        report_fatal_error(getName() + ": expected " + std::to_string(mStreamSetInputs.size()) +
146                           " input stream sets but generateKernel() was given "
147                           + std::to_string(mStreamSetInputBuffers.size()));
148    }
149
150    mStreamSetOutputBuffers.assign(outputs.begin(), outputs.end());
151    for (unsigned i = 0; i < mStreamSetOutputBuffers.size(); ++i) {
152        if (LLVM_UNLIKELY(mStreamSetOutputBuffers[i] == nullptr)) {
153            report_fatal_error(getName() + ": output stream set " + std::to_string(i)
154                               + " cannot be null when calling generateKernel()");
155        }
156    }
157    if (LLVM_UNLIKELY(mStreamSetOutputs.size() != mStreamSetOutputBuffers.size())) {
158        report_fatal_error(getName() + ": expected " + std::to_string(mStreamSetOutputs.size())
159                           + " output stream sets but generateKernel() was given "
160                           + std::to_string(mStreamSetOutputBuffers.size()));
161    }
162
163
164    auto savePoint = iBuilder->saveIP();
165    prepareKernel(); // possibly overridden by the KernelBuilder subtype
166    addKernelDeclarations(iBuilder->getModule());
167    callGenerateInitMethod();
168    generateInternalMethods();
169    callGenerateDoSegmentMethod();
170    // Implement the accumulator get functions
171    for (auto binding : mScalarOutputs) {
172        Function * f = getAccumulatorFunction(binding.name);
173        iBuilder->SetInsertPoint(BasicBlock::Create(iBuilder->getContext(), "get_" + binding.name, f));
174        Value * self = &*(f->arg_begin());
175        Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), getScalarIndex(binding.name)});
176        Value * retVal = iBuilder->CreateLoad(ptr);
177        iBuilder->CreateRet(retVal);
178    }
179    iBuilder->restoreIP(savePoint);
180}
181
182void KernelBuilder::callGenerateDoSegmentMethod() {
183    mCurrentFunction = getDoSegmentFunction();
184    iBuilder->SetInsertPoint(CreateBasicBlock(getName() + "_entry"));
185    auto args = mCurrentFunction->arg_begin();
186    mSelf = &*(args++);
187    Value * doFinal = &*(args++);
188    std::vector<Value *> producerPos;
189    for (unsigned i = 0; i < mStreamSetInputs.size(); i++) {
190        producerPos.push_back(&*(args++));
191    }
192    generateDoSegmentMethod(doFinal, producerPos); // must be overridden by the KernelBuilder subtype
193    iBuilder->CreateRetVoid();
194}
195
196void KernelBuilder::callGenerateInitMethod() {
197    mCurrentFunction = getInitFunction();
198    iBuilder->SetInsertPoint(CreateBasicBlock("entry"));
199    Function::arg_iterator args = mCurrentFunction->arg_begin();
200    mSelf = &*(args++);
201    iBuilder->CreateStore(ConstantAggregateZero::get(mKernelStateType), mSelf);
202    for (auto binding : mScalarInputs) {
203        Value * param = &*(args++);
204        Value * ptr = iBuilder->CreateGEP(mSelf, {iBuilder->getInt32(0), getScalarIndex(binding.name)});
205        iBuilder->CreateStore(param, ptr);
206    }
207    generateInitMethod();
208    iBuilder->CreateRetVoid();
209}
210
211ConstantInt * KernelBuilder::getScalarIndex(const std::string & name) const {
212    const auto f = mKernelMap.find(name);
213    if (LLVM_UNLIKELY(f == mKernelMap.end())) {
214        report_fatal_error(getName() + " does not contain scalar: " + name);
215    }
216    return iBuilder->getInt32(f->second);
217}
218
219unsigned KernelBuilder::getScalarCount() const {
220    return mKernelFields.size();
221}
222
223Value * KernelBuilder::getScalarFieldPtr(Value * instance, Value * index) const {
224    return iBuilder->CreateGEP(instance, {iBuilder->getInt32(0), index});
225}
226
227Value * KernelBuilder::getScalarFieldPtr(Value * instance, const std::string & fieldName) const {
228    return getScalarFieldPtr(instance, getScalarIndex(fieldName));
229}
230
231Value * KernelBuilder::getScalarField(Value * instance, const std::string & fieldName) const {
232    return iBuilder->CreateLoad(getScalarFieldPtr(instance, fieldName));
233}
234
235Value * KernelBuilder::getScalarField(Value * instance, Value * index) const {
236    return iBuilder->CreateLoad(getScalarFieldPtr(instance, index));
237}
238
239void KernelBuilder::setScalarField(Value * instance, const std::string & fieldName, Value * value) const {
240    iBuilder->CreateStore(value, getScalarFieldPtr(instance, fieldName));
241}
242
243void KernelBuilder::setScalarField(Value * instance, Value * index, Value * value) const {
244    iBuilder->CreateStore(value, getScalarFieldPtr(instance, index));
245}
246
247Value * KernelBuilder::getProcessedItemCount(Value * instance, const std::string & name) const {
248    unsigned ssIdx = getStreamSetIndex(name);
249    if (mStreamSetInputs[ssIdx].rate.isExact()) {
250        Value * principalItemsProcessed = getScalarField(instance, mStreamSetInputs[0].name + PROCESSED_ITEM_COUNT_SUFFIX);
251        return mStreamSetInputs[ssIdx].rate.CreateRatioCalculation(iBuilder, principalItemsProcessed);
252    }
253    return getScalarField(instance, name + PROCESSED_ITEM_COUNT_SUFFIX);
254}
255
256Value * KernelBuilder::getProducedItemCount(Value * instance, const std::string & name) const {
257    unsigned ssIdx = getStreamSetIndex(name);
258    if (mStreamSetOutputs[ssIdx].rate.isExact()) {
259        std::string principalField = mStreamSetInputs.empty() ? mStreamSetOutputs[0].name + PRODUCED_ITEM_COUNT_SUFFIX : mStreamSetInputs[0].name + PROCESSED_ITEM_COUNT_SUFFIX;
260        Value * principalItemsProcessed = getScalarField(instance, principalField);
261        return mStreamSetOutputs[ssIdx].rate.CreateRatioCalculation(iBuilder, principalItemsProcessed);
262    }
263    return getScalarField(instance, name + PRODUCED_ITEM_COUNT_SUFFIX);
264}
265
266void KernelBuilder::setProcessedItemCount(Value * instance, const std::string & name, Value * value) const {
267    //iBuilder->CallPrintInt(getName() + " " + name + " processed", value);
268    setScalarField(instance, name + PROCESSED_ITEM_COUNT_SUFFIX, value);
269}
270
271void KernelBuilder::setProducedItemCount(Value * instance, const std::string & name, Value * value) const {
272    //iBuilder->CallPrintInt(getName() + " " + name +  " produced", value);
273    setScalarField(instance, name + PRODUCED_ITEM_COUNT_SUFFIX, value);
274}
275
276Value * KernelBuilder::getTerminationSignal(Value * instance) const {
277    return getScalarField(instance, TERMINATION_SIGNAL);
278}
279
280void KernelBuilder::setTerminationSignal(Value * instance) const {
281    setScalarField(instance, TERMINATION_SIGNAL, iBuilder->getInt1(true));
282}
283
284LoadInst * KernelBuilder::acquireLogicalSegmentNo(Value * instance) const {
285    return iBuilder->CreateAtomicLoadAcquire(getScalarFieldPtr(instance, LOGICAL_SEGMENT_NO_SCALAR));
286}
287
288void KernelBuilder::releaseLogicalSegmentNo(Value * instance, Value * newCount) const {
289    iBuilder->CreateAtomicStoreRelease(newCount, getScalarFieldPtr(instance, LOGICAL_SEGMENT_NO_SCALAR));
290}
291
292inline Value * KernelBuilder::computeBlockIndex(const std::vector<Binding> & bindings, const std::string & name, Value * itemCount) const {
293    for (const Binding & b : bindings) {
294        if (b.name == name) {
295            const auto divisor = iBuilder->getBitBlockWidth();
296            if (LLVM_LIKELY((divisor & (divisor - 1)) == 0)) {
297                return iBuilder->CreateLShr(itemCount, std::log2(divisor));
298            } else {
299                return iBuilder->CreateUDiv(itemCount, iBuilder->getSize(divisor));
300            }
301        }
302    }
303    report_fatal_error("Error: no binding in " + getName() + " for " + name);
304}
305
306Value * KernelBuilder::getInputStreamBlockPtr(const std::string & name, Value * streamIndex) const {
307    Value * const blockIndex = computeBlockIndex(mStreamSetInputs, name, getProcessedItemCount(name));
308    const StreamSetBuffer * const buf = getInputStreamSetBuffer(name);
309    return buf->getStreamBlockPtr(getStreamSetBufferPtr(name), streamIndex, blockIndex, true);
310}
311
312Value * KernelBuilder::loadInputStreamBlock(const std::string & name, Value * streamIndex) const {
313    return iBuilder->CreateBlockAlignedLoad(getInputStreamBlockPtr(name, streamIndex));
314}
315
316Value * KernelBuilder::getInputStreamPackPtr(const std::string & name, Value * streamIndex, Value * packIndex) const {
317    Value * const blockIndex = computeBlockIndex(mStreamSetInputs, name, getProcessedItemCount(name));
318    const StreamSetBuffer * const buf = getInputStreamSetBuffer(name);
319    return buf->getStreamPackPtr(getStreamSetBufferPtr(name), streamIndex, blockIndex, packIndex, true);
320}
321
322Value * KernelBuilder::loadInputStreamPack(const std::string & name, Value * streamIndex, Value * packIndex) const {
323    return iBuilder->CreateBlockAlignedLoad(getInputStreamPackPtr(name, streamIndex, packIndex));
324}
325
326llvm::Value * KernelBuilder::getInputStreamSetCount(const std::string & name) const {
327    return getInputStreamSetBuffer(name)->getStreamSetCount(getStreamSetBufferPtr(name));
328}
329
330llvm::Value * KernelBuilder::getAdjustedInputStreamBlockPtr(Value * blockAdjustment, const std::string & name, llvm::Value * streamIndex) const {
331    Value * blockIndex = computeBlockIndex(mStreamSetInputs, name, getProcessedItemCount(name));
332    blockIndex = iBuilder->CreateAdd(blockIndex, blockAdjustment);
333    const StreamSetBuffer * const buf = getInputStreamSetBuffer(name);
334    return buf->getStreamBlockPtr(getStreamSetBufferPtr(name), streamIndex, blockIndex, true);
335}
336
337Value * KernelBuilder::getOutputStreamBlockPtr(const std::string & name, Value * streamIndex) const {
338    Value * const blockIndex = computeBlockIndex(mStreamSetOutputs, name, getProducedItemCount(name));
339    const StreamSetBuffer * const buf = getOutputStreamSetBuffer(name);
340    return buf->getStreamBlockPtr(getStreamSetBufferPtr(name), streamIndex, blockIndex, false);
341}
342
343void KernelBuilder::storeOutputStreamBlock(const std::string & name, Value * streamIndex, Value * toStore) const {
344    return iBuilder->CreateBlockAlignedStore(toStore, getOutputStreamBlockPtr(name, streamIndex));
345}
346
347Value * KernelBuilder::getOutputStreamPackPtr(const std::string & name, Value * streamIndex, Value * packIndex) const {
348    Value * const blockIndex = computeBlockIndex(mStreamSetOutputs, name, getProducedItemCount(name));
349    const StreamSetBuffer * const buf = getOutputStreamSetBuffer(name);
350    return buf->getStreamPackPtr(getStreamSetBufferPtr(name), streamIndex, blockIndex, packIndex, false);
351}
352
353void KernelBuilder::storeOutputStreamPack(const std::string & name, Value * streamIndex, Value * packIndex, Value * toStore) const {
354    return iBuilder->CreateBlockAlignedStore(toStore, getOutputStreamPackPtr(name, streamIndex, packIndex));
355}
356
357llvm::Value * KernelBuilder::getOutputStreamSetCount(const std::string & name) const {
358    return getOutputStreamSetBuffer(name)->getStreamSetCount(getStreamSetBufferPtr(name));
359}
360
361Value * KernelBuilder::getRawInputPointer(const std::string & name, Value * streamIndex, Value * absolutePosition) const {
362    return getInputStreamSetBuffer(name)->getRawItemPointer(getStreamSetBufferPtr(name), streamIndex, absolutePosition);
363}
364
365Value * KernelBuilder::getRawOutputPointer(const std::string & name, Value * streamIndex, Value * absolutePosition) const {
366    return getOutputStreamSetBuffer(name)->getRawItemPointer(getStreamSetBufferPtr(name), streamIndex, absolutePosition);
367}
368
369unsigned KernelBuilder::getStreamSetIndex(const std::string & name) const {
370    const auto f = mStreamSetNameMap.find(name);
371    if (LLVM_UNLIKELY(f == mStreamSetNameMap.end())) {
372        report_fatal_error(getName() + " does not contain stream set: " + name);
373    }
374    return f->second;
375}
376
377Value * KernelBuilder::getStreamSetBufferPtr(const std::string & name) const {
378    return getScalarField(getSelf(), name + BUFFER_PTR_SUFFIX);
379}
380
381Argument * KernelBuilder::getParameter(Function * const f, const std::string & name) const {
382    for (auto & arg : f->getArgumentList()) {
383        if (arg.getName().equals(name)) {
384            return &arg;
385        }
386    }
387    report_fatal_error(getName() + " does not have parameter " + name);
388}
389
390Value * KernelBuilder::createDoSegmentCall(const std::vector<Value *> & args) const {
391    return iBuilder->CreateCall(getDoSegmentFunction(), args);
392}
393
394Value * KernelBuilder::createGetAccumulatorCall(Value * self, const std::string & accumName) const {
395    return iBuilder->CreateCall(getAccumulatorFunction(accumName), {self});
396}
397
398BasicBlock * KernelBuilder::CreateBasicBlock(std::string && name) const {
399    return BasicBlock::Create(iBuilder->getContext(), name, mCurrentFunction);
400}
401
402void KernelBuilder::createInstance() {
403    if (LLVM_UNLIKELY(mKernelStateType == nullptr)) {
404        report_fatal_error("Cannot instantiate " + getName() + " before calling prepareKernel()");
405    }
406    mKernelInstance = iBuilder->CreateCacheAlignedAlloca(mKernelStateType);
407
408    std::vector<Value *> args;
409    args.reserve(mInitialArguments.size() + mStreamSetInputBuffers.size() + mStreamSetOutputBuffers.size() + 1);
410    args.push_back(mKernelInstance);
411    for (unsigned i = 0; i < mInitialArguments.size(); ++i) {
412        Value * arg = mInitialArguments[i];
413        if (LLVM_UNLIKELY(arg == nullptr)) {
414            report_fatal_error(getName() + ": initial argument " + std::to_string(i)
415                               + " cannot be null when calling createInstance()");
416        }
417        args.push_back(arg);
418    }
419    for (unsigned i = 0; i < mStreamSetInputBuffers.size(); ++i) {
420        assert (mStreamSetInputBuffers[i]);
421        Value * arg = mStreamSetInputBuffers[i]->getStreamSetBasePtr();
422        if (LLVM_UNLIKELY(arg == nullptr)) {
423            report_fatal_error(getName() + ": input stream set " + std::to_string(i)
424                               + " was not allocated prior to calling createInstance()");
425        }
426        args.push_back(arg);
427    }
428    assert (mStreamSetInputs.size() == mStreamSetInputBuffers.size());
429    for (unsigned i = 0; i < mStreamSetOutputBuffers.size(); ++i) {
430        assert (mStreamSetOutputBuffers[i]);
431        Value * arg = mStreamSetOutputBuffers[i]->getStreamSetBasePtr();
432        if (LLVM_UNLIKELY(arg == nullptr)) {
433            report_fatal_error(getName() + ": output stream set " + std::to_string(i)
434                               + " was not allocated prior to calling createInstance()");
435        }
436        args.push_back(arg);
437    }
438    assert (mStreamSetOutputs.size() == mStreamSetOutputBuffers.size());
439    iBuilder->CreateCall(getInitFunction(), args);
440}
441
442//  The default finalBlock method simply dispatches to the doBlock routine.
443void BlockOrientedKernel::generateFinalBlockMethod(Value * remainingBytes) {
444//    std::vector<Value *> args = {self};
445//    for (Argument & arg : function->getArgumentList()){
446//        args.push_back(&arg);
447//    }
448    CreateDoBlockMethodCall();
449}
450
451//  The default doSegment method dispatches to the doBlock routine for
452//  each block of the given number of blocksToDo, and then updates counts.
453void BlockOrientedKernel::generateDoSegmentMethod(Value * doFinal, const std::vector<Value *> & producerPos) {
454
455    BasicBlock * const entryBlock = iBuilder->GetInsertBlock();
456    BasicBlock * const strideLoopCond = CreateBasicBlock(getName() + "_strideLoopCond");
457    BasicBlock * const strideLoopBody = CreateBasicBlock(getName() + "_strideLoopBody");
458    BasicBlock * const stridesDone = CreateBasicBlock(getName() + "_stridesDone");
459    BasicBlock * const doFinalBlock = CreateBasicBlock(getName() + "_doFinalBlock");
460    BasicBlock * const segmentDone = CreateBasicBlock(getName() + "_segmentDone");
461
462    ConstantInt * stride = iBuilder->getSize(iBuilder->getStride());
463
464    Value * availablePos = producerPos[0];
465    for (unsigned i = 1; i < mStreamSetInputs.size(); i++) {
466        Value * p = producerPos[i];
467        availablePos = iBuilder->CreateSelect(iBuilder->CreateICmpULT(availablePos, p), availablePos, p);
468    }
469
470    Value * processed = getProcessedItemCount(mStreamSetInputs[0].name);
471    Value * itemsAvail = iBuilder->CreateSub(availablePos, processed);
472    Value * stridesToDo = iBuilder->CreateUDiv(itemsAvail, stride);
473    iBuilder->CreateBr(strideLoopCond);
474
475    iBuilder->SetInsertPoint(strideLoopCond);
476    PHINode * stridesRemaining = iBuilder->CreatePHI(iBuilder->getSizeTy(), 2, "stridesRemaining");
477    stridesRemaining->addIncoming(stridesToDo, entryBlock);
478    Value * notDone = iBuilder->CreateICmpNE(stridesRemaining, iBuilder->getSize(0));
479    iBuilder->CreateCondBr(notDone, strideLoopBody, stridesDone);
480
481    iBuilder->SetInsertPoint(strideLoopBody);
482
483    CreateDoBlockMethodCall();
484
485    processed = getProcessedItemCount(mStreamSetInputs[0].name);
486    Value * itemsDone = iBuilder->CreateAdd(processed, stride);
487    setProcessedItemCount(mStreamSetInputs[0].name, itemsDone);
488   
489    stridesRemaining->addIncoming(iBuilder->CreateSub(stridesRemaining, iBuilder->getSize(1)), strideLoopBody);
490    iBuilder->CreateBr(strideLoopCond);
491
492    iBuilder->SetInsertPoint(stridesDone);
493
494    // Now conditionally perform the final block processing depending on the doFinal parameter.
495    iBuilder->CreateCondBr(doFinal, doFinalBlock, segmentDone);
496    iBuilder->SetInsertPoint(doFinalBlock);
497
498    Value * remainingItems = iBuilder->CreateSub(producerPos[0], getProcessedItemCount(mStreamSetInputs[0].name));
499
500    CreateDoFinalBlockMethodCall(remainingItems);
501   
502    itemsDone = producerPos[0];
503    setProcessedItemCount(mStreamSetInputs[0].name, itemsDone);   
504   
505    setTerminationSignal();
506    iBuilder->CreateBr(segmentDone);
507
508    iBuilder->SetInsertPoint(segmentDone);
509
510}
511
512void BlockOrientedKernel::generateInternalMethods() {
513
514    callGenerateDoBlockMethod();
515
516    callGenerateDoFinalBlockMethod();
517}
518
519void BlockOrientedKernel::callGenerateDoBlockMethod() {
520    mCurrentFunction = getDoBlockFunction();
521    auto args = mCurrentFunction->arg_begin();
522    mSelf = &(*args);
523    iBuilder->SetInsertPoint(CreateBasicBlock("entry"));
524    std::vector<Value *> priorProduced;
525    for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
526        if (isa<CircularCopybackBuffer>(mStreamSetOutputBuffers[i]))  {
527            priorProduced.push_back(getProducedItemCount(mStreamSetOutputs[i].name));
528        }
529    }
530    generateDoBlockMethod(); // must be implemented by the KernelBuilder subtype
531    for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
532        unsigned priorIdx = 0;
533        if (auto cb = dyn_cast<CircularCopybackBuffer>(mStreamSetOutputBuffers[i]))  {
534            BasicBlock * copyBack = CreateBasicBlock(mStreamSetOutputs[i].name + "_copyBack");
535            BasicBlock * done = CreateBasicBlock(mStreamSetOutputs[i].name + "_copyBackDone");
536            Value * newlyProduced = iBuilder->CreateSub(getProducedItemCount(mStreamSetOutputs[i].name), priorProduced[priorIdx]);
537            Value * accessible = cb->getLinearlyAccessibleItems(priorProduced[priorIdx]);
538            Value * wraparound = iBuilder->CreateICmpULT(accessible, newlyProduced);
539            iBuilder->CreateCondBr(wraparound, copyBack, done);
540            iBuilder->SetInsertPoint(copyBack);
541            Value * copyItems = iBuilder->CreateSub(newlyProduced, accessible);
542            cb->createCopyBack(getStreamSetBufferPtr(mStreamSetOutputs[i].name), copyItems);
543            iBuilder->CreateBr(done);
544            iBuilder->SetInsertPoint(done);
545            priorIdx++;
546        }
547    }   
548    iBuilder->CreateRetVoid();
549    #ifndef NDEBUG
550    std::string tmp;
551    raw_string_ostream out(tmp);
552    if (verifyFunction(*mCurrentFunction, &out)) {
553        mCurrentFunction->dump();
554        report_fatal_error(getName() + ": " + out.str());
555    }
556    #endif
557    // Use the pass manager to optimize the function.
558    FunctionPassManager fpm(iBuilder->getModule());
559    fpm.add(createReassociatePass());             //Reassociate expressions.
560    fpm.add(createGVNPass());                     //Eliminate common subexpressions.
561    fpm.add(createInstructionCombiningPass());    //Simple peephole optimizations and bit-twiddling.
562    fpm.doInitialization();
563    fpm.run(*mCurrentFunction);
564}
565
566
567void BlockOrientedKernel::callGenerateDoFinalBlockMethod() {
568    mCurrentFunction = getDoFinalBlockFunction();
569    auto args = mCurrentFunction->arg_begin();
570    mSelf = &(*args++);
571    Value * const remainingBytes = &(*args);
572    iBuilder->SetInsertPoint(CreateBasicBlock("entry"));
573    generateFinalBlockMethod(remainingBytes); // possibly overridden by the KernelBuilder subtype
574    iBuilder->CreateRetVoid();
575}
576
577Function * BlockOrientedKernel::getDoBlockFunction() const {
578    const auto name = getName() + DO_BLOCK_SUFFIX;
579    Function * const f = iBuilder->getModule()->getFunction(name);
580    if (LLVM_UNLIKELY(f == nullptr)) {
581        report_fatal_error("Cannot find " + name);
582    }
583    return f;
584}
585
586CallInst * BlockOrientedKernel::CreateDoBlockMethodCall() const {
587    return iBuilder->CreateCall(getDoBlockFunction(), mSelf);
588}
589
590Function * BlockOrientedKernel::getDoFinalBlockFunction() const {
591    const auto name = getName() + FINAL_BLOCK_SUFFIX;
592    Function * const f = iBuilder->getModule()->getFunction(name);
593    if (LLVM_UNLIKELY(f == nullptr)) {
594        report_fatal_error("Cannot find " + name);
595    }
596    return f;
597}
598
599CallInst * BlockOrientedKernel::CreateDoFinalBlockMethodCall(Value * remainingItems) const {
600    return iBuilder->CreateCall(getDoFinalBlockFunction(), {mSelf, remainingItems});
601}
602
603void BlockOrientedKernel::addAdditionalKernelDeclarations(Module * m, PointerType * selfType) {
604    // Create the doBlock and finalBlock function prototypes
605    FunctionType * const doBlockType = FunctionType::get(iBuilder->getVoidTy(), {selfType}, false);
606    Function * const doBlock = Function::Create(doBlockType, GlobalValue::ExternalLinkage, getName() + DO_BLOCK_SUFFIX, m);
607    doBlock->setCallingConv(CallingConv::C);
608    doBlock->setDoesNotThrow();
609    doBlock->setDoesNotCapture(1);
610    auto args = doBlock->arg_begin();
611    args->setName("self");
612
613    FunctionType * const finalBlockType = FunctionType::get(iBuilder->getVoidTy(), {selfType, iBuilder->getSizeTy()}, false);
614    Function * const finalBlock = Function::Create(finalBlockType, GlobalValue::ExternalLinkage, getName() + FINAL_BLOCK_SUFFIX, m);
615    finalBlock->setCallingConv(CallingConv::C);
616    finalBlock->setDoesNotThrow();
617    finalBlock->setDoesNotCapture(1);
618    args = finalBlock->arg_begin();
619    args->setName("self");
620    (++args)->setName("remainingBytes");
621}
622
623// CONSTRUCTOR
624KernelBuilder::KernelBuilder(IDISA::IDISA_Builder * builder,
625                             std::string && kernelName,
626                             std::vector<Binding> && stream_inputs,
627                             std::vector<Binding> && stream_outputs,
628                             std::vector<Binding> && scalar_parameters,
629                             std::vector<Binding> && scalar_outputs,
630                             std::vector<Binding> && internal_scalars)
631: KernelInterface(builder, std::move(kernelName), std::move(stream_inputs), std::move(stream_outputs), std::move(scalar_parameters), std::move(scalar_outputs), std::move(internal_scalars))
632, mNoTerminateAttribute(false)
633, mDoBlockUpdatesProducedItemCountsAttribute(false) {
634
635}
636
637KernelBuilder::~KernelBuilder() { }
638
639// CONSTRUCTOR
640BlockOrientedKernel::BlockOrientedKernel(IDISA::IDISA_Builder * builder,
641                                         std::string && kernelName,
642                                         std::vector<Binding> && stream_inputs,
643                                         std::vector<Binding> && stream_outputs,
644                                         std::vector<Binding> && scalar_parameters,
645                                         std::vector<Binding> && scalar_outputs,
646                                         std::vector<Binding> && internal_scalars)
647: KernelBuilder(builder, std::move(kernelName), std::move(stream_inputs), std::move(stream_outputs), std::move(scalar_parameters), std::move(scalar_outputs), std::move(internal_scalars)) {
648
649}
650
651
652
653
654// CONSTRUCTOR
655SegmentOrientedKernel::SegmentOrientedKernel(IDISA::IDISA_Builder * builder,
656                                             std::string && kernelName,
657                                             std::vector<Binding> && stream_inputs,
658                                             std::vector<Binding> && stream_outputs,
659                                             std::vector<Binding> && scalar_parameters,
660                                             std::vector<Binding> && scalar_outputs,
661                                             std::vector<Binding> && internal_scalars)
662: KernelBuilder(builder, std::move(kernelName), std::move(stream_inputs), std::move(stream_outputs), std::move(scalar_parameters), std::move(scalar_outputs), std::move(internal_scalars)) {
663
664}
Note: See TracBrowser for help on using the repository browser.