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

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

Linear buffers; stdout_kernel; cache-aligned alloca, restructured u8u16, clean-ups

File size: 26.1 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 " + mStreamSetInputs[i].ssName);
57        }
58        mScalarInputs.push_back(ScalarBinding{mStreamSetInputBuffers[i]->getStreamSetStructPointerType(), mStreamSetInputs[i].ssName + structPtrSuffix});
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 " + mStreamSetOutputs[i].ssName);
65        }
66        mScalarInputs.push_back(ScalarBinding{mStreamSetOutputBuffers[i]->getStreamSetStructPointerType(), mStreamSetOutputs[i].ssName + structPtrSuffix});
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
151// Note: this may be overridden to incorporate doBlock logic directly into
152// the doSegment function.
153void KernelBuilder::generateDoBlockLogic(Value * self, Value * blockNo) {
154    Function * doBlockFunction = iBuilder->getModule()->getFunction(mKernelName + doBlock_suffix);
155    iBuilder->CreateCall(doBlockFunction, {self});
156}
157
158//  The default doSegment method dispatches to the doBlock routine for
159//  each block of the given number of blocksToDo, and then updates counts.
160void KernelBuilder::generateDoSegmentMethod() {
161    IDISA::IDISA_Builder::InsertPoint savePoint = iBuilder->saveIP();
162    Module * m = iBuilder->getModule();
163    Function * doSegmentFunction = m->getFunction(mKernelName + doSegment_suffix);
164    iBuilder->SetInsertPoint(BasicBlock::Create(iBuilder->getContext(), "entry", doSegmentFunction, 0));
165    BasicBlock * entryBlock = iBuilder->GetInsertBlock();
166    BasicBlock * blockLoopCond = BasicBlock::Create(iBuilder->getContext(), "blockLoopCond", doSegmentFunction, 0);
167    BasicBlock * blockLoopBody = BasicBlock::Create(iBuilder->getContext(), "blockLoopBody", doSegmentFunction, 0);
168    BasicBlock * blocksDone = BasicBlock::Create(iBuilder->getContext(), "blocksDone", doSegmentFunction, 0);
169    Type * const size_ty = iBuilder->getSizeTy();
170    Constant * stride = ConstantInt::get(size_ty, iBuilder->getStride());
171    Value * strideBlocks = ConstantInt::get(size_ty, iBuilder->getStride() / iBuilder->getBitBlockWidth());
172   
173    Function::arg_iterator args = doSegmentFunction->arg_begin();
174    Value * self = &*(args++);
175    Value * blocksToDo = &*(args);
176    Value * segmentNo = getLogicalSegmentNo(self);
177    std::vector<Value *> inbufProducerPtrs;
178   
179    for (unsigned i = 0; i < mStreamSetInputs.size(); i++) {
180        Value * ssStructPtr = getStreamSetStructPtr(self, mStreamSetInputs[i].ssName);
181        inbufProducerPtrs.push_back(mStreamSetInputBuffers[i]->getProducerPosPtr(ssStructPtr));
182    }
183   
184    /* Determine the actually available data examining all input stream sets. */
185    LoadInst * producerPos = iBuilder->CreateAlignedLoad(inbufProducerPtrs[0], sizeof(size_t));
186    producerPos->setOrdering(AtomicOrdering::Acquire);
187    Value * availablePos = producerPos;
188    for (unsigned i = 1; i < inbufProducerPtrs.size(); i++) {
189        LoadInst * producerPos = iBuilder->CreateAlignedLoad(inbufProducerPtrs[i], sizeof(size_t));
190        producerPos->setOrdering(AtomicOrdering::Acquire);
191        /* Set the available position to be the minimum of availablePos and producerPos. */
192        availablePos = iBuilder->CreateSelect(iBuilder->CreateICmpULT(availablePos, producerPos), availablePos, producerPos);
193    }
194    Value * processed = getProcessedItemCount(self);
195    Value * itemsAvail = iBuilder->CreateSub(availablePos, processed);
196#ifndef NDEBUG
197    iBuilder->CallPrintInt(mKernelName + "_itemsAvail", itemsAvail);
198#endif
199    Value * blocksAvail = iBuilder->CreateUDiv(itemsAvail, stride);
200    /* Adjust the number of full blocks to do, based on the available data, if necessary. */
201    blocksToDo = iBuilder->CreateSelect(iBuilder->CreateICmpULT(blocksToDo, blocksAvail), blocksToDo, blocksAvail);
202    //iBuilder->CallPrintInt(mKernelName + "_blocksAvail", blocksAvail);
203    iBuilder->CreateBr(blockLoopCond);
204
205    iBuilder->SetInsertPoint(blockLoopCond);
206    PHINode * blocksRemaining = iBuilder->CreatePHI(size_ty, 2, "blocksRemaining");
207    blocksRemaining->addIncoming(blocksToDo, entryBlock);
208    Value * notDone = iBuilder->CreateICmpUGT(blocksRemaining, ConstantInt::get(size_ty, 0));
209    iBuilder->CreateCondBr(notDone, blockLoopBody, blocksDone);
210
211    iBuilder->SetInsertPoint(blockLoopBody);
212    Value * blockNo = getScalarField(self, blockNoScalar);   
213
214    generateDoBlockLogic(self, blockNo);
215    setBlockNo(self, iBuilder->CreateAdd(blockNo, strideBlocks));
216    blocksRemaining->addIncoming(iBuilder->CreateSub(blocksRemaining, strideBlocks), blockLoopBody);
217    iBuilder->CreateBr(blockLoopCond);
218   
219    iBuilder->SetInsertPoint(blocksDone);
220    processed = iBuilder->CreateAdd(processed, iBuilder->CreateMul(blocksToDo, stride));
221    setProcessedItemCount(self, processed);
222    Value * produced = getProducedItemCount(self);
223#ifndef NDEBUG
224    iBuilder->CallPrintInt(mKernelName + "_produced", produced);
225#endif
226    for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
227        Value * ssStructPtr = getStreamSetStructPtr(self, mStreamSetOutputs[i].ssName);
228        Value * producerPosPtr = mStreamSetOutputBuffers[i]->getProducerPosPtr(ssStructPtr);
229        iBuilder->CreateAlignedStore(produced, producerPosPtr, sizeof(size_t))->setOrdering(AtomicOrdering::Release);
230    }
231
232    // Must be the last action, for synchronization.
233    setLogicalSegmentNo(self, iBuilder->CreateAdd(segmentNo, ConstantInt::get(size_ty, 1)));
234
235    iBuilder->CreateRetVoid();
236    iBuilder->restoreIP(savePoint);
237}
238
239Value * KernelBuilder::getScalarIndex(std::string fieldName) {
240    const auto f = mInternalStateNameMap.find(fieldName);
241    if (LLVM_UNLIKELY(f == mInternalStateNameMap.end())) {
242        llvm::report_fatal_error("Kernel does not contain internal state: " + fieldName);
243    }
244    return iBuilder->getInt32(f->second);
245}
246
247
248
249Value * KernelBuilder::getScalarField(Value * self, std::string fieldName) {
250    Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), getScalarIndex(fieldName)});
251    return iBuilder->CreateLoad(ptr);
252}
253
254void KernelBuilder::setScalarField(Value * self, std::string fieldName, Value * newFieldVal) {
255    Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), getScalarIndex(fieldName)});
256    iBuilder->CreateStore(newFieldVal, ptr);
257}
258
259Value * KernelBuilder::getLogicalSegmentNo(Value * self) { 
260    Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), getScalarIndex(logicalSegmentNoScalar)});
261    LoadInst * segNo = iBuilder->CreateAlignedLoad(ptr, sizeof(size_t));
262    segNo->setOrdering(AtomicOrdering::Acquire);
263    return segNo;
264}
265
266Value * KernelBuilder::getProcessedItemCount(Value * self) { 
267    return getScalarField(self, processedItemCount);
268}
269
270Value * KernelBuilder::getProducedItemCount(Value * self) {
271    return getScalarField(self, producedItemCount);
272}
273
274//  By default, kernels do not terminate early. 
275Value * KernelBuilder::getTerminationSignal(Value * self) {
276    return ConstantInt::getNullValue(iBuilder->getInt1Ty());
277}
278
279
280void KernelBuilder::setLogicalSegmentNo(Value * self, Value * newCount) {
281    Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), getScalarIndex(logicalSegmentNoScalar)});
282    iBuilder->CreateAlignedStore(newCount, ptr, sizeof(size_t))->setOrdering(AtomicOrdering::Release);
283}
284
285void KernelBuilder::setProcessedItemCount(Value * self, Value * newCount) {
286    Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), getScalarIndex(processedItemCount)});
287    iBuilder->CreateStore(newCount, ptr);
288}
289
290void KernelBuilder::setProducedItemCount(Value * self, Value * newCount) {
291    Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), getScalarIndex(producedItemCount)});
292    iBuilder->CreateStore(newCount, ptr);
293}
294
295void KernelBuilder::setTerminationSignal(Value * self, Value * newFieldVal) {
296    llvm::report_fatal_error("This kernel type does not support setTerminationSignal.");
297}
298
299
300Value * KernelBuilder::getBlockNo(Value * self) {
301    Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), getScalarIndex(blockNoScalar)});
302    LoadInst * blockNo = iBuilder->CreateLoad(ptr);
303    return blockNo;
304}
305
306void KernelBuilder::setBlockNo(Value * self, Value * newFieldVal) {
307    Value * ptr = iBuilder->CreateGEP(self, {iBuilder->getInt32(0), getScalarIndex(blockNoScalar)});
308    iBuilder->CreateStore(newFieldVal, ptr);
309}
310
311
312Value * KernelBuilder::getParameter(Function * f, std::string paramName) {
313    for (Function::arg_iterator argIter = f->arg_begin(), end = f->arg_end(); argIter != end; argIter++) {
314        Value * arg = &*argIter;
315        if (arg->getName() == paramName) return arg;
316    }
317    llvm::report_fatal_error("Method does not have parameter: " + paramName);
318}
319
320unsigned KernelBuilder::getStreamSetIndex(std::string ssName) {
321    const auto f = mStreamSetNameMap.find(ssName);
322    if (LLVM_UNLIKELY(f == mStreamSetNameMap.end())) {
323        llvm::report_fatal_error("Kernel does not contain stream set: " + ssName);
324    }
325    return f->second;
326}
327
328size_t KernelBuilder::getStreamSetBufferSize(Value * self, std::string ssName) {
329    unsigned ssIndex = getStreamSetIndex(ssName);
330    if (ssIndex < mStreamSetInputs.size()) {
331        return mStreamSetInputBuffers[ssIndex]->getBufferSize();
332    }
333    else {
334        return mStreamSetOutputBuffers[ssIndex - mStreamSetInputs.size()]->getBufferSize();
335    }
336}
337
338Value * KernelBuilder::getStreamSetStructPtr(Value * self, std::string ssName) {
339    return getScalarField(self, ssName + structPtrSuffix);
340}
341
342Value * KernelBuilder::getStreamSetBlockPtr(Value * self, std::string ssName, Value * blockNo) {
343    Value * ssStructPtr = getStreamSetStructPtr(self, ssName);
344    unsigned ssIndex = getStreamSetIndex(ssName);
345    if (ssIndex < mStreamSetInputs.size()) {
346        return mStreamSetInputBuffers[ssIndex]->getStreamSetBlockPointer(ssStructPtr, blockNo);
347    }
348    else {
349        return mStreamSetOutputBuffers[ssIndex - mStreamSetInputs.size()]->getStreamSetBlockPointer(ssStructPtr, blockNo);
350    }
351}
352
353Value * KernelBuilder::createInstance(std::vector<Value *> args) {
354    Value * kernelInstance = iBuilder->CreateCacheAlignedAlloca(mKernelStateType);
355    Module * m = iBuilder->getModule();
356    std::vector<Value *> init_args = {kernelInstance};
357    for (auto a : args) {
358        init_args.push_back(a);
359    }
360    for (auto b : mStreamSetInputBuffers) { 
361        init_args.push_back(b->getStreamSetStructPtr());
362    }
363    for (auto b : mStreamSetOutputBuffers) { 
364        init_args.push_back(b->getStreamSetStructPtr());
365    }
366    std::string initFnName = mKernelName + init_suffix;
367    Function * initMethod = m->getFunction(initFnName);
368    if (!initMethod) {
369        llvm::report_fatal_error("Cannot find " + initFnName);
370    }
371    iBuilder->CreateCall(initMethod, init_args);
372    return kernelInstance;
373}
374
375Function * KernelBuilder::generateThreadFunction(std::string name){
376    Module * m = iBuilder->getModule();
377    Type * const voidTy = Type::getVoidTy(m->getContext());
378    Type * const voidPtrTy = TypeBuilder<void *, false>::get(m->getContext());
379    Type * const int8PtrTy = iBuilder->getInt8PtrTy();
380    Type * const int1ty = iBuilder->getInt1Ty();
381
382    Function * const threadFunc = cast<Function>(m->getOrInsertFunction(name, voidTy, int8PtrTy, nullptr));
383    threadFunc->setCallingConv(CallingConv::C);
384    Function::arg_iterator args = threadFunc->arg_begin();
385
386    Value * const arg = &*(args++);
387    arg->setName("args");
388
389    iBuilder->SetInsertPoint(BasicBlock::Create(iBuilder->getContext(), "entry", threadFunc,0));
390
391    Value * self = iBuilder->CreateBitCast(arg, PointerType::get(mKernelStateType, 0));
392
393    std::vector<Value *> inbufProducerPtrs;
394    std::vector<Value *> inbufConsumerPtrs;
395    std::vector<Value *> outbufProducerPtrs;
396    std::vector<Value *> outbufConsumerPtrs;   
397    std::vector<Value *> endSignalPtrs;
398
399    for (unsigned i = 0; i < mStreamSetInputs.size(); i++) {
400        Value * ssStructPtr = getStreamSetStructPtr(self, mStreamSetInputs[i].ssName);
401        inbufProducerPtrs.push_back(mStreamSetInputBuffers[i]->getProducerPosPtr(ssStructPtr));
402        inbufConsumerPtrs.push_back(mStreamSetInputBuffers[i]->getConsumerPosPtr(ssStructPtr));
403        endSignalPtrs.push_back(mStreamSetInputBuffers[i]->hasEndOfInputPtr(ssStructPtr));
404    }
405    for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
406        Value * ssStructPtr = getStreamSetStructPtr(self, mStreamSetOutputs[i].ssName);
407        outbufProducerPtrs.push_back(mStreamSetOutputBuffers[i]->getProducerPosPtr(ssStructPtr));
408        outbufConsumerPtrs.push_back(mStreamSetOutputBuffers[i]->getConsumerPosPtr(ssStructPtr));
409    }
410
411    const unsigned segmentBlocks = codegen::SegmentSize;
412    const unsigned bufferSegments = codegen::BufferSegments;
413    const unsigned segmentSize = segmentBlocks * iBuilder->getBitBlockWidth();
414    Type * const size_ty = iBuilder->getSizeTy();
415
416    Value * segSize = ConstantInt::get(size_ty, segmentSize);
417    Value * bufferSize = ConstantInt::get(size_ty, segmentSize * (bufferSegments - 1));
418    Value * segBlocks = ConstantInt::get(size_ty, segmentBlocks);
419   
420    BasicBlock * outputCheckBlock = BasicBlock::Create(iBuilder->getContext(), "outputCheck", threadFunc, 0);
421    BasicBlock * inputCheckBlock = BasicBlock::Create(iBuilder->getContext(), "inputCheck", threadFunc, 0);
422   
423    BasicBlock * endSignalCheckBlock = BasicBlock::Create(iBuilder->getContext(), "endSignalCheck", threadFunc, 0);
424    BasicBlock * doSegmentBlock = BasicBlock::Create(iBuilder->getContext(), "doSegment", threadFunc, 0);
425    BasicBlock * endBlock = BasicBlock::Create(iBuilder->getContext(), "end", threadFunc, 0);
426    BasicBlock * doFinalSegBlock = BasicBlock::Create(iBuilder->getContext(), "doFinalSeg", threadFunc, 0);
427    BasicBlock * doFinalBlock = BasicBlock::Create(iBuilder->getContext(), "doFinal", threadFunc, 0);
428
429    iBuilder->CreateBr(outputCheckBlock);
430
431    iBuilder->SetInsertPoint(outputCheckBlock);
432
433    Value * waitCondTest = ConstantInt::get(int1ty, 1);   
434    for (unsigned i = 0; i < outbufProducerPtrs.size(); i++) {
435        LoadInst * producerPos = iBuilder->CreateAlignedLoad(outbufProducerPtrs[i], sizeof(size_t));
436        producerPos->setOrdering(AtomicOrdering::Acquire);
437        // iBuilder->CallPrintInt(name + ":output producerPos", producerPos);
438        LoadInst * consumerPos = iBuilder->CreateAlignedLoad(outbufConsumerPtrs[i], sizeof(size_t));
439        consumerPos->setOrdering(AtomicOrdering::Acquire);
440        // iBuilder->CallPrintInt(name + ":output consumerPos", consumerPos);
441        waitCondTest = iBuilder->CreateAnd(waitCondTest, iBuilder->CreateICmpULE(producerPos, iBuilder->CreateAdd(consumerPos, bufferSize)));
442    }
443   
444    iBuilder->CreateCondBr(waitCondTest, inputCheckBlock, outputCheckBlock); 
445
446    iBuilder->SetInsertPoint(inputCheckBlock); 
447
448    Value * requiredSize = segSize;
449    if (mLookAheadPositions > 0) {
450        requiredSize = iBuilder->CreateAdd(segSize, ConstantInt::get(size_ty, mLookAheadPositions));
451    }
452    waitCondTest = ConstantInt::get(int1ty, 1); 
453    for (unsigned i = 0; i < inbufProducerPtrs.size(); i++) {
454        LoadInst * producerPos = iBuilder->CreateAlignedLoad(inbufProducerPtrs[i], sizeof(size_t));
455        producerPos->setOrdering(AtomicOrdering::Acquire);
456        // iBuilder->CallPrintInt(name + ":input producerPos", producerPos);
457        LoadInst * consumerPos = iBuilder->CreateAlignedLoad(inbufConsumerPtrs[i], sizeof(size_t));
458        consumerPos->setOrdering(AtomicOrdering::Acquire);
459        // iBuilder->CallPrintInt(name + ":input consumerPos", consumerPos);
460        waitCondTest = iBuilder->CreateAnd(waitCondTest, iBuilder->CreateICmpULE(iBuilder->CreateAdd(consumerPos, requiredSize), producerPos));
461    }
462
463    iBuilder->CreateCondBr(waitCondTest, doSegmentBlock, endSignalCheckBlock);
464   
465    iBuilder->SetInsertPoint(endSignalCheckBlock);
466   
467    LoadInst * endSignal = iBuilder->CreateAlignedLoad(endSignalPtrs[0], sizeof(size_t));
468    // iBuilder->CallPrintInt(name + ":endSignal", endSignal);
469    endSignal->setOrdering(AtomicOrdering::Acquire);
470    for (unsigned i = 1; i < endSignalPtrs.size(); i++){
471        LoadInst * endSignal_next = iBuilder->CreateAlignedLoad(endSignalPtrs[i], sizeof(size_t));
472        endSignal_next->setOrdering(AtomicOrdering::Acquire);
473        iBuilder->CreateAnd(endSignal, endSignal_next);
474    }
475       
476    iBuilder->CreateCondBr(iBuilder->CreateICmpEQ(endSignal, ConstantInt::get(iBuilder->getInt8Ty(), 1)), endBlock, inputCheckBlock);
477   
478    iBuilder->SetInsertPoint(doSegmentBlock);
479 
480    createDoSegmentCall(self, segBlocks);
481
482    for (unsigned i = 0; i < inbufConsumerPtrs.size(); i++) {
483        Value * consumerPos = iBuilder->CreateAdd(iBuilder->CreateLoad(inbufConsumerPtrs[i]), segSize);
484        iBuilder->CreateAlignedStore(consumerPos, inbufConsumerPtrs[i], sizeof(size_t))->setOrdering(AtomicOrdering::Release);
485    }
486   
487    Value * produced = getProducedItemCount(self);
488    for (unsigned i = 0; i < outbufProducerPtrs.size(); i++) {
489        iBuilder->CreateAlignedStore(produced, outbufProducerPtrs[i], sizeof(size_t))->setOrdering(AtomicOrdering::Release);
490    }
491   
492    Value * earlyEndSignal = getTerminationSignal(self);
493    if (earlyEndSignal != ConstantInt::getNullValue(iBuilder->getInt1Ty())) {
494        BasicBlock * earlyEndBlock = BasicBlock::Create(iBuilder->getContext(), "earlyEndSignal", threadFunc, 0);
495        iBuilder->CreateCondBr(earlyEndSignal, earlyEndBlock, outputCheckBlock);
496
497        iBuilder->SetInsertPoint(earlyEndBlock);
498        for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
499            Value * ssStructPtr = getStreamSetStructPtr(self, mStreamSetOutputs[i].ssName);
500            mStreamSetOutputBuffers[i]->setEndOfInput(ssStructPtr);
501        }       
502    }
503    iBuilder->CreateBr(outputCheckBlock);
504     
505    iBuilder->SetInsertPoint(endBlock);
506    LoadInst * producerPos = iBuilder->CreateLoad(inbufProducerPtrs[0]);
507    LoadInst * consumerPos = iBuilder->CreateLoad(inbufConsumerPtrs[0]);
508    Value * remainingBytes = iBuilder->CreateSub(producerPos, consumerPos);
509    Value * blockSize = ConstantInt::get(size_ty, iBuilder->getBitBlockWidth());
510    Value * blocks = iBuilder->CreateUDiv(remainingBytes, blockSize);
511    Value * finalBlockRemainingBytes = iBuilder->CreateURem(remainingBytes, blockSize);
512
513    iBuilder->CreateCondBr(iBuilder->CreateICmpEQ(blocks, ConstantInt::get(size_ty, 0)), doFinalBlock, doFinalSegBlock);
514
515    iBuilder->SetInsertPoint(doFinalSegBlock);
516
517    createDoSegmentCall(self, blocks);
518
519    iBuilder->CreateBr(doFinalBlock);
520
521    iBuilder->SetInsertPoint(doFinalBlock);
522
523    createFinalBlockCall(self, finalBlockRemainingBytes);
524
525    for (unsigned i = 0; i < inbufConsumerPtrs.size(); i++) {
526        Value * consumerPos = iBuilder->CreateAdd(iBuilder->CreateLoad(inbufConsumerPtrs[i]), remainingBytes);
527        iBuilder->CreateAlignedStore(consumerPos, inbufConsumerPtrs[i], sizeof(size_t))->setOrdering(AtomicOrdering::Release);
528    }
529    for (unsigned i = 0; i < outbufProducerPtrs.size(); i++) {
530        iBuilder->CreateAlignedStore(producerPos, outbufProducerPtrs[i], sizeof(size_t))->setOrdering(AtomicOrdering::Release);
531    }
532
533    for (unsigned i = 0; i < mStreamSetOutputs.size(); i++) {
534        Value * ssStructPtr = getStreamSetStructPtr(self, mStreamSetOutputs[i].ssName);
535        mStreamSetOutputBuffers[i]->setEndOfInput(ssStructPtr);
536    }
537
538    Value * nullVal = Constant::getNullValue(voidPtrTy);
539    Function * pthreadExitFunc = m->getFunction("pthread_exit");
540    CallInst * exitThread = iBuilder->CreateCall(pthreadExitFunc, {nullVal}); 
541    exitThread->setDoesNotReturn();
542    iBuilder->CreateRetVoid();
543
544    return threadFunc;
545
546}
Note: See TracBrowser for help on using the repository browser.