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

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

Redesigned buffer system to allow the pipeline to control selection of the current input and output streams; DoBlock? functions containing lookahead now take multiple input stream arguments. Selection and passing occurs automatically. Some work on Symbol Table.

File size: 19.9 KB
Line 
1/*
2 *  Copyright (c) 2014-15 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/codegenstate.h>
9#include <pablo/carry_data.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 <IDISA/idisa_avx_builder.h>
18#include <llvm/Pass.h>
19#include <llvm/PassManager.h>
20#include <llvm/ADT/SmallVector.h>
21#include <llvm/Analysis/Passes.h>
22#include <llvm/IR/BasicBlock.h>
23#include <llvm/IR/CallingConv.h>
24#include <llvm/IR/DataLayout.h>
25#include <llvm/IR/DerivedTypes.h>
26#include <llvm/IR/Function.h>
27#include <llvm/IR/GlobalVariable.h>
28#include <llvm/IR/InlineAsm.h>
29#include <llvm/IR/Instructions.h>
30#include <llvm/IR/LLVMContext.h>
31#include <llvm/IR/Module.h>
32#include <llvm/Support/FormattedStream.h>
33#include <llvm/Support/MathExtras.h>
34#include <llvm/Support/Casting.h>
35#include <llvm/Support/Compiler.h>
36#include <llvm/Support/Debug.h>
37#include <llvm/Support/TargetSelect.h>
38#include <llvm/Support/Host.h>
39#include <llvm/Transforms/Scalar.h>
40#include <llvm/IRReader/IRReader.h>
41#include <llvm/Bitcode/ReaderWriter.h>
42#include <llvm/Support/MemoryBuffer.h>
43#include <llvm/IR/IRBuilder.h>
44#include <llvm/Support/CommandLine.h>
45#include <llvm/ADT/Twine.h>
46#include <iostream>
47#include <llvm/Support/raw_ostream.h>
48#include <llvm/Support/FileSystem.h>
49#ifndef NDEBUG
50#include <llvm/IR/Verifier.h>
51#endif
52#include <hrtime.h>
53
54static cl::OptionCategory fTracingOptions("Run-time Tracing Options", "These options control execution traces.");
55static cl::opt<bool> DumpTrace("dump-trace", cl::init(false), cl::desc("Generate dynamic traces of executed assignments."), cl::cat(fTracingOptions));
56
57namespace pablo {
58
59#define DSSLI_FIELDWIDTH 64
60
61PabloCompiler::PabloCompiler(Module * m, IDISA::IDISA_Builder * b)
62: mMod(m)
63, iBuilder(b)
64, mBitBlockType(b->getBitBlockType())
65, mCarryManager(nullptr)
66, mPabloFunction(nullptr)
67, mPabloBlock(nullptr)
68, mKernelBuilder(nullptr)
69, mWhileDepth(0)
70, mIfDepth(0)
71, mFunction(nullptr)
72, mMaxWhileDepth(0) {
73   
74}
75
76void PabloCompiler::setKernel(kernel::KernelBuilder * kBuilder){
77    mKernelBuilder = kBuilder;
78} 
79
80llvm::Function * PabloCompiler::compile(PabloFunction * function) {
81
82    #ifdef PRINT_TIMING_INFORMATION
83    const timestamp_t pablo_compilation_start = read_cycle_counter();
84    #endif
85 
86    Examine(function);
87
88    mCarryManager = new CarryManager(iBuilder);
89
90    GenerateKernel(function);
91       
92    delete mCarryManager;
93    mCarryManager = nullptr;
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    return mFunction;
101}
102
103inline void PabloCompiler::GenerateKernel(PabloFunction * const function) {
104 
105    mPabloFunction = function;
106
107    for (unsigned i = 0; i < function->getNumOfParameters(); ++i) {
108        mKernelBuilder->addInputStream(1, function->getParameter(i)->getName()->to_string());
109    }
110    for (unsigned i = 0; i < function->getNumOfResults(); ++i) {
111        mKernelBuilder->addOutputStream(1);
112    }
113
114    mCarryManager->initialize(function, mKernelBuilder);
115
116    mFunction = mKernelBuilder->prepareFunction({mInputStreamOffset.begin(), mInputStreamOffset.end()});
117
118    mCarryManager->reset();
119
120    for (unsigned j = 0; j < function->getNumOfParameters(); ++j) {
121        Value * inputVal = mKernelBuilder->getInputStream(j);
122        const Var * const var = function->getParameter(j);
123        if (DumpTrace) {
124            iBuilder->CallPrintRegister(var->getName()->to_string(), iBuilder->CreateBlockAlignedLoad(inputVal));
125        }
126        mMarkerMap.insert(std::make_pair(var, inputVal));
127    }
128
129    compileBlock(function->getEntryBlock());
130
131    for (unsigned j = 0; j < function->getNumOfResults(); ++j) {
132        const auto f = mMarkerMap.find(function->getResult(j));
133        if (LLVM_UNLIKELY(f == mMarkerMap.end())) {
134            throw std::runtime_error("PabloCompiler: result " + std::to_string(j) + " was not assigned a value!");
135        }
136        iBuilder->CreateBlockAlignedStore(f->second, mKernelBuilder->getOutputStream(j));
137    }
138
139    mKernelBuilder->finalize();
140}
141
142inline void PabloCompiler::Examine(const PabloFunction * const function) {
143    mWhileDepth = 0;
144    mIfDepth = 0;
145    mMaxWhileDepth = 0;
146    LookaheadOffsetMap offsetMap;
147    Examine(function->getEntryBlock(), offsetMap);
148    mInputStreamOffset.clear();
149    for (const auto & oi : offsetMap) {
150        for (const auto offset : oi.second) {
151            mInputStreamOffset.insert(offset / iBuilder->getBitBlockWidth());
152        }
153    }
154}
155
156void PabloCompiler::Examine(const PabloBlock * const block, LookaheadOffsetMap & offsetMap) {
157    for (const Statement * stmt : *block) {
158         boost::container::flat_set<unsigned> offsets;
159        if (LLVM_UNLIKELY(isa<Lookahead>(stmt))) {
160            const Lookahead * const la = cast<Lookahead>(stmt);
161            assert (isa<Var>(la->getExpr()));
162            offsets.insert(la->getAmount());
163            offsets.insert(la->getAmount() + iBuilder->getBitBlockWidth() - 1);
164        } else {
165            for (unsigned i = 0; i < stmt->getNumOperands(); ++i) {
166                const PabloAST * expr = stmt->getOperand(i);
167                if (isa<Var>(expr)) {
168                    offsets.insert(0);
169                } else if (LLVM_LIKELY(isa<Statement>(expr) && !isa<Assign>(expr) && !isa<Next>(expr))) {
170                    const auto f = offsetMap.find(expr);
171                    assert (f != offsetMap.end());
172                    const auto & o = f->second;
173                    offsets.insert(o.begin(), o.end());
174                }
175            }
176            if (LLVM_UNLIKELY(isa<If>(stmt))) {
177                Examine(cast<If>(stmt)->getBody(), offsetMap);
178            } else if (LLVM_UNLIKELY(isa<While>(stmt))) {
179                mMaxWhileDepth = std::max(mMaxWhileDepth, ++mWhileDepth);
180                Examine(cast<While>(stmt)->getBody(), offsetMap);
181                --mWhileDepth;
182            }
183        }
184        offsetMap.emplace(stmt, offsets);
185    }
186}
187
188void PabloCompiler::compileBlock(const PabloBlock * const block) {
189    mPabloBlock = block;
190    for (const Statement * statement : *block) {
191        compileStatement(statement);
192    }
193    mPabloBlock = block->getParent();
194}
195
196void PabloCompiler::compileIf(const If * ifStatement) {       
197    //
198    //  The If-ElseZero stmt:
199    //  if <predicate:expr> then <body:stmt>* elsezero <defined:var>* endif
200    //  If the value of the predicate is nonzero, then determine the values of variables
201    //  <var>* by executing the given statements.  Otherwise, the value of the
202    //  variables are all zero.  Requirements: (a) no variable that is defined within
203    //  the body of the if may be accessed outside unless it is explicitly
204    //  listed in the variable list, (b) every variable in the defined list receives
205    //  a value within the body, and (c) the logical consequence of executing
206    //  the statements in the event that the predicate is zero is that the
207    //  values of all defined variables indeed work out to be 0.
208    //
209    //  Simple Implementation with Phi nodes:  a phi node in the if exit block
210    //  is inserted for each variable in the defined variable list.  It receives
211    //  a zero value from the ifentry block and the defined value from the if
212    //  body.
213    //
214
215    BasicBlock * const ifEntryBlock = iBuilder->GetInsertBlock();
216    BasicBlock * const ifBodyBlock = BasicBlock::Create(mMod->getContext(), "if.body", mFunction, 0);
217    BasicBlock * const ifEndBlock = BasicBlock::Create(mMod->getContext(), "if.end", mFunction, 0);
218   
219    PabloBlock * ifBody = ifStatement->getBody();
220   
221    Value * const condition = compileExpression(ifStatement->getCondition());
222   
223    mCarryManager->enterScope(ifBody);
224    iBuilder->CreateCondBr(mCarryManager->generateSummaryTest(condition), ifBodyBlock, ifEndBlock);
225   
226    // Entry processing is complete, now handle the body of the if.
227    iBuilder->SetInsertPoint(ifBodyBlock);
228   
229    compileBlock(ifBody);
230    BasicBlock * ifExitBlock = iBuilder->GetInsertBlock();
231
232    if (mCarryManager->hasCarries()) {
233        mCarryManager->storeCarryOutSummary();
234    }
235    mCarryManager->addOuterSummaryToNestedSummary();
236
237    iBuilder->CreateBr(ifEndBlock);
238    //End Block
239    iBuilder->SetInsertPoint(ifEndBlock);
240    for (const PabloAST * node : ifStatement->getDefined()) {
241        const Assign * assign = cast<Assign>(node);
242        PHINode * phi = iBuilder->CreatePHI(mBitBlockType, 2, assign->getName()->value());
243        auto f = mMarkerMap.find(assign);
244        assert (f != mMarkerMap.end());
245        phi->addIncoming(iBuilder->allZeroes(), ifEntryBlock);
246        phi->addIncoming(f->second, ifExitBlock);
247        mMarkerMap[assign] = phi;
248    }
249    // Create the phi Node for the summary variable, if needed.
250    mCarryManager->buildCarryDataPhisAfterIfBody(ifEntryBlock, ifExitBlock);
251    mCarryManager->leaveScope();
252}
253
254void PabloCompiler::compileWhile(const While * whileStatement) {
255
256    PabloBlock * const whileBody = whileStatement->getBody();
257   
258    BasicBlock * whileEntryBlock = iBuilder->GetInsertBlock();
259    BasicBlock * whileBodyBlock = BasicBlock::Create(mMod->getContext(), "while.body", mFunction, 0);
260    BasicBlock * whileEndBlock = BasicBlock::Create(mMod->getContext(), "while.end", mFunction, 0);
261
262    mCarryManager->enterScope(whileBody);
263    mCarryManager->ensureCarriesLoadedRecursive();
264
265    const auto & nextNodes = whileStatement->getVariants();
266    std::vector<PHINode *> nextPhis;
267    nextPhis.reserve(nextNodes.size());
268
269    // On entry to the while structure, proceed to execute the first iteration
270    // of the loop body unconditionally.   The while condition is tested at the end of
271    // the loop.
272
273    iBuilder->CreateBr(whileBodyBlock);
274    iBuilder->SetInsertPoint(whileBodyBlock);
275
276    //
277    // There are 3 sets of Phi nodes for the while loop.
278    // (1) Carry-ins: (a) incoming carry data first iterations, (b) zero thereafter
279    // (2) Carry-out accumulators: (a) zero first iteration, (b) |= carry-out of each iteration
280    // (3) Next nodes: (a) values set up before loop, (b) modified values calculated in loop.
281
282    mCarryManager->initializeWhileEntryCarryDataPhis(whileEntryBlock);
283
284    // for any Next nodes in the loop body, initialize to (a) pre-loop value.
285    for (const Next * n : nextNodes) {
286        PHINode * phi = iBuilder->CreatePHI(mBitBlockType, 2, n->getName()->value());
287        auto f = mMarkerMap.find(n->getInitial());
288        assert (f != mMarkerMap.end());
289        phi->addIncoming(f->second, whileEntryBlock);
290        mMarkerMap[n->getInitial()] = phi;
291        nextPhis.push_back(phi);
292    }
293
294    //
295    // Now compile the loop body proper.  Carry-out accumulated values
296    // and iterated values of Next nodes will be computed.
297    ++mWhileDepth;
298    compileBlock(whileBody);
299
300    BasicBlock * whileExitBlock = iBuilder->GetInsertBlock();
301
302    if (mCarryManager->hasCarries()) {
303        mCarryManager->storeCarryOutSummary();
304    }
305    mCarryManager->finalizeWhileBlockCarryDataPhis(whileExitBlock);
306
307    // Terminate the while loop body with a conditional branch back.
308    iBuilder->CreateCondBr(iBuilder->bitblock_any(compileExpression(whileStatement->getCondition())), whileBodyBlock, whileEndBlock);
309
310    // and for any Next nodes in the loop body
311    for (unsigned i = 0; i < nextNodes.size(); i++) {
312        const Next * n = nextNodes[i];
313        auto f = mMarkerMap.find(n->getExpr());
314        if (LLVM_UNLIKELY(f == mMarkerMap.end())) {
315            throw std::runtime_error("Next node expression was not compiled!");
316        }
317        nextPhis[i]->addIncoming(f->second, whileExitBlock);
318    }
319
320    iBuilder->SetInsertPoint(whileEndBlock);
321    --mWhileDepth;
322
323    mCarryManager->ensureCarriesStoredRecursive();
324    mCarryManager->leaveScope();
325}
326
327
328void PabloCompiler::compileStatement(const Statement * stmt) {
329    Value * expr = nullptr;
330    if (const Assign * assign = dyn_cast<const Assign>(stmt)) {
331        expr = compileExpression(assign->getExpression());
332    } else if (const Next * next = dyn_cast<const Next>(stmt)) {
333        expr = compileExpression(next->getExpr());
334    } else if (const If * ifStatement = dyn_cast<const If>(stmt)) {
335        compileIf(ifStatement);
336        return;
337    } else if (const While * whileStatement = dyn_cast<const While>(stmt)) {
338        compileWhile(whileStatement);
339        return;
340//    } else if (const Call* call = dyn_cast<Call>(stmt)) {
341//        // Call the callee once and store the result in the marker map.
342//        if (LLVM_UNLIKELY(mMarkerMap.count(call) == 0)) {
343//            return;
344//        }
345
346//        const Prototype * proto = call->getPrototype();
347//        const String * callee = proto->getName();
348
349//        Type * inputType = StructType::get(mMod->getContext(), std::vector<Type *>{proto->getNumOfParameters(), mBitBlockType});
350//        Type * outputType = StructType::get(mMod->getContext(), std::vector<Type *>{proto->getNumOfResults(), mBitBlockType});
351//        FunctionType * functionType = FunctionType::get(Type::getVoidTy(mMod->getContext()), std::vector<Type *>{PointerType::get(inputType, 0), PointerType::get(outputType, 0)}, false);
352
353//        //Starts on process_block
354//        SmallVector<AttributeSet, 3> Attrs;
355//        Attrs.push_back(AttributeSet::get(mMod->getContext(), 1U, std::vector<Attribute::AttrKind>({ Attribute::ReadOnly, Attribute::NoCapture })));
356//        Attrs.push_back(AttributeSet::get(mMod->getContext(), 2U, std::vector<Attribute::AttrKind>({ Attribute::ReadNone, Attribute::NoCapture })));
357//        AttributeSet AttrSet = AttributeSet::get(mMod->getContext(), Attrs);
358
359//        Function * externalFunction = cast<Function>(mMod->getOrInsertFunction(callee->value(), functionType, AttrSet));
360//        if (LLVM_UNLIKELY(externalFunction == nullptr)) {
361//            throw std::runtime_error("Could not create static method call for external function \"" + callee->to_string() + "\"");
362//        }
363//        externalFunction->setCallingConv(llvm::CallingConv::C);
364
365//        AllocaInst * outputStruct = iBuilder->CreateAlloca(outputType);
366//        iBuilder->CreateCall2(externalFunction, mInputAddressPtr, outputStruct);
367//        Value * outputPtr = iBuilder->CreateGEP(outputStruct, std::vector<Value *>({ iBuilder->getInt32(0), iBuilder->getInt32(0) }));
368
369//        expr = iBuilder->CreateBlockAlignedLoad(outputPtr);
370    } else if (const And * pablo_and = dyn_cast<And>(stmt)) {
371        expr = iBuilder->simd_and(compileExpression(pablo_and->getOperand(0)), compileExpression(pablo_and->getOperand(1)));
372    } else if (const Or * pablo_or = dyn_cast<Or>(stmt)) {
373        expr = iBuilder->simd_or(compileExpression(pablo_or->getOperand(0)), compileExpression(pablo_or->getOperand(1)));
374    } else if (const Xor * pablo_xor = dyn_cast<Xor>(stmt)) {
375        expr = iBuilder->simd_xor(compileExpression(pablo_xor->getOperand(0)), compileExpression(pablo_xor->getOperand(1)));
376    } else if (const Sel * sel = dyn_cast<Sel>(stmt)) {
377        Value* ifMask = compileExpression(sel->getCondition());
378        Value* ifTrue = iBuilder->simd_and(ifMask, compileExpression(sel->getTrueExpr()));
379        Value* ifFalse = iBuilder->simd_and(iBuilder->simd_not(ifMask), compileExpression(sel->getFalseExpr()));
380        expr = iBuilder->simd_or(ifTrue, ifFalse);
381    } else if (const Not * pablo_not = dyn_cast<Not>(stmt)) {
382        expr = iBuilder->simd_not(compileExpression(pablo_not->getExpr()));
383    } else if (const Advance * adv = dyn_cast<Advance>(stmt)) {
384        Value * const strm_value = compileExpression(adv->getExpr());
385        expr = mCarryManager->advanceCarryInCarryOut(adv->getLocalIndex(), adv->getAmount(), strm_value);
386    } else if (const MatchStar * mstar = dyn_cast<MatchStar>(stmt)) {
387        Value * const marker = compileExpression(mstar->getMarker());
388        Value * const cc = compileExpression(mstar->getCharClass());
389        Value * const marker_and_cc = iBuilder->simd_and(marker, cc);
390        Value * const sum = mCarryManager->addCarryInCarryOut(mstar->getLocalCarryIndex(), marker_and_cc, cc);
391        expr = iBuilder->simd_or(iBuilder->simd_xor(sum, cc), marker);
392    } else if (const ScanThru * sthru = dyn_cast<ScanThru>(stmt)) {
393        Value * const  marker_expr = compileExpression(sthru->getScanFrom());
394        Value * const  cc_expr = compileExpression(sthru->getScanThru());
395        Value * const  sum = mCarryManager->addCarryInCarryOut(sthru->getLocalCarryIndex(), marker_expr, cc_expr);
396        expr = iBuilder->simd_and(sum, iBuilder->simd_not(cc_expr));
397    } else if (const Count * c = dyn_cast<Count>(stmt)) {
398        Value * const to_count = compileExpression(c->getExpr());
399        expr = mCarryManager->popCount(to_count, c->getGlobalCountIndex());
400    } else if (const Lookahead * l = dyn_cast<Lookahead>(stmt)) {
401        PabloAST * const var = l->getExpr();
402        if (LLVM_UNLIKELY(!isa<Var>(var))) {
403            throw std::runtime_error("Lookahead input type must be a Var object");
404        }
405        unsigned index = 0;
406        for (; index < mPabloFunction->getNumOfParameters(); ++index) {
407            if (mPabloFunction->getParameter(index) == var) {
408                break;
409            }
410        }
411        if (LLVM_UNLIKELY(index >= mPabloFunction->getNumOfParameters())) {
412            throw std::runtime_error("Lookahead has an illegal Var operand");
413        }
414        const unsigned offset0 = (l->getAmount() / iBuilder->getBitBlockWidth());
415        const unsigned offset1 = ((l->getAmount() + iBuilder->getBitBlockWidth() - 1) / iBuilder->getBitBlockWidth());
416        const unsigned shift = (l->getAmount() % iBuilder->getBitBlockWidth());
417        Value * const v0 = iBuilder->CreateBlockAlignedLoad(mKernelBuilder->getInputStream(index, offset0));
418        Value * const v1 = iBuilder->CreateBlockAlignedLoad(mKernelBuilder->getInputStream(index, offset1));
419        if (LLVM_UNLIKELY((shift % 8) == 0)) { // Use a single whole-byte shift, if possible.
420            expr = iBuilder->mvmd_dslli(8, v1, v0, (shift / 8));
421        } else if (LLVM_LIKELY(shift < DSSLI_FIELDWIDTH)) {
422            Value * ahead = iBuilder->mvmd_dslli(DSSLI_FIELDWIDTH, v1, v0, 1);
423            ahead = iBuilder->simd_slli(DSSLI_FIELDWIDTH, ahead, DSSLI_FIELDWIDTH - shift);
424            Value * value = iBuilder->simd_srli(DSSLI_FIELDWIDTH, v0, shift);
425            expr = iBuilder->simd_or(value, ahead);
426        } else {
427            Type  * const streamType = iBuilder->getIntNTy(iBuilder->getBitBlockWidth());
428            Value * b0 = iBuilder->CreateBitCast(v0, streamType);
429            Value * b1 = iBuilder->CreateBitCast(v1, streamType);
430            Value * result = iBuilder->CreateOr(iBuilder->CreateShl(b1, iBuilder->getBitBlockWidth() - shift), iBuilder->CreateLShr(b0, shift));
431            expr = iBuilder->CreateBitCast(result, mBitBlockType);
432        }
433    } else {
434        std::string tmp;
435        llvm::raw_string_ostream msg(tmp);
436        msg << "Internal error: ";
437        PabloPrinter::print(stmt, msg);
438        msg << " is not a recognized statement in the Pablo compiler.";
439        throw std::runtime_error(msg.str());
440    }
441    mMarkerMap[stmt] = expr;
442    if (DumpTrace) {
443        iBuilder->CallPrintRegister(stmt->getName()->to_string(), expr);
444    }
445   
446}
447
448Value * PabloCompiler::compileExpression(const PabloAST * expr) {
449    if (LLVM_UNLIKELY(isa<Ones>(expr))) {
450        return iBuilder->allOnes();
451    } else if (LLVM_UNLIKELY(isa<Zeroes>(expr))) {
452        return iBuilder->allZeroes();
453    }
454    auto f = mMarkerMap.find(expr);
455    if (LLVM_UNLIKELY(f == mMarkerMap.end())) {
456        std::string o;
457        llvm::raw_string_ostream str(o);
458        str << "\"";
459        PabloPrinter::print(expr, str);
460        str << "\" was used before definition!";
461        throw std::runtime_error(str.str());
462    }
463    Value * result = f->second;
464    if (LLVM_UNLIKELY(isa<Var>(expr))) {
465        assert (isa<GetElementPtrInst>(result));
466        result = iBuilder->CreateBlockAlignedLoad(result);
467    }
468    return result;
469}
470
471}
Note: See TracBrowser for help on using the repository browser.