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

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

More work on symbol table; unexpected bug with 4KiB-one page tests observed.

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