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

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

First attempt at dynamic segment size intergration.

File size: 18.4 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();
117
118    mCarryManager->reset();
119
120    for (unsigned j = 0; j < function->getNumOfParameters(); ++j) {
121        Value * inputVal = mKernelBuilder->getInputStream(j);
122        if (DumpTrace) {
123            iBuilder->CallPrintRegister("param" + std::to_string(j + 1), iBuilder->CreateBlockAlignedLoad(inputVal));
124        }
125        mMarkerMap.insert(std::make_pair(function->getParameter(j), inputVal));
126    }
127
128    compileBlock(function->getEntryBlock());
129
130    for (unsigned j = 0; j < function->getNumOfResults(); ++j) {
131        const auto f = mMarkerMap.find(function->getResult(j));
132        Value * result = nullptr;
133        if (LLVM_UNLIKELY(f == mMarkerMap.end())) {
134            result = iBuilder->allZeroes();
135        } else {
136            result = f->second;
137        }
138        iBuilder->CreateBlockAlignedStore(result, mKernelBuilder->getOutputStream(j));
139    }
140
141    mKernelBuilder->finalize();
142}
143
144inline void PabloCompiler::Examine(PabloFunction & function) {
145    mWhileDepth = 0;
146    mIfDepth = 0;
147    mMaxWhileDepth = 0;
148    Examine(function.getEntryBlock());
149}
150
151void PabloCompiler::Examine(PabloBlock * block) {
152    for (Statement * stmt : *block) {
153        if (LLVM_UNLIKELY(isa<If>(stmt))) {
154            Examine(cast<If>(stmt)->getBody());
155        } else if (LLVM_UNLIKELY(isa<While>(stmt))) {
156            mMaxWhileDepth = std::max(mMaxWhileDepth, ++mWhileDepth);
157            Examine(cast<While>(stmt)->getBody());
158            --mWhileDepth;
159        }
160    }
161}
162
163void PabloCompiler::compileBlock(const PabloBlock * const block) {
164    mPabloBlock = block;
165    for (const Statement * statement : *block) {
166        compileStatement(statement);
167    }
168    mPabloBlock = block->getParent();
169}
170
171void PabloCompiler::compileIf(const If * ifStatement) {       
172    //
173    //  The If-ElseZero stmt:
174    //  if <predicate:expr> then <body:stmt>* elsezero <defined:var>* endif
175    //  If the value of the predicate is nonzero, then determine the values of variables
176    //  <var>* by executing the given statements.  Otherwise, the value of the
177    //  variables are all zero.  Requirements: (a) no variable that is defined within
178    //  the body of the if may be accessed outside unless it is explicitly
179    //  listed in the variable list, (b) every variable in the defined list receives
180    //  a value within the body, and (c) the logical consequence of executing
181    //  the statements in the event that the predicate is zero is that the
182    //  values of all defined variables indeed work out to be 0.
183    //
184    //  Simple Implementation with Phi nodes:  a phi node in the if exit block
185    //  is inserted for each variable in the defined variable list.  It receives
186    //  a zero value from the ifentry block and the defined value from the if
187    //  body.
188    //
189
190    BasicBlock * const ifEntryBlock = iBuilder->GetInsertBlock();
191    BasicBlock * const ifBodyBlock = BasicBlock::Create(mMod->getContext(), "if.body", mFunction, 0);
192    BasicBlock * const ifEndBlock = BasicBlock::Create(mMod->getContext(), "if.end", mFunction, 0);
193   
194    PabloBlock * ifBody = ifStatement->getBody();
195   
196    Value * const condition = compileExpression(ifStatement->getCondition());
197   
198    mCarryManager->enterScope(ifBody);
199    iBuilder->CreateCondBr(mCarryManager->generateSummaryTest(condition), ifBodyBlock, ifEndBlock);
200   
201    // Entry processing is complete, now handle the body of the if.
202    iBuilder->SetInsertPoint(ifBodyBlock);
203   
204    compileBlock(ifBody);
205    BasicBlock * ifExitBlock = iBuilder->GetInsertBlock();
206
207    if (mCarryManager->hasCarries()) {
208        mCarryManager->storeCarryOutSummary();
209    }
210    mCarryManager->addOuterSummaryToNestedSummary();
211
212    iBuilder->CreateBr(ifEndBlock);
213    //End Block
214    iBuilder->SetInsertPoint(ifEndBlock);
215    for (const PabloAST * node : ifStatement->getDefined()) {
216        const Assign * assign = cast<Assign>(node);
217        PHINode * phi = iBuilder->CreatePHI(mBitBlockType, 2, assign->getName()->value());
218        auto f = mMarkerMap.find(assign);
219        assert (f != mMarkerMap.end());
220        phi->addIncoming(iBuilder->allZeroes(), ifEntryBlock);
221        phi->addIncoming(f->second, ifExitBlock);
222        mMarkerMap[assign] = phi;
223    }
224    // Create the phi Node for the summary variable, if needed.
225    mCarryManager->buildCarryDataPhisAfterIfBody(ifEntryBlock, ifExitBlock);
226    mCarryManager->leaveScope();
227}
228
229void PabloCompiler::compileWhile(const While * whileStatement) {
230
231    PabloBlock * const whileBody = whileStatement->getBody();
232   
233    BasicBlock * whileEntryBlock = iBuilder->GetInsertBlock();
234    BasicBlock * whileBodyBlock = BasicBlock::Create(mMod->getContext(), "while.body", mFunction, 0);
235    BasicBlock * whileEndBlock = BasicBlock::Create(mMod->getContext(), "while.end", mFunction, 0);
236
237    mCarryManager->enterScope(whileBody);
238    mCarryManager->ensureCarriesLoadedRecursive();
239
240    const auto & nextNodes = whileStatement->getVariants();
241    std::vector<PHINode *> nextPhis;
242    nextPhis.reserve(nextNodes.size());
243
244    // On entry to the while structure, proceed to execute the first iteration
245    // of the loop body unconditionally.   The while condition is tested at the end of
246    // the loop.
247
248    iBuilder->CreateBr(whileBodyBlock);
249    iBuilder->SetInsertPoint(whileBodyBlock);
250
251    //
252    // There are 3 sets of Phi nodes for the while loop.
253    // (1) Carry-ins: (a) incoming carry data first iterations, (b) zero thereafter
254    // (2) Carry-out accumulators: (a) zero first iteration, (b) |= carry-out of each iteration
255    // (3) Next nodes: (a) values set up before loop, (b) modified values calculated in loop.
256
257    mCarryManager->initializeWhileEntryCarryDataPhis(whileEntryBlock);
258
259    // for any Next nodes in the loop body, initialize to (a) pre-loop value.
260    for (const Next * n : nextNodes) {
261        PHINode * phi = iBuilder->CreatePHI(mBitBlockType, 2, n->getName()->value());
262        auto f = mMarkerMap.find(n->getInitial());
263        assert (f != mMarkerMap.end());
264        phi->addIncoming(f->second, whileEntryBlock);
265        mMarkerMap[n->getInitial()] = phi;
266        nextPhis.push_back(phi);
267    }
268
269    //
270    // Now compile the loop body proper.  Carry-out accumulated values
271    // and iterated values of Next nodes will be computed.
272    ++mWhileDepth;
273    compileBlock(whileBody);
274
275    BasicBlock * whileExitBlock = iBuilder->GetInsertBlock();
276
277    if (mCarryManager->hasCarries()) {
278        mCarryManager->storeCarryOutSummary();
279    }
280    mCarryManager->finalizeWhileBlockCarryDataPhis(whileExitBlock);
281
282    // Terminate the while loop body with a conditional branch back.
283    iBuilder->CreateCondBr(iBuilder->bitblock_any(compileExpression(whileStatement->getCondition())), whileBodyBlock, whileEndBlock);
284
285    // and for any Next nodes in the loop body
286    for (unsigned i = 0; i < nextNodes.size(); i++) {
287        const Next * n = nextNodes[i];
288        auto f = mMarkerMap.find(n->getExpr());
289        if (LLVM_UNLIKELY(f == mMarkerMap.end())) {
290            throw std::runtime_error("Next node expression was not compiled!");
291        }
292        nextPhis[i]->addIncoming(f->second, whileExitBlock);
293    }
294
295    iBuilder->SetInsertPoint(whileEndBlock);
296    --mWhileDepth;
297
298    mCarryManager->ensureCarriesStoredRecursive();
299    mCarryManager->leaveScope();
300}
301
302
303void PabloCompiler::compileStatement(const Statement * stmt) {
304    Value * expr = nullptr;
305    if (const Assign * assign = dyn_cast<const Assign>(stmt)) {
306        expr = compileExpression(assign->getExpression());
307    } else if (const Next * next = dyn_cast<const Next>(stmt)) {
308        expr = compileExpression(next->getExpr());
309    } else if (const If * ifStatement = dyn_cast<const If>(stmt)) {
310        compileIf(ifStatement);
311        return;
312    } else if (const While * whileStatement = dyn_cast<const While>(stmt)) {
313        compileWhile(whileStatement);
314        return;
315//    } else if (const Call* call = dyn_cast<Call>(stmt)) {
316//        // Call the callee once and store the result in the marker map.
317//        if (LLVM_UNLIKELY(mMarkerMap.count(call) == 0)) {
318//            return;
319//        }
320
321//        const Prototype * proto = call->getPrototype();
322//        const String * callee = proto->getName();
323
324//        Type * inputType = StructType::get(mMod->getContext(), std::vector<Type *>{proto->getNumOfParameters(), mBitBlockType});
325//        Type * outputType = StructType::get(mMod->getContext(), std::vector<Type *>{proto->getNumOfResults(), mBitBlockType});
326//        FunctionType * functionType = FunctionType::get(Type::getVoidTy(mMod->getContext()), std::vector<Type *>{PointerType::get(inputType, 0), PointerType::get(outputType, 0)}, false);
327
328//        //Starts on process_block
329//        SmallVector<AttributeSet, 3> Attrs;
330//        Attrs.push_back(AttributeSet::get(mMod->getContext(), 1U, std::vector<Attribute::AttrKind>({ Attribute::ReadOnly, Attribute::NoCapture })));
331//        Attrs.push_back(AttributeSet::get(mMod->getContext(), 2U, std::vector<Attribute::AttrKind>({ Attribute::ReadNone, Attribute::NoCapture })));
332//        AttributeSet AttrSet = AttributeSet::get(mMod->getContext(), Attrs);
333
334//        Function * externalFunction = cast<Function>(mMod->getOrInsertFunction(callee->value(), functionType, AttrSet));
335//        if (LLVM_UNLIKELY(externalFunction == nullptr)) {
336//            throw std::runtime_error("Could not create static method call for external function \"" + callee->to_string() + "\"");
337//        }
338//        externalFunction->setCallingConv(llvm::CallingConv::C);
339
340//        AllocaInst * outputStruct = iBuilder->CreateAlloca(outputType);
341//        iBuilder->CreateCall2(externalFunction, mInputAddressPtr, outputStruct);
342//        Value * outputPtr = iBuilder->CreateGEP(outputStruct, std::vector<Value *>({ iBuilder->getInt32(0), iBuilder->getInt32(0) }));
343
344//        expr = iBuilder->CreateBlockAlignedLoad(outputPtr);
345    } else if (const And * pablo_and = dyn_cast<And>(stmt)) {
346        expr = iBuilder->simd_and(compileExpression(pablo_and->getOperand(0)), compileExpression(pablo_and->getOperand(1)));
347    } else if (const Or * pablo_or = dyn_cast<Or>(stmt)) {
348        expr = iBuilder->simd_or(compileExpression(pablo_or->getOperand(0)), compileExpression(pablo_or->getOperand(1)));
349    } else if (const Xor * pablo_xor = dyn_cast<Xor>(stmt)) {
350        expr = iBuilder->simd_xor(compileExpression(pablo_xor->getOperand(0)), compileExpression(pablo_xor->getOperand(1)));
351    } else if (const Sel * sel = dyn_cast<Sel>(stmt)) {
352        Value* ifMask = compileExpression(sel->getCondition());
353        Value* ifTrue = iBuilder->simd_and(ifMask, compileExpression(sel->getTrueExpr()));
354        Value* ifFalse = iBuilder->simd_and(iBuilder->simd_not(ifMask), compileExpression(sel->getFalseExpr()));
355        expr = iBuilder->simd_or(ifTrue, ifFalse);
356    } else if (const Not * pablo_not = dyn_cast<Not>(stmt)) {
357        expr = iBuilder->simd_not(compileExpression(pablo_not->getExpr()));
358    } else if (const Advance * adv = dyn_cast<Advance>(stmt)) {
359        Value * const strm_value = compileExpression(adv->getExpr());
360        expr = mCarryManager->advanceCarryInCarryOut(adv->getLocalIndex(), adv->getAmount(), strm_value);
361    } else if (const MatchStar * mstar = dyn_cast<MatchStar>(stmt)) {
362        Value * const marker = compileExpression(mstar->getMarker());
363        Value * const cc = compileExpression(mstar->getCharClass());
364        Value * const marker_and_cc = iBuilder->simd_and(marker, cc);
365        Value * const sum = mCarryManager->addCarryInCarryOut(mstar->getLocalCarryIndex(), marker_and_cc, cc);
366        expr = iBuilder->simd_or(iBuilder->simd_xor(sum, cc), marker);
367    } else if (const ScanThru * sthru = dyn_cast<ScanThru>(stmt)) {
368        Value * const  marker_expr = compileExpression(sthru->getScanFrom());
369        Value * const  cc_expr = compileExpression(sthru->getScanThru());
370        Value * const  sum = mCarryManager->addCarryInCarryOut(sthru->getLocalCarryIndex(), marker_expr, cc_expr);
371        expr = iBuilder->simd_and(sum, iBuilder->simd_not(cc_expr));
372    } else if (const Count * c = dyn_cast<Count>(stmt)) {
373        Value * const to_count = compileExpression(c->getExpr());
374        expr = mCarryManager->popCount(to_count, c->getGlobalCountIndex());
375    } else if (const Lookahead * l = dyn_cast<Lookahead>(stmt)) {
376        PabloAST * const var = l->getExpr();
377        if (LLVM_UNLIKELY(!isa<Var>(var))) {
378            throw std::runtime_error("Lookahead input type must be a Var object");
379        }
380        unsigned index = 0;
381        for (; index < mPabloFunction->getNumOfParameters(); ++index) {
382            if (mPabloFunction->getParameter(index) == var) {
383                break;
384            }
385        }
386        if (LLVM_UNLIKELY(index >= mPabloFunction->getNumOfParameters())) {
387            throw std::runtime_error("Lookahead has an illegal Var operand");
388        }
389        const unsigned offset = l->getAmount() / iBuilder->getBitBlockWidth();
390        const unsigned shift = (l->getAmount() % iBuilder->getBitBlockWidth());
391        Value * const v0 = iBuilder->CreateBlockAlignedLoad(mKernelBuilder->getInputStream(index, offset));
392        Value * const v1 = iBuilder->CreateBlockAlignedLoad(mKernelBuilder->getInputStream(index, offset + 1));
393        if (LLVM_UNLIKELY((shift % 8) == 0)) { // Use a single whole-byte shift, if possible.
394            expr = iBuilder->mvmd_dslli(8, v1, v0, (shift / 8));
395        } else if (LLVM_LIKELY(shift < DSSLI_FIELDWIDTH)) {
396            Value * ahead = iBuilder->mvmd_dslli(DSSLI_FIELDWIDTH, v1, v0, 1);
397            ahead = iBuilder->simd_slli(DSSLI_FIELDWIDTH, ahead, DSSLI_FIELDWIDTH - shift);
398            Value * value = iBuilder->simd_srli(DSSLI_FIELDWIDTH, v0, shift);
399            expr = iBuilder->simd_or(value, ahead);
400        } else {
401            Type  * const streamType = iBuilder->getIntNTy(iBuilder->getBitBlockWidth());
402            Value * b0 = iBuilder->CreateBitCast(v0, streamType);
403            Value * b1 = iBuilder->CreateBitCast(v1, streamType);
404            Value * result = iBuilder->CreateOr(iBuilder->CreateShl(b1, iBuilder->getBitBlockWidth() - shift), iBuilder->CreateLShr(b0, shift));
405            expr = iBuilder->CreateBitCast(result, mBitBlockType);
406        }
407    } else {
408        std::string tmp;
409        llvm::raw_string_ostream msg(tmp);
410        msg << "Internal error: ";
411        PabloPrinter::print(stmt, msg);
412        msg << " is not a recognized statement in the Pablo compiler.";
413        throw std::runtime_error(msg.str());
414    }
415    mMarkerMap[stmt] = expr;
416    if (DumpTrace) {
417        iBuilder->CallPrintRegister(stmt->getName()->to_string(), expr);
418    }
419   
420}
421
422Value * PabloCompiler::compileExpression(const PabloAST * expr) {
423    if (LLVM_UNLIKELY(isa<Ones>(expr))) {
424        return iBuilder->allOnes();
425    } else if (LLVM_UNLIKELY(isa<Zeroes>(expr))) {
426        return iBuilder->allZeroes();
427    }
428    auto f = mMarkerMap.find(expr);
429    if (LLVM_UNLIKELY(f == mMarkerMap.end())) {
430        std::string o;
431        llvm::raw_string_ostream str(o);
432        str << "\"";
433        PabloPrinter::print(expr, str);
434        str << "\" was used before definition!";
435        throw std::runtime_error(str.str());
436    }
437    Value * result = f->second;
438    if (LLVM_UNLIKELY(isa<Var>(expr))) {
439        assert (isa<GetElementPtrInst>(result));
440        result = iBuilder->CreateBlockAlignedLoad(result);
441    }
442    return result;
443}
444
445}
Note: See TracBrowser for help on using the repository browser.