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

Last change on this file since 4827 was 4827, checked in by cameron, 4 years ago

Parameterize carry_manager to inherit BitBlockWidth? from idisa builder

File size: 22.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 <include/simd-lib/bitblock.hpp>
16#include <sstream>
17#include <IDISA/idisa_builder.h>
18#include <llvm/IR/Verifier.h>
19#include <llvm/Pass.h>
20#include <llvm/PassManager.h>
21#include <llvm/ADT/SmallVector.h>
22#include <llvm/Analysis/Passes.h>
23#include <llvm/IR/BasicBlock.h>
24#include <llvm/IR/CallingConv.h>
25#include <llvm/IR/DataLayout.h>
26#include <llvm/IR/DerivedTypes.h>
27#include <llvm/IR/Function.h>
28#include <llvm/IR/GlobalVariable.h>
29#include <llvm/IR/InlineAsm.h>
30#include <llvm/IR/Instructions.h>
31#include <llvm/IR/LLVMContext.h>
32#include <llvm/IR/Module.h>
33#include <llvm/Support/FormattedStream.h>
34#include <llvm/Support/MathExtras.h>
35#include <llvm/Support/Casting.h>
36#include <llvm/Support/Compiler.h>
37#include <llvm/Support/Debug.h>
38#include <llvm/Support/TargetSelect.h>
39#include <llvm/Support/Host.h>
40#include <llvm/Transforms/Scalar.h>
41#include <llvm/IRReader/IRReader.h>
42#include <llvm/Bitcode/ReaderWriter.h>
43#include <llvm/Support/MemoryBuffer.h>
44#include <llvm/IR/IRBuilder.h>
45#include <llvm/Support/CommandLine.h>
46#include <llvm/ADT/Twine.h>
47#include <iostream>
48
49static cl::OptionCategory eIRDumpOptions("LLVM IR Dump Options", "These options control dumping of LLVM IR.");
50static cl::opt<bool> DumpGeneratedIR("dump-generated-IR", cl::init(false), cl::desc("Print LLVM IR generated by Pablo Compiler."), cl::cat(eIRDumpOptions));
51
52static cl::OptionCategory fTracingOptions("Run-time Tracing Options", "These options control execution traces.");
53static cl::opt<bool> DumpTrace("dump-trace", cl::init(false), cl::desc("Generate dynamic traces of executed assignments."), cl::cat(fTracingOptions));
54
55namespace pablo {
56
57PabloCompiler::PabloCompiler()
58: mMod(nullptr)
59, mBuilder(nullptr)
60, mCarryManager(nullptr)
61, mBitBlockType(VectorType::get(IntegerType::get(getGlobalContext(), 64), BLOCK_SIZE / 64))
62, iBuilder(mBitBlockType)
63, mInputType(nullptr)
64, mWhileDepth(0)
65, mIfDepth(0)
66, mFunction(nullptr)
67, mInputAddressPtr(nullptr)
68, mOutputAddressPtr(nullptr)
69, mMaxWhileDepth(0)
70, mPrintRegisterFunction(nullptr) {
71
72}
73
74PabloCompiler::~PabloCompiler() {
75}
76   
77
78void PabloCompiler::genPrintRegister(std::string regName, Value * bitblockValue) {
79    Constant * regNameData = ConstantDataArray::getString(mMod->getContext(), regName);
80    GlobalVariable *regStrVar = new GlobalVariable(*mMod,
81                                                   ArrayType::get(IntegerType::get(mMod->getContext(), 8), regName.length()+1),
82                                                   /*isConstant=*/ true,
83                                                   /*Linkage=*/ GlobalValue::PrivateLinkage,
84                                                   /*Initializer=*/ regNameData);
85    Value * regStrPtr = mBuilder->CreateGEP(regStrVar, std::vector<Value *>({mBuilder->getInt64(0), mBuilder->getInt32(0)}));
86    mBuilder->CreateCall(mPrintRegisterFunction, std::vector<Value *>({regStrPtr, bitblockValue}));
87}
88
89llvm::Function * PabloCompiler::compile(PabloFunction * function) {
90    Module * module = new Module("", getGlobalContext());
91   
92    auto func = compile(function, module);
93   
94    //Display the IR that has been generated by this module.
95    if (LLVM_UNLIKELY(DumpGeneratedIR)) {
96        module->dump();
97    }
98    //Create a verifier.  The verifier will print an error message if our module is malformed in any way.
99    verifyModule(*module, &dbgs());
100
101    return func;
102}
103
104llvm::Function * PabloCompiler::compile(PabloFunction * function, Module * module) {
105
106 
107    PabloBlock & mainScope = function->getEntryBlock();
108
109    mainScope.enumerateScopes(0);
110   
111    Examine(*function);
112
113    mMod = module;
114
115    mBuilder = new IRBuilder<>(mMod->getContext());
116
117    iBuilder.initialize(mMod, mBuilder);
118
119    mCarryManager = new CarryManager(mBuilder, &iBuilder);
120   
121    if (DumpTrace) DeclareDebugFunctions();
122       
123    GenerateFunction(*function);
124   
125    mBuilder->SetInsertPoint(BasicBlock::Create(mMod->getContext(), "entry", mFunction,0));
126
127    //The basis bits structure
128    for (unsigned i = 0; i != function->getNumOfParameters(); ++i) {
129        Value* indices[] = {mBuilder->getInt64(0), mBuilder->getInt32(i)};
130        Value * gep = mBuilder->CreateGEP(mInputAddressPtr, indices);
131        LoadInst * basisBit = mBuilder->CreateAlignedLoad(gep, iBuilder.getBitBlockWidth()/8, false, function->getParameter(i)->getName()->to_string());
132        mMarkerMap[function->getParameter(i)] = basisBit;
133        if (DumpTrace) {
134            genPrintRegister(function->getParameter(i)->getName()->to_string(), basisBit);
135        }
136    }
137     
138    //Generate the IR instructions for the function.
139   
140    mCarryManager->initialize(mMod, &mainScope);
141   
142    compileBlock(mainScope);
143   
144    mCarryManager->ensureCarriesStoredLocal();
145    mCarryManager->leaveScope();
146   
147   
148    mCarryManager->generateBlockNoIncrement();
149
150    if (DumpTrace) {
151        genPrintRegister("mBlockNo", mBuilder->CreateAlignedLoad(mBuilder->CreateBitCast(mCarryManager->getBlockNoPtr(), PointerType::get(mBitBlockType, 0)), iBuilder.getBitBlockWidth()/8, false));
152    }
153   
154    // Write the output values out
155    for (unsigned i = 0; i != function->getNumOfResults(); ++i) {
156        assert (function->getResult(i));
157        SetOutputValue(mMarkerMap[function->getResult(i)], i);
158    }
159
160    //Terminate the block
161    ReturnInst::Create(mMod->getContext(), mBuilder->GetInsertBlock());
162   
163    // Clean up
164    delete mCarryManager; mCarryManager = nullptr;
165    delete mBuilder; mBuilder = nullptr;
166    mMod = nullptr; // don't delete this. It's either owned by the ExecutionEngine or the calling function.
167
168    return mFunction;
169}
170
171inline void PabloCompiler::GenerateFunction(PabloFunction & function) {
172    mInputType = PointerType::get(StructType::get(mMod->getContext(), std::vector<Type *>(function.getNumOfParameters(), mBitBlockType)), 0);
173    Type * outputType = PointerType::get(StructType::get(mMod->getContext(), std::vector<Type *>(function.getNumOfResults(), mBitBlockType)), 0);
174    FunctionType * functionType = FunctionType::get(Type::getVoidTy(mMod->getContext()), std::vector<Type *>({mInputType, outputType}), false);
175
176
177    //Starts on process_block
178    SmallVector<AttributeSet, 3> Attrs;
179    Attrs.push_back(AttributeSet::get(mMod->getContext(), ~0U, std::vector<Attribute::AttrKind>({ Attribute::NoUnwind, Attribute::UWTable })));
180    Attrs.push_back(AttributeSet::get(mMod->getContext(), 1U, std::vector<Attribute::AttrKind>({ Attribute::ReadOnly, Attribute::NoCapture })));
181    Attrs.push_back(AttributeSet::get(mMod->getContext(), 2U, std::vector<Attribute::AttrKind>({ Attribute::ReadNone, Attribute::NoCapture })));
182    AttributeSet AttrSet = AttributeSet::get(mMod->getContext(), Attrs);
183
184    // Create the function that will be generated.
185    mFunction = Function::Create(functionType, GlobalValue::ExternalLinkage, function.getName()->value(), mMod);
186    mFunction->setCallingConv(CallingConv::C);
187    mFunction->setAttributes(AttrSet);
188
189    Function::arg_iterator args = mFunction->arg_begin();
190    mInputAddressPtr = args++;
191    mInputAddressPtr->setName("input");
192    mOutputAddressPtr = args++;
193    mOutputAddressPtr->setName("output");
194}
195
196inline void PabloCompiler::Examine(PabloFunction & function) {
197    mWhileDepth = 0;
198    mIfDepth = 0;
199    mMaxWhileDepth = 0;
200    Examine(function.getEntryBlock());
201    if (LLVM_UNLIKELY(mWhileDepth != 0 || mIfDepth != 0)) {
202        throw std::runtime_error("Malformed Pablo AST: Unbalanced If or While nesting depth!");
203    }
204}
205
206
207void PabloCompiler::Examine(PabloBlock & block) {
208    for (Statement * stmt : block) {
209        if (If * ifStatement = dyn_cast<If>(stmt)) {
210            Examine(ifStatement->getBody());
211        }
212        else if (While * whileStatement = dyn_cast<While>(stmt)) {
213            mMaxWhileDepth = std::max(mMaxWhileDepth, ++mWhileDepth);
214            Examine(whileStatement->getBody());
215            --mWhileDepth;
216        }
217    }
218}
219
220inline void PabloCompiler::DeclareDebugFunctions() {
221        //This function can be used for testing to print the contents of a register from JIT'd code to the terminal window.
222        mPrintRegisterFunction = mMod->getOrInsertFunction("wrapped_print_register", Type::getVoidTy(mMod->getContext()), Type::getInt8PtrTy(mMod->getContext()), mBitBlockType, NULL);
223}
224
225void PabloCompiler::compileBlock(PabloBlock & block) {
226    mPabloBlock = & block;
227    for (const Statement * statement : block) {
228        compileStatement(statement);
229    }
230    mPabloBlock = block.getParent();
231}
232
233    Value * PabloCompiler::genBitTest2(Value * e1, Value * e2) {
234        Type * t1 = e1->getType();
235        Type * t2 = e2->getType();
236        if (t1 == mBitBlockType) {
237            if (t2 == mBitBlockType) {
238                return iBuilder.bitblock_any(mBuilder->CreateOr(e1, e2));
239            }
240            else {
241                Value * m1 = mBuilder->CreateZExt(iBuilder.hsimd_signmask(16, e1), t2);
242                return mBuilder->CreateICmpNE(mBuilder->CreateOr(m1, e2), ConstantInt::get(t2, 0));
243            }
244        }
245        else if (t2 == mBitBlockType) {
246            Value * m2 = mBuilder->CreateZExt(iBuilder.hsimd_signmask(16, e2), t1);
247            return mBuilder->CreateICmpNE(mBuilder->CreateOr(e1, m2), ConstantInt::get(t1, 0));
248        }
249        else {
250            return mBuilder->CreateICmpNE(mBuilder->CreateOr(e1, e2), ConstantInt::get(t1, 0));
251        }
252    }
253   
254void PabloCompiler::compileIf(const If * ifStatement) {       
255    //
256    //  The If-ElseZero stmt:
257    //  if <predicate:expr> then <body:stmt>* elsezero <defined:var>* endif
258    //  If the value of the predicate is nonzero, then determine the values of variables
259    //  <var>* by executing the given statements.  Otherwise, the value of the
260    //  variables are all zero.  Requirements: (a) no variable that is defined within
261    //  the body of the if may be accessed outside unless it is explicitly
262    //  listed in the variable list, (b) every variable in the defined list receives
263    //  a value within the body, and (c) the logical consequence of executing
264    //  the statements in the event that the predicate is zero is that the
265    //  values of all defined variables indeed work out to be 0.
266    //
267    //  Simple Implementation with Phi nodes:  a phi node in the if exit block
268    //  is inserted for each variable in the defined variable list.  It receives
269    //  a zero value from the ifentry block and the defined value from the if
270    //  body.
271    //
272
273    BasicBlock * ifEntryBlock = mBuilder->GetInsertBlock();
274    BasicBlock * ifBodyBlock = BasicBlock::Create(mMod->getContext(), "if.body", mFunction, 0);
275    BasicBlock * ifEndBlock = BasicBlock::Create(mMod->getContext(), "if.end", mFunction, 0);
276   
277    PabloBlock & ifBody = ifStatement -> getBody();
278   
279    Value * if_test_value = compileExpression(ifStatement->getCondition());
280   
281    mCarryManager->enterScope(&ifBody);
282    if (mCarryManager->blockHasCarries()) {
283        // load the summary variable
284        Value* last_if_pending_data = mCarryManager->getCarrySummaryExpr();
285        mBuilder->CreateCondBr(genBitTest2(if_test_value, last_if_pending_data), ifBodyBlock, ifEndBlock);
286
287    }
288    else {
289        mBuilder->CreateCondBr(iBuilder.bitblock_any(if_test_value), ifBodyBlock, ifEndBlock);
290    }
291    // Entry processing is complete, now handle the body of the if.
292    mBuilder->SetInsertPoint(ifBodyBlock);
293   
294    mCarryManager->initializeCarryDataAtIfEntry();
295    compileBlock(ifBody);
296    if (mCarryManager->blockHasCarries()) {
297        mCarryManager->generateCarryOutSummaryCodeIfNeeded();
298    }
299    BasicBlock * ifBodyFinalBlock = mBuilder->GetInsertBlock();
300    mCarryManager->ensureCarriesStoredLocal();
301    mBuilder->CreateBr(ifEndBlock);
302    //End Block
303    mBuilder->SetInsertPoint(ifEndBlock);
304    for (const PabloAST * node : ifStatement->getDefined()) {
305        const Assign * assign = cast<Assign>(node);
306        PHINode * phi = mBuilder->CreatePHI(mBitBlockType, 2, assign->getName()->value());
307        auto f = mMarkerMap.find(assign);
308        assert (f != mMarkerMap.end());
309        phi->addIncoming(iBuilder.allZeroes(), ifEntryBlock);
310        phi->addIncoming(f->second, ifBodyFinalBlock);
311        mMarkerMap[assign] = phi;
312    }
313    // Create the phi Node for the summary variable, if needed.
314    mCarryManager->buildCarryDataPhisAfterIfBody(ifEntryBlock, ifBodyFinalBlock);
315    mCarryManager->leaveScope();
316}
317
318void PabloCompiler::compileWhile(const While * whileStatement) {
319
320    PabloBlock & whileBody = whileStatement -> getBody();
321   
322    BasicBlock * whileEntryBlock = mBuilder->GetInsertBlock();
323    BasicBlock * whileBodyBlock = BasicBlock::Create(mMod->getContext(), "while.body", mFunction, 0);
324    BasicBlock * whileEndBlock = BasicBlock::Create(mMod->getContext(), "while.end", mFunction, 0);
325
326    mCarryManager->enterScope(&whileBody);
327    mCarryManager->ensureCarriesLoadedRecursive();
328
329    const auto & nextNodes = whileStatement->getVariants();
330    std::vector<PHINode *> nextPhis;
331    nextPhis.reserve(nextNodes.size());
332
333    // On entry to the while structure, proceed to execute the first iteration
334    // of the loop body unconditionally.   The while condition is tested at the end of
335    // the loop.
336
337    mBuilder->CreateBr(whileBodyBlock);
338    mBuilder->SetInsertPoint(whileBodyBlock);
339
340    //
341    // There are 3 sets of Phi nodes for the while loop.
342    // (1) Carry-ins: (a) incoming carry data first iterations, (b) zero thereafter
343    // (2) Carry-out accumulators: (a) zero first iteration, (b) |= carry-out of each iteration
344    // (3) Next nodes: (a) values set up before loop, (b) modified values calculated in loop.
345
346    mCarryManager->initializeCarryDataPhisAtWhileEntry(whileEntryBlock);
347
348    // for any Next nodes in the loop body, initialize to (a) pre-loop value.
349    for (const Next * n : nextNodes) {
350        PHINode * phi = mBuilder->CreatePHI(mBitBlockType, 2, n->getName()->value());
351        auto f = mMarkerMap.find(n->getInitial());
352        assert (f != mMarkerMap.end());
353        phi->addIncoming(f->second, whileEntryBlock);
354        mMarkerMap[n->getInitial()] = phi;
355        nextPhis.push_back(phi);
356    }
357
358    //
359    // Now compile the loop body proper.  Carry-out accumulated values
360    // and iterated values of Next nodes will be computed.
361    ++mWhileDepth;
362    compileBlock(whileBody);
363
364    BasicBlock * whileBodyFinalBlock = mBuilder->GetInsertBlock();
365
366    if (mCarryManager->blockHasCarries()) {
367        mCarryManager->generateCarryOutSummaryCodeIfNeeded();
368    }
369    mCarryManager->extendCarryDataPhisAtWhileBodyFinalBlock(whileBodyFinalBlock);
370
371    // Terminate the while loop body with a conditional branch back.
372    mBuilder->CreateCondBr(iBuilder.bitblock_any(compileExpression(whileStatement->getCondition())), whileBodyBlock, whileEndBlock);
373
374    // and for any Next nodes in the loop body
375    for (unsigned i = 0; i < nextNodes.size(); i++) {
376        const Next * n = nextNodes[i];
377        auto f = mMarkerMap.find(n->getExpr());
378        if (LLVM_UNLIKELY(f == mMarkerMap.end())) {
379            throw std::runtime_error("Next node expression was not compiled!");
380        }
381        nextPhis[i]->addIncoming(f->second, whileBodyFinalBlock);
382    }
383
384    mBuilder->SetInsertPoint(whileEndBlock);
385    --mWhileDepth;
386
387    mCarryManager->ensureCarriesStoredRecursive();
388    mCarryManager->leaveScope();
389}
390
391
392void PabloCompiler::compileStatement(const Statement * stmt) {
393    Value * expr = nullptr;
394    if (const Assign * assign = dyn_cast<const Assign>(stmt)) {
395        expr = compileExpression(assign->getExpression());
396    }
397    else if (const Next * next = dyn_cast<const Next>(stmt)) {
398        expr = compileExpression(next->getExpr());
399    }
400    else if (const If * ifStatement = dyn_cast<const If>(stmt)) {
401        compileIf(ifStatement);
402        return;
403    }
404    else if (const While * whileStatement = dyn_cast<const While>(stmt)) {
405        compileWhile(whileStatement);
406        return;
407    }
408    else if (const Call* call = dyn_cast<Call>(stmt)) {
409        //Call the callee once and store the result in the marker map.
410        if (mMarkerMap.count(call) != 0) {
411            return;
412        }
413
414        const Prototype * proto = call->getPrototype();
415        const String * callee = proto->getName();
416
417        Type * inputType = StructType::get(mMod->getContext(), std::vector<Type *>{proto->getNumOfParameters(), mBitBlockType});
418        Type * outputType = StructType::get(mMod->getContext(), std::vector<Type *>{proto->getNumOfResults(), mBitBlockType});
419        FunctionType * functionType = FunctionType::get(Type::getVoidTy(mMod->getContext()), std::vector<Type *>{PointerType::get(inputType, 0), PointerType::get(outputType, 0)}, false);
420
421        //Starts on process_block
422        SmallVector<AttributeSet, 3> Attrs;
423        Attrs.push_back(AttributeSet::get(mMod->getContext(), 1U, std::vector<Attribute::AttrKind>({ Attribute::ReadOnly, Attribute::NoCapture })));
424        Attrs.push_back(AttributeSet::get(mMod->getContext(), 2U, std::vector<Attribute::AttrKind>({ Attribute::ReadNone, Attribute::NoCapture })));
425        AttributeSet AttrSet = AttributeSet::get(mMod->getContext(), Attrs);
426
427        Function * externalFunction = cast<Function>(mMod->getOrInsertFunction(callee->value(), functionType, AttrSet));
428        if (LLVM_UNLIKELY(externalFunction == nullptr)) {
429            throw std::runtime_error("Could not create static method call for external function \"" + callee->to_string() + "\"");
430        }
431        externalFunction->setCallingConv(llvm::CallingConv::C);
432
433
434        AllocaInst * outputStruct = mBuilder->CreateAlloca(outputType);
435        mBuilder->CreateCall2(externalFunction, mInputAddressPtr, outputStruct);
436        Value * outputPtr = mBuilder->CreateGEP(outputStruct, std::vector<Value *>({ mBuilder->getInt32(0), mBuilder->getInt32(0) }));
437        expr = mBuilder->CreateAlignedLoad(outputPtr, iBuilder.getBitBlockWidth() / 8, false);
438    }
439    else if (const And * pablo_and = dyn_cast<And>(stmt)) {
440        expr = mBuilder->CreateAnd(compileExpression(pablo_and->getExpr1()), compileExpression(pablo_and->getExpr2()), "and");
441    }
442    else if (const Or * pablo_or = dyn_cast<Or>(stmt)) {
443        expr = mBuilder->CreateOr(compileExpression(pablo_or->getExpr1()), compileExpression(pablo_or->getExpr2()), "or");
444    }
445    else if (const Xor * pablo_xor = dyn_cast<Xor>(stmt)) {
446        expr = mBuilder->CreateXor(compileExpression(pablo_xor->getExpr1()), compileExpression(pablo_xor->getExpr2()), "xor");
447    }
448    else if (const Sel * sel = dyn_cast<Sel>(stmt)) {
449        Value* ifMask = compileExpression(sel->getCondition());
450        Value* ifTrue = mBuilder->CreateAnd(ifMask, compileExpression(sel->getTrueExpr()));
451        Value* ifFalse = mBuilder->CreateAnd(mBuilder->CreateNot(ifMask), compileExpression(sel->getFalseExpr()));
452        expr = mBuilder->CreateOr(ifTrue, ifFalse);
453    }
454    else if (const Not * pablo_not = dyn_cast<Not>(stmt)) {
455        expr = mBuilder->CreateNot(compileExpression(pablo_not->getExpr()));
456    }
457    else if (const Advance * adv = dyn_cast<Advance>(stmt)) {
458        Value* strm_value = compileExpression(adv->getExpr());
459        int shift = adv->getAdvanceAmount();
460        unsigned advance_index = adv->getLocalAdvanceIndex();
461        expr = mCarryManager->advanceCarryInCarryOut(advance_index, shift, strm_value);
462    }
463    else if (const Mod64Advance * adv = dyn_cast<Mod64Advance>(stmt)) {
464        Value* strm_value = compileExpression(adv->getExpr());
465        int shift = adv->getAdvanceAmount();
466        expr = iBuilder.simd_slli(64, strm_value, shift);
467    }
468    else if (const MatchStar * mstar = dyn_cast<MatchStar>(stmt)) {
469        Value * marker = compileExpression(mstar->getMarker());
470        Value * cc = compileExpression(mstar->getCharClass());
471        Value * marker_and_cc = mBuilder->CreateAnd(marker, cc);
472        unsigned carry_index = mstar->getLocalCarryIndex();
473        Value * sum = mCarryManager->addCarryInCarryOut(carry_index, marker_and_cc, cc);
474        expr = mBuilder->CreateOr(mBuilder->CreateXor(sum, cc), marker, "matchstar");
475    }
476    else if (const Mod64MatchStar * mstar = dyn_cast<Mod64MatchStar>(stmt)) {
477        Value * marker = compileExpression(mstar->getMarker());
478        Value * cc = compileExpression(mstar->getCharClass());
479        Value * marker_and_cc = mBuilder->CreateAnd(marker, cc);
480        Value * sum = iBuilder.simd_add(64, marker_and_cc, cc);
481        expr = mBuilder->CreateOr(mBuilder->CreateXor(sum, cc), marker, "matchstar64");
482    }
483    else if (const ScanThru * sthru = dyn_cast<ScanThru>(stmt)) {
484        Value * marker_expr = compileExpression(sthru->getScanFrom());
485        Value * cc_expr = compileExpression(sthru->getScanThru());
486        unsigned carry_index = sthru->getLocalCarryIndex();
487        Value * sum = mCarryManager->addCarryInCarryOut(carry_index, marker_expr, cc_expr);
488        expr = mBuilder->CreateAnd(sum, mBuilder->CreateNot(cc_expr), "scanthru");
489    }
490    else if (const Mod64ScanThru * sthru = dyn_cast<Mod64ScanThru>(stmt)) {
491        Value * marker_expr = compileExpression(sthru->getScanFrom());
492        Value * cc_expr = compileExpression(sthru->getScanThru());
493        Value * sum = iBuilder.simd_add(64, marker_expr, cc_expr);
494        expr = mBuilder->CreateAnd(sum, mBuilder->CreateNot(cc_expr), "scanthru64");
495    }
496    else if (const Count * c = dyn_cast<Count>(stmt)) {
497        unsigned count_index = c->getGlobalCountIndex();
498        Value * to_count = compileExpression(c->getExpr());
499        expr = mCarryManager->popCount(to_count, count_index);
500    }
501    else {
502        llvm::raw_os_ostream cerr(std::cerr);
503        PabloPrinter::print(stmt, cerr);
504        throw std::runtime_error("Unrecognized Pablo Statement! can't compile.");
505    }
506    mMarkerMap[stmt] = expr;
507    if (DumpTrace) {
508        genPrintRegister(stmt->getName()->to_string(), expr);
509    }
510   
511}
512
513Value * PabloCompiler::compileExpression(const PabloAST * expr) {
514    if (isa<Ones>(expr)) {
515        return iBuilder.allOnes();
516    }
517    else if (isa<Zeroes>(expr)) {
518        return iBuilder.allZeroes();
519    }
520    auto f = mMarkerMap.find(expr);
521    if (LLVM_UNLIKELY(f == mMarkerMap.end())) {
522        std::string o;
523        llvm::raw_string_ostream str(o);
524        str << "\"";
525        PabloPrinter::print(expr, str);
526        str << "\" was used before definition!";
527        throw std::runtime_error(str.str());
528    }
529    return f->second;
530}
531
532void PabloCompiler::SetOutputValue(Value * marker, const unsigned index) {
533    if (LLVM_UNLIKELY(marker == nullptr)) {
534        throw std::runtime_error("Cannot set result " + std::to_string(index) + " to Null");
535    }
536    if (LLVM_UNLIKELY(marker->getType()->isPointerTy())) {
537        marker = mBuilder->CreateAlignedLoad(marker, iBuilder.getBitBlockWidth()/8, false);
538    }
539    Value* indices[] = {mBuilder->getInt64(0), mBuilder->getInt32(index)};
540    Value* gep = mBuilder->CreateGEP(mOutputAddressPtr, indices);
541    mBuilder->CreateAlignedStore(marker, gep, iBuilder.getBitBlockWidth()/8, false);
542}
543
544}
Note: See TracBrowser for help on using the repository browser.