source: icGREP/icgrep-devel/icgrep/toolchain/pipeline.cpp @ 5486

Last change on this file since 5486 was 5486, checked in by nmedfort, 2 years ago

Initial attempt to improve debugging capabilities with compilation stack traces on error.

File size: 28.9 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/toolchain.h>
8#include <kernels/kernel.h>
9#include <kernels/streamset.h>
10#include <llvm/IR/Module.h>
11#include <boost/container/flat_set.hpp>
12#include <boost/container/flat_map.hpp>
13#include <llvm/Support/CommandLine.h>
14#include <kernels/kernel_builder.h>
15
16#include <llvm/Support/raw_ostream.h>
17
18using namespace kernel;
19using namespace parabix;
20using namespace llvm;
21
22// static cl::opt<bool> UseYield("yield", cl::desc("yield after waiting"), cl::init(false));
23
24template <typename Value>
25using StreamSetBufferMap = boost::container::flat_map<const StreamSetBuffer *, Value>;
26
27template <typename Value>
28using FlatSet = boost::container::flat_set<Value>;
29
30Function * makeThreadFunction(const std::unique_ptr<kernel::KernelBuilder> & b, const std::string & name) {
31    Function * const f = Function::Create(FunctionType::get(b->getVoidTy(), {b->getVoidPtrTy()}, false), Function::InternalLinkage, name, b->getModule());
32    f->setCallingConv(CallingConv::C);
33    f->arg_begin()->setName("input");
34    return f;
35}
36
37/** ------------------------------------------------------------------------------------------------------------- *
38 * @brief generateSegmentParallelPipeline
39 *
40 * Given a computation expressed as a logical pipeline of K kernels k0, k_1, ...k_(K-1)
41 * operating over an input stream set S, a segment-parallel implementation divides the input
42 * into segments and coordinates a set of T <= K threads to each process one segment at a time.
43 * Let S_0, S_1, ... S_N be the segments of S.   Segments are assigned to threads in a round-robin
44 * fashion such that processing of segment S_i by the full pipeline is carried out by thread i mod T.
45 ** ------------------------------------------------------------------------------------------------------------- */
46void generateSegmentParallelPipeline(const std::unique_ptr<KernelBuilder> & iBuilder, const std::vector<Kernel *> & kernels) {
47
48    const unsigned n = kernels.size();
49    Module * const m = iBuilder->getModule();
50    IntegerType * const sizeTy = iBuilder->getSizeTy();
51    PointerType * const voidPtrTy = iBuilder->getVoidPtrTy();
52    Constant * nullVoidPtrVal = ConstantPointerNull::getNullValue(voidPtrTy);
53    std::vector<Type *> structTypes;
54
55    Value * instance[n];
56    for (unsigned i = 0; i < n; ++i) {
57        instance[i] = kernels[i]->getInstance();
58        structTypes.push_back(instance[i]->getType());
59    }
60    StructType * const sharedStructType = StructType::get(m->getContext(), structTypes);
61    StructType * const threadStructType = StructType::get(sharedStructType->getPointerTo(), sizeTy, nullptr);
62
63    Function * const threadFunc = makeThreadFunction(iBuilder, "segment");
64
65    // -------------------------------------------------------------------------------------------------------------------------
66    // MAKE SEGMENT PARALLEL PIPELINE THREAD
67    // -------------------------------------------------------------------------------------------------------------------------
68    const auto ip = iBuilder->saveIP();
69
70     // Create the basic blocks for the thread function.
71    BasicBlock * entryBlock = BasicBlock::Create(iBuilder->getContext(), "entry", threadFunc);
72    iBuilder->SetInsertPoint(entryBlock);
73    Value * const input = &threadFunc->getArgumentList().front();
74    Value * const threadStruct = iBuilder->CreatePointerCast(input, threadStructType->getPointerTo());
75    Value * const sharedStatePtr = iBuilder->CreateLoad(iBuilder->CreateGEP(threadStruct, {iBuilder->getInt32(0), iBuilder->getInt32(0)}));
76    for (unsigned k = 0; k < n; ++k) {
77        Value * ptr = iBuilder->CreateLoad(iBuilder->CreateGEP(sharedStatePtr, {iBuilder->getInt32(0), iBuilder->getInt32(k)}));
78        kernels[k]->setInstance(ptr);
79    }
80    Value * const segOffset = iBuilder->CreateLoad(iBuilder->CreateGEP(threadStruct, {iBuilder->getInt32(0), iBuilder->getInt32(1)}));
81
82    BasicBlock * segmentLoop = BasicBlock::Create(iBuilder->getContext(), "segmentLoop", threadFunc);
83    iBuilder->CreateBr(segmentLoop);
84
85    iBuilder->SetInsertPoint(segmentLoop);
86    PHINode * const segNo = iBuilder->CreatePHI(iBuilder->getSizeTy(), 2, "segNo");
87    segNo->addIncoming(segOffset, entryBlock);
88
89    Value * terminated = iBuilder->getFalse();
90    Value * const nextSegNo = iBuilder->CreateAdd(segNo, iBuilder->getSize(1));
91
92    BasicBlock * segmentLoopBody = nullptr;
93    BasicBlock * const exitThreadBlock = BasicBlock::Create(iBuilder->getContext(), "exitThread", threadFunc);
94
95    StreamSetBufferMap<Value *> producedPos;
96    StreamSetBufferMap<Value *> consumedPos;
97
98    Value * cycleCountStart = nullptr;
99    Value * cycleCountEnd = nullptr;
100    if (codegen::EnableCycleCounter) {
101        cycleCountStart = iBuilder->CreateReadCycleCounter();
102    }
103
104    for (unsigned k = 0; k < n; ++k) {
105
106        const auto & kernel = kernels[k];
107
108        BasicBlock * const segmentWait = BasicBlock::Create(iBuilder->getContext(), kernel->getName() + "Wait", threadFunc);
109
110        BasicBlock * segmentYield = segmentWait;
111//        if (UseYield) {
112//            segmentYield = BasicBlock::Create(iBuilder->getContext(), kernel->getName() + "Yield", threadFunc);
113//        }
114
115        iBuilder->CreateBr(segmentWait);
116
117        segmentLoopBody = BasicBlock::Create(iBuilder->getContext(), kernel->getName() + "Do", threadFunc);
118
119        iBuilder->SetInsertPoint(segmentWait);
120        const unsigned waitIdx = codegen::DebugOptionIsSet(codegen::SerializeThreads) ? (n - 1) : k;
121
122        iBuilder->setKernel(kernels[waitIdx]);
123        Value * const processedSegmentCount = iBuilder->acquireLogicalSegmentNo();
124        iBuilder->setKernel(kernel);
125
126        assert (processedSegmentCount->getType() == segNo->getType());
127        Value * const ready = iBuilder->CreateICmpEQ(segNo, processedSegmentCount);
128
129        if (kernel->hasNoTerminateAttribute()) {
130            iBuilder->CreateCondBr(ready, segmentLoopBody, segmentYield);
131        } else { // If the kernel was terminated in a previous segment then the pipeline is done.
132            BasicBlock * completionTest = BasicBlock::Create(iBuilder->getContext(), kernel->getName() + "Completed", threadFunc, 0);
133            BasicBlock * exitBlock = BasicBlock::Create(iBuilder->getContext(), kernel->getName() + "Exit", threadFunc, 0);
134            iBuilder->CreateCondBr(ready, completionTest, segmentYield);
135
136            iBuilder->SetInsertPoint(completionTest);
137            Value * terminationSignal = iBuilder->getTerminationSignal();
138            iBuilder->CreateCondBr(terminationSignal, exitBlock, segmentLoopBody);
139            iBuilder->SetInsertPoint(exitBlock);
140            // Ensure that the next thread will also exit.
141            iBuilder->releaseLogicalSegmentNo(nextSegNo);
142            iBuilder->CreateBr(exitThreadBlock);
143        }
144
145//        if (UseYield) {
146//            // Yield the thread after waiting
147//            iBuilder->SetInsertPoint(segmentYield);
148//            iBuilder->CreatePThreadYield();
149//            iBuilder->CreateBr(segmentWait);
150//        }
151
152        // Execute the kernel segment
153        iBuilder->SetInsertPoint(segmentLoopBody);
154        const auto & inputs = kernel->getStreamInputs();
155        std::vector<Value *> args = {kernel->getInstance(), terminated};
156        for (unsigned i = 0; i < inputs.size(); ++i) {
157            const auto f = producedPos.find(kernel->getStreamSetInputBuffer(i));
158            assert (f != producedPos.end());
159            args.push_back(f->second);
160        }
161
162        iBuilder->setKernel(kernel);
163        iBuilder->createDoSegmentCall(args);
164        if (!kernel->hasNoTerminateAttribute()) {
165            terminated = iBuilder->CreateOr(terminated, iBuilder->getTerminationSignal());
166        }
167
168        const auto & outputs = kernel->getStreamOutputs();
169        for (unsigned i = 0; i < outputs.size(); ++i) {           
170            Value * const produced = iBuilder->getProducedItemCount(outputs[i].name, terminated);
171            const StreamSetBuffer * const buf = kernel->getStreamSetOutputBuffer(i);
172            assert (producedPos.count(buf) == 0);
173            producedPos.emplace(buf, produced);
174        }
175        for (unsigned i = 0; i < inputs.size(); ++i) {
176            Value * const processedItemCount = iBuilder->getProcessedItemCount(inputs[i].name);
177            const StreamSetBuffer * const buf = kernel->getStreamSetInputBuffer(i);           
178            auto f = consumedPos.find(buf);
179            if (f == consumedPos.end()) {
180                consumedPos.emplace(buf, processedItemCount);
181            } else {
182                Value * lesser = iBuilder->CreateICmpULT(processedItemCount, f->second);
183                f->second = iBuilder->CreateSelect(lesser, processedItemCount, f->second);
184            }
185        }
186        if (codegen::EnableCycleCounter) {
187            cycleCountEnd = iBuilder->CreateReadCycleCounter();
188            Value * counterPtr = iBuilder->getScalarFieldPtr(Kernel::CYCLECOUNT_SCALAR);
189            iBuilder->CreateStore(iBuilder->CreateAdd(iBuilder->CreateLoad(counterPtr), iBuilder->CreateSub(cycleCountEnd, cycleCountStart)), counterPtr);
190            cycleCountStart = cycleCountEnd;
191        }
192       
193        iBuilder->releaseLogicalSegmentNo(nextSegNo);
194    }
195
196    assert (segmentLoopBody);
197    exitThreadBlock->moveAfter(segmentLoopBody);
198
199    for (const auto consumed : consumedPos) {
200        const StreamSetBuffer * const buf = consumed.first;
201        Kernel * kernel = buf->getProducer();
202        const auto & outputs = kernel->getStreamSetOutputBuffers();
203        for (unsigned i = 0; i < outputs.size(); ++i) {
204            if (outputs[i] == buf) {
205                iBuilder->setKernel(kernel);
206                iBuilder->setConsumedItemCount(kernel->getStreamOutput(i).name, consumed.second);
207                break;
208            }
209        }
210    }
211
212    segNo->addIncoming(iBuilder->CreateAdd(segNo, iBuilder->getSize(codegen::ThreadNum)), segmentLoopBody);
213    iBuilder->CreateCondBr(terminated, exitThreadBlock, segmentLoop);
214
215    iBuilder->SetInsertPoint(exitThreadBlock);
216
217    // only call pthread_exit() within spawned threads; otherwise it'll be equivalent to calling exit() within the process
218    BasicBlock * const exitThread = BasicBlock::Create(iBuilder->getContext(), "ExitThread", threadFunc);
219    BasicBlock * const exitFunction = BasicBlock::Create(iBuilder->getContext(), "ExitProcessFunction", threadFunc);
220
221    Value * const exitCond = iBuilder->CreateICmpEQ(segOffset, ConstantInt::getNullValue(segOffset->getType()));
222    iBuilder->CreateCondBr(exitCond, exitFunction, exitThread);
223    iBuilder->SetInsertPoint(exitThread);
224    iBuilder->CreatePThreadExitCall(nullVoidPtrVal);
225    iBuilder->CreateBr(exitFunction);
226    iBuilder->SetInsertPoint(exitFunction);
227    iBuilder->CreateRetVoid();
228
229    // -------------------------------------------------------------------------------------------------------------------------
230    iBuilder->restoreIP(ip);
231
232    for (unsigned i = 0; i < n; ++i) {
233        kernels[i]->setInstance(instance[i]);
234    }
235
236    // -------------------------------------------------------------------------------------------------------------------------
237    // MAKE SEGMENT PARALLEL PIPELINE DRIVER
238    // -------------------------------------------------------------------------------------------------------------------------
239    const unsigned threads = codegen::ThreadNum - 1;
240    assert (codegen::ThreadNum > 1);
241    Type * const pthreadsTy = ArrayType::get(sizeTy, threads);
242    AllocaInst * const pthreads = iBuilder->CreateAlloca(pthreadsTy);
243    Value * threadIdPtr[threads];
244
245    for (unsigned i = 0; i < threads; ++i) {
246        threadIdPtr[i] = iBuilder->CreateGEP(pthreads, {iBuilder->getInt32(0), iBuilder->getInt32(i)});
247    }
248
249    for (unsigned i = 0; i < n; ++i) {
250        iBuilder->setKernel(kernels[i]);
251        iBuilder->releaseLogicalSegmentNo(iBuilder->getSize(0));
252    }
253
254    AllocaInst * const sharedStruct = iBuilder->CreateCacheAlignedAlloca(sharedStructType);
255    for (unsigned i = 0; i < n; ++i) {
256        Value * ptr = iBuilder->CreateGEP(sharedStruct, {iBuilder->getInt32(0), iBuilder->getInt32(i)});
257        iBuilder->CreateStore(kernels[i]->getInstance(), ptr);
258    }
259
260    // use the process thread to handle the initial segment function after spawning (n - 1) threads to handle the subsequent offsets
261    for (unsigned i = 0; i < threads; ++i) {
262        AllocaInst * const threadState = iBuilder->CreateAlloca(threadStructType);
263        iBuilder->CreateStore(sharedStruct, iBuilder->CreateGEP(threadState, {iBuilder->getInt32(0), iBuilder->getInt32(0)}));
264        iBuilder->CreateStore(iBuilder->getSize(i + 1), iBuilder->CreateGEP(threadState, {iBuilder->getInt32(0), iBuilder->getInt32(1)}));
265        iBuilder->CreatePThreadCreateCall(threadIdPtr[i], nullVoidPtrVal, threadFunc, threadState);
266    }
267
268    AllocaInst * const threadState = iBuilder->CreateAlloca(threadStructType);
269    iBuilder->CreateStore(sharedStruct, iBuilder->CreateGEP(threadState, {iBuilder->getInt32(0), iBuilder->getInt32(0)}));
270    iBuilder->CreateStore(iBuilder->getSize(0), iBuilder->CreateGEP(threadState, {iBuilder->getInt32(0), iBuilder->getInt32(1)}));
271    iBuilder->CreateCall(threadFunc, iBuilder->CreatePointerCast(threadState, voidPtrTy));
272
273    AllocaInst * const status = iBuilder->CreateAlloca(voidPtrTy);
274    for (unsigned i = 0; i < threads; ++i) {
275        Value * threadId = iBuilder->CreateLoad(threadIdPtr[i]);
276        iBuilder->CreatePThreadJoinCall(threadId, status);
277    }
278   
279    if (codegen::EnableCycleCounter) {
280        for (unsigned k = 0; k < kernels.size(); k++) {
281            auto & kernel = kernels[k];
282            iBuilder->setKernel(kernel);
283            const auto & inputs = kernel->getStreamInputs();
284            const auto & outputs = kernel->getStreamOutputs();
285            Value * items = nullptr;
286            if (inputs.empty()) {
287                items = iBuilder->getProducedItemCount(outputs[0].name);
288            } else {
289                items = iBuilder->getProcessedItemCount(inputs[0].name);
290            }
291            Value * fItems = iBuilder->CreateUIToFP(items, iBuilder->getDoubleTy());
292            Value * cycles = iBuilder->CreateLoad(iBuilder->getScalarFieldPtr(Kernel::CYCLECOUNT_SCALAR));
293            Value * fCycles = iBuilder->CreateUIToFP(cycles, iBuilder->getDoubleTy());
294            std::string formatString = kernel->getName() + ": %7.2e items processed; %7.2e CPU cycles,  %6.2f cycles per item.\n";
295            Value * stringPtr = iBuilder->CreatePointerCast(iBuilder->GetString(formatString), iBuilder->getInt8PtrTy());
296            iBuilder->CreateCall(iBuilder->GetDprintf(), {iBuilder->getInt32(2), stringPtr, fItems, fCycles, iBuilder->CreateFDiv(fCycles, fItems)});
297        }
298    }
299   
300}
301
302
303/** ------------------------------------------------------------------------------------------------------------- *
304 * @brief generateParallelPipeline
305 ** ------------------------------------------------------------------------------------------------------------- */
306void generateParallelPipeline(const std::unique_ptr<KernelBuilder> & iBuilder, const std::vector<Kernel *> &kernels) {
307
308    Module * const m = iBuilder->getModule();
309    IntegerType * const sizeTy = iBuilder->getSizeTy();
310    PointerType * const voidPtrTy = iBuilder->getVoidPtrTy();
311    ConstantInt * bufferSegments = ConstantInt::get(sizeTy, codegen::BufferSegments - 1);
312    ConstantInt * segmentItems = ConstantInt::get(sizeTy, codegen::SegmentSize * iBuilder->getBitBlockWidth());
313    Constant * const nullVoidPtrVal = ConstantPointerNull::getNullValue(voidPtrTy);
314
315    const unsigned n = kernels.size();
316
317    Type * const pthreadsTy = ArrayType::get(sizeTy, n);
318    AllocaInst * const pthreads = iBuilder->CreateAlloca(pthreadsTy);
319    Value * threadIdPtr[n];
320    for (unsigned i = 0; i < n; ++i) {
321        threadIdPtr[i] = iBuilder->CreateGEP(pthreads, {iBuilder->getInt32(0), iBuilder->getInt32(i)});
322    }
323
324    Value * instance[n];
325    Type * structTypes[n];
326    for (unsigned i = 0; i < n; ++i) {
327        instance[i] = kernels[i]->getInstance();
328        structTypes[i] = instance[i]->getType();
329    }
330
331    Type * const sharedStructType = StructType::get(m->getContext(), ArrayRef<Type *>{structTypes, n});
332
333
334    AllocaInst * sharedStruct = iBuilder->CreateAlloca(sharedStructType);
335    for (unsigned i = 0; i < n; ++i) {
336        Value * ptr = iBuilder->CreateGEP(sharedStruct, {iBuilder->getInt32(0), iBuilder->getInt32(i)});
337        iBuilder->CreateStore(instance[i], ptr);
338    }
339
340    for (auto & kernel : kernels) {
341        iBuilder->setKernel(kernel);
342        iBuilder->releaseLogicalSegmentNo(iBuilder->getSize(0));
343    }
344
345    // GENERATE THE PRODUCING AND CONSUMING KERNEL MAPS
346    StreamSetBufferMap<unsigned> producingKernel;
347    StreamSetBufferMap<std::vector<unsigned>> consumingKernels;
348    for (unsigned id = 0; id < n; ++id) {
349        const auto & kernel = kernels[id];
350        const auto & inputs = kernel->getStreamInputs();
351        const auto & outputs = kernel->getStreamOutputs();
352        // add any outputs from this kernel to the producing kernel map
353        for (unsigned j = 0; j < outputs.size(); ++j) {
354            const StreamSetBuffer * const buf = kernel->getStreamSetOutputBuffer(j);
355            if (LLVM_UNLIKELY(producingKernel.count(buf) != 0)) {
356                report_fatal_error(kernel->getName() + " redefines stream set " + outputs[j].name);
357            }
358            producingKernel.emplace(buf, id);
359        }
360        // and any inputs to the consuming kernels list
361        for (unsigned j = 0; j < inputs.size(); ++j) {
362            const StreamSetBuffer * const buf = kernel->getStreamSetInputBuffer(j);
363            auto f = consumingKernels.find(buf);
364            if (f == consumingKernels.end()) {
365                if (LLVM_UNLIKELY(producingKernel.count(buf) == 0)) {
366                    report_fatal_error(kernel->getName() + " uses stream set " + inputs[j].name + " prior to its definition");
367                }
368                consumingKernels.emplace(buf, std::vector<unsigned>{ id });
369            } else {
370                f->second.push_back(id);
371            }
372        }
373    }
374
375    const auto ip = iBuilder->saveIP();
376
377    // GENERATE UNIQUE PIPELINE PARALLEL THREAD FUNCTION FOR EACH KERNEL
378    FlatSet<unsigned> kernelSet;
379    kernelSet.reserve(n);
380
381    Function * thread_functions[n];
382    Value * producerSegNo[n];
383    for (unsigned id = 0; id < n; id++) {
384        const auto & kernel = kernels[id];
385
386        iBuilder->setKernel(kernel);
387
388        const auto & inputs = kernel->getStreamInputs();
389
390        Function * const threadFunc = makeThreadFunction(iBuilder, "ppt:" + kernel->getName());
391
392         // Create the basic blocks for the thread function.
393        BasicBlock * entryBlock = BasicBlock::Create(iBuilder->getContext(), "entry", threadFunc);
394        BasicBlock * outputCheckBlock = BasicBlock::Create(iBuilder->getContext(), "outputCheck", threadFunc);
395        BasicBlock * inputCheckBlock = BasicBlock::Create(iBuilder->getContext(), "inputCheck", threadFunc);
396        BasicBlock * doSegmentBlock = BasicBlock::Create(iBuilder->getContext(), "doSegment", threadFunc);
397        BasicBlock * exitThreadBlock = BasicBlock::Create(iBuilder->getContext(), "exitThread", threadFunc);
398
399        iBuilder->SetInsertPoint(entryBlock);
400
401        Value * sharedStruct = iBuilder->CreateBitCast(&threadFunc->getArgumentList().front(), sharedStructType->getPointerTo());
402
403        for (unsigned k = 0; k < n; k++) {
404            Value * const ptr = iBuilder->CreateGEP(sharedStruct, {iBuilder->getInt32(0), iBuilder->getInt32(k)});
405            kernels[k]->setInstance(iBuilder->CreateLoad(ptr));
406        }
407
408        iBuilder->CreateBr(outputCheckBlock);
409
410        // Check whether the output buffers are ready for more data
411        iBuilder->SetInsertPoint(outputCheckBlock);
412        PHINode * segNo = iBuilder->CreatePHI(iBuilder->getSizeTy(), 3, "segNo");
413        segNo->addIncoming(iBuilder->getSize(0), entryBlock);
414        segNo->addIncoming(segNo, outputCheckBlock);
415
416        Value * outputWaitCond = iBuilder->getTrue();
417        for (const StreamSetBuffer * buf : kernel->getStreamSetOutputBuffers()) {
418            const auto & list = consumingKernels[buf];
419            assert(std::is_sorted(list.begin(), list.end()));
420            kernelSet.insert(list.begin(), list.end());
421        }
422        for (unsigned k : kernelSet) {
423            iBuilder->setKernel(kernels[k]);
424            Value * consumerSegNo = iBuilder->acquireLogicalSegmentNo();
425            assert (consumerSegNo->getType() == segNo->getType());
426            Value * consumedSegNo = iBuilder->CreateAdd(consumerSegNo, bufferSegments);
427            outputWaitCond = iBuilder->CreateAnd(outputWaitCond, iBuilder->CreateICmpULE(segNo, consumedSegNo));
428        }
429        kernelSet.clear();
430        iBuilder->setKernel(kernel);
431        iBuilder->CreateCondBr(outputWaitCond, inputCheckBlock, outputCheckBlock);
432
433        // Check whether the input buffers have enough data for this kernel to begin
434        iBuilder->SetInsertPoint(inputCheckBlock);
435        for (const StreamSetBuffer * buf : kernel->getStreamSetInputBuffers()) {
436            kernelSet.insert(producingKernel[buf]);
437        }
438
439        Value * inputWaitCond = iBuilder->getTrue();
440        for (unsigned k : kernelSet) {
441            iBuilder->setKernel(kernels[k]);
442            producerSegNo[k] = iBuilder->acquireLogicalSegmentNo();
443            assert (producerSegNo[k]->getType() == segNo->getType());
444            inputWaitCond = iBuilder->CreateAnd(inputWaitCond, iBuilder->CreateICmpULT(segNo, producerSegNo[k]));
445        }
446        iBuilder->setKernel(kernel);
447        iBuilder->CreateCondBr(inputWaitCond, doSegmentBlock, inputCheckBlock);
448
449        // Process the segment
450        iBuilder->SetInsertPoint(doSegmentBlock);
451
452        Value * const nextSegNo = iBuilder->CreateAdd(segNo, iBuilder->getSize(1));
453        Value * terminated = nullptr;
454        if (kernelSet.empty()) {
455            // if this kernel has no input streams, the kernel itself must decide when it terminates.
456            terminated = iBuilder->getTerminationSignal();
457        } else {
458            // ... otherwise the kernel terminates only when it exhausts all of its input streams
459            terminated = iBuilder->getTrue();
460            for (unsigned k : kernelSet) {
461                iBuilder->setKernel(kernels[k]);
462                terminated = iBuilder->CreateAnd(terminated, iBuilder->getTerminationSignal());
463                terminated = iBuilder->CreateAnd(terminated, iBuilder->CreateICmpEQ(nextSegNo, producerSegNo[k]));
464            }
465            kernelSet.clear();
466            iBuilder->setKernel(kernel);
467        }
468
469        std::vector<Value *> args = {kernel->getInstance(), terminated};
470        args.insert(args.end(), inputs.size(), iBuilder->CreateMul(segmentItems, segNo));
471
472        iBuilder->createDoSegmentCall(args);
473        segNo->addIncoming(nextSegNo, doSegmentBlock);
474        iBuilder->releaseLogicalSegmentNo(nextSegNo);
475
476        iBuilder->CreateCondBr(terminated, exitThreadBlock, outputCheckBlock);
477
478        iBuilder->SetInsertPoint(exitThreadBlock);
479
480        iBuilder->CreatePThreadExitCall(nullVoidPtrVal);
481
482        iBuilder->CreateRetVoid();
483
484        thread_functions[id] = threadFunc;
485    }
486
487    iBuilder->restoreIP(ip);
488
489    for (unsigned i = 0; i < n; ++i) {
490        kernels[i]->setInstance(instance[i]);
491    }
492
493    for (unsigned i = 0; i < n; ++i) {
494        iBuilder->CreatePThreadCreateCall(threadIdPtr[i], nullVoidPtrVal, thread_functions[i], sharedStruct);
495    }
496
497    AllocaInst * const status = iBuilder->CreateAlloca(voidPtrTy);
498    for (unsigned i = 0; i < n; ++i) {
499        Value * threadId = iBuilder->CreateLoad(threadIdPtr[i]);
500        iBuilder->CreatePThreadJoinCall(threadId, status);
501    }
502}
503
504/** ------------------------------------------------------------------------------------------------------------- *
505 * @brief generatePipelineLoop
506 ** ------------------------------------------------------------------------------------------------------------- */
507void generatePipelineLoop(const std::unique_ptr<KernelBuilder> & iBuilder, const std::vector<Kernel *> & kernels) {
508
509    BasicBlock * entryBlock = iBuilder->GetInsertBlock();
510    Function * main = entryBlock->getParent();
511
512    // Create the basic blocks for the loop.
513    BasicBlock * pipelineLoop = BasicBlock::Create(iBuilder->getContext(), "pipelineLoop", main);
514    BasicBlock * pipelineExit = BasicBlock::Create(iBuilder->getContext(), "pipelineExit", main);
515
516    StreamSetBufferMap<Value *> producedPos;
517    StreamSetBufferMap<Value *> consumedPos;
518
519    iBuilder->CreateBr(pipelineLoop);
520    iBuilder->SetInsertPoint(pipelineLoop);
521   
522    Value * cycleCountStart = nullptr;
523    Value * cycleCountEnd = nullptr;
524    if (codegen::EnableCycleCounter) {
525        cycleCountStart = iBuilder->CreateReadCycleCounter();
526    }
527    Value * terminated = iBuilder->getFalse();
528    for (unsigned k = 0; k < kernels.size(); k++) {
529
530        auto & kernel = kernels[k];
531
532        iBuilder->setKernel(kernel);
533        const auto & inputs = kernel->getStreamInputs();
534        const auto & outputs = kernel->getStreamOutputs();
535
536        std::vector<Value *> args = {kernel->getInstance(), terminated};
537        for (unsigned i = 0; i < inputs.size(); ++i) {
538            const auto f = producedPos.find(kernel->getStreamSetInputBuffer(i));
539            if (LLVM_UNLIKELY(f == producedPos.end())) {
540                report_fatal_error(kernel->getName() + " uses stream set " + inputs[i].name + " prior to its definition");
541            }
542            args.push_back(f->second);
543        }
544
545        iBuilder->createDoSegmentCall(args);
546        if (!kernel->hasNoTerminateAttribute()) {
547            Value * terminatedSignal = iBuilder->getTerminationSignal();
548            terminated = iBuilder->CreateOr(terminated, terminatedSignal);
549        }
550        for (unsigned i = 0; i < outputs.size(); ++i) {
551            Value * const produced = iBuilder->getProducedItemCount(outputs[i].name, terminated);
552            const StreamSetBuffer * const buf = kernel->getStreamSetOutputBuffer(i);
553            assert (producedPos.count(buf) == 0);
554            producedPos.emplace(buf, produced);
555        }
556
557        for (unsigned i = 0; i < inputs.size(); ++i) {
558            Value * const processedItemCount = iBuilder->getProcessedItemCount(inputs[i].name);
559            const StreamSetBuffer * const buf = kernel->getStreamSetInputBuffer(i);
560            auto f = consumedPos.find(buf);
561            if (f == consumedPos.end()) {
562                consumedPos.emplace(buf, processedItemCount);
563            } else {
564                Value * lesser = iBuilder->CreateICmpULT(processedItemCount, f->second);
565                f->second = iBuilder->CreateSelect(lesser, processedItemCount, f->second);
566            }
567        }
568        if (codegen::EnableCycleCounter) {
569            cycleCountEnd = iBuilder->CreateReadCycleCounter();
570            //Value * counterPtr = iBuilder->CreateGEP(mCycleCounts, {iBuilder->getInt32(0), iBuilder->getInt32(k)});
571            Value * counterPtr = iBuilder->getScalarFieldPtr(Kernel::CYCLECOUNT_SCALAR);
572            iBuilder->CreateStore(iBuilder->CreateAdd(iBuilder->CreateLoad(counterPtr), iBuilder->CreateSub(cycleCountEnd, cycleCountStart)), counterPtr);
573            cycleCountStart = cycleCountEnd;
574        }
575
576        Value * const segNo = iBuilder->acquireLogicalSegmentNo();
577        Value * nextSegNo = iBuilder->CreateAdd(segNo, iBuilder->getSize(1));
578        iBuilder->releaseLogicalSegmentNo(nextSegNo);
579    }
580
581    for (const auto consumed : consumedPos) {
582        const StreamSetBuffer * const buf = consumed.first;
583        Kernel * k = buf->getProducer();
584        const auto & outputs = k->getStreamSetOutputBuffers();
585        for (unsigned i = 0; i < outputs.size(); ++i) {
586            if (outputs[i] == buf) {
587                iBuilder->setKernel(k);
588                iBuilder->setConsumedItemCount(k->getStreamOutput(i).name, consumed.second);
589                break;
590            }
591        }
592    }
593
594    iBuilder->CreateCondBr(terminated, pipelineExit, pipelineLoop);
595    iBuilder->SetInsertPoint(pipelineExit);
596    if (codegen::EnableCycleCounter) {
597        for (unsigned k = 0; k < kernels.size(); k++) {
598            auto & kernel = kernels[k];
599            iBuilder->setKernel(kernel);
600            const auto & inputs = kernel->getStreamInputs();
601            const auto & outputs = kernel->getStreamOutputs();
602            Value * items = nullptr;
603            if (inputs.empty()) {
604                items = iBuilder->getProducedItemCount(outputs[0].name);
605            } else {
606                items = iBuilder->getProcessedItemCount(inputs[0].name);
607            }
608            Value * fItems = iBuilder->CreateUIToFP(items, iBuilder->getDoubleTy());
609            Value * cycles = iBuilder->CreateLoad(iBuilder->getScalarFieldPtr(Kernel::CYCLECOUNT_SCALAR));
610            Value * fCycles = iBuilder->CreateUIToFP(cycles, iBuilder->getDoubleTy());
611            std::string formatString = kernel->getName() + ": %7.2e items processed; %7.2e CPU cycles,  %6.2f cycles per item.\n";
612            Value * stringPtr = iBuilder->CreatePointerCast(iBuilder->GetString(formatString), iBuilder->getInt8PtrTy());
613            iBuilder->CreateCall(iBuilder->GetDprintf(), {iBuilder->getInt32(2), stringPtr, fItems, fCycles, iBuilder->CreateFDiv(fCycles, fItems)});
614        }
615    }
616}
Note: See TracBrowser for help on using the repository browser.