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

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

Encapsulating all-zeroes and all-ones initializers within IDISA builder

File size: 23.0 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, BLOCK_SIZE/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)), BLOCK_SIZE/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 the required size of the carry data area to the process_block function.
169    return mFunction;
170}
171
172inline void PabloCompiler::GenerateFunction(PabloFunction & function) {
173    mInputType = PointerType::get(StructType::get(mMod->getContext(), std::vector<Type *>(function.getNumOfParameters(), mBitBlockType)), 0);
174    Type * outputType = PointerType::get(StructType::get(mMod->getContext(), std::vector<Type *>(function.getNumOfResults(), mBitBlockType)), 0);
175    FunctionType * functionType = FunctionType::get(Type::getVoidTy(mMod->getContext()), std::vector<Type *>({mInputType, outputType}), false);
176
177
178    //Starts on process_block
179    SmallVector<AttributeSet, 3> Attrs;
180    Attrs.push_back(AttributeSet::get(mMod->getContext(), ~0U, std::vector<Attribute::AttrKind>({ Attribute::NoUnwind, Attribute::UWTable })));
181    Attrs.push_back(AttributeSet::get(mMod->getContext(), 1U, std::vector<Attribute::AttrKind>({ Attribute::ReadOnly, Attribute::NoCapture })));
182    Attrs.push_back(AttributeSet::get(mMod->getContext(), 2U, std::vector<Attribute::AttrKind>({ Attribute::ReadNone, Attribute::NoCapture })));
183    AttributeSet AttrSet = AttributeSet::get(mMod->getContext(), Attrs);
184
185    // Create the function that will be generated.
186    mFunction = Function::Create(functionType, GlobalValue::ExternalLinkage, function.getName()->value(), mMod);
187    mFunction->setCallingConv(CallingConv::C);
188    mFunction->setAttributes(AttrSet);
189
190    Function::arg_iterator args = mFunction->arg_begin();
191    mInputAddressPtr = args++;
192    mInputAddressPtr->setName("input");
193    mOutputAddressPtr = args++;
194    mOutputAddressPtr->setName("output");
195}
196
197inline void PabloCompiler::Examine(PabloFunction & function) {
198    mWhileDepth = 0;
199    mIfDepth = 0;
200    mMaxWhileDepth = 0;
201    Examine(function.getEntryBlock());
202    if (LLVM_UNLIKELY(mWhileDepth != 0 || mIfDepth != 0)) {
203        throw std::runtime_error("Malformed Pablo AST: Unbalanced If or While nesting depth!");
204    }
205}
206
207
208void PabloCompiler::Examine(PabloBlock & block) {
209    for (Statement * stmt : block) {
210        if (If * ifStatement = dyn_cast<If>(stmt)) {
211            Examine(ifStatement->getBody());
212        }
213        else if (While * whileStatement = dyn_cast<While>(stmt)) {
214            mMaxWhileDepth = std::max(mMaxWhileDepth, ++mWhileDepth);
215            Examine(whileStatement->getBody());
216            --mWhileDepth;
217        }
218    }
219}
220
221inline void PabloCompiler::DeclareDebugFunctions() {
222        //This function can be used for testing to print the contents of a register from JIT'd code to the terminal window.
223        mPrintRegisterFunction = mMod->getOrInsertFunction("wrapped_print_register", Type::getVoidTy(mMod->getContext()), Type::getInt8PtrTy(mMod->getContext()), mBitBlockType, NULL);
224}
225
226void PabloCompiler::compileBlock(PabloBlock & block) {
227    mPabloBlock = & block;
228    for (const Statement * statement : block) {
229        compileStatement(statement);
230    }
231    mPabloBlock = block.getParent();
232}
233
234    Value * PabloCompiler::genBitTest2(Value * e1, Value * e2) {
235        Type * t1 = e1->getType();
236        Type * t2 = e2->getType();
237        if (t1 == mBitBlockType) {
238            if (t2 == mBitBlockType) {
239                return iBuilder.bitblock_any(mBuilder->CreateOr(e1, e2));
240            }
241            else {
242                Value * m1 = mBuilder->CreateZExt(iBuilder.hsimd_signmask(16, e1), t2);
243                return mBuilder->CreateICmpNE(mBuilder->CreateOr(m1, e2), ConstantInt::get(t2, 0));
244            }
245        }
246        else if (t2 == mBitBlockType) {
247            Value * m2 = mBuilder->CreateZExt(iBuilder.hsimd_signmask(16, e2), t1);
248            return mBuilder->CreateICmpNE(mBuilder->CreateOr(e1, m2), ConstantInt::get(t1, 0));
249        }
250        else {
251            return mBuilder->CreateICmpNE(mBuilder->CreateOr(e1, e2), ConstantInt::get(t1, 0));
252        }
253    }
254   
255    void PabloCompiler::compileIf(const If * ifStatement) {       
256    //
257    //  The If-ElseZero stmt:
258    //  if <predicate:expr> then <body:stmt>* elsezero <defined:var>* endif
259    //  If the value of the predicate is nonzero, then determine the values of variables
260    //  <var>* by executing the given statements.  Otherwise, the value of the
261    //  variables are all zero.  Requirements: (a) no variable that is defined within
262    //  the body of the if may be accessed outside unless it is explicitly
263    //  listed in the variable list, (b) every variable in the defined list receives
264    //  a value within the body, and (c) the logical consequence of executing
265    //  the statements in the event that the predicate is zero is that the
266    //  values of all defined variables indeed work out to be 0.
267    //
268    //  Simple Implementation with Phi nodes:  a phi node in the if exit block
269    //  is inserted for each variable in the defined variable list.  It receives
270    //  a zero value from the ifentry block and the defined value from the if
271    //  body.
272    //
273
274    BasicBlock * ifEntryBlock = mBuilder->GetInsertBlock();
275    BasicBlock * ifBodyBlock = BasicBlock::Create(mMod->getContext(), "if.body", mFunction, 0);
276    BasicBlock * ifEndBlock = BasicBlock::Create(mMod->getContext(), "if.end", mFunction, 0);
277   
278    PabloBlock & ifBody = ifStatement -> getBody();
279   
280    Value * if_test_value = compileExpression(ifStatement->getCondition());
281   
282    mCarryManager->enterScope(&ifBody);
283    if (mCarryManager->blockHasCarries()) {
284        // load the summary variable
285        Value* last_if_pending_data = mCarryManager->getCarrySummaryExpr();
286        mBuilder->CreateCondBr(genBitTest2(if_test_value, last_if_pending_data), ifBodyBlock, ifEndBlock);
287
288    }
289    else {
290        mBuilder->CreateCondBr(iBuilder.bitblock_any(if_test_value), ifBodyBlock, ifEndBlock);
291    }
292    // Entry processing is complete, now handle the body of the if.
293    mBuilder->SetInsertPoint(ifBodyBlock);
294   
295    mCarryManager->initializeCarryDataAtIfEntry();
296    compileBlock(ifBody);
297    if (mCarryManager->blockHasCarries()) {
298        mCarryManager->generateCarryOutSummaryCodeIfNeeded();
299    }
300    BasicBlock * ifBodyFinalBlock = mBuilder->GetInsertBlock();
301    mCarryManager->ensureCarriesStoredLocal();
302    mBuilder->CreateBr(ifEndBlock);
303    //End Block
304    mBuilder->SetInsertPoint(ifEndBlock);
305    for (const PabloAST * node : ifStatement->getDefined()) {
306        const Assign * assign = cast<Assign>(node);
307        PHINode * phi = mBuilder->CreatePHI(mBitBlockType, 2, assign->getName()->value());
308        auto f = mMarkerMap.find(assign);
309        assert (f != mMarkerMap.end());
310        phi->addIncoming(iBuilder.allZeroes(), ifEntryBlock);
311        phi->addIncoming(f->second, ifBodyFinalBlock);
312        mMarkerMap[assign] = phi;
313    }
314    // Create the phi Node for the summary variable, if needed.
315    mCarryManager->buildCarryDataPhisAfterIfBody(ifEntryBlock, ifBodyFinalBlock);
316    mCarryManager->leaveScope();
317}
318
319void PabloCompiler::compileWhile(const While * whileStatement) {
320
321    PabloBlock & whileBody = whileStatement -> getBody();
322   
323    BasicBlock * whileEntryBlock = mBuilder->GetInsertBlock();
324    BasicBlock * whileBodyBlock = BasicBlock::Create(mMod->getContext(), "while.body", mFunction, 0);
325    BasicBlock * whileEndBlock = BasicBlock::Create(mMod->getContext(), "while.end", mFunction, 0);
326
327    mCarryManager->enterScope(&whileBody);
328    mCarryManager->ensureCarriesLoadedRecursive();
329
330    const auto & nextNodes = whileStatement->getVariants();
331    std::vector<PHINode *> nextPhis;
332    nextPhis.reserve(nextNodes.size());
333
334    // On entry to the while structure, proceed to execute the first iteration
335    // of the loop body unconditionally.   The while condition is tested at the end of
336    // the loop.
337
338    mBuilder->CreateBr(whileBodyBlock);
339    mBuilder->SetInsertPoint(whileBodyBlock);
340
341    //
342    // There are 3 sets of Phi nodes for the while loop.
343    // (1) Carry-ins: (a) incoming carry data first iterations, (b) zero thereafter
344    // (2) Carry-out accumulators: (a) zero first iteration, (b) |= carry-out of each iteration
345    // (3) Next nodes: (a) values set up before loop, (b) modified values calculated in loop.
346
347    mCarryManager->initializeCarryDataPhisAtWhileEntry(whileEntryBlock);
348
349    // for any Next nodes in the loop body, initialize to (a) pre-loop value.
350    for (const Next * n : nextNodes) {
351        PHINode * phi = mBuilder->CreatePHI(mBitBlockType, 2, n->getName()->value());
352        auto f = mMarkerMap.find(n->getInitial());
353        assert (f != mMarkerMap.end());
354        phi->addIncoming(f->second, whileEntryBlock);
355        mMarkerMap[n->getInitial()] = phi;
356        nextPhis.push_back(phi);
357    }
358
359    //
360    // Now compile the loop body proper.  Carry-out accumulated values
361    // and iterated values of Next nodes will be computed.
362    ++mWhileDepth;
363    compileBlock(whileBody);
364
365    BasicBlock * whileBodyFinalBlock = mBuilder->GetInsertBlock();
366
367    if (mCarryManager->blockHasCarries()) {
368        mCarryManager->generateCarryOutSummaryCodeIfNeeded();
369    }
370    mCarryManager->extendCarryDataPhisAtWhileBodyFinalBlock(whileBodyFinalBlock);
371
372    // Terminate the while loop body with a conditional branch back.
373    mBuilder->CreateCondBr(iBuilder.bitblock_any(compileExpression(whileStatement->getCondition())), whileBodyBlock, whileEndBlock);
374
375    // and for any Next nodes in the loop body
376    for (unsigned i = 0; i < nextNodes.size(); i++) {
377        const Next * n = nextNodes[i];
378        auto f = mMarkerMap.find(n->getExpr());
379        if (LLVM_UNLIKELY(f == mMarkerMap.end())) {
380            throw std::runtime_error("Next node expression was not compiled!");
381        }
382        nextPhis[i]->addIncoming(f->second, whileBodyFinalBlock);
383    }
384
385    mBuilder->SetInsertPoint(whileEndBlock);
386    --mWhileDepth;
387
388    mCarryManager->ensureCarriesStoredRecursive();
389    mCarryManager->leaveScope();
390}
391
392
393void PabloCompiler::compileStatement(const Statement * stmt) {
394    Value * expr = nullptr;
395    if (const Assign * assign = dyn_cast<const Assign>(stmt)) {
396        expr = compileExpression(assign->getExpression());
397    }
398    else if (const Next * next = dyn_cast<const Next>(stmt)) {
399        expr = compileExpression(next->getExpr());
400    }
401    else if (const If * ifStatement = dyn_cast<const If>(stmt)) {
402        compileIf(ifStatement);
403        return;
404    }
405    else if (const While * whileStatement = dyn_cast<const While>(stmt)) {
406        compileWhile(whileStatement);
407        return;
408    }
409    else if (const Call* call = dyn_cast<Call>(stmt)) {
410        //Call the callee once and store the result in the marker map.
411        if (mMarkerMap.count(call) != 0) {
412            return;
413        }
414
415        const Prototype * proto = call->getPrototype();
416        const String * callee = proto->getName();
417
418        Type * inputType = StructType::get(mMod->getContext(), std::vector<Type *>{proto->getNumOfParameters(), mBitBlockType});
419        Type * outputType = StructType::get(mMod->getContext(), std::vector<Type *>{proto->getNumOfResults(), mBitBlockType});
420        FunctionType * functionType = FunctionType::get(Type::getVoidTy(mMod->getContext()), std::vector<Type *>{PointerType::get(inputType, 0), PointerType::get(outputType, 0)}, false);
421
422        //Starts on process_block
423        SmallVector<AttributeSet, 3> Attrs;
424        Attrs.push_back(AttributeSet::get(mMod->getContext(), 1U, std::vector<Attribute::AttrKind>({ Attribute::ReadOnly, Attribute::NoCapture })));
425        Attrs.push_back(AttributeSet::get(mMod->getContext(), 2U, std::vector<Attribute::AttrKind>({ Attribute::ReadNone, Attribute::NoCapture })));
426        AttributeSet AttrSet = AttributeSet::get(mMod->getContext(), Attrs);
427
428        Function * externalFunction = cast<Function>(mMod->getOrInsertFunction(callee->value(), functionType, AttrSet));
429        if (LLVM_UNLIKELY(externalFunction == nullptr)) {
430            throw std::runtime_error("Could not create static method call for external function \"" + callee->to_string() + "\"");
431        }
432        externalFunction->setCallingConv(llvm::CallingConv::C);
433
434
435        AllocaInst * outputStruct = mBuilder->CreateAlloca(outputType);
436        mBuilder->CreateCall2(externalFunction, mInputAddressPtr, outputStruct);
437        Value * outputPtr = mBuilder->CreateGEP(outputStruct, std::vector<Value *>({ mBuilder->getInt32(0), mBuilder->getInt32(0) }));
438        expr = mBuilder->CreateAlignedLoad(outputPtr, BLOCK_SIZE / 8, false);
439    }
440    else if (const And * pablo_and = dyn_cast<And>(stmt)) {
441        expr = mBuilder->CreateAnd(compileExpression(pablo_and->getExpr1()), compileExpression(pablo_and->getExpr2()), "and");
442    }
443    else if (const Or * pablo_or = dyn_cast<Or>(stmt)) {
444        expr = mBuilder->CreateOr(compileExpression(pablo_or->getExpr1()), compileExpression(pablo_or->getExpr2()), "or");
445    }
446    else if (const Xor * pablo_xor = dyn_cast<Xor>(stmt)) {
447        expr = mBuilder->CreateXor(compileExpression(pablo_xor->getExpr1()), compileExpression(pablo_xor->getExpr2()), "xor");
448    }
449    else if (const Sel * sel = dyn_cast<Sel>(stmt)) {
450        Value* ifMask = compileExpression(sel->getCondition());
451        Value* ifTrue = mBuilder->CreateAnd(ifMask, compileExpression(sel->getTrueExpr()));
452        Value* ifFalse = mBuilder->CreateAnd(mBuilder->CreateNot(ifMask), compileExpression(sel->getFalseExpr()));
453        expr = mBuilder->CreateOr(ifTrue, ifFalse);
454    }
455    else if (const Not * pablo_not = dyn_cast<Not>(stmt)) {
456        expr = mBuilder->CreateNot(compileExpression(pablo_not->getExpr()));
457    }
458    else if (const Advance * adv = dyn_cast<Advance>(stmt)) {
459        Value* strm_value = compileExpression(adv->getExpr());
460        int shift = adv->getAdvanceAmount();
461        unsigned advance_index = adv->getLocalAdvanceIndex();
462        expr = mCarryManager->advanceCarryInCarryOut(advance_index, shift, strm_value);
463    }
464    else if (const Mod64Advance * adv = dyn_cast<Mod64Advance>(stmt)) {
465        Value* strm_value = compileExpression(adv->getExpr());
466        int shift = adv->getAdvanceAmount();
467        expr = iBuilder.simd_slli(64, strm_value, shift);
468    }
469    else if (const MatchStar * mstar = dyn_cast<MatchStar>(stmt)) {
470        Value * marker = compileExpression(mstar->getMarker());
471        Value * cc = compileExpression(mstar->getCharClass());
472        Value * marker_and_cc = mBuilder->CreateAnd(marker, cc);
473        unsigned carry_index = mstar->getLocalCarryIndex();
474        Value * sum = mCarryManager->addCarryInCarryOut(carry_index, marker_and_cc, cc);
475        expr = mBuilder->CreateOr(mBuilder->CreateXor(sum, cc), marker, "matchstar");
476    }
477    else if (const Mod64MatchStar * mstar = dyn_cast<Mod64MatchStar>(stmt)) {
478        Value * marker = compileExpression(mstar->getMarker());
479        Value * cc = compileExpression(mstar->getCharClass());
480        Value * marker_and_cc = mBuilder->CreateAnd(marker, cc);
481        Value * sum = iBuilder.simd_add(64, marker_and_cc, cc);
482        expr = mBuilder->CreateOr(mBuilder->CreateXor(sum, cc), marker, "matchstar64");
483    }
484    else if (const ScanThru * sthru = dyn_cast<ScanThru>(stmt)) {
485        Value * marker_expr = compileExpression(sthru->getScanFrom());
486        Value * cc_expr = compileExpression(sthru->getScanThru());
487        unsigned carry_index = sthru->getLocalCarryIndex();
488        Value * sum = mCarryManager->addCarryInCarryOut(carry_index, marker_expr, cc_expr);
489        expr = mBuilder->CreateAnd(sum, mBuilder->CreateNot(cc_expr), "scanthru");
490    }
491    else if (const Mod64ScanThru * sthru = dyn_cast<Mod64ScanThru>(stmt)) {
492        Value * marker_expr = compileExpression(sthru->getScanFrom());
493        Value * cc_expr = compileExpression(sthru->getScanThru());
494        Value * sum = iBuilder.simd_add(64, marker_expr, cc_expr);
495        expr = mBuilder->CreateAnd(sum, mBuilder->CreateNot(cc_expr), "scanthru64");
496    }
497    else if (const Count * c = dyn_cast<Count>(stmt)) {
498        unsigned count_index = c->getGlobalCountIndex();
499        Value * to_count = compileExpression(c->getExpr());
500        expr = mCarryManager->popCount(to_count, count_index);
501    }
502    else {
503        llvm::raw_os_ostream cerr(std::cerr);
504        PabloPrinter::print(stmt, cerr);
505        throw std::runtime_error("Unrecognized Pablo Statement! can't compile.");
506    }
507    mMarkerMap[stmt] = expr;
508    if (DumpTrace) {
509        genPrintRegister(stmt->getName()->to_string(), expr);
510    }
511   
512}
513
514Value * PabloCompiler::compileExpression(const PabloAST * expr) {
515    if (isa<Ones>(expr)) {
516        return iBuilder.allOnes();
517    }
518    else if (isa<Zeroes>(expr)) {
519        return iBuilder.allZeroes();
520    }
521    auto f = mMarkerMap.find(expr);
522    if (LLVM_UNLIKELY(f == mMarkerMap.end())) {
523        std::string o;
524        llvm::raw_string_ostream str(o);
525        str << "\"";
526        PabloPrinter::print(expr, str);
527        str << "\" was used before definition!";
528        throw std::runtime_error(str.str());
529    }
530    return f->second;
531}
532
533void PabloCompiler::SetOutputValue(Value * marker, const unsigned index) {
534    if (LLVM_UNLIKELY(marker == nullptr)) {
535        throw std::runtime_error("Cannot set result " + std::to_string(index) + " to Null");
536    }
537    if (LLVM_UNLIKELY(marker->getType()->isPointerTy())) {
538        marker = mBuilder->CreateAlignedLoad(marker, BLOCK_SIZE/8, false);
539    }
540    Value* indices[] = {mBuilder->getInt64(0), mBuilder->getInt32(index)};
541    Value* gep = mBuilder->CreateGEP(mOutputAddressPtr, indices);
542    mBuilder->CreateAlignedStore(marker, gep, BLOCK_SIZE/8, false);
543}
544
545}
Note: See TracBrowser for help on using the repository browser.