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

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

Debug Options: SerializeThreads?; unify ShowIR, ShowPablo?, ShowREs, ShowASM

File size: 13.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 "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 * cond = iBuilder->CreateICmpEQ(segNo, processedSegmentCount);
131
132        if (kernels[k]->hasNoTerminateAttribute()) {
133            iBuilder->CreateCondBr(cond, 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            iBuilder->CreateCondBr(cond, completionTest, segmentWait[k]);
137            iBuilder->SetInsertPoint(completionTest);
138            Value * alreadyDone = kernels[k]->getTerminationSignal(instancePtrs[k]);
139            iBuilder->CreateCondBr(alreadyDone, exitThreadBlock, segmentLoopBody[k]);
140        }
141        iBuilder->SetInsertPoint(segmentLoopBody[k]);
142        std::vector<Value *> doSegmentArgs = {instancePtrs[k], doFinal};
143        for (unsigned j = 0; j < kernels[k]->getStreamInputs().size(); j++) {
144            unsigned producerKernel, outputIndex;
145            std::tie(producerKernel, outputIndex) = producerTable[k][j];
146            doSegmentArgs.push_back(ProducerPos[producerKernel][outputIndex]);
147        }
148        kernels[k]->createDoSegmentCall(doSegmentArgs);
149        std::vector<Value *> produced;
150        for (unsigned i = 0; i < kernels[k]->getStreamOutputs().size(); i++) {
151            produced.push_back(kernels[k]->getProducedItemCount(instancePtrs[k], kernels[k]->getStreamOutputs()[i].name));
152        }
153        ProducerPos.push_back(produced);
154        if (! (kernels[k]->hasNoTerminateAttribute())) {
155            Value * terminated = kernels[k]->getTerminationSignal(instancePtrs[k]);
156            doFinal = iBuilder->CreateOr(doFinal, terminated);
157        }
158
159        kernels[k]->releaseLogicalSegmentNo(instancePtrs[k], nextSegNo);
160        if (k == last_kernel) {
161            segNo->addIncoming(iBuilder->CreateAdd(segNo, iBuilder->getSize(codegen::ThreadNum)), segmentLoopBody[last_kernel]);
162            iBuilder->CreateCondBr(doFinal, exitThreadBlock, segmentLoop);
163        } else {
164            iBuilder->CreateBr(segmentWait[k+1]);
165        }
166    }
167
168    iBuilder->SetInsertPoint(exitThreadBlock);
169    Value * nullVal = Constant::getNullValue(voidPtrTy);
170    iBuilder->CreatePThreadExitCall(nullVal);
171    iBuilder->CreateRetVoid();
172    iBuilder->restoreIP(ip);
173
174    return threadFunc;
175}
176
177// Given a computation expressed as a logical pipeline of K kernels k0, k_1, ...k_(K-1)
178// operating over an input stream set S, a segment-parallel implementation divides the input
179// into segments and coordinates a set of T <= K threads to each process one segment at a time.   
180// Let S_0, S_1, ... S_N be the segments of S.   Segments are assigned to threads in a round-robin
181// fashion such that processing of segment S_i by the full pipeline is carried out by thread i mod T.
182
183
184void generateSegmentParallelPipeline(IDISA::IDISA_Builder * iBuilder, const std::vector<KernelBuilder *> & kernels) {
185   
186    const unsigned threadNum = codegen::ThreadNum;
187   
188    Module * m = iBuilder->getModule();
189   
190    IntegerType * const size_ty = iBuilder->getSizeTy();
191    PointerType * const voidPtrTy = iBuilder->getVoidPtrTy();
192    PointerType * const int8PtrTy = iBuilder->getInt8PtrTy();
193   
194    for (auto k : kernels) k->createInstance();
195   
196    ProducerTable producerTable = createProducerTable(kernels);
197   
198    Type * const pthreadsTy = ArrayType::get(size_ty, threadNum);
199    AllocaInst * const pthreads = iBuilder->CreateAlloca(pthreadsTy);
200    std::vector<Value *> pthreadsPtrs;
201    for (unsigned i = 0; i < threadNum; i++) {
202        pthreadsPtrs.push_back(iBuilder->CreateGEP(pthreads, {iBuilder->getInt32(0), iBuilder->getInt32(i)}));
203    }
204    Value * nullVal = Constant::getNullValue(voidPtrTy);
205    AllocaInst * const status = iBuilder->CreateAlloca(int8PtrTy);
206   
207    std::vector<Type *> structTypes;
208    for (unsigned i = 0; i < kernels.size(); i++) {
209        structTypes.push_back(kernels[i]->getInstance()->getType());
210    }
211    Type * sharedStructType = StructType::get(m->getContext(), structTypes);
212   
213    AllocaInst * sharedStruct = iBuilder->CreateAlloca(sharedStructType);
214    for (unsigned i = 0; i < kernels.size(); i++) {
215        Value * ptr = iBuilder->CreateGEP(sharedStruct, {iBuilder->getInt32(0), iBuilder->getInt32(i)});
216        iBuilder->CreateStore(kernels[i]->getInstance(), ptr);
217    }
218    for (unsigned i = 0; i < kernels.size(); i++) {
219        kernels[i]->releaseLogicalSegmentNo(kernels[i]->getInstance(), iBuilder->getSize(0));
220    }
221
222    std::vector<Function *> thread_functions;
223    const auto ip = iBuilder->saveIP();
224    for (unsigned i = 0; i < threadNum; i++) {
225        thread_functions.push_back(generateSegmentParallelPipelineThreadFunction("thread"+std::to_string(i), iBuilder, kernels, sharedStructType, producerTable, i));
226    }
227    iBuilder->restoreIP(ip);
228   
229    for (unsigned i = 0; i < threadNum; i++) {
230        iBuilder->CreatePThreadCreateCall(pthreadsPtrs[i], nullVal, thread_functions[i], iBuilder->CreateBitCast(sharedStruct, int8PtrTy));
231    }
232   
233    std::vector<Value *> threadIDs;
234    for (unsigned i = 0; i < threadNum; i++) { 
235        threadIDs.push_back(iBuilder->CreateLoad(pthreadsPtrs[i]));
236    }
237   
238    for (unsigned i = 0; i < threadNum; i++) { 
239        iBuilder->CreatePThreadJoinCall(threadIDs[i], status);
240    }
241   
242}
243
244void generatePipelineParallel(IDISA::IDISA_Builder * iBuilder, const std::vector<KernelBuilder *> & kernels) {
245    llvm::report_fatal_error("Pipeline parallelism no longer supported!");
246}
247
248
249void generatePipelineLoop(IDISA::IDISA_Builder * iBuilder, const std::vector<KernelBuilder *> & kernels) {
250    for (auto k : kernels) k->createInstance();
251   
252    BasicBlock * entryBlock = iBuilder->GetInsertBlock();
253    Function * main = entryBlock->getParent();
254
255    // Create the basic blocks for the loop.
256    BasicBlock * segmentLoop = BasicBlock::Create(iBuilder->getContext(), "segmentLoop", main, 0);
257    BasicBlock * exitBlock = BasicBlock::Create(iBuilder->getContext(), "exitBlock", main, 0);
258   
259    ProducerTable producerTable = createProducerTable(kernels);
260   
261    // ProducerPos[k][i] will hold the producedItemCount of the i^th output stream
262    // set of the k^th kernel.  These values will be loaded immediately after the
263    // doSegment and finalSegment calls for kernel k and later used as the
264    // producer position arguments for later doSegment/finalSegment calls.
265   
266    std::vector<std::vector<Value *>> ProducerPos;
267   
268    iBuilder->CreateBr(segmentLoop);
269    iBuilder->SetInsertPoint(segmentLoop);
270
271    Value * terminationFound = ConstantInt::getNullValue(iBuilder->getInt1Ty());
272    for (unsigned k = 0; k < kernels.size(); k++) {
273        Value * instance = kernels[k]->getInstance();
274        std::vector<Value *> doSegmentArgs = {instance, terminationFound};
275        for (unsigned j = 0; j < kernels[k]->getStreamInputs().size(); j++) {
276            unsigned producerKernel, outputIndex;
277            std::tie(producerKernel, outputIndex) = producerTable[k][j];
278            doSegmentArgs.push_back(ProducerPos[producerKernel][outputIndex]);
279        }
280        kernels[k]->createDoSegmentCall(doSegmentArgs);
281        if (! (kernels[k]->hasNoTerminateAttribute())) {
282            Value * terminated = kernels[k]->getTerminationSignal(instance);
283            terminationFound = iBuilder->CreateOr(terminationFound, terminated);
284        }
285        std::vector<Value *> produced;
286        for (unsigned i = 0; i < kernels[k]->getStreamOutputs().size(); i++) {
287            produced.push_back(kernels[k]->getProducedItemCount(instance, kernels[k]->getStreamOutputs()[i].name));
288        }
289        ProducerPos.push_back(produced);
290        Value * segNo = kernels[k]->acquireLogicalSegmentNo(instance);
291        kernels[k]->releaseLogicalSegmentNo(instance, iBuilder->CreateAdd(segNo, iBuilder->getSize(1)));
292    }
293    iBuilder->CreateCondBr(terminationFound, exitBlock, segmentLoop);
294    iBuilder->SetInsertPoint(exitBlock);
295}
296
297   
Note: See TracBrowser for help on using the repository browser.