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

Last change on this file since 5273 was 5273, checked in by cameron, 19 months ago

For segment-pipeline-parallelism, threads must not overwrite buffer segments belonging to other threads

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