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

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

Clean ups for compilation with gcc 4.8

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