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

Last change on this file since 5441 was 5441, checked in by cameron, 2 years ago

Reimplement StdoutKernel? using MultiBlockKernel?

File size: 50.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#include "kernel.h"
7#include <toolchain/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/MDBuilder.h>
13#include <llvm/IR/Module.h>
14#include <llvm/Support/raw_ostream.h>
15#include <llvm/Bitcode/ReaderWriter.h>
16#include <llvm/Transforms/Utils/Local.h>
17#include <kernels/streamset.h>
18#include <sstream>
19#include <kernels/kernel_builder.h>
20
21using namespace llvm;
22using namespace parabix;
23
24namespace kernel {
25
26const std::string Kernel::DO_BLOCK_SUFFIX = "_DoBlock";
27const std::string Kernel::FINAL_BLOCK_SUFFIX = "_FinalBlock";
28const std::string Kernel::MULTI_BLOCK_SUFFIX = "_MultiBlock";
29const std::string Kernel::LOGICAL_SEGMENT_NO_SCALAR = "logicalSegNo";
30const std::string Kernel::PROCESSED_ITEM_COUNT_SUFFIX = "_processedItemCount";
31const std::string Kernel::CONSUMED_ITEM_COUNT_SUFFIX = "_consumedItemCount";
32const std::string Kernel::PRODUCED_ITEM_COUNT_SUFFIX = "_producedItemCount";
33const std::string Kernel::TERMINATION_SIGNAL = "terminationSignal";
34const std::string Kernel::BUFFER_PTR_SUFFIX = "_bufferPtr";
35const std::string Kernel::CONSUMER_SUFFIX = "_consumerLocks";
36
37unsigned Kernel::addScalar(Type * const type, const std::string & name) {
38    if (LLVM_UNLIKELY(mKernelStateType != nullptr)) {
39        report_fatal_error("Cannot add field " + name + " to " + getName() + " after kernel state finalized");
40    }
41    if (LLVM_UNLIKELY(mKernelMap.count(name))) {
42        report_fatal_error(getName() + " already contains scalar field " + name);
43    }
44    const auto index = mKernelFields.size();
45    mKernelMap.emplace(name, index);
46    mKernelFields.push_back(type);
47    return index;
48}
49
50unsigned Kernel::addUnnamedScalar(Type * const type) {
51    if (LLVM_UNLIKELY(mKernelStateType != nullptr)) {
52        report_fatal_error("Cannot add unnamed field  to " + getName() + " after kernel state finalized");
53    }
54    const auto index = mKernelFields.size();
55    mKernelFields.push_back(type);
56    return index;
57}
58
59void Kernel::prepareStreamSetNameMap() {
60    for (unsigned i = 0; i < mStreamSetInputs.size(); i++) {
61        mStreamMap.emplace(mStreamSetInputs[i].name, std::make_pair(Port::Input, i));
62    }
63    for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
64        mStreamMap.emplace(mStreamSetOutputs[i].name, std::make_pair(Port::Output, i));
65    }
66}
67   
68void Kernel::createKernelStub(const std::unique_ptr<KernelBuilder> & idb, const StreamSetBuffers & inputs, const StreamSetBuffers & outputs) {
69    assert ("KernelBuilder does not have a valid IDISA Builder" && idb);
70    assert ("IDISA Builder does not have a valid Module" && idb->getModule());
71    std::stringstream cacheName;   
72    cacheName << getName() << '_' << idb->getBuilderUniqueName();
73    for (const StreamSetBuffer * b: inputs) {
74        cacheName <<  ':' <<  b->getUniqueID();
75    }
76    for (const StreamSetBuffer * b: outputs) {
77        cacheName <<  ':' <<  b->getUniqueID();
78    }
79    Module * const kernelModule = new Module(cacheName.str(), idb->getContext());
80    createKernelStub(idb, inputs, outputs, kernelModule);
81}
82
83void Kernel::createKernelStub(const std::unique_ptr<KernelBuilder> & idb, const StreamSetBuffers & inputs, const StreamSetBuffers & outputs, Module * const kernelModule) {
84    assert (mModule == nullptr);
85    assert ("KernelBuilder does not have a valid IDISA Builder" && idb);
86    assert (mStreamSetInputBuffers.empty());
87    assert (mStreamSetOutputBuffers.empty());
88
89    if (LLVM_UNLIKELY(mStreamSetInputs.size() != inputs.size())) {
90        report_fatal_error(getName() + ": expected " + std::to_string(mStreamSetInputs.size()) +
91                           " input stream sets but was given "
92                           + std::to_string(inputs.size()));
93    }
94
95    for (unsigned i = 0; i < inputs.size(); ++i) {
96        StreamSetBuffer * const buf = inputs[i];
97        if (LLVM_UNLIKELY(buf == nullptr)) {
98            report_fatal_error(getName() + ": input stream set " + std::to_string(i)
99                               + " cannot be null");
100        }
101        buf->addConsumer(this);
102    }
103
104    if (LLVM_UNLIKELY(mStreamSetOutputs.size() != outputs.size())) {
105        report_fatal_error(getName() + ": expected " + std::to_string(mStreamSetOutputs.size())
106                           + " output stream sets but was given "
107                           + std::to_string(outputs.size()));
108    }
109
110    for (unsigned i = 0; i < outputs.size(); ++i) {
111        StreamSetBuffer * const buf = outputs[i];
112        if (LLVM_UNLIKELY(buf == nullptr)) {
113            report_fatal_error(getName() + ": output stream set " + std::to_string(i) + " cannot be null");
114        }
115        if (LLVM_LIKELY(buf->getProducer() == nullptr)) {
116            buf->setProducer(this);
117        } else {
118            report_fatal_error(getName() + ": output stream set " + std::to_string(i)
119                               + " is already produced by kernel " + buf->getProducer()->getName());
120        }
121    }
122
123    mModule = kernelModule;
124    mStreamSetInputBuffers.assign(inputs.begin(), inputs.end());
125    mStreamSetOutputBuffers.assign(outputs.begin(), outputs.end());
126    prepareKernel(idb);
127}
128
129void Kernel::prepareKernel(const std::unique_ptr<KernelBuilder> & idb) {
130    assert ("KernelBuilder does not have a valid IDISA Builder" && idb);
131    if (LLVM_UNLIKELY(mKernelStateType != nullptr)) {
132        report_fatal_error("Cannot prepare kernel after kernel state finalized");
133    }
134    if (mStreamSetInputs.size() != mStreamSetInputBuffers.size()) {
135        std::string tmp;
136        raw_string_ostream out(tmp);
137        out << "kernel contains " << mStreamSetInputBuffers.size() << " input buffers for "
138            << mStreamSetInputs.size() << " input stream sets.";
139        report_fatal_error(out.str());
140    }
141    if (mStreamSetOutputs.size() != mStreamSetOutputBuffers.size()) {
142        std::string tmp;
143        raw_string_ostream out(tmp);
144        out << "kernel contains " << mStreamSetOutputBuffers.size() << " output buffers for "
145            << mStreamSetOutputs.size() << " output stream sets.";
146        report_fatal_error(out.str());
147    }
148    const auto blockSize = idb->getBitBlockWidth();
149    for (unsigned i = 0; i < mStreamSetInputs.size(); i++) {
150        if ((mStreamSetInputBuffers[i]->getBufferBlocks() > 0) && (mStreamSetInputBuffers[i]->getBufferBlocks() < codegen::SegmentSize + (blockSize + mLookAheadPositions - 1)/blockSize)) {
151            report_fatal_error("Kernel preparation: Buffer size too small " + mStreamSetInputs[i].name);
152        }
153        mScalarInputs.emplace_back(mStreamSetInputBuffers[i]->getPointerType(), mStreamSetInputs[i].name + BUFFER_PTR_SUFFIX);
154        if ((i == 0) || !mStreamSetInputs[i].rate.isExact()) {
155            addScalar(idb->getSizeTy(), mStreamSetInputs[i].name + PROCESSED_ITEM_COUNT_SUFFIX);
156        }
157    }
158
159    IntegerType * const sizeTy = idb->getSizeTy();
160    for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
161        mScalarInputs.emplace_back(mStreamSetOutputBuffers[i]->getPointerType(), mStreamSetOutputs[i].name + BUFFER_PTR_SUFFIX);
162        if ((mStreamSetInputs.empty() && (i == 0)) || !mStreamSetOutputs[i].rate.isExact()) {
163            addScalar(sizeTy, mStreamSetOutputs[i].name + PRODUCED_ITEM_COUNT_SUFFIX);
164        }
165    }
166    for (const auto binding : mScalarInputs) {
167        addScalar(binding.type, binding.name);
168    }
169    for (const auto binding : mScalarOutputs) {
170        addScalar(binding.type, binding.name);
171    }
172    if (mStreamMap.empty()) {
173        prepareStreamSetNameMap();
174    }
175    for (auto binding : mInternalScalars) {
176        addScalar(binding.type, binding.name);
177    }
178
179    Type * const consumerSetTy = StructType::get(sizeTy, sizeTy->getPointerTo()->getPointerTo(), nullptr)->getPointerTo();
180    for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
181        addScalar(consumerSetTy, mStreamSetOutputs[i].name + CONSUMER_SUFFIX);
182    }
183
184    addScalar(sizeTy, LOGICAL_SEGMENT_NO_SCALAR);
185    addScalar(idb->getInt1Ty(), TERMINATION_SIGNAL);
186
187    for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
188        addScalar(sizeTy, mStreamSetOutputs[i].name + CONSUMED_ITEM_COUNT_SUFFIX);
189    }
190
191    mKernelStateType = StructType::create(idb->getContext(), mKernelFields, getName());
192}
193
194// Default kernel signature: generate the IR and emit as byte code.
195std::string Kernel::makeSignature(const std::unique_ptr<kernel::KernelBuilder> & idb) {
196    assert ("KernelBuilder does not have a valid IDISA Builder" && idb.get());
197    if (LLVM_LIKELY(moduleIDisSignature())) {
198        return getModule()->getModuleIdentifier();
199    } else {
200        generateKernel(idb);
201        std::string signature;
202        raw_string_ostream OS(signature);
203        WriteBitcodeToFile(getModule(), OS);
204        return signature;
205    }
206}
207
208void Kernel::generateKernel(const std::unique_ptr<kernel::KernelBuilder> & idb) {
209    assert ("KernelBuilder does not have a valid IDISA Builder" && idb.get());
210    // If the module id cannot uniquely identify this kernel, "generateKernelSignature()" will have already
211    // generated the unoptimized IR.
212    if (!mIsGenerated) {
213        const auto m = idb->getModule();
214        const auto ip = idb->saveIP();
215        const auto saveInstance = getInstance();
216        idb->setModule(mModule);
217        addKernelDeclarations(idb);
218        callGenerateInitializeMethod(idb);
219        callGenerateDoSegmentMethod(idb);
220        callGenerateFinalizeMethod(idb);
221        setInstance(saveInstance);
222        idb->setModule(m);
223        idb->restoreIP(ip);
224        mIsGenerated = true;
225    }
226}
227
228inline void Kernel::callGenerateInitializeMethod(const std::unique_ptr<kernel::KernelBuilder> & idb) {
229    mCurrentMethod = getInitFunction(idb->getModule());
230    idb->SetInsertPoint(BasicBlock::Create(idb->getContext(), "entry", mCurrentMethod));
231    Function::arg_iterator args = mCurrentMethod->arg_begin();
232    setInstance(&*(args++));
233    idb->CreateStore(ConstantAggregateZero::get(mKernelStateType), getInstance());
234    for (const auto & binding : mScalarInputs) {
235        idb->setScalarField(binding.name, &*(args++));
236    }
237    for (const auto & binding : mStreamSetOutputs) {
238        idb->setConsumerLock(binding.name, &*(args++));
239    }
240    generateInitializeMethod(idb);
241    idb->CreateRetVoid();
242}
243
244inline void Kernel::callGenerateDoSegmentMethod(const std::unique_ptr<kernel::KernelBuilder> & idb) {
245    mCurrentMethod = getDoSegmentFunction(idb->getModule());
246    idb->SetInsertPoint(BasicBlock::Create(idb->getContext(), "entry", mCurrentMethod));
247    auto args = mCurrentMethod->arg_begin();
248    setInstance(&*(args++));
249    mIsFinal = &*(args++);
250    const auto n = mStreamSetInputs.size();
251    mAvailableItemCount.resize(n, nullptr);
252    for (unsigned i = 0; i < mStreamSetInputs.size(); i++) {
253        mAvailableItemCount[i] = &*(args++);
254    }
255    generateDoSegmentMethod(idb); // must be overridden by the KernelBuilder subtype
256    mIsFinal = nullptr;
257    mAvailableItemCount.clear();
258    idb->CreateRetVoid();
259}
260
261inline void Kernel::callGenerateFinalizeMethod(const std::unique_ptr<KernelBuilder> & idb) {
262    mCurrentMethod = getTerminateFunction(idb->getModule());
263    idb->SetInsertPoint(BasicBlock::Create(idb->getContext(), "entry", mCurrentMethod));
264    auto args = mCurrentMethod->arg_begin();
265    setInstance(&*(args++));
266    generateFinalizeMethod(idb); // may be overridden by the KernelBuilder subtype
267    const auto n = mScalarOutputs.size();
268    if (n == 0) {
269        idb->CreateRetVoid();
270    } else {
271        Value * outputs[n];
272        for (unsigned i = 0; i < n; ++i) {
273            outputs[i] = idb->getScalarField(mScalarOutputs[i].name);
274        }
275        if (n == 1) {
276            idb->CreateRet(outputs[0]);
277        } else {
278            idb->CreateAggregateRet(outputs, n);
279        }
280    }
281}
282
283unsigned Kernel::getScalarIndex(const std::string & name) const {
284    const auto f = mKernelMap.find(name);
285    if (LLVM_UNLIKELY(f == mKernelMap.end())) {
286        assert (false);
287        report_fatal_error(getName() + " does not contain scalar: " + name);
288    }
289    return f->second;
290}
291
292Value * Kernel::createInstance(const std::unique_ptr<KernelBuilder> & idb) {
293    assert ("KernelBuilder does not have a valid IDISA Builder" && idb);
294    if (LLVM_UNLIKELY(mKernelStateType == nullptr)) {
295        report_fatal_error("Cannot instantiate " + getName() + " before calling prepareKernel()");
296    }
297    setInstance(idb->CreateCacheAlignedAlloca(mKernelStateType));
298    return getInstance();
299}
300
301void Kernel::initializeInstance(const std::unique_ptr<KernelBuilder> & idb) {
302    assert ("KernelBuilder does not have a valid IDISA Builder" && idb);
303    if (LLVM_UNLIKELY(getInstance() == nullptr)) {
304        report_fatal_error("Cannot initialize " + getName() + " before calling createInstance()");
305    }
306    std::vector<Value *> args;
307    args.reserve(1 + mInitialArguments.size() + mStreamSetInputBuffers.size() + (mStreamSetOutputBuffers.size() * 2));
308    args.push_back(getInstance());
309    for (unsigned i = 0; i < mInitialArguments.size(); ++i) {
310        Value * arg = mInitialArguments[i];
311        if (LLVM_UNLIKELY(arg == nullptr)) {
312            report_fatal_error(getName() + ": initial argument " + std::to_string(i)
313                               + " cannot be null when calling createInstance()");
314        }
315        args.push_back(arg);
316    }
317    for (unsigned i = 0; i < mStreamSetInputBuffers.size(); ++i) {
318        assert (mStreamSetInputBuffers[i]);
319        Value * arg = mStreamSetInputBuffers[i]->getStreamSetBasePtr();
320        if (LLVM_UNLIKELY(arg == nullptr)) {
321            report_fatal_error(getName() + ": input stream set " + std::to_string(i)
322                               + " was not allocated prior to calling createInstance()");
323        }
324        args.push_back(arg);
325    }
326    assert (mStreamSetInputs.size() == mStreamSetInputBuffers.size());
327    for (unsigned i = 0; i < mStreamSetOutputBuffers.size(); ++i) {
328        assert (mStreamSetOutputBuffers[i]);
329        Value * arg = mStreamSetOutputBuffers[i]->getStreamSetBasePtr();
330        if (LLVM_UNLIKELY(arg == nullptr)) {
331            report_fatal_error(getName() + ": output stream set " + std::to_string(i)
332                               + " was not allocated prior to calling createInstance()");
333        }
334        args.push_back(arg);
335    }
336    assert (mStreamSetOutputs.size() == mStreamSetOutputBuffers.size());
337    IntegerType * const sizeTy = idb->getSizeTy();
338    PointerType * const sizePtrTy = sizeTy->getPointerTo();
339    PointerType * const sizePtrPtrTy = sizePtrTy->getPointerTo();
340    StructType * const consumerTy = StructType::get(sizeTy, sizePtrPtrTy, nullptr);
341    for (unsigned i = 0; i < mStreamSetOutputBuffers.size(); ++i) {
342        const auto output = mStreamSetOutputBuffers[i];
343        const auto & consumers = output->getConsumers();
344        const auto n = consumers.size();
345        AllocaInst * const outputConsumers = idb->CreateAlloca(consumerTy);
346        Value * const consumerSegNoArray = idb->CreateAlloca(ArrayType::get(sizePtrTy, n));
347        for (unsigned i = 0; i < n; ++i) {
348            Kernel * const consumer = consumers[i];
349            assert ("all instances must be created prior to initialization of any instance" && consumer->getInstance());
350            idb->setKernel(consumer);
351            Value * const segmentNoPtr = idb->getScalarFieldPtr(LOGICAL_SEGMENT_NO_SCALAR);
352            idb->CreateStore(segmentNoPtr, idb->CreateGEP(consumerSegNoArray, { idb->getInt32(0), idb->getInt32(i) }));
353        }
354        idb->setKernel(this);
355        Value * const consumerCountPtr = idb->CreateGEP(outputConsumers, {idb->getInt32(0), idb->getInt32(0)});
356        idb->CreateStore(idb->getSize(n), consumerCountPtr);
357        Value * const consumerSegNoArrayPtr = idb->CreateGEP(outputConsumers, {idb->getInt32(0), idb->getInt32(1)});
358        idb->CreateStore(idb->CreatePointerCast(consumerSegNoArray, sizePtrPtrTy), consumerSegNoArrayPtr);
359        args.push_back(outputConsumers);
360    }
361    idb->CreateCall(getInitFunction(idb->getModule()), args);
362}
363
364//  The default doSegment method dispatches to the doBlock routine for
365//  each block of the given number of blocksToDo, and then updates counts.
366
367void BlockOrientedKernel::generateDoSegmentMethod(const std::unique_ptr<KernelBuilder> & idb) {
368    BasicBlock * const entryBlock = idb->GetInsertBlock();
369    BasicBlock * const strideLoopCond = idb->CreateBasicBlock(getName() + "_strideLoopCond");
370    mStrideLoopBody = idb->CreateBasicBlock(getName() + "_strideLoopBody");
371    BasicBlock * const stridesDone = idb->CreateBasicBlock(getName() + "_stridesDone");
372    BasicBlock * const doFinalBlock = idb->CreateBasicBlock(getName() + "_doFinalBlock");
373    BasicBlock * const segmentDone = idb->CreateBasicBlock(getName() + "_segmentDone");
374
375    Value * baseTarget = nullptr;
376    if (idb->supportsIndirectBr()) {
377        baseTarget = idb->CreateSelect(mIsFinal, BlockAddress::get(doFinalBlock), BlockAddress::get(segmentDone));
378    }
379
380    ConstantInt * stride = idb->getSize(idb->getStride());
381    Value * availablePos = mAvailableItemCount[0];
382    Value * processed = idb->getProcessedItemCount(mStreamSetInputs[0].name);
383    Value * itemsAvail = idb->CreateSub(availablePos, processed);
384    Value * stridesToDo = idb->CreateUDiv(itemsAvail, stride);
385
386    idb->CreateBr(strideLoopCond);
387
388    idb->SetInsertPoint(strideLoopCond);
389
390    PHINode * branchTarget = nullptr;
391    if (idb->supportsIndirectBr()) {
392        branchTarget = idb->CreatePHI(baseTarget->getType(), 2, "branchTarget");
393        branchTarget->addIncoming(baseTarget, entryBlock);
394    }
395
396    PHINode * const stridesRemaining = idb->CreatePHI(idb->getSizeTy(), 2, "stridesRemaining");
397    stridesRemaining->addIncoming(stridesToDo, entryBlock);
398    // NOTE: stridesRemaining may go to a negative number in the final block if the generateFinalBlockMethod(...)
399    // calls CreateDoBlockMethodCall(). Do *not* replace the comparator with an unsigned one!
400    Value * notDone = idb->CreateICmpSGT(stridesRemaining, idb->getSize(0));
401    idb->CreateLikelyCondBr(notDone, mStrideLoopBody, stridesDone);
402
403    idb->SetInsertPoint(mStrideLoopBody);
404
405    if (idb->supportsIndirectBr()) {
406        mStrideLoopTarget = idb->CreatePHI(baseTarget->getType(), 2, "strideTarget");
407        mStrideLoopTarget->addIncoming(branchTarget, strideLoopCond);
408    }
409
410    /// GENERATE DO BLOCK METHOD
411
412    writeDoBlockMethod(idb);
413
414    /// UPDATE PROCESSED COUNTS
415
416    processed = idb->getProcessedItemCount(mStreamSetInputs[0].name);
417    Value * itemsDone = idb->CreateAdd(processed, stride);
418    idb->setProcessedItemCount(mStreamSetInputs[0].name, itemsDone);
419
420    stridesRemaining->addIncoming(idb->CreateSub(stridesRemaining, idb->getSize(1)), idb->GetInsertBlock());
421
422    BasicBlock * bodyEnd = idb->GetInsertBlock();
423    if (idb->supportsIndirectBr()) {
424        branchTarget->addIncoming(mStrideLoopTarget, bodyEnd);
425    }
426    idb->CreateBr(strideLoopCond);
427
428    stridesDone->moveAfter(bodyEnd);
429
430    idb->SetInsertPoint(stridesDone);
431
432    // Now conditionally perform the final block processing depending on the doFinal parameter.
433    if (idb->supportsIndirectBr()) {
434        mStrideLoopBranch = idb->CreateIndirectBr(branchTarget, 3);
435        mStrideLoopBranch->addDestination(doFinalBlock);
436        mStrideLoopBranch->addDestination(segmentDone);
437    } else {
438        idb->CreateUnlikelyCondBr(mIsFinal, doFinalBlock, segmentDone);
439    }
440
441    doFinalBlock->moveAfter(stridesDone);
442
443    idb->SetInsertPoint(doFinalBlock);
444
445    Value * remainingItems = idb->CreateSub(mAvailableItemCount[0], idb->getProcessedItemCount(mStreamSetInputs[0].name));
446
447    writeFinalBlockMethod(idb, remainingItems);
448
449    itemsDone = mAvailableItemCount[0];
450    idb->setProcessedItemCount(mStreamSetInputs[0].name, itemsDone);
451    idb->setTerminationSignal();
452    idb->CreateBr(segmentDone);
453
454    segmentDone->moveAfter(idb->GetInsertBlock());
455
456    idb->SetInsertPoint(segmentDone);
457
458    // Update the branch prediction metadata to indicate that the likely target will be segmentDone
459    if (idb->supportsIndirectBr()) {
460        MDBuilder mdb(idb->getContext());
461        const auto destinations = mStrideLoopBranch->getNumDestinations();
462        uint32_t weights[destinations];
463        for (unsigned i = 0; i < destinations; ++i) {
464            weights[i] = (mStrideLoopBranch->getDestination(i) == segmentDone) ? 100 : 1;
465        }
466        ArrayRef<uint32_t> bw(weights, destinations);
467        mStrideLoopBranch->setMetadata(LLVMContext::MD_prof, mdb.createBranchWeights(bw));
468    }
469
470}
471
472inline void BlockOrientedKernel::writeDoBlockMethod(const std::unique_ptr<KernelBuilder> & idb) {
473
474    Value * const self = getInstance();
475    Function * const cp = mCurrentMethod;
476    auto ip = idb->saveIP();
477
478    /// Check if the do block method is called and create the function if necessary   
479    if (!idb->supportsIndirectBr()) {
480        FunctionType * const type = FunctionType::get(idb->getVoidTy(), {self->getType()}, false);
481        mCurrentMethod = Function::Create(type, GlobalValue::InternalLinkage, getName() + DO_BLOCK_SUFFIX, idb->getModule());
482        mCurrentMethod->setCallingConv(CallingConv::C);
483        mCurrentMethod->setDoesNotThrow();
484        mCurrentMethod->setDoesNotCapture(1);
485        auto args = mCurrentMethod->arg_begin();
486        args->setName("self");
487        setInstance(&*args);
488        idb->SetInsertPoint(idb->CreateBasicBlock("entry"));
489    }
490
491    std::vector<Value *> priorProduced;
492    for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
493        if (isa<CircularCopybackBuffer>(mStreamSetOutputBuffers[i]) || isa<SwizzledCopybackBuffer>(mStreamSetOutputBuffers[i]))  {
494            priorProduced.push_back(idb->getProducedItemCount(mStreamSetOutputs[i].name));
495        }
496    }
497
498    generateDoBlockMethod(idb); // must be implemented by the BlockOrientedKernelBuilder subtype
499
500    unsigned priorIdx = 0;
501    for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
502        Value * log2BlockSize = idb->getSize(std::log2(idb->getBitBlockWidth()));
503        if (SwizzledCopybackBuffer * const cb = dyn_cast<SwizzledCopybackBuffer>(mStreamSetOutputBuffers[i]))  {
504            BasicBlock * copyBack = idb->CreateBasicBlock(mStreamSetOutputs[i].name + "_copyBack");
505            BasicBlock * done = idb->CreateBasicBlock(mStreamSetOutputs[i].name + "_copyBackDone");
506            Value * newlyProduced = idb->CreateSub(idb->getProducedItemCount(mStreamSetOutputs[i].name), priorProduced[priorIdx]);
507            Value * priorBlock = idb->CreateLShr(priorProduced[priorIdx], log2BlockSize);
508            Value * priorOffset = idb->CreateAnd(priorProduced[priorIdx], idb->getSize(idb->getBitBlockWidth() - 1));
509            Value * instance = idb->getStreamSetBufferPtr(mStreamSetOutputs[i].name);
510            Value * accessibleBlocks = cb->getLinearlyAccessibleBlocks(idb.get(), priorBlock);
511            Value * accessible = idb->CreateSub(idb->CreateShl(accessibleBlocks, log2BlockSize), priorOffset);
512            Value * wraparound = idb->CreateICmpULT(accessible, newlyProduced);
513            idb->CreateCondBr(wraparound, copyBack, done);
514            idb->SetInsertPoint(copyBack);
515            Value * copyItems = idb->CreateSub(newlyProduced, accessible);
516            cb->createCopyBack(idb.get(), instance, copyItems);
517            idb->CreateBr(done);
518            idb->SetInsertPoint(done);
519            priorIdx++;
520        }
521        if (CircularCopybackBuffer * const cb = dyn_cast<CircularCopybackBuffer>(mStreamSetOutputBuffers[i]))  {
522            BasicBlock * copyBack = idb->CreateBasicBlock(mStreamSetOutputs[i].name + "_copyBack");
523            BasicBlock * done = idb->CreateBasicBlock(mStreamSetOutputs[i].name + "_copyBackDone");
524            Value * instance = idb->getStreamSetBufferPtr(mStreamSetOutputs[i].name);
525            Value * newlyProduced = idb->CreateSub(idb->getProducedItemCount(mStreamSetOutputs[i].name), priorProduced[priorIdx]);
526            Value * accessible = cb->getLinearlyAccessibleItems(idb.get(), priorProduced[priorIdx]);
527            Value * wraparound = idb->CreateICmpULT(accessible, newlyProduced);
528            idb->CreateCondBr(wraparound, copyBack, done);
529            idb->SetInsertPoint(copyBack);
530            Value * copyItems = idb->CreateSub(newlyProduced, accessible);
531            cb->createCopyBack(idb.get(), instance, copyItems);
532            idb->CreateBr(done);
533            idb->SetInsertPoint(done);
534            priorIdx++;
535        }
536    }
537
538
539    /// Call the do block method if necessary then restore the current function state to the do segement method
540    if (!idb->supportsIndirectBr()) {
541        idb->CreateRetVoid();
542        mDoBlockMethod = mCurrentMethod;
543        idb->restoreIP(ip);
544        idb->CreateCall(mCurrentMethod, self);
545        setInstance(self);
546        mCurrentMethod = cp;
547    }
548
549}
550
551inline void BlockOrientedKernel::writeFinalBlockMethod(const std::unique_ptr<KernelBuilder> & idb, Value * remainingItems) {
552
553    Value * const self = getInstance();
554    Function * const cp = mCurrentMethod;
555    Value * const remainingItemCount = remainingItems;
556    auto ip = idb->saveIP();
557
558    if (!idb->supportsIndirectBr()) {
559        FunctionType * const type = FunctionType::get(idb->getVoidTy(), {self->getType(), idb->getSizeTy()}, false);
560        mCurrentMethod = Function::Create(type, GlobalValue::InternalLinkage, getName() + FINAL_BLOCK_SUFFIX, idb->getModule());
561        mCurrentMethod->setCallingConv(CallingConv::C);
562        mCurrentMethod->setDoesNotThrow();
563        mCurrentMethod->setDoesNotCapture(1);
564        auto args = mCurrentMethod->arg_begin();
565        args->setName("self");
566        setInstance(&*args);
567        remainingItems = &*(++args);
568        remainingItems->setName("remainingItems");
569        idb->SetInsertPoint(idb->CreateBasicBlock("entry"));
570    }
571
572    generateFinalBlockMethod(idb, remainingItems); // may be implemented by the BlockOrientedKernel subtype
573
574    RecursivelyDeleteTriviallyDeadInstructions(remainingItems); // if remainingItems was not used, this will eliminate it.
575
576    if (!idb->supportsIndirectBr()) {
577        idb->CreateRetVoid();
578        idb->restoreIP(ip);
579        idb->CreateCall(mCurrentMethod, {self, remainingItemCount});
580        mCurrentMethod = cp;
581        setInstance(self);
582    }
583
584}
585
586//  The default finalBlock method simply dispatches to the doBlock routine.
587void BlockOrientedKernel::generateFinalBlockMethod(const std::unique_ptr<KernelBuilder> & idb, Value * /* remainingItems */) {
588    CreateDoBlockMethodCall(idb);
589}
590
591void BlockOrientedKernel::CreateDoBlockMethodCall(const std::unique_ptr<KernelBuilder> & idb) {
592    if (idb->supportsIndirectBr()) {
593        BasicBlock * bb = idb->CreateBasicBlock("resume");
594        mStrideLoopBranch->addDestination(bb);
595        mStrideLoopTarget->addIncoming(BlockAddress::get(bb), idb->GetInsertBlock());
596        idb->CreateBr(mStrideLoopBody);
597        bb->moveAfter(idb->GetInsertBlock());
598        idb->SetInsertPoint(bb);
599    } else {
600        idb->CreateCall(mDoBlockMethod, getInstance());
601    }
602}
603
604void MultiBlockKernel::generateDoSegmentMethod(const std::unique_ptr<KernelBuilder> & kb) {
605
606    // First prepare the multi-block method that will be used.
607    KernelBuilder * const iBuilder = kb.get();
608
609    std::vector<Type *> multiBlockParmTypes;
610    multiBlockParmTypes.push_back(mKernelStateType->getPointerTo());
611    for (auto buffer : mStreamSetInputBuffers) {
612        multiBlockParmTypes.push_back(buffer->getPointerType());
613    }
614    for (auto buffer : mStreamSetOutputBuffers) {
615        multiBlockParmTypes.push_back(buffer->getPointerType());
616    }
617    FunctionType * const type = FunctionType::get(iBuilder->getVoidTy(), multiBlockParmTypes, false);
618    Function * multiBlockFunction = Function::Create(type, GlobalValue::InternalLinkage, getName() + MULTI_BLOCK_SUFFIX, iBuilder->getModule());
619    multiBlockFunction->setCallingConv(CallingConv::C);
620    multiBlockFunction->setDoesNotThrow();
621    auto args = multiBlockFunction->arg_begin();
622    args->setName("self");
623    (++args)->setName("itemsToDo");
624    for (auto binding : mStreamSetInputs) {
625        (++args)->setName(binding.name + "BufPtr");
626    }
627    for (auto binding : mStreamSetOutputs) {
628        (++args)->setName(binding.name + "BufPtr");
629    }
630
631    // Now use the generateMultiBlockLogic method of the MultiBlockKernelBuilder subtype to
632    // provide the required multi-block kernel logic.
633    auto ip = iBuilder->saveIP();
634    iBuilder->SetInsertPoint(BasicBlock::Create(iBuilder->getContext(), "multiBlockEntry", multiBlockFunction, 0));
635
636    generateMultiBlockLogic(kb);
637
638    iBuilder->CreateRetVoid();
639    iBuilder->restoreIP(ip);
640
641    // Now proceed with creation of the doSegment method.
642
643    BasicBlock * const entry = iBuilder->GetInsertBlock();
644    BasicBlock * const doSegmentOuterLoop = iBuilder->CreateBasicBlock(getName() + "_doSegmentOuterLoop");
645    BasicBlock * const doMultiBlockCall = iBuilder->CreateBasicBlock(getName() + "_doMultiBlockCall");
646    BasicBlock * const finalBlockCheck = iBuilder->CreateBasicBlock(getName() + "_finalBlockCheck");
647    BasicBlock * const doTempBufferBlock = iBuilder->CreateBasicBlock(getName() + "_doTempBufferBlock");
648    BasicBlock * const segmentDone = iBuilder->CreateBasicBlock(getName() + "_segmentDone");
649
650    Value * blockBaseMask = iBuilder->CreateNot(iBuilder->getSize(iBuilder->getBitBlockWidth() - 1));
651
652    //
653    //  A. Temporary Buffer Area Determination
654    //
655    // For final block processing and for processing near the end of physical buffer
656    // boundaries, we need to allocate temporary space for processing a full block of input.
657    // Compute the size requirements to store stream set data at the declared processing
658    // rates in reference to one block of the principal input stream.
659    //
660
661    unsigned bitBlockWidth = iBuilder->getBitBlockWidth();
662    std::vector<Type *> tempBuffers;
663    std::vector<unsigned> itemsPerPrincipalBlock;
664    for (unsigned i = 0; i < mStreamSetInputs.size(); i++) {
665        auto & rate = mStreamSetInputs[i].rate;
666        std::string refSet = mStreamSetInputs[i].rate.referenceStreamSet();
667        if (refSet.empty()) {
668            itemsPerPrincipalBlock.push_back(rate.calculateRatio(bitBlockWidth));
669        }
670        else {
671            Port port; unsigned ssIdx;
672            std::tie(port, ssIdx) = getStreamPort(mStreamSetInputs[i].name);
673            assert (port == Port::Input && ssIdx < i);
674            itemsPerPrincipalBlock.push_back(rate.calculateRatio(itemsPerPrincipalBlock[ssIdx]));
675        }
676        unsigned blocks = (itemsPerPrincipalBlock.back() + bitBlockWidth - 1)/bitBlockWidth;
677        if (blocks > 1) {
678            tempBuffers.push_back(ArrayType::get(mStreamSetInputBuffers[i]->getType(), blocks));
679        }
680        else {
681            tempBuffers.push_back(mStreamSetInputBuffers[i]->getType());
682        }
683    }
684    for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
685        auto & rate = mStreamSetOutputs[i].rate;
686        std::string refSet = mStreamSetOutputs[i].rate.referenceStreamSet();
687        if (refSet.empty()) {
688            itemsPerPrincipalBlock.push_back(rate.calculateRatio(bitBlockWidth));
689        }
690        else {
691            Port port; unsigned ssIdx;
692            std::tie(port, ssIdx) = getStreamPort(mStreamSetOutputs[i].name);
693            if (port == Port::Output) ssIdx += mStreamSetInputs.size();
694            itemsPerPrincipalBlock.push_back(rate.calculateRatio(itemsPerPrincipalBlock[ssIdx]));
695        }
696        unsigned blocks = (itemsPerPrincipalBlock.back() + bitBlockWidth - 1)/bitBlockWidth;
697        if (blocks > 1) {
698            tempBuffers.push_back(ArrayType::get(mStreamSetOutputBuffers[i]->getType(), blocks));
699        }
700        else {
701            tempBuffers.push_back(mStreamSetOutputBuffers[i]->getType());
702        }
703    }
704    Type * tempParameterStructType = StructType::create(iBuilder->getContext(), tempBuffers);
705    Value * tempParameterArea = iBuilder->CreateCacheAlignedAlloca(tempParameterStructType);
706
707    ConstantInt * blockSize = iBuilder->getSize(iBuilder->getBitBlockWidth());
708    Value * availablePos = mAvailableItemCount[0];
709    Value * itemsAvail = availablePos;
710    //  Make sure that corresponding data is available depending on processing rate
711    //  for all input stream sets.
712    for (unsigned i = 1; i < mStreamSetInputs.size(); i++) {
713        Value * a = mAvailableItemCount[i];
714        auto & rate = mStreamSetInputs[i].rate;
715        assert (((rate.referenceStreamSet().empty()) || (rate.referenceStreamSet() == mStreamSetInputs[0].name)) && "Multiblock kernel input rate not with respect to principal stream.");
716        Value * maxItems = rate.CreateMaxReferenceItemsCalculation(iBuilder, a);
717        itemsAvail = iBuilder->CreateSelect(iBuilder->CreateICmpULT(itemsAvail, maxItems), itemsAvail, maxItems);
718    }
719
720    Value * processed = iBuilder->getProcessedItemCount(mStreamSetInputs[0].name);
721    Value * itemsToDo = iBuilder->CreateSub(itemsAvail, processed);
722    Value * fullBlocksToDo = iBuilder->CreateUDiv(itemsToDo, blockSize);
723    Value * excessItems = iBuilder->CreateURem(itemsToDo, blockSize);
724
725    //  Now we iteratively process these blocks using the doMultiBlock method.
726    //  In each iteration, we process the maximum number of linearly accessible
727    //  blocks on the principal input, reduced to ensure that the corresponding
728    //  data is linearly available at the specified processing rates for the other inputs,
729    //  and that each of the output buffers has sufficient linearly available space
730    //  (using overflow areas, if necessary) for the maximum output that can be
731    //  produced.
732
733    //iBuilder->CreateCondBr(iBuilder->CreateICmpUGT(fullBlocksToDo, iBuilder->getSize(0)), doSegmentOuterLoop, finalBlockCheck);
734    iBuilder->CreateBr(doSegmentOuterLoop);
735
736    iBuilder->SetInsertPoint(doSegmentOuterLoop);
737    PHINode * const blocksRemaining = iBuilder->CreatePHI(iBuilder->getSizeTy(), 2, "blocksRemaining");
738    blocksRemaining->addIncoming(fullBlocksToDo, entry);
739
740
741    // For each input buffer, determine the processedItemCount, the block pointer for the
742    // buffer block containing the next item, and the number of linearly available items.
743    //
744    std::vector<Value *> processedItemCount;
745    std::vector<Value *> inputBlockPtr;
746    std::vector<Value *> producedItemCount;
747    std::vector<Value *> outputBlockPtr;
748
749    //  Calculate linearly available blocks for all input stream sets.
750    Value * linearlyAvailBlocks = nullptr;
751    for (unsigned i = 0; i < mStreamSetInputs.size(); i++) {
752        Value * p = iBuilder->getProcessedItemCount(mStreamSetInputs[i].name);
753        Value * blkNo = iBuilder->CreateUDiv(p, blockSize);
754        Value * b = iBuilder->getInputStreamBlockPtr(mStreamSetInputs[i].name, iBuilder->getInt32(0));
755        processedItemCount.push_back(p);
756        inputBlockPtr.push_back(b);
757        auto & rate = mStreamSetInputs[i].rate;
758        Value * blocks = nullptr;
759        if ((rate.isFixedRatio()) && (rate.getRatioNumerator() == rate.getRatioDenominator()) && (rate.referenceStreamSet() == "")) {
760            blocks = mStreamSetInputBuffers[i]->getLinearlyAccessibleBlocks(iBuilder, blkNo);
761        } else {
762            Value * linearlyAvailItems = mStreamSetInputBuffers[i]->getLinearlyAccessibleItems(iBuilder, p);
763            Value * items = rate.CreateMaxReferenceItemsCalculation(iBuilder, linearlyAvailItems);
764            blocks = iBuilder->CreateUDiv(items, blockSize);
765        }
766        if (i == 0) {
767            linearlyAvailBlocks = blocks;
768        } else {
769            linearlyAvailBlocks = iBuilder->CreateSelect(iBuilder->CreateICmpULT(blocks, linearlyAvailBlocks), blocks, linearlyAvailBlocks);
770        }
771    }
772
773    //  Now determine the linearly writeable blocks, based on available blocks reduced
774    //  by limitations of output buffer space.
775    Value * linearlyWritableBlocks = linearlyAvailBlocks;
776
777    for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
778        Value * p = iBuilder->getProducedItemCount(mStreamSetOutputs[i].name);
779        Value * blkNo = iBuilder->CreateUDiv(p, blockSize);
780        Value * b = iBuilder->getOutputStreamBlockPtr(mStreamSetOutputs[i].name, iBuilder->getInt32(0));
781        producedItemCount.push_back(p);
782        outputBlockPtr.push_back(b);
783        auto & rate = mStreamSetOutputs[i].rate;
784        Value * blocks = nullptr;
785        if ((rate.isFixedRatio()) && (rate.getRatioNumerator() == rate.getRatioDenominator())) {
786            blocks = mStreamSetOutputBuffers[0]->getLinearlyWritableBlocks(iBuilder, blkNo);
787        } else {
788            Value * writableItems = mStreamSetOutputBuffers[0]->getLinearlyWritableItems(iBuilder, p);
789            blocks = iBuilder->CreateUDiv(writableItems, blockSize);
790        }
791        linearlyWritableBlocks = iBuilder->CreateSelect(iBuilder->CreateICmpULT(blocks, linearlyWritableBlocks), blocks, linearlyWritableBlocks);
792    }
793    Value * haveBlocks = iBuilder->CreateICmpUGT(linearlyWritableBlocks, iBuilder->getSize(0));
794
795    iBuilder->CreateCondBr(haveBlocks, doMultiBlockCall, doTempBufferBlock);
796
797    //  At this point we have verified the availability of one or more blocks of input data and output buffer space for all stream sets.
798    //  Now prepare the doMultiBlock call.
799    iBuilder->SetInsertPoint(doMultiBlockCall);
800
801    Value * linearlyAvailItems = iBuilder->CreateMul(linearlyWritableBlocks, blockSize);
802
803    std::vector<Value *> doMultiBlockArgs;
804    doMultiBlockArgs.push_back(getInstance());
805    doMultiBlockArgs.push_back(linearlyAvailItems);
806    for (unsigned i = 0; i < mStreamSetInputs.size(); i++) {
807        doMultiBlockArgs.push_back(iBuilder->getRawInputPointer(mStreamSetInputs[i].name, iBuilder->getInt32(0), processedItemCount[i]));
808    }
809    for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
810        doMultiBlockArgs.push_back(iBuilder->getRawOutputPointer(mStreamSetOutputs[i].name, iBuilder->getInt32(0), producedItemCount[i]));
811    }
812
813    iBuilder->CreateCall(multiBlockFunction, doMultiBlockArgs);
814
815    // Do copybacks if necessary.
816    unsigned priorIdx = 0;
817    for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
818        Value * log2BlockSize = iBuilder->getSize(std::log2(iBuilder->getBitBlockWidth()));
819        if (auto cb = dyn_cast<SwizzledCopybackBuffer>(mStreamSetOutputBuffers[i]))  {
820            BasicBlock * copyBack = iBuilder->CreateBasicBlock(mStreamSetOutputs[i].name + "_copyBack");
821            BasicBlock * done = iBuilder->CreateBasicBlock(mStreamSetOutputs[i].name + "_copyBackDone");
822            Value * newlyProduced = iBuilder->CreateSub(iBuilder->getProducedItemCount(mStreamSetOutputs[i].name), producedItemCount[i]);
823            Value * priorBlock = iBuilder->CreateLShr(producedItemCount[i], log2BlockSize);
824            Value * priorOffset = iBuilder->CreateAnd(producedItemCount[i], iBuilder->getSize(iBuilder->getBitBlockWidth() - 1));
825            Value * instance = iBuilder->getStreamSetBufferPtr(mStreamSetOutputs[i].name);
826            Value * accessibleBlocks = cb->getLinearlyAccessibleBlocks(iBuilder, priorBlock);
827            Value * accessible = iBuilder->CreateSub(iBuilder->CreateShl(accessibleBlocks, log2BlockSize), priorOffset);
828            Value * wraparound = iBuilder->CreateICmpULT(accessible, newlyProduced);
829            iBuilder->CreateCondBr(wraparound, copyBack, done);
830            iBuilder->SetInsertPoint(copyBack);
831            Value * copyItems = iBuilder->CreateSub(newlyProduced, accessible);
832            cb->createCopyBack(iBuilder, instance, copyItems);
833            iBuilder->CreateBr(done);
834            iBuilder->SetInsertPoint(done);
835            priorIdx++;
836        }
837        if (auto cb = dyn_cast<CircularCopybackBuffer>(mStreamSetOutputBuffers[i]))  {
838            BasicBlock * copyBack = iBuilder->CreateBasicBlock(mStreamSetOutputs[i].name + "_copyBack");
839            BasicBlock * done = iBuilder->CreateBasicBlock(mStreamSetOutputs[i].name + "_copyBackDone");
840            Value * instance = iBuilder->getStreamSetBufferPtr(mStreamSetOutputs[i].name);
841            Value * newlyProduced = iBuilder->CreateSub(iBuilder->getProducedItemCount(mStreamSetOutputs[i].name), producedItemCount[i]);
842            Value * accessible = cb->getLinearlyAccessibleItems(iBuilder, producedItemCount[i]);
843            Value * wraparound = iBuilder->CreateICmpULT(accessible, newlyProduced);
844            iBuilder->CreateCondBr(wraparound, copyBack, done);
845            iBuilder->SetInsertPoint(copyBack);
846            Value * copyItems = iBuilder->CreateSub(newlyProduced, accessible);
847            cb->createCopyBack(iBuilder, instance, copyItems);
848            iBuilder->CreateBr(done);
849            iBuilder->SetInsertPoint(done);
850            priorIdx++;
851        }
852    }
853    iBuilder->setProcessedItemCount(mStreamSetInputs[0].name, iBuilder->CreateAdd(processed, linearlyAvailItems));
854    Value * reducedBlocksToDo = iBuilder->CreateSub(blocksRemaining, linearlyWritableBlocks);
855    Value * fullBlocksRemain = iBuilder->CreateICmpUGT(reducedBlocksToDo, iBuilder->getSize(0));
856    BasicBlock * multiBlockFinal = iBuilder->GetInsertBlock();
857    blocksRemaining->addIncoming(reducedBlocksToDo, multiBlockFinal);
858    iBuilder->CreateCondBr(fullBlocksRemain, doSegmentOuterLoop, finalBlockCheck);
859
860    // All the full blocks of input have been processed.  If mIsFinal is true,
861    // we should process the remaining partial block (i.e., excessItems as determined at entry).
862    iBuilder->SetInsertPoint(finalBlockCheck);
863    iBuilder->CreateCondBr(mIsFinal, doTempBufferBlock, segmentDone);
864
865    //
866    // We use temporary buffers in 3 different cases that preclude full block processing.
867    // (a) One or more input buffers does not have a sufficient number of input items linearly available.
868    // (b) One or more output buffers does not have sufficient linearly available buffer space.
869    // (c) We have processed all the full blocks of input and only the excessItems remain.
870    // In each case we set up temporary buffers for input and output and then
871    // call the Multiblock routine.
872    //
873    iBuilder->SetInsertPoint(doTempBufferBlock);
874    PHINode * const tempBlockItems = iBuilder->CreatePHI(iBuilder->getSizeTy(), 2, "tempBlockItems");
875    tempBlockItems->addIncoming(blockSize, doSegmentOuterLoop);
876    tempBlockItems->addIncoming(excessItems, finalBlockCheck);
877
878    // Will this be the final block processing?
879    Value * doFinal = iBuilder->CreateICmpULT(tempBlockItems, blockSize);
880
881    // Begin constructing the doMultiBlock args.
882    std::vector<Value *> tempArgs;
883    tempArgs.push_back(getInstance());
884    tempArgs.push_back(tempBlockItems);
885
886    // Prepare the temporary buffer area.
887    //
888    // First zero it out.
889    Constant * const tempAreaSize = ConstantExpr::getIntegerCast(ConstantExpr::getSizeOf(tempParameterStructType), iBuilder->getSizeTy(), false);
890    iBuilder->CreateMemZero(tempParameterArea, tempAreaSize);
891
892    // For each input and output buffer, copy over necessary data starting from the last
893    // block boundary.
894    std::vector<Value *> finalItemPos;
895    finalItemPos.push_back(iBuilder->CreateAdd(processedItemCount[0], tempBlockItems));
896
897    for (unsigned i = 0; i < mStreamSetInputBuffers.size(); i++) {
898        Value * tempBufPtr = iBuilder->CreateGEP(tempParameterArea, iBuilder->getInt32(i));
899        tempBufPtr = iBuilder->CreatePointerCast(tempBufPtr, mStreamSetInputBuffers[i]->getPointerType());
900
901        auto & rate = mStreamSetInputs[i].rate;
902        Value * blockItemPos = iBuilder->CreateAnd(processedItemCount[i], blockBaseMask);
903
904        // The number of items to copy is determined by the processing rate requirements.
905        if (i > 1) {
906            std::string refSet = mStreamSetInputs[i].rate.referenceStreamSet();
907            if (refSet.empty()) {
908                finalItemPos.push_back(rate.CreateRatioCalculation(iBuilder, finalItemPos[0], doFinal));
909            }
910            else {
911                Port port; unsigned ssIdx;
912                std::tie(port, ssIdx) = getStreamPort(mStreamSetInputs[i].name);
913                assert (port == Port::Input && ssIdx < i);
914                finalItemPos.push_back(rate.CreateRatioCalculation(iBuilder, finalItemPos[ssIdx], doFinal));
915            }
916        }
917        Value * neededItems = iBuilder->CreateSub(finalItemPos[i], blockItemPos);
918        Value * availFromBase = mStreamSetInputBuffers[i]->getLinearlyAccessibleItems(iBuilder, blockItemPos);
919        Value * copyItems1 = iBuilder->CreateSelect(iBuilder->CreateICmpULT(neededItems, availFromBase), neededItems, availFromBase);
920        Value * copyItems2 = iBuilder->CreateSub(neededItems, copyItems1);
921        mStreamSetInputBuffers[i]->createBlockAlignedCopy(iBuilder, tempBufPtr, inputBlockPtr[i], copyItems1);
922        Value * nextBufPtr = iBuilder->CreateGEP(tempBufPtr, iBuilder->CreateUDiv(availFromBase, blockSize));
923        mStreamSetInputBuffers[i]->createBlockAlignedCopy(iBuilder, nextBufPtr, iBuilder->getStreamSetBufferPtr(mStreamSetInputs[i].name), copyItems2);
924        Value * itemAddress = iBuilder->CreatePtrToInt(iBuilder->getRawOutputPointer(mStreamSetInputs[i].name, iBuilder->getInt32(0), processedItemCount[i]), iBuilder->getSizeTy());
925        Value * baseAddress = iBuilder->CreatePtrToInt(inputBlockPtr[i], iBuilder->getSizeTy());
926        Value * tempAddress = iBuilder->CreateAdd(iBuilder->CreatePtrToInt(tempBufPtr, iBuilder->getSizeTy()), iBuilder->CreateSub(itemAddress, baseAddress));
927        tempArgs.push_back(iBuilder->CreateBitCast(tempAddress, mStreamSetInputBuffers[i]->getPointerType()));
928    }
929
930    std::vector<Value *> blockItemPos;
931    for (unsigned i = 0; i < mStreamSetOutputBuffers.size(); i++) {
932        Value * tempBufPtr = iBuilder->CreateGEP(tempParameterArea, iBuilder->getInt32(mStreamSetInputs.size() + i));
933        tempBufPtr = iBuilder->CreatePointerCast(tempBufPtr, mStreamSetOutputBuffers[i]->getPointerType());
934        blockItemPos.push_back(iBuilder->CreateAnd(producedItemCount[i], blockBaseMask));
935        mStreamSetOutputBuffers[i]->createBlockAlignedCopy(iBuilder, tempBufPtr, outputBlockPtr[i], iBuilder->CreateSub(producedItemCount[i], blockItemPos[i]));
936        Value * itemAddress = iBuilder->CreatePtrToInt(iBuilder->getRawOutputPointer(mStreamSetInputs[i].name, iBuilder->getInt32(0), producedItemCount[i]), iBuilder->getSizeTy());
937        Value * baseAddress = iBuilder->CreatePtrToInt(outputBlockPtr[i], iBuilder->getSizeTy());
938        Value * tempAddress = iBuilder->CreateAdd(iBuilder->CreatePtrToInt(tempBufPtr, iBuilder->getSizeTy()), iBuilder->CreateSub(itemAddress, baseAddress));
939        tempArgs.push_back(iBuilder->CreateBitCast(tempAddress, mStreamSetOutputBuffers[i]->getPointerType()));
940    }
941
942    iBuilder->CreateCall(multiBlockFunction, tempArgs);
943
944    // Copy back data to the actual output buffers.
945
946    for (unsigned i = 0; i < mStreamSetOutputBuffers.size(); i++) {
947        Value * tempBufPtr = iBuilder->CreateGEP(tempParameterArea, iBuilder->getInt32(mStreamSetInputs.size() + i));
948        tempBufPtr = iBuilder->CreatePointerCast(tempBufPtr, mStreamSetOutputBuffers[i]->getPointerType());
949        Value * final_items = iBuilder->getProducedItemCount(mStreamSetOutputs[i].name);
950        Value * copyItems = iBuilder->CreateSub(final_items, blockItemPos[i]);
951        Value * copyItems1 = mStreamSetOutputBuffers[i]->getLinearlyWritableItems(iBuilder, blockItemPos[i]); // must be a whole number of blocks.
952        mStreamSetOutputBuffers[i]->createBlockAlignedCopy(iBuilder, outputBlockPtr[i], tempBufPtr, copyItems1);
953        Value * copyItems2 = iBuilder->CreateSelect(iBuilder->CreateICmpULT(copyItems, copyItems), iBuilder->getSize(0), iBuilder->CreateSub(copyItems, copyItems1));
954        tempBufPtr = iBuilder->CreateGEP(tempBufPtr, iBuilder->CreateUDiv(copyItems1, blockSize));
955        mStreamSetOutputBuffers[i]->createBlockAlignedCopy(iBuilder, iBuilder->getStreamSetBufferPtr(mStreamSetOutputs[i].name), tempBufPtr, copyItems2);
956    }
957
958    iBuilder->setProcessedItemCount(mStreamSetInputs[0].name, finalItemPos[0]);
959
960    //  We've dealt with the partial block processing and copied information back into the
961    //  actual buffers.  If this isn't the final block, loop back for more multiblock processing.
962    //
963    iBuilder->CreateCondBr(doFinal, segmentDone, doSegmentOuterLoop);
964    iBuilder->SetInsertPoint(segmentDone);
965}
966
967void Kernel::finalizeInstance(const std::unique_ptr<KernelBuilder> & idb) {
968    assert ("KernelBuilder does not have a valid IDISA Builder" && idb);
969    mOutputScalarResult = idb->CreateCall(getTerminateFunction(idb->getModule()), { getInstance() });
970}
971
972Kernel::StreamPort Kernel::getStreamPort(const std::string & name) const {
973    const auto f = mStreamMap.find(name);
974    if (LLVM_UNLIKELY(f == mStreamMap.end())) {
975        report_fatal_error(getName() + " does not contain stream set " + name);
976    }
977    return f->second;
978}
979
980// CONSTRUCTOR
981Kernel::Kernel(std::string && kernelName,
982                             std::vector<Binding> && stream_inputs,
983                             std::vector<Binding> && stream_outputs,
984                             std::vector<Binding> && scalar_parameters,
985                             std::vector<Binding> && scalar_outputs,
986                             std::vector<Binding> && internal_scalars)
987: KernelInterface(std::move(kernelName), std::move(stream_inputs), std::move(stream_outputs), std::move(scalar_parameters), std::move(scalar_outputs), std::move(internal_scalars))
988, mCurrentMethod(nullptr)
989, mNoTerminateAttribute(false)
990, mIsGenerated(false)
991, mIsFinal(nullptr)
992, mOutputScalarResult(nullptr) {
993
994}
995
996Kernel::~Kernel() {
997
998}
999
1000// CONSTRUCTOR
1001BlockOrientedKernel::BlockOrientedKernel(std::string && kernelName,
1002                                         std::vector<Binding> && stream_inputs,
1003                                         std::vector<Binding> && stream_outputs,
1004                                         std::vector<Binding> && scalar_parameters,
1005                                         std::vector<Binding> && scalar_outputs,
1006                                         std::vector<Binding> && internal_scalars)
1007: Kernel(std::move(kernelName), std::move(stream_inputs), std::move(stream_outputs), std::move(scalar_parameters), std::move(scalar_outputs), std::move(internal_scalars))
1008, mDoBlockMethod(nullptr)
1009, mStrideLoopBody(nullptr)
1010, mStrideLoopBranch(nullptr)
1011, mStrideLoopTarget(nullptr) {
1012
1013}
1014
1015// CONSTRUCTOR
1016MultiBlockKernel::MultiBlockKernel(std::string && kernelName,
1017                                     std::vector<Binding> && stream_inputs,
1018                                     std::vector<Binding> && stream_outputs,
1019                                     std::vector<Binding> && scalar_parameters,
1020                                     std::vector<Binding> && scalar_outputs,
1021                                             std::vector<Binding> && internal_scalars)
1022: Kernel(std::move(kernelName), std::move(stream_inputs), std::move(stream_outputs), std::move(scalar_parameters), std::move(scalar_outputs), std::move(internal_scalars)) {
1023   
1024}
1025
1026// CONSTRUCTOR
1027SegmentOrientedKernel::SegmentOrientedKernel(std::string && kernelName,
1028                                             std::vector<Binding> && stream_inputs,
1029                                             std::vector<Binding> && stream_outputs,
1030                                             std::vector<Binding> && scalar_parameters,
1031                                             std::vector<Binding> && scalar_outputs,
1032                                             std::vector<Binding> && internal_scalars)
1033: Kernel(std::move(kernelName), std::move(stream_inputs), std::move(stream_outputs), std::move(scalar_parameters), std::move(scalar_outputs), std::move(internal_scalars)) {
1034   
1035}
1036   
1037}
Note: See TracBrowser for help on using the repository browser.