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

Last change on this file since 5183 was 5183, checked in by cameron, 3 years ago

Kernels compute and check produced item counts

File size: 25.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 <llvm/IR/Module.h>
8#include <llvm/IR/Type.h>
9#include <llvm/IR/Value.h>
10#include <llvm/Support/raw_ostream.h>
11#include <llvm/IR/TypeBuilder.h>
12#include <llvm/Support/ErrorHandling.h>
13#include <toolchain.h>
14
15using namespace llvm;
16using namespace kernel;
17
18KernelBuilder::KernelBuilder(IDISA::IDISA_Builder * builder,
19                                 std::string kernelName,
20                                 std::vector<StreamSetBinding> stream_inputs,
21                                 std::vector<StreamSetBinding> stream_outputs,
22                                 std::vector<ScalarBinding> scalar_parameters,
23                                 std::vector<ScalarBinding> scalar_outputs,
24                                 std::vector<ScalarBinding> internal_scalars) :
25    KernelInterface(builder, kernelName, stream_inputs, stream_outputs, scalar_parameters, scalar_outputs, internal_scalars) {}
26
27void KernelBuilder::addScalar(Type * t, std::string scalarName) {
28    if (LLVM_UNLIKELY(mKernelStateType != nullptr)) {
29        llvm::report_fatal_error("Illegal addition of kernel field after kernel state finalized: " + scalarName);
30    }
31    unsigned index = mKernelFields.size();
32    mKernelFields.push_back(t);
33    mInternalStateNameMap.emplace(scalarName, index);
34}
35
36void KernelBuilder::prepareKernel() {
37    unsigned blockSize = iBuilder->getBitBlockWidth();
38    if (mStreamSetInputs.size() != mStreamSetInputBuffers.size()) {
39        llvm::report_fatal_error("Kernel preparation: Incorrect number of input buffers");
40    }
41    if (mStreamSetOutputs.size() != mStreamSetOutputBuffers.size()) {
42        llvm::report_fatal_error("Kernel preparation: Incorrect number of output buffers");
43    }
44    addScalar(iBuilder->getSizeTy(), blockNoScalar);
45    addScalar(iBuilder->getSizeTy(), logicalSegmentNoScalar);
46    addScalar(iBuilder->getSizeTy(), processedItemCount);
47    addScalar(iBuilder->getSizeTy(), producedItemCount);
48    addScalar(iBuilder->getInt1Ty(), terminationSignal);
49    int streamSetNo = 0;
50    for (unsigned i = 0; i < mStreamSetInputs.size(); i++) {
51        if (!(mStreamSetInputBuffers[i]->getBufferStreamSetType() == mStreamSetInputs[i].ssType)) {
52             llvm::report_fatal_error("Kernel preparation: Incorrect input buffer type");
53        }
54        if ((mStreamSetInputBuffers[i]->getBufferSize() > 0) && (mStreamSetInputBuffers[i]->getBufferSize() < codegen::SegmentSize + (blockSize + mLookAheadPositions - 1)/blockSize)) {
55             errs() << "buffer size = " << mStreamSetInputBuffers[i]->getBufferSize() << "\n";
56             llvm::report_fatal_error("Kernel preparation: Buffer size too small.");
57        }
58        mScalarInputs.push_back(ScalarBinding{mStreamSetInputBuffers[i]->getStreamSetStructPointerType(), mStreamSetInputs[i].ssName + basePtrSuffix});
59        mStreamSetNameMap.emplace(mStreamSetInputs[i].ssName, streamSetNo);
60        streamSetNo++;
61    }
62    for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
63        if (!(mStreamSetOutputBuffers[i]->getBufferStreamSetType() == mStreamSetOutputs[i].ssType)) {
64             llvm::report_fatal_error("Kernel preparation: Incorrect output buffer type");
65        }
66        mScalarInputs.push_back(ScalarBinding{mStreamSetOutputBuffers[i]->getStreamSetStructPointerType(), mStreamSetOutputs[i].ssName + basePtrSuffix});
67        mStreamSetNameMap.emplace(mStreamSetOutputs[i].ssName, streamSetNo);
68        streamSetNo++;
69    }
70    for (auto binding : mScalarInputs) {
71        addScalar(binding.scalarType, binding.scalarName);
72    }
73    for (auto binding : mScalarOutputs) {
74        addScalar(binding.scalarType, binding.scalarName);
75    }
76    for (auto binding : mInternalScalars) {
77        addScalar(binding.scalarType, binding.scalarName);
78    }
79    mKernelStateType = StructType::create(iBuilder->getContext(), mKernelFields, mKernelName);
80}
81
82std::unique_ptr<Module> KernelBuilder::createKernelModule(std::vector<StreamSetBuffer *> input_buffers, std::vector<StreamSetBuffer *> output_buffers) {
83    Module * saveModule = iBuilder->getModule();
84    IDISA::IDISA_Builder::InsertPoint savePoint = iBuilder->saveIP();
85    std::unique_ptr<Module> theModule = make_unique<Module>(mKernelName + "_" + iBuilder->getBitBlockTypeName(), iBuilder->getContext());
86    Module * m = theModule.get();
87    iBuilder->setModule(m);
88    generateKernel(input_buffers, output_buffers);
89    iBuilder->setModule(saveModule);
90    iBuilder->restoreIP(savePoint);
91    return theModule;
92}
93
94void KernelBuilder::generateKernel(std::vector<StreamSetBuffer *> input_buffers, std::vector<StreamSetBuffer*> output_buffers) {
95    IDISA::IDISA_Builder::InsertPoint savePoint = iBuilder->saveIP();
96    Module * m = iBuilder->getModule();
97    mStreamSetInputBuffers = input_buffers;
98    mStreamSetOutputBuffers = output_buffers;
99    prepareKernel();  // possibly overriden by the KernelBuilder subtype
100    KernelInterface::addKernelDeclarations(m);
101    generateDoBlockMethod();     // must be implemented by the KernelBuilder subtype
102    generateFinalBlockMethod();  // possibly overriden by the KernelBuilder subtype
103    generateDoSegmentMethod();
104
105    // Implement the accumulator get functions
106    for (auto binding : mScalarOutputs) {
107        auto fnName = mKernelName + accumulator_infix + binding.scalarName;
108        Function * accumFn = m->getFunction(fnName);
109        iBuilder->SetInsertPoint(BasicBlock::Create(iBuilder->getContext(), "get_" + binding.scalarName, accumFn, 0));
110        Value * self = &*(accumFn->arg_begin());
111        Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), getScalarIndex(binding.scalarName)});
112        Value * retVal = iBuilder->CreateLoad(ptr);
113        iBuilder->CreateRet(retVal);
114    }
115    // Implement the initializer function
116    Function * initFunction = m->getFunction(mKernelName + init_suffix);
117    iBuilder->SetInsertPoint(BasicBlock::Create(iBuilder->getContext(), "Init_entry", initFunction, 0));
118   
119    Function::arg_iterator args = initFunction->arg_begin();
120    Value * self = &*(args++);
121    iBuilder->CreateStore(Constant::getNullValue(mKernelStateType), self);
122    for (auto binding : mScalarInputs) {
123        Value * parm = &*(args++);
124        Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), getScalarIndex(binding.scalarName)});
125        iBuilder->CreateStore(parm, ptr);
126    }
127    iBuilder->CreateRetVoid();
128    iBuilder->restoreIP(savePoint);
129}
130
131//  The default finalBlock method simply dispatches to the doBlock routine.
132void KernelBuilder::generateFinalBlockMethod() {
133    IDISA::IDISA_Builder::InsertPoint savePoint = iBuilder->saveIP();
134    Module * m = iBuilder->getModule();
135    Function * doBlockFunction = m->getFunction(mKernelName + doBlock_suffix);
136    Function * finalBlockFunction = m->getFunction(mKernelName + finalBlock_suffix);
137    iBuilder->SetInsertPoint(BasicBlock::Create(iBuilder->getContext(), "fb_entry", finalBlockFunction, 0));
138    // Final Block arguments: self, remaining, then the standard DoBlock args.
139    Function::arg_iterator args = finalBlockFunction->arg_begin();
140    Value * self = &*(args++);
141    /* Skip "remaining" arg */ args++;
142    std::vector<Value *> doBlockArgs = {self};
143    while (args != finalBlockFunction->arg_end()){
144        doBlockArgs.push_back(&*args++);
145    }
146    iBuilder->CreateCall(doBlockFunction, doBlockArgs);
147    iBuilder->CreateRetVoid();
148    iBuilder->restoreIP(savePoint);
149}
150
151void KernelBuilder::generateDoBlockLogic(Value * self, Value * blockNo) {
152    Function * doBlockFunction = iBuilder->getModule()->getFunction(mKernelName + doBlock_suffix);
153    iBuilder->CreateCall(doBlockFunction, {self});
154}
155
156//  The default doSegment method dispatches to the doBlock routine for
157//  each block of the given number of blocksToDo, and then updates counts.
158void KernelBuilder::generateDoSegmentMethod() {
159    IDISA::IDISA_Builder::InsertPoint savePoint = iBuilder->saveIP();
160    Module * m = iBuilder->getModule();
161    Function * doSegmentFunction = m->getFunction(mKernelName + doSegment_suffix);
162    iBuilder->SetInsertPoint(BasicBlock::Create(iBuilder->getContext(), "entry", doSegmentFunction, 0));
163    BasicBlock * entryBlock = iBuilder->GetInsertBlock();
164    BasicBlock * blockLoopCond = BasicBlock::Create(iBuilder->getContext(), "blockLoopCond", doSegmentFunction, 0);
165    BasicBlock * blockLoopBody = BasicBlock::Create(iBuilder->getContext(), "blockLoopBody", doSegmentFunction, 0);
166    BasicBlock * blocksDone = BasicBlock::Create(iBuilder->getContext(), "blocksDone", doSegmentFunction, 0);
167    Type * const size_ty = iBuilder->getSizeTy();
168    Constant * stride = ConstantInt::get(size_ty, iBuilder->getStride());
169    Value * strideBlocks = ConstantInt::get(size_ty, iBuilder->getStride() / iBuilder->getBitBlockWidth());
170   
171    Function::arg_iterator args = doSegmentFunction->arg_begin();
172    Value * self = &*(args++);
173    Value * blocksToDo = &*(args);
174    Value * segmentNo = getLogicalSegmentNo(self);
175    std::vector<Value *> inbufProducerPtrs;
176   
177    for (unsigned i = 0; i < mStreamSetInputs.size(); i++) {
178        Value * basePtr = getStreamSetBasePtr(self, mStreamSetInputs[i].ssName);
179        inbufProducerPtrs.push_back(mStreamSetInputBuffers[i]->getProducerPosPtr(basePtr));
180    }
181   
182    /* Determine the actually available data examining all input stream sets. */
183    LoadInst * producerPos = iBuilder->CreateAlignedLoad(inbufProducerPtrs[0], sizeof(size_t));
184    producerPos->setOrdering(AtomicOrdering::Acquire);
185    Value * availablePos = producerPos;
186    for (unsigned i = 1; i < inbufProducerPtrs.size(); i++) {
187        LoadInst * producerPos = iBuilder->CreateAlignedLoad(inbufProducerPtrs[i], sizeof(size_t));
188        producerPos->setOrdering(AtomicOrdering::Acquire);
189        /* Set the available position to be the minimum of availablePos and producerPos. */
190        availablePos = iBuilder->CreateSelect(iBuilder->CreateICmpULT(availablePos, producerPos), availablePos, producerPos);
191    }
192    Value * processed = getProcessedItemCount(self);
193    Value * itemsAvail = iBuilder->CreateSub(availablePos, processed);
194#ifndef NDEBUG
195    iBuilder->CallPrintInt(mKernelName + "_itemsAvail", itemsAvail);
196#endif
197    Value * blocksAvail = iBuilder->CreateUDiv(itemsAvail, stride);
198    /* Adjust the number of full blocks to do, based on the available data, if necessary. */
199    blocksToDo = iBuilder->CreateSelect(iBuilder->CreateICmpULT(blocksToDo, blocksAvail), blocksToDo, blocksAvail);
200    iBuilder->CreateBr(blockLoopCond);
201
202    iBuilder->SetInsertPoint(blockLoopCond);
203    PHINode * blocksRemaining = iBuilder->CreatePHI(size_ty, 2, "blocksRemaining");
204    blocksRemaining->addIncoming(blocksToDo, entryBlock);
205    Value * notDone = iBuilder->CreateICmpUGT(blocksRemaining, ConstantInt::get(size_ty, 0));
206    iBuilder->CreateCondBr(notDone, blockLoopBody, blocksDone);
207
208    iBuilder->SetInsertPoint(blockLoopBody);
209    Value * blockNo = getScalarField(self, blockNoScalar);   
210    generateDoBlockLogic(self, blockNo);
211    setBlockNo(self, iBuilder->CreateAdd(blockNo, strideBlocks));
212    blocksRemaining->addIncoming(iBuilder->CreateSub(blocksRemaining, strideBlocks), blockLoopBody);
213    iBuilder->CreateBr(blockLoopCond);
214   
215    iBuilder->SetInsertPoint(blocksDone);
216    processed = iBuilder->CreateAdd(processed, iBuilder->CreateMul(blocksToDo, stride));
217    setProcessedItemCount(self, processed);
218    Value * produced = getProducedItemCount(self);
219#ifndef NDEBUG
220    iBuilder->CallPrintInt(mKernelName + "_produced", produced);
221#endif
222    for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
223        Value * basePtr = getStreamSetBasePtr(self, mStreamSetOutputs[i].ssName);
224        Value * producerPosPtr = mStreamSetOutputBuffers[i]->getProducerPosPtr(basePtr);
225        iBuilder->CreateAlignedStore(produced, producerPosPtr, sizeof(size_t))->setOrdering(AtomicOrdering::Release);
226    }
227
228    // Must be the last action, for synchronization.
229    setLogicalSegmentNo(self, iBuilder->CreateAdd(segmentNo, ConstantInt::get(size_ty, 1)));
230
231    iBuilder->CreateRetVoid();
232    iBuilder->restoreIP(savePoint);
233}
234
235Value * KernelBuilder::getScalarIndex(std::string fieldName) {
236    const auto f = mInternalStateNameMap.find(fieldName);
237    if (LLVM_UNLIKELY(f == mInternalStateNameMap.end())) {
238        llvm::report_fatal_error("Kernel does not contain internal state: " + fieldName);
239    }
240    return iBuilder->getInt32(f->second);
241}
242
243
244
245Value * KernelBuilder::getScalarField(Value * self, std::string fieldName) {
246    Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), getScalarIndex(fieldName)});
247    return iBuilder->CreateLoad(ptr);
248}
249
250void KernelBuilder::setScalarField(Value * self, std::string fieldName, Value * newFieldVal) {
251    Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), getScalarIndex(fieldName)});
252    iBuilder->CreateStore(newFieldVal, ptr);
253}
254
255Value * KernelBuilder::getLogicalSegmentNo(Value * self) { 
256    Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), getScalarIndex(logicalSegmentNoScalar)});
257    LoadInst * segNo = iBuilder->CreateAlignedLoad(ptr, sizeof(size_t));
258    segNo->setOrdering(AtomicOrdering::Acquire);
259    return segNo;
260}
261
262Value * KernelBuilder::getProcessedItemCount(Value * self) { 
263    return getScalarField(self, processedItemCount);
264}
265
266Value * KernelBuilder::getProducedItemCount(Value * self) {
267    return getScalarField(self, producedItemCount);
268}
269
270//  By default, kernels do not terminate early. 
271Value * KernelBuilder::getTerminationSignal(Value * self) {
272    return ConstantInt::getNullValue(iBuilder->getInt1Ty());
273}
274
275
276void KernelBuilder::setLogicalSegmentNo(Value * self, Value * newCount) {
277    Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), getScalarIndex(logicalSegmentNoScalar)});
278    iBuilder->CreateAlignedStore(newCount, ptr, sizeof(size_t))->setOrdering(AtomicOrdering::Release);
279}
280
281void KernelBuilder::setProcessedItemCount(Value * self, Value * newCount) {
282    Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), getScalarIndex(processedItemCount)});
283    iBuilder->CreateStore(newCount, ptr);
284}
285
286void KernelBuilder::setProducedItemCount(Value * self, Value * newCount) {
287    Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), getScalarIndex(producedItemCount)});
288    iBuilder->CreateStore(newCount, ptr);
289}
290
291void KernelBuilder::setTerminationSignal(Value * self, Value * newFieldVal) {
292    llvm::report_fatal_error("This kernel type does not support setTerminationSignal.");
293}
294
295
296Value * KernelBuilder::getBlockNo(Value * self) {
297    Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), getScalarIndex(blockNoScalar)});
298    LoadInst * blockNo = iBuilder->CreateLoad(ptr);
299    return blockNo;
300}
301
302void KernelBuilder::setBlockNo(Value * self, Value * newFieldVal) {
303    Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), getScalarIndex(blockNoScalar)});
304    iBuilder->CreateStore(newFieldVal, ptr);
305}
306
307
308Value * KernelBuilder::getParameter(Function * f, std::string paramName) {
309    for (Function::arg_iterator argIter = f->arg_begin(), end = f->arg_end(); argIter != end; argIter++) {
310        Value * arg = &*argIter;
311        if (arg->getName() == paramName) return arg;
312    }
313    llvm::report_fatal_error("Method does not have parameter: " + paramName);
314}
315
316unsigned KernelBuilder::getStreamSetIndex(std::string ssName) {
317    const auto f = mStreamSetNameMap.find(ssName);
318    if (LLVM_UNLIKELY(f == mStreamSetNameMap.end())) {
319        llvm::report_fatal_error("Kernel does not contain stream set: " + ssName);
320    }
321    return f->second;
322}
323
324size_t KernelBuilder::getStreamSetBufferSize(Value * self, std::string ssName) {
325    unsigned ssIndex = getStreamSetIndex(ssName);
326    if (ssIndex < mStreamSetInputs.size()) {
327        return mStreamSetInputBuffers[ssIndex]->getBufferSize();
328    }
329    else {
330        return mStreamSetOutputBuffers[ssIndex - mStreamSetInputs.size()]->getBufferSize();
331    }
332}
333
334Value * KernelBuilder::getStreamSetBasePtr(Value * self, std::string ssName) {
335    return getScalarField(self, ssName + basePtrSuffix);
336}
337
338Value * KernelBuilder::getStreamSetBlockPtr(Value * self, std::string ssName, Value * blockNo) {
339    Value * basePtr = getStreamSetBasePtr(self, ssName);
340    unsigned ssIndex = getStreamSetIndex(ssName);
341    if (ssIndex < mStreamSetInputs.size()) {
342        return mStreamSetInputBuffers[ssIndex]->getStreamSetBlockPointer(basePtr, blockNo);
343    }
344    else {
345        return mStreamSetOutputBuffers[ssIndex - mStreamSetInputs.size()]->getStreamSetBlockPointer(basePtr, blockNo);
346    }
347}
348
349Value * KernelBuilder::createInstance(std::vector<Value *> args) {
350    Value * kernelInstance = iBuilder->CreateAlloca(mKernelStateType);
351    Module * m = iBuilder->getModule();
352    std::vector<Value *> init_args = {kernelInstance};
353    for (auto a : args) {
354        init_args.push_back(a);
355    }
356    for (auto b : mStreamSetInputBuffers) { 
357        init_args.push_back(b->getStreamSetStructPtr());
358    }
359    for (auto b : mStreamSetOutputBuffers) { 
360        init_args.push_back(b->getStreamSetStructPtr());
361    }
362    std::string initFnName = mKernelName + init_suffix;
363    Function * initMethod = m->getFunction(initFnName);
364    if (!initMethod) {
365        llvm::report_fatal_error("Cannot find " + initFnName);
366    }
367    iBuilder->CreateCall(initMethod, init_args);
368    return kernelInstance;
369}
370
371Function * KernelBuilder::generateThreadFunction(std::string name){
372    Module * m = iBuilder->getModule();
373    Type * const voidTy = Type::getVoidTy(m->getContext());
374    Type * const voidPtrTy = TypeBuilder<void *, false>::get(m->getContext());
375    Type * const int8PtrTy = iBuilder->getInt8PtrTy();
376    Type * const int1ty = iBuilder->getInt1Ty();
377
378    Function * const threadFunc = cast<Function>(m->getOrInsertFunction(name, voidTy, int8PtrTy, nullptr));
379    threadFunc->setCallingConv(CallingConv::C);
380    Function::arg_iterator args = threadFunc->arg_begin();
381
382    Value * const arg = &*(args++);
383    arg->setName("args");
384
385    iBuilder->SetInsertPoint(BasicBlock::Create(iBuilder->getContext(), "entry", threadFunc,0));
386
387    Value * self = iBuilder->CreateBitCast(arg, PointerType::get(mKernelStateType, 0));
388
389    std::vector<Value *> inbufProducerPtrs;
390    std::vector<Value *> inbufConsumerPtrs;
391    std::vector<Value *> outbufProducerPtrs;
392    std::vector<Value *> outbufConsumerPtrs;   
393    std::vector<Value *> endSignalPtrs;
394
395    for (unsigned i = 0; i < mStreamSetInputs.size(); i++) {
396        Value * basePtr = getStreamSetBasePtr(self, mStreamSetInputs[i].ssName);
397        inbufProducerPtrs.push_back(mStreamSetInputBuffers[i]->getProducerPosPtr(basePtr));
398        inbufConsumerPtrs.push_back(mStreamSetInputBuffers[i]->getConsumerPosPtr(basePtr));
399        endSignalPtrs.push_back(mStreamSetInputBuffers[i]->hasEndOfInputPtr(basePtr));
400    }
401    for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
402        Value * basePtr = getStreamSetBasePtr(self, mStreamSetOutputs[i].ssName);
403        outbufProducerPtrs.push_back(mStreamSetOutputBuffers[i]->getProducerPosPtr(basePtr));
404        outbufConsumerPtrs.push_back(mStreamSetOutputBuffers[i]->getConsumerPosPtr(basePtr));
405    }
406
407    const unsigned segmentBlocks = codegen::SegmentSize;
408    const unsigned bufferSegments = codegen::BufferSegments;
409    const unsigned segmentSize = segmentBlocks * iBuilder->getBitBlockWidth();
410    Type * const size_ty = iBuilder->getSizeTy();
411
412    Value * segSize = ConstantInt::get(size_ty, segmentSize);
413    Value * bufferSize = ConstantInt::get(size_ty, segmentSize * (bufferSegments - 1));
414    Value * segBlocks = ConstantInt::get(size_ty, segmentBlocks);
415   
416    BasicBlock * outputCheckBlock = BasicBlock::Create(iBuilder->getContext(), "outputCheck", threadFunc, 0);
417    BasicBlock * inputCheckBlock = BasicBlock::Create(iBuilder->getContext(), "inputCheck", threadFunc, 0);
418   
419    BasicBlock * endSignalCheckBlock = BasicBlock::Create(iBuilder->getContext(), "endSignalCheck", threadFunc, 0);
420    BasicBlock * doSegmentBlock = BasicBlock::Create(iBuilder->getContext(), "doSegment", threadFunc, 0);
421    BasicBlock * endBlock = BasicBlock::Create(iBuilder->getContext(), "end", threadFunc, 0);
422    BasicBlock * doFinalSegBlock = BasicBlock::Create(iBuilder->getContext(), "doFinalSeg", threadFunc, 0);
423    BasicBlock * doFinalBlock = BasicBlock::Create(iBuilder->getContext(), "doFinal", threadFunc, 0);
424
425    iBuilder->CreateBr(outputCheckBlock);
426
427    iBuilder->SetInsertPoint(outputCheckBlock);
428
429    Value * waitCondTest = ConstantInt::get(int1ty, 1);   
430    for (unsigned i = 0; i < outbufProducerPtrs.size(); i++) {
431        LoadInst * producerPos = iBuilder->CreateAlignedLoad(outbufProducerPtrs[i], sizeof(size_t));
432        producerPos->setOrdering(AtomicOrdering::Acquire);
433        // iBuilder->CallPrintInt(name + ":output producerPos", producerPos);
434        LoadInst * consumerPos = iBuilder->CreateAlignedLoad(outbufConsumerPtrs[i], sizeof(size_t));
435        consumerPos->setOrdering(AtomicOrdering::Acquire);
436        // iBuilder->CallPrintInt(name + ":output consumerPos", consumerPos);
437        waitCondTest = iBuilder->CreateAnd(waitCondTest, iBuilder->CreateICmpULE(producerPos, iBuilder->CreateAdd(consumerPos, bufferSize)));
438    }
439   
440    iBuilder->CreateCondBr(waitCondTest, inputCheckBlock, outputCheckBlock); 
441
442    iBuilder->SetInsertPoint(inputCheckBlock); 
443
444    Value * requiredSize = segSize;
445    if (mLookAheadPositions > 0) {
446        requiredSize = iBuilder->CreateAdd(segSize, ConstantInt::get(size_ty, mLookAheadPositions));
447    }
448    waitCondTest = ConstantInt::get(int1ty, 1); 
449    for (unsigned i = 0; i < inbufProducerPtrs.size(); i++) {
450        LoadInst * producerPos = iBuilder->CreateAlignedLoad(inbufProducerPtrs[i], sizeof(size_t));
451        producerPos->setOrdering(AtomicOrdering::Acquire);
452        // iBuilder->CallPrintInt(name + ":input producerPos", producerPos);
453        LoadInst * consumerPos = iBuilder->CreateAlignedLoad(inbufConsumerPtrs[i], sizeof(size_t));
454        consumerPos->setOrdering(AtomicOrdering::Acquire);
455        // iBuilder->CallPrintInt(name + ":input consumerPos", consumerPos);
456        waitCondTest = iBuilder->CreateAnd(waitCondTest, iBuilder->CreateICmpULE(iBuilder->CreateAdd(consumerPos, requiredSize), producerPos));
457    }
458
459    iBuilder->CreateCondBr(waitCondTest, doSegmentBlock, endSignalCheckBlock);
460   
461    iBuilder->SetInsertPoint(endSignalCheckBlock);
462   
463    LoadInst * endSignal = iBuilder->CreateAlignedLoad(endSignalPtrs[0], sizeof(size_t));
464    // iBuilder->CallPrintInt(name + ":endSignal", endSignal);
465    endSignal->setOrdering(AtomicOrdering::Acquire);
466    for (unsigned i = 1; i < endSignalPtrs.size(); i++){
467        LoadInst * endSignal_next = iBuilder->CreateAlignedLoad(endSignalPtrs[i], sizeof(size_t));
468        endSignal_next->setOrdering(AtomicOrdering::Acquire);
469        iBuilder->CreateAnd(endSignal, endSignal_next);
470    }
471       
472    iBuilder->CreateCondBr(iBuilder->CreateICmpEQ(endSignal, ConstantInt::get(iBuilder->getInt8Ty(), 1)), endBlock, inputCheckBlock);
473   
474    iBuilder->SetInsertPoint(doSegmentBlock);
475 
476    createDoSegmentCall(self, segBlocks);
477
478    for (unsigned i = 0; i < inbufConsumerPtrs.size(); i++) {
479        Value * consumerPos = iBuilder->CreateAdd(iBuilder->CreateLoad(inbufConsumerPtrs[i]), segSize);
480        iBuilder->CreateAlignedStore(consumerPos, inbufConsumerPtrs[i], sizeof(size_t))->setOrdering(AtomicOrdering::Release);
481    }
482   
483    Value * produced = getProducedItemCount(self);
484    for (unsigned i = 0; i < outbufProducerPtrs.size(); i++) {
485        iBuilder->CreateAlignedStore(produced, outbufProducerPtrs[i], sizeof(size_t))->setOrdering(AtomicOrdering::Release);
486    }
487   
488    Value * earlyEndSignal = getTerminationSignal(self);
489    if (earlyEndSignal != ConstantInt::getNullValue(iBuilder->getInt1Ty())) {
490        BasicBlock * earlyEndBlock = BasicBlock::Create(iBuilder->getContext(), "earlyEndSignal", threadFunc, 0);
491        iBuilder->CreateCondBr(earlyEndSignal, earlyEndBlock, outputCheckBlock);
492
493        iBuilder->SetInsertPoint(earlyEndBlock);
494        for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
495            Value * basePtr = getStreamSetBasePtr(self, mStreamSetOutputs[i].ssName);
496            mStreamSetOutputBuffers[i]->setEndOfInput(basePtr);
497        }       
498    }
499    iBuilder->CreateBr(outputCheckBlock);
500     
501    iBuilder->SetInsertPoint(endBlock);
502    LoadInst * producerPos = iBuilder->CreateLoad(inbufProducerPtrs[0]);
503    LoadInst * consumerPos = iBuilder->CreateLoad(inbufConsumerPtrs[0]);
504    Value * remainingBytes = iBuilder->CreateSub(producerPos, consumerPos);
505    Value * blockSize = ConstantInt::get(size_ty, iBuilder->getBitBlockWidth());
506    Value * blocks = iBuilder->CreateUDiv(remainingBytes, blockSize);
507    Value * finalBlockRemainingBytes = iBuilder->CreateURem(remainingBytes, blockSize);
508
509    iBuilder->CreateCondBr(iBuilder->CreateICmpEQ(blocks, ConstantInt::get(size_ty, 0)), doFinalBlock, doFinalSegBlock);
510
511    iBuilder->SetInsertPoint(doFinalSegBlock);
512
513    createDoSegmentCall(self, blocks);
514
515    iBuilder->CreateBr(doFinalBlock);
516
517    iBuilder->SetInsertPoint(doFinalBlock);
518
519    createFinalBlockCall(self, finalBlockRemainingBytes);
520
521    for (unsigned i = 0; i < inbufConsumerPtrs.size(); i++) {
522        Value * consumerPos = iBuilder->CreateAdd(iBuilder->CreateLoad(inbufConsumerPtrs[i]), remainingBytes);
523        iBuilder->CreateAlignedStore(consumerPos, inbufConsumerPtrs[i], sizeof(size_t))->setOrdering(AtomicOrdering::Release);
524    }
525    for (unsigned i = 0; i < outbufProducerPtrs.size(); i++) {
526        iBuilder->CreateAlignedStore(producerPos, outbufProducerPtrs[i], sizeof(size_t))->setOrdering(AtomicOrdering::Release);
527    }
528
529    for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
530        Value * basePtr = getStreamSetBasePtr(self, mStreamSetOutputs[i].ssName);
531        mStreamSetOutputBuffers[i]->setEndOfInput(basePtr);
532    }
533
534    Value * nullVal = Constant::getNullValue(voidPtrTy);
535    Function * pthreadExitFunc = m->getFunction("pthread_exit");
536    CallInst * exitThread = iBuilder->CreateCall(pthreadExitFunc, {nullVal}); 
537    exitThread->setDoesNotReturn();
538    iBuilder->CreateRetVoid();
539
540    return threadFunc;
541
542}
Note: See TracBrowser for help on using the repository browser.