source: icGREP/icgrep-devel/icgrep/kernels/pipeline.cpp @ 5305

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

When a termination signal is detected for a kernel in one thread, ensure remaining threads exit.

File size: 14.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 "pipeline.h"
7#include <toolchain.h>
8#include <kernels/kernel.h>
9#include <kernels/streamset.h>
10#include <llvm/IR/Module.h>
11#include <unordered_map>
12
13using namespace kernel;
14using namespace parabix;
15using namespace llvm;
16
17using ProducerTable = std::vector<std::vector<std::pair<unsigned, unsigned>>>;
18
19ProducerTable createProducerTable(const std::vector<KernelBuilder *> & kernels) {
20    ProducerTable producerTable(kernels.size());
21   
22    std::vector<std::vector<bool>> userTable(kernels.size());
23   
24    // First prepare a map from streamSet output buffers to their producing kernel and output index.
25    std::unordered_map<const StreamSetBuffer *, std::pair<unsigned, unsigned>> bufferMap;
26   
27    for (unsigned k = 0; k < kernels.size(); k++) {
28        auto outputSets = kernels[k]->getStreamSetOutputBuffers();
29        for (unsigned j = 0; j < outputSets.size(); j++) {
30            userTable[k].push_back(false);
31            bufferMap.insert(std::make_pair(outputSets[j], std::make_pair(k, j)));
32        }
33    }
34    for (unsigned k = 0; k < kernels.size(); k++) {
35        auto inputSets = kernels[k]->getStreamSetInputBuffers();
36        for (unsigned i = 0; i < inputSets.size(); i++) {
37            auto f = bufferMap.find(inputSets[i]);
38            if (f == bufferMap.end()) {
39                llvm::report_fatal_error("Pipeline error: input buffer #" + std::to_string(i) + " of " + kernels[k]->getName() + ": no corresponding output buffer. ");
40            }
41            producerTable[k].push_back(f->second);
42            unsigned sourceKernel, outputIndex;
43            std::tie(sourceKernel, outputIndex) = f->second;
44            if (sourceKernel >= k) {
45                llvm::report_fatal_error("Pipeline error: input buffer #" + std::to_string(i) + " of " + kernels[k]->getName() + ": not defined before use. ");
46            }
47            //errs() << "sourceKernel: " + std::to_string(sourceKernel) + ", outputIndex: " + std::to_string(outputIndex) + ", user: " + std::to_string(k) + "\n";
48            userTable[sourceKernel][outputIndex]= true;
49           
50        }
51    }
52    /*  TODO:  define sinks for  all outputs so that the following check succeeds on
53     *  well-structured pipelines.
54    for (unsigned k = 0; k < kernels.size(); k++) {
55        auto outputSets = kernels[k]->getStreamSetOutputBuffers();
56        //errs() << "kernel: " + kernels[k]->getName() + "\n";
57        for (unsigned j = 0; j < outputSets.size(); j++) {
58            if (userTable[k][j] == false) {
59                llvm::report_fatal_error("Pipeline error: output buffer #" + std::to_string(j) + " of " + kernels[k]->getName() + ": no users. ");
60            }
61        }
62    }
63    */
64    return producerTable;
65}
66
67Function * generateSegmentParallelPipelineThreadFunction(std::string name, IDISA::IDISA_Builder * iBuilder, const std::vector<KernelBuilder *> & kernels, Type * sharedStructType, ProducerTable & producerTable, int id) {
68   
69    // ProducerPos[k][i] will hold the producedItemCount of the i^th output stream
70    // set of the k^th kernel.  These values will be loaded immediately after the
71    // doSegment and finalSegment calls for kernel k and later used as the
72    // producer position arguments for later doSegment/finalSegment calls.
73   
74    std::vector<std::vector<Value *>> ProducerPos;
75   
76   
77    const auto ip = iBuilder->saveIP();
78   
79    Module * m = iBuilder->getModule();
80    Type * const voidTy = iBuilder->getVoidTy();
81    PointerType * const voidPtrTy = iBuilder->getVoidPtrTy();
82    PointerType * const int8PtrTy = iBuilder->getInt8PtrTy();
83
84    Function * const threadFunc = cast<Function>(m->getOrInsertFunction(name, voidTy, int8PtrTy, nullptr));
85    threadFunc->setCallingConv(CallingConv::C);
86    Function::arg_iterator args = threadFunc->arg_begin();
87
88    Value * const input = &*(args++);
89    input->setName("input");
90
91
92     // Create the basic blocks for the thread function.
93    BasicBlock * entryBlock = BasicBlock::Create(iBuilder->getContext(), "entry", threadFunc, 0);
94    BasicBlock * segmentLoop = BasicBlock::Create(iBuilder->getContext(), "segmentLoop", threadFunc, 0);
95    BasicBlock * exitThreadBlock = BasicBlock::Create(iBuilder->getContext(), "exitThread", threadFunc, 0);
96   
97    std::vector<BasicBlock *> segmentWait;
98    std::vector<BasicBlock *> segmentLoopBody;
99    for (unsigned i = 0; i < kernels.size(); i++) {
100        auto kname = kernels[i]->getName();
101        segmentWait.push_back(BasicBlock::Create(iBuilder->getContext(), kname + "Wait", threadFunc, 0));
102        segmentLoopBody.push_back(BasicBlock::Create(iBuilder->getContext(), kname + "Do", threadFunc, 0));
103    }
104
105    iBuilder->SetInsertPoint(entryBlock);
106   
107    Value * sharedStruct = iBuilder->CreateBitCast(input, PointerType::get(sharedStructType, 0));
108    std::vector<Value *> instancePtrs;
109    for (unsigned k = 0; k < kernels.size(); k++) {
110        Value * ptr = iBuilder->CreateGEP(sharedStruct, {iBuilder->getInt32(0), iBuilder->getInt32(k)});
111        instancePtrs.push_back(iBuilder->CreateLoad(ptr));
112    }
113   
114    iBuilder->CreateBr(segmentLoop);
115
116    iBuilder->SetInsertPoint(segmentLoop);
117    PHINode * segNo = iBuilder->CreatePHI(iBuilder->getSizeTy(), 2, "segNo");
118    segNo->addIncoming(iBuilder->getSize(id), entryBlock);
119    const unsigned last_kernel = kernels.size() - 1;
120    Value * doFinal = ConstantInt::getNullValue(iBuilder->getInt1Ty());
121    Value * nextSegNo = iBuilder->CreateAdd(segNo, iBuilder->getSize(1));
122    iBuilder->CreateBr(segmentWait[0]);
123    for (unsigned k = 0; k < kernels.size(); k++) {
124        iBuilder->SetInsertPoint(segmentWait[k]);
125        unsigned waitForKernel = k;
126        if (codegen::DebugOptionIsSet(codegen::SerializeThreads)) {
127            waitForKernel = last_kernel;
128        }
129        Value * processedSegmentCount = kernels[waitForKernel]->acquireLogicalSegmentNo(instancePtrs[waitForKernel]);
130        Value * ready = iBuilder->CreateICmpEQ(segNo, processedSegmentCount);
131
132        if (kernels[k]->hasNoTerminateAttribute()) {
133            iBuilder->CreateCondBr(ready, segmentLoopBody[k], segmentWait[k]);
134        } else { // If the kernel was terminated in a previous segment then the pipeline is done.
135            BasicBlock * completionTest = BasicBlock::Create(iBuilder->getContext(), kernels[k]->getName() + "Completed", threadFunc, 0);
136            BasicBlock * exitBlock = BasicBlock::Create(iBuilder->getContext(), kernels[k]->getName() + "Exit", threadFunc, 0);
137            iBuilder->CreateCondBr(ready, completionTest, segmentWait[k]);
138            iBuilder->SetInsertPoint(completionTest);
139            Value * alreadyDone = kernels[k]->getTerminationSignal(instancePtrs[k]);
140            iBuilder->CreateCondBr(alreadyDone, exitBlock, segmentLoopBody[k]);
141            iBuilder->SetInsertPoint(exitBlock);
142            // Ensure that the next thread will also exit.
143            kernels[k]->releaseLogicalSegmentNo(instancePtrs[k], nextSegNo);
144            iBuilder->CreateBr(exitThreadBlock);
145        }
146        iBuilder->SetInsertPoint(segmentLoopBody[k]);
147        std::vector<Value *> doSegmentArgs = {instancePtrs[k], doFinal};
148        for (unsigned j = 0; j < kernels[k]->getStreamInputs().size(); j++) {
149            unsigned producerKernel, outputIndex;
150            std::tie(producerKernel, outputIndex) = producerTable[k][j];
151            doSegmentArgs.push_back(ProducerPos[producerKernel][outputIndex]);
152        }
153        kernels[k]->createDoSegmentCall(doSegmentArgs);
154        std::vector<Value *> produced;
155        for (unsigned i = 0; i < kernels[k]->getStreamOutputs().size(); i++) {
156            produced.push_back(kernels[k]->getProducedItemCount(instancePtrs[k], kernels[k]->getStreamOutputs()[i].name));
157        }
158        ProducerPos.push_back(produced);
159        if (! (kernels[k]->hasNoTerminateAttribute())) {
160            Value * terminated = kernels[k]->getTerminationSignal(instancePtrs[k]);
161            doFinal = iBuilder->CreateOr(doFinal, terminated);
162        }
163
164        kernels[k]->releaseLogicalSegmentNo(instancePtrs[k], nextSegNo);
165        if (k == last_kernel) {
166            segNo->addIncoming(iBuilder->CreateAdd(segNo, iBuilder->getSize(codegen::ThreadNum)), segmentLoopBody[last_kernel]);
167            iBuilder->CreateCondBr(doFinal, exitThreadBlock, segmentLoop);
168        } else {
169            iBuilder->CreateBr(segmentWait[k+1]);
170        }
171    }
172
173    iBuilder->SetInsertPoint(exitThreadBlock);
174    Value * nullVal = Constant::getNullValue(voidPtrTy);
175    iBuilder->CreatePThreadExitCall(nullVal);
176    iBuilder->CreateRetVoid();
177    iBuilder->restoreIP(ip);
178
179    return threadFunc;
180}
181
182// Given a computation expressed as a logical pipeline of K kernels k0, k_1, ...k_(K-1)
183// operating over an input stream set S, a segment-parallel implementation divides the input
184// into segments and coordinates a set of T <= K threads to each process one segment at a time.   
185// Let S_0, S_1, ... S_N be the segments of S.   Segments are assigned to threads in a round-robin
186// fashion such that processing of segment S_i by the full pipeline is carried out by thread i mod T.
187
188
189void generateSegmentParallelPipeline(IDISA::IDISA_Builder * iBuilder, const std::vector<KernelBuilder *> & kernels) {
190   
191    const unsigned threadNum = codegen::ThreadNum;
192   
193    Module * m = iBuilder->getModule();
194   
195    IntegerType * const size_ty = iBuilder->getSizeTy();
196    PointerType * const voidPtrTy = iBuilder->getVoidPtrTy();
197    PointerType * const int8PtrTy = iBuilder->getInt8PtrTy();
198   
199    for (auto k : kernels) k->createInstance();
200   
201    ProducerTable producerTable = createProducerTable(kernels);
202   
203    Type * const pthreadsTy = ArrayType::get(size_ty, threadNum);
204    AllocaInst * const pthreads = iBuilder->CreateAlloca(pthreadsTy);
205    std::vector<Value *> pthreadsPtrs;
206    for (unsigned i = 0; i < threadNum; i++) {
207        pthreadsPtrs.push_back(iBuilder->CreateGEP(pthreads, {iBuilder->getInt32(0), iBuilder->getInt32(i)}));
208    }
209    Value * nullVal = Constant::getNullValue(voidPtrTy);
210    AllocaInst * const status = iBuilder->CreateAlloca(int8PtrTy);
211   
212    std::vector<Type *> structTypes;
213    for (unsigned i = 0; i < kernels.size(); i++) {
214        structTypes.push_back(kernels[i]->getInstance()->getType());
215    }
216    Type * sharedStructType = StructType::get(m->getContext(), structTypes);
217   
218    AllocaInst * sharedStruct = iBuilder->CreateAlloca(sharedStructType);
219    for (unsigned i = 0; i < kernels.size(); i++) {
220        Value * ptr = iBuilder->CreateGEP(sharedStruct, {iBuilder->getInt32(0), iBuilder->getInt32(i)});
221        iBuilder->CreateStore(kernels[i]->getInstance(), ptr);
222    }
223    for (unsigned i = 0; i < kernels.size(); i++) {
224        kernels[i]->releaseLogicalSegmentNo(kernels[i]->getInstance(), iBuilder->getSize(0));
225    }
226
227    std::vector<Function *> thread_functions;
228    const auto ip = iBuilder->saveIP();
229    for (unsigned i = 0; i < threadNum; i++) {
230        thread_functions.push_back(generateSegmentParallelPipelineThreadFunction("thread"+std::to_string(i), iBuilder, kernels, sharedStructType, producerTable, i));
231    }
232    iBuilder->restoreIP(ip);
233   
234    for (unsigned i = 0; i < threadNum; i++) {
235        iBuilder->CreatePThreadCreateCall(pthreadsPtrs[i], nullVal, thread_functions[i], iBuilder->CreateBitCast(sharedStruct, int8PtrTy));
236    }
237   
238    std::vector<Value *> threadIDs;
239    for (unsigned i = 0; i < threadNum; i++) { 
240        threadIDs.push_back(iBuilder->CreateLoad(pthreadsPtrs[i]));
241    }
242   
243    for (unsigned i = 0; i < threadNum; i++) { 
244        iBuilder->CreatePThreadJoinCall(threadIDs[i], status);
245    }
246   
247}
248
249void generatePipelineParallel(IDISA::IDISA_Builder * iBuilder, const std::vector<KernelBuilder *> & kernels) {
250    llvm::report_fatal_error("Pipeline parallelism no longer supported!");
251}
252
253
254void generatePipelineLoop(IDISA::IDISA_Builder * iBuilder, const std::vector<KernelBuilder *> & kernels) {
255    for (auto k : kernels) k->createInstance();
256   
257    BasicBlock * entryBlock = iBuilder->GetInsertBlock();
258    Function * main = entryBlock->getParent();
259
260    // Create the basic blocks for the loop.
261    BasicBlock * segmentLoop = BasicBlock::Create(iBuilder->getContext(), "segmentLoop", main, 0);
262    BasicBlock * exitBlock = BasicBlock::Create(iBuilder->getContext(), "exitBlock", main, 0);
263   
264    ProducerTable producerTable = createProducerTable(kernels);
265   
266    // ProducerPos[k][i] will hold the producedItemCount of the i^th output stream
267    // set of the k^th kernel.  These values will be loaded immediately after the
268    // doSegment and finalSegment calls for kernel k and later used as the
269    // producer position arguments for later doSegment/finalSegment calls.
270   
271    std::vector<std::vector<Value *>> ProducerPos;
272   
273    iBuilder->CreateBr(segmentLoop);
274    iBuilder->SetInsertPoint(segmentLoop);
275
276    Value * terminationFound = ConstantInt::getNullValue(iBuilder->getInt1Ty());
277    for (unsigned k = 0; k < kernels.size(); k++) {
278        Value * instance = kernels[k]->getInstance();
279        std::vector<Value *> doSegmentArgs = {instance, terminationFound};
280        for (unsigned j = 0; j < kernels[k]->getStreamInputs().size(); j++) {
281            unsigned producerKernel, outputIndex;
282            std::tie(producerKernel, outputIndex) = producerTable[k][j];
283            doSegmentArgs.push_back(ProducerPos[producerKernel][outputIndex]);
284        }
285        kernels[k]->createDoSegmentCall(doSegmentArgs);
286        if (! (kernels[k]->hasNoTerminateAttribute())) {
287            Value * terminated = kernels[k]->getTerminationSignal(instance);
288            terminationFound = iBuilder->CreateOr(terminationFound, terminated);
289        }
290        std::vector<Value *> produced;
291        for (unsigned i = 0; i < kernels[k]->getStreamOutputs().size(); i++) {
292            produced.push_back(kernels[k]->getProducedItemCount(instance, kernels[k]->getStreamOutputs()[i].name));
293        }
294        ProducerPos.push_back(produced);
295        Value * segNo = kernels[k]->acquireLogicalSegmentNo(instance);
296        kernels[k]->releaseLogicalSegmentNo(instance, iBuilder->CreateAdd(segNo, iBuilder->getSize(1)));
297    }
298    iBuilder->CreateCondBr(terminationFound, exitBlock, segmentLoop);
299    iBuilder->SetInsertPoint(exitBlock);
300}
301
302   
Note: See TracBrowser for help on using the repository browser.