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

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

Fix for segment-pipeline-parallel

File size: 15.3 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 <IR_Gen/idisa_builder.h>
9#include <kernels/interface.h>
10#include <kernels/kernel.h>
11#include <kernels/s2p_kernel.h>
12#include <iostream>
13#include <unordered_map>
14
15using namespace kernel;
16
17using BufferMap = std::unordered_map<StreamSetBuffer *, std::pair<KernelBuilder *, unsigned>>;
18
19
20static void createStreamBufferMap(BufferMap & bufferMap, std::vector<KernelBuilder *> kernels) {
21    for (auto k: kernels) {
22        auto outputSets = k->getStreamSetOutputBuffers();
23        for (unsigned i = 0; i < outputSets.size(); i++) {
24            bufferMap.insert(std::make_pair(outputSets[i], std::make_pair(k, i)));
25        }
26    }
27    for (auto k: kernels) {
28        auto inputSets = k->getStreamSetInputBuffers();
29        for (unsigned i = 0; i < inputSets.size(); i++) {
30            if (bufferMap.find(inputSets[i]) == bufferMap.end()) {
31                llvm::report_fatal_error("Pipeline error: input buffer #" + std::to_string(i) + " of " + k->getName() + ": no corresponding output buffer. ");
32            }
33        }
34    }
35}
36
37static Value * getSegmentBlocks(BufferMap & bufferMap, KernelBuilder * kernel) {
38    IDISA::IDISA_Builder * iBuilder = kernel->getBuilder();
39    std::cerr << "getSegmentBlocks\n"; 
40
41    KernelBuilder * sourceKernel;
42
43    unsigned outputIndex;
44    auto inputs = kernel->getStreamSetInputBuffers();
45    if (inputs.empty()) return iBuilder->getSize(codegen::SegmentSize * iBuilder->getStride() / iBuilder->getBitBlockWidth());
46    std::string inputSetName = kernel->getStreamInputs()[0].name;
47    std::cerr << "inputSetName = " << inputSetName << "\n"; 
48    auto f = bufferMap.find(inputs[0]);
49    assert(f != bufferMap.end()  && "bufferMap failure");
50    std::tie(sourceKernel, outputIndex) = f->second;
51    std::cerr << "outputIndex = " << outputIndex << "\n"; 
52    Value * produced = sourceKernel->getProducedItemCount(sourceKernel->getInstance(), sourceKernel->getStreamOutputs()[outputIndex].name);
53    iBuilder->CallPrintInt("produced", produced);
54    Value * processed = kernel->getProcessedItemCount(kernel->getInstance(), inputSetName);
55    iBuilder->CallPrintInt("processed", processed);
56    Value * itemsToDo = iBuilder->CreateSub(produced, processed);
57    return iBuilder->CreateUDiv(itemsToDo, iBuilder->getSize(iBuilder->getStride()));
58}
59                                   
60
61
62Function * generateSegmentParallelPipelineThreadFunction(std::string name, IDISA::IDISA_Builder * iBuilder, std::vector<KernelBuilder *> kernels, Type * sharedStructType, int id) {
63
64    Module * m = iBuilder->getModule();
65    Type * const size_ty = iBuilder->getSizeTy();
66    Type * const voidTy = iBuilder->getVoidTy();
67    Type * const voidPtrTy = iBuilder->getVoidPtrTy();
68    Type * const int8PtrTy = iBuilder->getInt8PtrTy();
69
70    Function * const threadFunc = cast<Function>(m->getOrInsertFunction(name, voidTy, int8PtrTy, nullptr));
71    threadFunc->setCallingConv(CallingConv::C);
72    Function::arg_iterator args = threadFunc->arg_begin();
73
74    Value * const input = &*(args++);
75    input->setName("input");
76
77    unsigned threadNum = codegen::ThreadNum;
78
79     // Create the basic blocks for the thread function.
80    BasicBlock * entryBlock = BasicBlock::Create(iBuilder->getContext(), "entry", threadFunc, 0);
81    BasicBlock * segmentLoop = BasicBlock::Create(iBuilder->getContext(), "segmentLoop", threadFunc, 0);
82    BasicBlock * exitThreadBlock = BasicBlock::Create(iBuilder->getContext(), "exitThread", threadFunc, 0);
83   
84    std::vector<BasicBlock *> segmentWait;
85    std::vector<BasicBlock *> segmentLoopBody;
86    std::vector<BasicBlock *> partialSegmentWait;
87    std::vector<BasicBlock *> partialSegmentLoopBody;
88    bool terminationSignalEncountered = false;
89    for (unsigned i = 0; i < kernels.size(); i++) {
90        std::string kname = kernels[i]->getName();
91        segmentWait.push_back(BasicBlock::Create(iBuilder->getContext(), kname + "Wait", threadFunc, 0));
92        segmentLoopBody.push_back(BasicBlock::Create(iBuilder->getContext(), "do_" + kname, threadFunc, 0));
93        if (terminationSignalEncountered) {
94            partialSegmentWait.push_back(BasicBlock::Create(iBuilder->getContext(), kname + "WaitFinal", threadFunc, 0));
95            partialSegmentLoopBody.push_back(BasicBlock::Create(iBuilder->getContext(), "finish_" + kname, threadFunc, 0));
96        }
97        else {
98            partialSegmentWait.push_back(nullptr);
99            partialSegmentLoopBody.push_back(nullptr);
100            terminationSignalEncountered = kernels[i]->hasNoTerminateAttribute() == false;
101        }
102    }
103    segmentWait.push_back(segmentLoop); // If the last kernel does not terminate, loop back.
104    partialSegmentWait.push_back(exitThreadBlock); // After the last kernel terminates, we're done.
105
106    iBuilder->SetInsertPoint(entryBlock);
107    Value * sharedStruct = iBuilder->CreateBitCast(input, PointerType::get(sharedStructType, 0));
108    Constant * myThreadId = ConstantInt::get(size_ty, id);
109    std::vector<Value *> instancePtrs;
110    for (unsigned i = 0; i < kernels.size(); i++) {
111        Value * ptr = iBuilder->CreateGEP(sharedStruct, {iBuilder->getInt32(0), iBuilder->getInt32(i)});
112        instancePtrs.push_back(iBuilder->CreateLoad(ptr));
113    }
114   
115    // Some important constant values.
116    int segmentSize = codegen::SegmentSize;
117    Constant * segmentBlocks = ConstantInt::get(size_ty, segmentSize);
118    iBuilder->CreateBr(segmentLoop);
119
120    iBuilder->SetInsertPoint(segmentLoop);
121    PHINode * segNo = iBuilder->CreatePHI(size_ty, 2, "segNo");
122    segNo->addIncoming(myThreadId, entryBlock);
123    Value * nextSegNo = iBuilder->CreateAdd(segNo, iBuilder->getSize(1));
124    unsigned last_kernel = kernels.size() - 1;
125    Value * alreadyDone = kernels[last_kernel]->getTerminationSignal(instancePtrs[last_kernel]);
126    iBuilder->CreateCondBr(alreadyDone, exitThreadBlock, segmentWait[0]);
127
128   
129   
130    for (unsigned i = 0; i < kernels.size(); i++) {
131        iBuilder->SetInsertPoint(segmentWait[i]);
132        Value * processedSegmentCount = kernels[i]->acquireLogicalSegmentNo(instancePtrs[i]);
133        Value * cond = iBuilder->CreateICmpEQ(segNo, processedSegmentCount);
134        iBuilder->CreateCondBr(cond, segmentLoopBody[i], segmentWait[i]);
135
136        iBuilder->SetInsertPoint(segmentLoopBody[i]);
137        if (i == last_kernel) {
138            segNo->addIncoming(iBuilder->CreateAdd(segNo, ConstantInt::get(size_ty, threadNum)), segmentLoopBody[last_kernel]);
139        }
140        kernels[i]->createDoSegmentCall(instancePtrs[i], segmentBlocks);
141        if (kernels[i]->hasNoTerminateAttribute()) {
142            kernels[i]->releaseLogicalSegmentNo(instancePtrs[i], nextSegNo);
143            iBuilder->CreateBr(segmentWait[i+1]);
144        }
145        else {
146            Value * terminated = kernels[i]->getTerminationSignal(instancePtrs[i]);
147            kernels[i]->releaseLogicalSegmentNo(instancePtrs[i], nextSegNo);
148            iBuilder->CreateCondBr(terminated, partialSegmentWait[i+1], segmentWait[i+1]);
149        }
150        if (partialSegmentWait[i] != nullptr) {
151            iBuilder->SetInsertPoint(partialSegmentWait[i]);
152            Value * processedSegmentCount = kernels[i]->acquireLogicalSegmentNo(instancePtrs[i]);
153            Value * cond = iBuilder->CreateICmpEQ(segNo, processedSegmentCount);
154            iBuilder->CreateCondBr(cond, partialSegmentLoopBody[i], partialSegmentWait[i]);
155           
156            iBuilder->SetInsertPoint(partialSegmentLoopBody[i]);
157            kernels[i]->createFinalSegmentCall(instancePtrs[i], segmentBlocks);
158            kernels[i]->releaseLogicalSegmentNo(instancePtrs[i], nextSegNo);
159            iBuilder->CreateBr(partialSegmentWait[i+1]);
160        }
161    }
162   
163    iBuilder->SetInsertPoint(exitThreadBlock);
164    Value * nullVal = Constant::getNullValue(voidPtrTy);
165    iBuilder->CreatePThreadExitCall(nullVal);
166    iBuilder->CreateRetVoid();
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, std::vector<KernelBuilder *> kernels) {
179   
180    unsigned threadNum = codegen::ThreadNum;
181
182    Module * m = iBuilder->getModule();
183
184    Type * const size_ty = iBuilder->getSizeTy();
185    Type * const voidPtrTy = iBuilder->getVoidPtrTy();
186    Type * const int8PtrTy = iBuilder->getInt8PtrTy();
187
188    for (auto k : kernels) k->createInstance();
189
190    Type * const pthreadsTy = ArrayType::get(size_ty, threadNum);
191    AllocaInst * const pthreads = iBuilder->CreateAlloca(pthreadsTy);
192    std::vector<Value *> pthreadsPtrs;
193    for (unsigned i = 0; i < threadNum; i++) {
194        pthreadsPtrs.push_back(iBuilder->CreateGEP(pthreads, {iBuilder->getInt32(0), iBuilder->getInt32(i)}));
195    }
196    Value * nullVal = Constant::getNullValue(voidPtrTy);
197    AllocaInst * const status = iBuilder->CreateAlloca(int8PtrTy);
198
199    std::vector<Type *> structTypes;
200    for (unsigned i = 0; i < kernels.size(); i++) {
201        structTypes.push_back(kernels[i]->getInstance()->getType());
202    }
203    Type * sharedStructType = StructType::get(m->getContext(), structTypes);
204
205    AllocaInst * sharedStruct = iBuilder->CreateAlloca(sharedStructType);
206    for (unsigned i = 0; i < kernels.size(); i++) {
207        Value * ptr = iBuilder->CreateGEP(sharedStruct, {iBuilder->getInt32(0), iBuilder->getInt32(i)});
208        iBuilder->CreateStore(kernels[i]->getInstance(), ptr);
209    }
210
211    std::vector<Function *> thread_functions;
212    const auto ip = iBuilder->saveIP();
213    for (unsigned i = 0; i < threadNum; i++) {
214        thread_functions.push_back(generateSegmentParallelPipelineThreadFunction("thread"+std::to_string(i), iBuilder, kernels, sharedStructType, i));
215    }
216    iBuilder->restoreIP(ip);
217
218    for (unsigned i = 0; i < threadNum; i++) {
219        iBuilder->CreatePThreadCreateCall(pthreadsPtrs[i], nullVal, thread_functions[i], iBuilder->CreateBitCast(sharedStruct, int8PtrTy));
220    }
221
222    std::vector<Value *> threadIDs;
223    for (unsigned i = 0; i < threadNum; i++) { 
224        threadIDs.push_back(iBuilder->CreateLoad(pthreadsPtrs[i]));
225    }
226   
227    for (unsigned i = 0; i < threadNum; i++) { 
228        iBuilder->CreatePThreadJoinCall(threadIDs[i], status);
229    }
230
231}
232
233void generatePipelineParallel(IDISA::IDISA_Builder * iBuilder, std::vector<KernelBuilder *> kernels) {
234 
235    Type * pthreadTy = iBuilder->getSizeTy();
236    Type * const voidPtrTy = iBuilder->getVoidPtrTy();
237    Type * const int8PtrTy = iBuilder->getInt8PtrTy();
238
239    Type * const pthreadsTy = ArrayType::get(pthreadTy, kernels.size());
240
241    for (auto k : kernels) k->createInstance();
242
243    AllocaInst * const pthreads = iBuilder->CreateAlloca(pthreadsTy);
244    std::vector<Value *> pthreadsPtrs;
245    for (unsigned i = 0; i < kernels.size(); i++) {
246        pthreadsPtrs.push_back(iBuilder->CreateGEP(pthreads, {iBuilder->getInt32(0), iBuilder->getInt32(i)}));
247    }
248    Value * nullVal = Constant::getNullValue(voidPtrTy);
249    AllocaInst * const status = iBuilder->CreateAlloca(int8PtrTy);
250
251    std::vector<Function *> kernel_functions;
252    const auto ip = iBuilder->saveIP();
253    for (unsigned i = 0; i < kernels.size(); i++) {
254        kernel_functions.push_back(kernels[i]->generateThreadFunction("k_"+std::to_string(i)));
255    }
256    iBuilder->restoreIP(ip);
257
258    for (unsigned i = 0; i < kernels.size(); i++) {
259        iBuilder->CreatePThreadCreateCall(pthreadsPtrs[i], nullVal, kernel_functions[i], iBuilder->CreateBitCast(kernels[i]->getInstance(), int8PtrTy));
260    }
261
262    std::vector<Value *> threadIDs;
263    for (unsigned i = 0; i < kernels.size(); i++) { 
264        threadIDs.push_back(iBuilder->CreateLoad(pthreadsPtrs[i]));
265    }
266   
267    for (unsigned i = 0; i < kernels.size(); i++) { 
268        iBuilder->CreatePThreadJoinCall(threadIDs[i], status);
269    }
270}
271
272
273void generatePipelineLoop(IDISA::IDISA_Builder * iBuilder, std::vector<KernelBuilder *> kernels) {
274    for (auto k : kernels) k->createInstance();
275    //BufferMap bufferMap;
276    //createStreamBufferMap(bufferMap, kernels);
277   
278    BasicBlock * entryBlock = iBuilder->GetInsertBlock();
279    Function * main = entryBlock->getParent();
280
281    // Create the basic blocks. 
282    BasicBlock * segmentLoop = BasicBlock::Create(iBuilder->getContext(), "segmentLoop", main, 0);
283    BasicBlock * exitBlock = BasicBlock::Create(iBuilder->getContext(), "exitBlock", main, 0);
284    // We create vectors of loop body and final segment blocks indexed by kernel.
285    std::vector<BasicBlock *> loopBodyBlocks;
286    std::vector<BasicBlock *> finalSegmentBlocks;
287
288    loopBodyBlocks.push_back(segmentLoop); 
289    finalSegmentBlocks.push_back(nullptr); 
290   
291    for (unsigned i = 1; i < kernels.size(); i++) {
292        if (kernels[i-1]->hasNoTerminateAttribute()) {
293            // Previous kernel cannot terminate.   Continue with the previous blocks;
294            loopBodyBlocks.push_back(loopBodyBlocks.back());
295            finalSegmentBlocks.push_back(finalSegmentBlocks.back());
296        }
297        else {
298            loopBodyBlocks.push_back(BasicBlock::Create(iBuilder->getContext(), "do_" + kernels[i]->getName(), main, 0));
299            finalSegmentBlocks.push_back(BasicBlock::Create(iBuilder->getContext(), "finish_" + kernels[i]->getName(), main, 0));
300        }
301    }
302    loopBodyBlocks.push_back(segmentLoop); // If the last kernel does not terminate, loop back.
303    finalSegmentBlocks.push_back(exitBlock); // If the last kernel does terminate, we're done.
304   
305    iBuilder->CreateBr(segmentLoop);
306    Constant * segBlocks = iBuilder->getSize(codegen::SegmentSize * iBuilder->getStride() / iBuilder->getBitBlockWidth());
307    for (unsigned i = 0; i < kernels.size(); i++) {
308        iBuilder->SetInsertPoint(loopBodyBlocks[i]);
309        //Value * segBlocks = getSegmentBlocks(bufferMap, kernels[i]);
310        Value * segNo = kernels[i]->acquireLogicalSegmentNo(kernels[i]->getInstance());
311        kernels[i]->createDoSegmentCall(kernels[i]->getInstance(), segBlocks);
312        if (kernels[i]->hasNoTerminateAttribute()) {
313            kernels[i]->releaseLogicalSegmentNo(kernels[i]->getInstance(), iBuilder->CreateAdd(segNo, iBuilder->getSize(1)));
314            if (i == kernels.size() - 1) {
315                iBuilder->CreateBr(segmentLoop);
316            }
317        }
318        else {
319            Value * terminated = kernels[i]->getTerminationSignal(kernels[i]->getInstance());
320            kernels[i]->releaseLogicalSegmentNo(kernels[i]->getInstance(), iBuilder->CreateAdd(segNo, iBuilder->getSize(1)));
321            iBuilder->CreateCondBr(terminated, finalSegmentBlocks[i+1], loopBodyBlocks[i+1]);
322        }
323        if (finalSegmentBlocks[i] != nullptr) {
324            iBuilder->SetInsertPoint(finalSegmentBlocks[i]);
325            Value * segNo = kernels[i]->acquireLogicalSegmentNo(kernels[i]->getInstance());
326            kernels[i]->createFinalSegmentCall(kernels[i]->getInstance(), segBlocks);
327            kernels[i]->releaseLogicalSegmentNo(kernels[i]->getInstance(), iBuilder->CreateAdd(segNo, iBuilder->getSize(1)));
328            if (finalSegmentBlocks[i] != finalSegmentBlocks[i+1]) {
329                iBuilder->CreateBr(finalSegmentBlocks[i+1]);
330            }
331        }
332    }
333    iBuilder->SetInsertPoint(exitBlock);
334}
Note: See TracBrowser for help on using the repository browser.