source: icGREP/icgrep-devel/icgrep/pablo/pablo_compiler.cpp @ 5157

Last change on this file since 5157 was 5156, checked in by nmedfort, 3 years ago

Work on multiplexing and distribution passes + a few AST modification bug fixes.

File size: 19.9 KB
Line 
1/*
2 *  Copyright (c) 2014-16 International Characters.
3 *  This software is licensed to the public under the Open Software License 3.0.
4 *  icgrep is a trademark of International Characters.
5 */
6
7#include <pablo/pablo_compiler.h>
8#include <pablo/pablo_toolchain.h>
9#include <pablo/codegenstate.h>
10#include <pablo/carry_manager.h>
11#include <pablo/printer_pablos.h>
12#include <pablo/function.h>
13#include <re/re_name.h>
14#include <stdexcept>
15#include <sstream>
16#include <IDISA/idisa_builder.h>
17#include <llvm/IR/Module.h>
18#include <llvm/IR/IRBuilder.h>
19#include <iostream>
20#include <hrtime.h>
21#include <llvm/Support/Debug.h>
22
23namespace pablo {
24
25PabloCompiler::PabloCompiler(IDISA::IDISA_Builder * b, PabloKernel * k, PabloFunction * const function)
26: mMod(b->getModule())
27, iBuilder(b)
28, mBitBlockType(b->getBitBlockType())
29, mCarryManager(nullptr)
30, mPabloFunction(function)
31, mPabloBlock(nullptr)
32, mKernelBuilder(k)
33, mWhileDepth(0)
34, mIfDepth(0)
35, mFunction(nullptr)
36, mMaxWhileDepth(0) {
37   
38}
39
40
41Type * PabloCompiler::initializeKernelData() {
42    Examine(mPabloFunction);
43   
44    mCarryManager = make_unique<CarryManager>(iBuilder);
45    Type * carryDataType = mCarryManager->initializeCarryData(mPabloFunction);
46    return carryDataType;
47}
48   
49void PabloCompiler::compile(Function * doBlockFunction) {
50
51    // Make sure that we generate code into the right module.
52    mMod = iBuilder->getModule();
53    mFunction = doBlockFunction;
54    #ifdef PRINT_TIMING_INFORMATION
55    const timestamp_t pablo_compilation_start = read_cycle_counter();
56    #endif
57
58    //Generate Kernel//
59    iBuilder->SetInsertPoint(BasicBlock::Create(iBuilder->getContext(), "entry", doBlockFunction, 0));
60    mSelf = mKernelBuilder->getParameter(doBlockFunction, "self");
61    mCarryManager->initializeCodeGen(mKernelBuilder, mSelf);
62     
63    Value * blockNo = mKernelBuilder->getScalarField(mSelf, blockNoScalar);
64    std::string inputName = mKernelBuilder->mStreamSetInputs[0].ssName;
65    Value * inputSet_ptr  = mKernelBuilder->getStreamSetBlockPtr(mSelf, inputName, blockNo);
66
67    Value * outputSet_ptr = nullptr;
68    if (mPabloFunction->getNumOfResults() > 0) {
69        std::string outputName = mKernelBuilder->mStreamSetOutputs[0].ssName;
70        outputSet_ptr = mKernelBuilder->getStreamSetBlockPtr(mSelf, outputName, blockNo);
71    }
72
73    mMarkerMap.emplace(PabloBlock::createZeroes(), iBuilder->allZeroes());
74    mMarkerMap.emplace(PabloBlock::createOnes(), iBuilder->allOnes());
75    for (unsigned j = 0; j < mPabloFunction->getNumOfParameters(); ++j) {
76        Value * inputVal = iBuilder->CreateGEP(inputSet_ptr, {iBuilder->getInt32(0), iBuilder->getInt32(j)}); 
77        const Var * const var = mPabloFunction->getParameter(j);
78        if (DebugOptionIsSet(DumpTrace)) {
79            iBuilder->CallPrintRegister(var->getName()->to_string(), iBuilder->CreateBlockAlignedLoad(inputVal));
80        }
81        mMarkerMap.insert(std::make_pair(var, inputVal));
82    }
83   
84    compileBlock(mPabloFunction->getEntryBlock());
85   
86    for (unsigned j = 0; j < mPabloFunction->getNumOfResults(); ++j) {
87        const auto f = mMarkerMap.find(mPabloFunction->getResult(j));
88        if (LLVM_UNLIKELY(f == mMarkerMap.end())) {
89            throw std::runtime_error("PabloCompiler: result " + std::to_string(j) + " was not assigned a value!");
90        }
91        iBuilder->CreateBlockAlignedStore(f->second, outputSet_ptr, {iBuilder->getInt32(0), iBuilder->getInt32(j)});
92    }
93    iBuilder->CreateRetVoid();
94   
95    #ifdef PRINT_TIMING_INFORMATION
96    const timestamp_t pablo_compilation_end = read_cycle_counter();
97    std::cerr << "PABLO COMPILATION TIME: " << (pablo_compilation_end - pablo_compilation_start) << std::endl;
98    #endif
99}
100
101inline void PabloCompiler::Examine(const PabloFunction * const function) {
102    mWhileDepth = 0;
103    mIfDepth = 0;
104    mMaxWhileDepth = 0;
105    Examine(function->getEntryBlock());
106}
107
108void PabloCompiler::Examine(const PabloBlock * const block) {
109    unsigned maxOffset = 0;
110    for (const Statement * stmt : *block) {
111         boost::container::flat_set<unsigned> offsets;
112        if (LLVM_UNLIKELY(isa<Lookahead>(stmt))) {
113            const Lookahead * const la = cast<Lookahead>(stmt);
114            assert (isa<Var>(la->getExpr()));
115            if (la->getAmount() > maxOffset) maxOffset = la->getAmount();
116        } else {
117            if (LLVM_UNLIKELY(isa<If>(stmt))) {
118                Examine(cast<If>(stmt)->getBody());
119            } else if (LLVM_UNLIKELY(isa<While>(stmt))) {
120                mMaxWhileDepth = std::max(mMaxWhileDepth, ++mWhileDepth);
121                Examine(cast<While>(stmt)->getBody());
122                --mWhileDepth;
123            }
124        }
125        mKernelBuilder->setLookAhead(maxOffset);
126    }
127}
128
129void PabloCompiler::compileBlock(const PabloBlock * const block) {
130    mPabloBlock = block;
131    for (const Statement * statement : *block) {
132        compileStatement(statement);
133    }
134    mPabloBlock = block->getParent();
135}
136
137void PabloCompiler::compileIf(const If * ifStatement) {       
138    //
139    //  The If-ElseZero stmt:
140    //  if <predicate:expr> then <body:stmt>* elsezero <defined:var>* endif
141    //  If the value of the predicate is nonzero, then determine the values of variables
142    //  <var>* by executing the given statements.  Otherwise, the value of the
143    //  variables are all zero.  Requirements: (a) no variable that is defined within
144    //  the body of the if may be accessed outside unless it is explicitly
145    //  listed in the variable list, (b) every variable in the defined list receives
146    //  a value within the body, and (c) the logical consequence of executing
147    //  the statements in the event that the predicate is zero is that the
148    //  values of all defined variables indeed work out to be 0.
149    //
150    //  Simple Implementation with Phi nodes:  a phi node in the if exit block
151    //  is inserted for each variable in the defined variable list.  It receives
152    //  a zero value from the ifentry block and the defined value from the if
153    //  body.
154    //
155
156    BasicBlock * const ifEntryBlock = iBuilder->GetInsertBlock();
157    BasicBlock * const ifBodyBlock = BasicBlock::Create(mMod->getContext(), "if.body", mFunction, 0);
158    BasicBlock * const ifEndBlock = BasicBlock::Create(mMod->getContext(), "if.end", mFunction, 0);
159   
160    PabloBlock * ifBody = ifStatement->getBody();
161   
162    Value * const condition = compileExpression(ifStatement->getCondition());
163   
164    mCarryManager->enterScope(ifBody);
165    iBuilder->CreateCondBr(mCarryManager->generateSummaryTest(condition), ifBodyBlock, ifEndBlock);
166   
167    // Entry processing is complete, now handle the body of the if.
168    iBuilder->SetInsertPoint(ifBodyBlock);
169   
170    compileBlock(ifBody);
171    BasicBlock * ifExitBlock = iBuilder->GetInsertBlock();
172
173    if (mCarryManager->hasCarries()) {
174        mCarryManager->storeCarryOutSummary();
175    }
176    mCarryManager->addOuterSummaryToNestedSummary();
177
178    iBuilder->CreateBr(ifEndBlock);
179    //End Block
180    iBuilder->SetInsertPoint(ifEndBlock);
181    for (const PabloAST * node : ifStatement->getDefined()) {
182        const Assign * assign = cast<Assign>(node);
183        PHINode * phi = iBuilder->CreatePHI(mBitBlockType, 2, assign->getName()->value());
184        auto f = mMarkerMap.find(assign);
185        assert (f != mMarkerMap.end());
186        phi->addIncoming(iBuilder->allZeroes(), ifEntryBlock);
187        phi->addIncoming(f->second, ifExitBlock);
188        mMarkerMap[assign] = phi;
189    }
190    // Create the phi Node for the summary variable, if needed.
191    mCarryManager->buildCarryDataPhisAfterIfBody(ifEntryBlock, ifExitBlock);
192    mCarryManager->leaveScope();
193}
194
195void PabloCompiler::compileWhile(const While * whileStatement) {
196
197    PabloBlock * const whileBody = whileStatement->getBody();
198   
199    BasicBlock * whileEntryBlock = iBuilder->GetInsertBlock();
200    BasicBlock * whileBodyBlock = BasicBlock::Create(mMod->getContext(), "while.body", mFunction, 0);
201    BasicBlock * whileEndBlock = BasicBlock::Create(mMod->getContext(), "while.end", mFunction, 0);
202
203    mCarryManager->enterScope(whileBody);
204    mCarryManager->ensureCarriesLoadedRecursive();
205
206    const auto & nextNodes = whileStatement->getVariants();
207    std::vector<PHINode *> nextPhis;
208    nextPhis.reserve(nextNodes.size());
209
210    // On entry to the while structure, proceed to execute the first iteration
211    // of the loop body unconditionally.   The while condition is tested at the end of
212    // the loop.
213
214    iBuilder->CreateBr(whileBodyBlock);
215    iBuilder->SetInsertPoint(whileBodyBlock);
216
217    //
218    // There are 3 sets of Phi nodes for the while loop.
219    // (1) Carry-ins: (a) incoming carry data first iterations, (b) zero thereafter
220    // (2) Carry-out accumulators: (a) zero first iteration, (b) |= carry-out of each iteration
221    // (3) Next nodes: (a) values set up before loop, (b) modified values calculated in loop.
222
223    mCarryManager->initializeWhileEntryCarryDataPhis(whileEntryBlock);
224
225    // for any Next nodes in the loop body, initialize to (a) pre-loop value.
226    for (const Next * n : nextNodes) {
227        PHINode * phi = iBuilder->CreatePHI(mBitBlockType, 2, n->getName()->value());
228        auto f = mMarkerMap.find(n->getInitial());       
229        assert (f != mMarkerMap.end());
230        phi->addIncoming(f->second, whileEntryBlock);
231        mMarkerMap[n->getInitial()] = phi;
232        nextPhis.push_back(phi);
233    }
234
235    //
236    // Now compile the loop body proper.  Carry-out accumulated values
237    // and iterated values of Next nodes will be computed.
238    ++mWhileDepth;
239    compileBlock(whileBody);
240
241    BasicBlock * whileExitBlock = iBuilder->GetInsertBlock();
242
243    if (mCarryManager->hasCarries()) {
244        mCarryManager->storeCarryOutSummary();
245    }
246    mCarryManager->finalizeWhileBlockCarryDataPhis(whileExitBlock);
247
248    // Terminate the while loop body with a conditional branch back.
249    iBuilder->CreateCondBr(iBuilder->bitblock_any(compileExpression(whileStatement->getCondition())), whileBodyBlock, whileEndBlock);
250
251    // and for any Next nodes in the loop body
252    for (unsigned i = 0; i < nextNodes.size(); i++) {
253        const Next * n = nextNodes[i];
254        auto f = mMarkerMap.find(n->getExpr());
255        if (LLVM_UNLIKELY(f == mMarkerMap.end())) {
256            throw std::runtime_error("Next node expression was not compiled!");
257        }
258        nextPhis[i]->addIncoming(f->second, whileExitBlock);
259    }
260
261    iBuilder->SetInsertPoint(whileEndBlock);
262    --mWhileDepth;
263
264    mCarryManager->ensureCarriesStoredRecursive();
265    mCarryManager->leaveScope();
266}
267
268
269void PabloCompiler::compileStatement(const Statement * stmt) {
270    Value * expr = nullptr;
271    if (const Assign * assign = dyn_cast<const Assign>(stmt)) {
272        expr = compileExpression(assign->getExpression());
273    } else if (const Next * next = dyn_cast<const Next>(stmt)) {
274        expr = compileExpression(next->getExpr());
275    } else if (const If * ifStatement = dyn_cast<const If>(stmt)) {
276        compileIf(ifStatement);
277        return;
278    } else if (const While * whileStatement = dyn_cast<const While>(stmt)) {
279        compileWhile(whileStatement);
280        return;
281//    } else if (const Call* call = dyn_cast<Call>(stmt)) {
282//        // Call the callee once and store the result in the marker map.
283//        if (LLVM_UNLIKELY(mMarkerMap.count(call) == 0)) {
284//            return;
285//        }
286
287//        const Prototype * proto = call->getPrototype();
288//        const String * callee = proto->getName();
289
290//        Type * inputType = StructType::get(mMod->getContext(), std::vector<Type *>{proto->getNumOfParameters(), mBitBlockType});
291//        Type * outputType = StructType::get(mMod->getContext(), std::vector<Type *>{proto->getNumOfResults(), mBitBlockType});
292//        FunctionType * functionType = FunctionType::get(Type::getVoidTy(mMod->getContext()), std::vector<Type *>{PointerType::get(inputType, 0), PointerType::get(outputType, 0)}, false);
293
294//        //Starts on process_block
295//        SmallVector<AttributeSet, 3> Attrs;
296//        Attrs.push_back(AttributeSet::get(mMod->getContext(), 1U, std::vector<Attribute::AttrKind>({ Attribute::ReadOnly, Attribute::NoCapture })));
297//        Attrs.push_back(AttributeSet::get(mMod->getContext(), 2U, std::vector<Attribute::AttrKind>({ Attribute::ReadNone, Attribute::NoCapture })));
298//        AttributeSet AttrSet = AttributeSet::get(mMod->getContext(), Attrs);
299
300//        Function * externalFunction = cast<Function>(mMod->getOrInsertFunction(callee->value(), functionType, AttrSet));
301//        if (LLVM_UNLIKELY(externalFunction == nullptr)) {
302//            throw std::runtime_error("Could not create static method call for external function \"" + callee->to_string() + "\"");
303//        }
304//        externalFunction->setCallingConv(llvm::CallingConv::C);
305
306//        AllocaInst * outputStruct = iBuilder->CreateAlloca(outputType);
307//        iBuilder->CreateCall2(externalFunction, mInputAddressPtr, outputStruct);
308//        Value * outputPtr = iBuilder->CreateGEP(outputStruct, std::vector<Value *>({ iBuilder->getInt32(0), iBuilder->getInt32(0) }));
309
310//        expr = iBuilder->CreateBlockAlignedLoad(outputPtr);
311    } else if (const And * pablo_and = dyn_cast<And>(stmt)) {
312        expr = iBuilder->simd_and(compileExpression(pablo_and->getOperand(0)), compileExpression(pablo_and->getOperand(1)));
313    } else if (const Or * pablo_or = dyn_cast<Or>(stmt)) {
314        expr = iBuilder->simd_or(compileExpression(pablo_or->getOperand(0)), compileExpression(pablo_or->getOperand(1)));
315    } else if (const Xor * pablo_xor = dyn_cast<Xor>(stmt)) {
316        expr = iBuilder->simd_xor(compileExpression(pablo_xor->getOperand(0)), compileExpression(pablo_xor->getOperand(1)));
317    } else if (const Sel * sel = dyn_cast<Sel>(stmt)) {
318        Value* ifMask = compileExpression(sel->getCondition());
319        Value* ifTrue = iBuilder->simd_and(ifMask, compileExpression(sel->getTrueExpr()));
320        Value* ifFalse = iBuilder->simd_and(iBuilder->simd_not(ifMask), compileExpression(sel->getFalseExpr()));
321        expr = iBuilder->simd_or(ifTrue, ifFalse);
322    } else if (const Not * pablo_not = dyn_cast<Not>(stmt)) {
323        expr = iBuilder->simd_not(compileExpression(pablo_not->getExpr()));
324    } else if (const Advance * adv = dyn_cast<Advance>(stmt)) {
325        Value * const strm_value = compileExpression(adv->getExpr());
326        expr = mCarryManager->advanceCarryInCarryOut(adv->getLocalIndex(), adv->getAmount(), strm_value);
327    } else if (const MatchStar * mstar = dyn_cast<MatchStar>(stmt)) {
328        Value * const marker = compileExpression(mstar->getMarker());
329        Value * const cc = compileExpression(mstar->getCharClass());
330        Value * const marker_and_cc = iBuilder->simd_and(marker, cc);
331        Value * const sum = mCarryManager->addCarryInCarryOut(mstar->getLocalCarryIndex(), marker_and_cc, cc);
332        expr = iBuilder->simd_or(iBuilder->simd_xor(sum, cc), marker);
333    } else if (const ScanThru * sthru = dyn_cast<ScanThru>(stmt)) {
334        Value * const  marker_expr = compileExpression(sthru->getScanFrom());
335        Value * const  cc_expr = compileExpression(sthru->getScanThru());
336        Value * const  sum = mCarryManager->addCarryInCarryOut(sthru->getLocalCarryIndex(), marker_expr, cc_expr);
337        expr = iBuilder->simd_and(sum, iBuilder->simd_not(cc_expr));
338    } else if (const InFile * e = dyn_cast<InFile>(stmt)) {
339        Value * EOFmask = mKernelBuilder->getScalarField(mSelf, "EOFmask");
340        expr = iBuilder->simd_xor(compileExpression(e->getExpr()), EOFmask);
341    } else if (const AtEOF * e = dyn_cast<AtEOF>(stmt)) {
342        Value * EOFbit = mKernelBuilder->getScalarField(mSelf, "EOFbit");
343                expr = iBuilder->simd_and(compileExpression(e->getExpr()), EOFbit);
344    } else if (const Count * c = dyn_cast<Count>(stmt)) {
345        Value * const to_count = compileExpression(c->getExpr());
346        std::string counter = c->getName()->to_string();
347        Value * countSoFar = mKernelBuilder->getScalarField(mSelf, counter);
348        unsigned counterSize = countSoFar->getType()->getIntegerBitWidth();
349        Value * fieldCounts = iBuilder->simd_popcount(counterSize, to_count);
350        for (unsigned i = 0; i < iBuilder->getBitBlockWidth()/counterSize; ++i) {
351            countSoFar = iBuilder->CreateAdd(countSoFar, iBuilder->mvmd_extract(counterSize, fieldCounts, i));
352        }
353        mKernelBuilder->setScalarField(mSelf, counter, countSoFar);
354        expr = iBuilder->bitCast(iBuilder->CreateZExt(countSoFar, iBuilder->getIntNTy(iBuilder->getBitBlockWidth())));
355    } else if (const Lookahead * l = dyn_cast<Lookahead>(stmt)) {
356        PabloAST * const var = l->getExpr();
357        if (LLVM_UNLIKELY(!isa<Var>(var))) {
358            throw std::runtime_error("Lookahead operations may only be applied to input streams");
359        }
360        unsigned index = 0;
361        for (; index < mPabloFunction->getNumOfParameters(); ++index) {
362            if (mPabloFunction->getParameter(index) == var) {
363                break;
364            }
365        }
366        if (LLVM_UNLIKELY(index >= mPabloFunction->getNumOfParameters())) {
367            throw std::runtime_error("Lookahead has an illegal Var operand");
368        }
369        const unsigned bit_shift = (l->getAmount() % iBuilder->getBitBlockWidth());
370        const unsigned block_shift = (l->getAmount() / iBuilder->getBitBlockWidth());
371        std::string inputName = mKernelBuilder->mStreamSetInputs[0].ssName;
372        Value * blockNo = mKernelBuilder->getScalarField(mSelf, blockNoScalar);
373        Value * lookAhead_blockPtr  = mKernelBuilder->getStreamSetBlockPtr(mSelf, inputName, iBuilder->CreateAdd(blockNo, ConstantInt::get(iBuilder->getSizeTy(), block_shift)));
374        Value * lookAhead_inputPtr = iBuilder->CreateGEP(lookAhead_blockPtr, {iBuilder->getInt32(0), iBuilder->getInt32(index)});
375        Value * lookAhead = iBuilder->CreateBlockAlignedLoad(lookAhead_inputPtr);
376        if (bit_shift == 0) {  // Simple case with no intra-block shifting.
377            expr = lookAhead; 
378        }
379        else { // Need to form shift result from two adjacent blocks.
380            Value * lookAhead_blockPtr1  = mKernelBuilder->getStreamSetBlockPtr(mSelf, inputName, iBuilder->CreateAdd(blockNo, ConstantInt::get(iBuilder->getSizeTy(), block_shift + 1)));
381            Value * lookAhead_inputPtr1 = iBuilder->CreateGEP(lookAhead_blockPtr1, {iBuilder->getInt32(0), iBuilder->getInt32(index)});
382            Value * lookAhead1 = iBuilder->CreateBlockAlignedLoad(lookAhead_inputPtr1);
383            if (LLVM_UNLIKELY((bit_shift % 8) == 0)) { // Use a single whole-byte shift, if possible.
384                expr = iBuilder->mvmd_dslli(8, lookAhead1, lookAhead, (bit_shift / 8));
385            }
386            else {
387                Type  * const streamType = iBuilder->getIntNTy(iBuilder->getBitBlockWidth());
388                Value * b1 = iBuilder->CreateBitCast(lookAhead1, streamType);
389                Value * b0 = iBuilder->CreateBitCast(lookAhead, streamType);
390                Value * result = iBuilder->CreateOr(iBuilder->CreateShl(b1, iBuilder->getBitBlockWidth() - bit_shift), iBuilder->CreateLShr(b0, bit_shift));
391                expr = iBuilder->CreateBitCast(result, mBitBlockType);
392            }
393        }
394    } else {
395        std::string tmp;
396        llvm::raw_string_ostream msg(tmp);
397        msg << "Internal error: ";
398        PabloPrinter::print(stmt, msg);
399        msg << " is not a recognized statement in the Pablo compiler.";
400        throw std::runtime_error(msg.str());
401    }
402    mMarkerMap[stmt] = expr;
403    if (DebugOptionIsSet(DumpTrace)) {
404        iBuilder->CallPrintRegister(stmt->getName()->to_string(), expr);
405    }
406   
407}
408
409Value * PabloCompiler::compileExpression(const PabloAST * expr) {
410    if (LLVM_UNLIKELY(isa<Ones>(expr))) {
411        return iBuilder->allOnes();
412    } else if (LLVM_UNLIKELY(isa<Zeroes>(expr))) {
413        return iBuilder->allZeroes();
414    }
415    auto f = mMarkerMap.find(expr);
416    if (LLVM_UNLIKELY(f == mMarkerMap.end())) {
417        std::string o;
418        llvm::raw_string_ostream str(o);
419        str << "\"";
420        PabloPrinter::print(expr, str);
421        str << "\" was used before definition!";
422        throw std::runtime_error(str.str());
423    }
424    Value * result = f->second;
425    if (LLVM_UNLIKELY(isa<Var>(expr))) {
426        assert (isa<GetElementPtrInst>(result));
427        result = iBuilder->CreateBlockAlignedLoad(result);
428    }
429    return result;
430}
431
432}
Note: See TracBrowser for help on using the repository browser.