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

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

mBlockNo; include block number in traces.

File size: 46.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/printer_pablos.h>
10#include <cc/cc_namemap.hpp>
11#include <re/re_name.h>
12#include <stdexcept>
13#include <include/simd-lib/bitblock.hpp>
14#include <sstream>
15#include <llvm/IR/Verifier.h>
16#include <llvm/Pass.h>
17#include <llvm/PassManager.h>
18#include <llvm/ADT/SmallVector.h>
19#include <llvm/Analysis/Passes.h>
20#include <llvm/IR/BasicBlock.h>
21#include <llvm/IR/CallingConv.h>
22#include <llvm/IR/Constants.h>
23#include <llvm/IR/DataLayout.h>
24#include <llvm/IR/DerivedTypes.h>
25#include <llvm/IR/Function.h>
26#include <llvm/IR/GlobalVariable.h>
27#include <llvm/IR/InlineAsm.h>
28#include <llvm/IR/Instructions.h>
29#include <llvm/IR/LLVMContext.h>
30#include <llvm/IR/Module.h>
31#include <llvm/Support/FormattedStream.h>
32#include <llvm/Support/MathExtras.h>
33#include <llvm/Support/Casting.h>
34#include <llvm/Support/Compiler.h>
35#include <llvm/Support/Debug.h>
36#include <llvm/Support/TargetSelect.h>
37#include <llvm/Support/Host.h>
38#include <llvm/Transforms/Scalar.h>
39#include <llvm/ExecutionEngine/ExecutionEngine.h>
40#include <llvm/ExecutionEngine/MCJIT.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 RE compilation"), cl::cat(eIRDumpOptions));
51
52static cl::OptionCategory fTracingOptions("Run-time Tracing Options", "These options control execution traces.");
53static cl::opt<bool> TraceNext("trace-next-nodes", cl::init(false), cl::desc("Generate dynamic traces of executed Next nodes (while control variables)."), cl::cat(fTracingOptions));
54static cl::opt<bool> DumpTrace("dump-trace", cl::init(false), cl::desc("Generate dynamic traces of executed assignments."), cl::cat(fTracingOptions));
55
56extern "C" {
57  void wrapped_print_register(char * regName, BitBlock bit_block) {
58      print_register<BitBlock>(regName, bit_block);
59  }
60}
61
62namespace pablo {
63
64PabloCompiler::PabloCompiler(const std::vector<Var*> & basisBits)
65: mBasisBits(basisBits)
66, mMod(new Module("icgrep", getGlobalContext()))
67, mBasicBlock(nullptr)
68, mExecutionEngine(nullptr)
69, mBitBlockType(VectorType::get(IntegerType::get(mMod->getContext(), 64), BLOCK_SIZE / 64))
70, mBasisBitsInputPtr(nullptr)
71, mCarryDataPtr(nullptr)
72, mBlockNo(nullptr)
73, mWhileDepth(0)
74, mIfDepth(0)
75, mZeroInitializer(ConstantAggregateZero::get(mBitBlockType))
76, mOneInitializer(ConstantVector::getAllOnesValue(mBitBlockType))
77, mFunctionType(nullptr)
78, mFunction(nullptr)
79, mBasisBitsAddr(nullptr)
80, mOutputAddrPtr(nullptr)
81, mMaxWhileDepth(0)
82, mPrintRegisterFunction(nullptr)
83{
84    //Create the jit execution engine.up
85    InitializeNativeTarget();
86    InitializeNativeTargetAsmPrinter();
87    InitializeNativeTargetAsmParser();
88    DefineTypes();
89}
90
91PabloCompiler::~PabloCompiler()
92{
93
94}
95   
96void PabloCompiler::InstallExternalFunction(std::string C_fn_name, void * fn_ptr) {
97    mExternalMap.insert(std::make_pair(C_fn_name, fn_ptr));
98}
99
100void PabloCompiler::genPrintRegister(std::string regName, Value * bitblockValue) {
101    IRBuilder <> b(mBasicBlock);
102    Constant * regNameData = ConstantDataArray::getString(mMod->getContext(), regName);
103    GlobalVariable *regStrVar = new GlobalVariable(*mMod, 
104                                                   ArrayType::get(IntegerType::get(mMod->getContext(), 8), regName.length()+1),
105                                                   /*isConstant=*/ true,
106                                                   /*Linkage=*/ GlobalValue::PrivateLinkage,
107                                                   /*Initializer=*/ regNameData);
108    Value * regStrPtr = b.CreateGEP(regStrVar, {b.getInt64(0), b.getInt32(0)});
109    b.CreateCall(mPrintRegisterFunction, {regStrPtr, bitblockValue});
110}
111
112CompiledPabloFunction PabloCompiler::compile(PabloBlock & pb)
113{
114    mWhileDepth = 0;
115    mIfDepth = 0;
116    mMaxWhileDepth = 0;
117    unsigned totalCarryDataSize = Examine(pb, 0); 
118    mCarryInVector.resize(totalCarryDataSize);
119    mCarryOutVector.resize(totalCarryDataSize);
120    mCarryDataSummaryIdx.resize(totalCarryDataSize);
121    std::string errMessage;
122    EngineBuilder builder(mMod);
123    builder.setErrorStr(&errMessage);
124    builder.setMCPU(sys::getHostCPUName());
125    builder.setUseMCJIT(true);
126    builder.setOptLevel(mMaxWhileDepth ? CodeGenOpt::Level::Less : CodeGenOpt::Level::None);
127    mExecutionEngine = builder.create();
128    if (mExecutionEngine == nullptr) {
129        throw std::runtime_error("Could not create ExecutionEngine: " + errMessage);
130    }
131    DeclareFunctions();
132
133    DeclareCallFunctions();
134
135    Function::arg_iterator args = mFunction->arg_begin();
136    mBasisBitsAddr = args++;
137    mBasisBitsAddr->setName("basis_bits");
138    mCarryDataPtr = args++;
139    mCarryDataPtr->setName("carry_data");
140    mOutputAddrPtr = args++;
141    mOutputAddrPtr->setName("output");
142
143    mWhileDepth = 0;
144    mIfDepth = 0;
145    mMaxWhileDepth = 0;
146    mBasicBlock = BasicBlock::Create(mMod->getContext(), "parabix_entry", mFunction,0);
147    IRBuilder<> b(mBasicBlock);
148
149    //The basis bits structure
150    for (unsigned i = 0; i != mBasisBits.size(); ++i) {
151        Value* indices[] = {b.getInt64(0), b.getInt32(i)};
152        Value * gep = b.CreateGEP(mBasisBitsAddr, indices);
153        LoadInst * basisBit = b.CreateAlignedLoad(gep, BLOCK_SIZE/8, false, mBasisBits[i]->getName()->to_string());
154        mMarkerMap.insert(std::make_pair(mBasisBits[i], basisBit));
155    }
156   
157    // The block number is a 64-bit integer at the end of the carry data area.
158    Value * blockNoPtr = b.CreateBitCast(b.CreateGEP(mCarryDataPtr, b.getInt64(totalCarryDataSize)), Type::getInt64PtrTy(b.getContext()));
159    mBlockNo = b.CreateLoad(blockNoPtr);
160    //Generate the IR instructions for the function.
161    compileBlock(pb);
162    {   IRBuilder<> b(mBasicBlock);  // may be in new basic block, set builder
163        b.CreateStore(b.CreateAdd(mBlockNo, b.getInt64(1)), blockNoPtr);
164    }
165
166    if (DumpTrace || TraceNext) {
167        genPrintRegister("blockNo", genCarryDataLoad(totalCarryDataSize));
168    }
169    if (LLVM_UNLIKELY(mWhileDepth != 0)) {
170        throw std::runtime_error("Non-zero nesting depth error (" + std::to_string(mWhileDepth) + ")");
171    }
172
173    //Terminate the block
174    ReturnInst::Create(mMod->getContext(), mBasicBlock);
175
176    //Display the IR that has been generated by this module.
177    if (LLVM_UNLIKELY(DumpGeneratedIR)) {
178        mMod->dump();
179    }
180    //Create a verifier.  The verifier will print an error message if our module is malformed in any way.
181    verifyModule(*mMod, &dbgs());
182
183    mExecutionEngine->finalizeObject();
184
185    //Return the required size of the carry data area to the process_block function.
186    // Reserve 1 element in the carry data area for current block number (future). TODO
187    return CompiledPabloFunction((totalCarryDataSize + 1) * sizeof(BitBlock), mFunction, mExecutionEngine);
188}
189
190void PabloCompiler::DefineTypes()
191{
192    StructType * structBasisBits = mMod->getTypeByName("struct.Basis_bits");
193    if (structBasisBits == nullptr) {
194        structBasisBits = StructType::create(mMod->getContext(), "struct.Basis_bits");
195    }
196    std::vector<Type*>StructTy_struct_Basis_bits_fields;
197    for (int i = 0; i != mBasisBits.size(); i++)
198    {
199        StructTy_struct_Basis_bits_fields.push_back(mBitBlockType);
200    }
201    if (structBasisBits->isOpaque()) {
202        structBasisBits->setBody(StructTy_struct_Basis_bits_fields, /*isPacked=*/false);
203    }
204    mBasisBitsInputPtr = PointerType::get(structBasisBits, 0);
205
206    std::vector<Type*>functionTypeArgs;
207    functionTypeArgs.push_back(mBasisBitsInputPtr);
208
209    //The carry data array.
210    //A pointer to the BitBlock vector.
211    functionTypeArgs.push_back(PointerType::get(mBitBlockType, 0));
212
213    //The output structure.
214    StructType * outputStruct = mMod->getTypeByName("struct.Output");
215    if (!outputStruct) {
216        outputStruct = StructType::create(mMod->getContext(), "struct.Output");
217    }
218    if (outputStruct->isOpaque()) {
219        std::vector<Type*>fields;
220        fields.push_back(mBitBlockType);
221        fields.push_back(mBitBlockType);
222        outputStruct->setBody(fields, /*isPacked=*/false);
223    }
224    PointerType* outputStructPtr = PointerType::get(outputStruct, 0);
225
226    //The &output parameter.
227    functionTypeArgs.push_back(outputStructPtr);
228
229    mFunctionType = FunctionType::get(
230     /*Result=*/Type::getVoidTy(mMod->getContext()),
231     /*Params=*/functionTypeArgs,
232     /*isVarArg=*/false);
233}
234
235void PabloCompiler::DeclareFunctions()
236{
237    //This function can be used for testing to print the contents of a register from JIT'd code to the terminal window.
238    mPrintRegisterFunction = mMod->getOrInsertFunction("wrapped_print_register", Type::getVoidTy(getGlobalContext()), Type::getInt8PtrTy(getGlobalContext()), mBitBlockType, NULL);
239    mExecutionEngine->addGlobalMapping(cast<GlobalValue>(mPrintRegisterFunction), (void *)&wrapped_print_register);
240    // to call->  b.CreateCall(mFunc_print_register, unicode_category);
241
242#ifdef USE_UADD_OVERFLOW
243#ifdef USE_TWO_UADD_OVERFLOW
244    // Type Definitions for llvm.uadd.with.overflow.carryin.i128 or .i256
245    std::vector<Type*>StructTy_0_fields;
246    StructTy_0_fields.push_back(IntegerType::get(mMod->getContext(), BLOCK_SIZE));
247    StructTy_0_fields.push_back(IntegerType::get(mMod->getContext(), 1));
248    StructType *StructTy_0 = StructType::get(mMod->getContext(), StructTy_0_fields, /*isPacked=*/false);
249
250    std::vector<Type*>FuncTy_1_args;
251    FuncTy_1_args.push_back(IntegerType::get(mMod->getContext(), BLOCK_SIZE));
252    FuncTy_1_args.push_back(IntegerType::get(mMod->getContext(), BLOCK_SIZE));
253    FunctionType* FuncTy_1 = FunctionType::get(
254                                              /*Result=*/StructTy_0,
255                                              /*Params=*/FuncTy_1_args,
256                                              /*isVarArg=*/false);
257
258    mFunctionUaddOverflow = mMod->getFunction("llvm.uadd.with.overflow.i" +
259                                              std::to_string(BLOCK_SIZE));
260    if (!mFunctionUaddOverflow) {
261        mFunctionUaddOverflow= Function::Create(
262          /*Type=*/ FuncTy_1,
263          /*Linkage=*/ GlobalValue::ExternalLinkage,
264          /*Name=*/ "llvm.uadd.with.overflow.i" + std::to_string(BLOCK_SIZE), mMod); // (external, no body)
265        mFunctionUaddOverflow->setCallingConv(CallingConv::C);
266    }
267    AttributeSet mFunctionUaddOverflowPAL;
268    {
269        SmallVector<AttributeSet, 4> Attrs;
270        AttributeSet PAS;
271        {
272          AttrBuilder B;
273          B.addAttribute(Attribute::NoUnwind);
274          B.addAttribute(Attribute::ReadNone);
275          PAS = AttributeSet::get(mMod->getContext(), ~0U, B);
276        }
277
278        Attrs.push_back(PAS);
279        mFunctionUaddOverflowPAL = AttributeSet::get(mMod->getContext(), Attrs);
280    }
281    mFunctionUaddOverflow->setAttributes(mFunctionUaddOverflowPAL);
282#else
283    // Type Definitions for llvm.uadd.with.overflow.carryin.i128 or .i256
284    std::vector<Type*>StructTy_0_fields;
285    StructTy_0_fields.push_back(IntegerType::get(mMod->getContext(), BLOCK_SIZE));
286    StructTy_0_fields.push_back(IntegerType::get(mMod->getContext(), 1));
287    StructType *StructTy_0 = StructType::get(mMod->getContext(), StructTy_0_fields, /*isPacked=*/false);
288
289    std::vector<Type*>FuncTy_1_args;
290    FuncTy_1_args.push_back(IntegerType::get(mMod->getContext(), BLOCK_SIZE));
291    FuncTy_1_args.push_back(IntegerType::get(mMod->getContext(), BLOCK_SIZE));
292    FuncTy_1_args.push_back(IntegerType::get(mMod->getContext(), 1));
293    FunctionType* FuncTy_1 = FunctionType::get(
294                                              /*Result=*/StructTy_0,
295                                              /*Params=*/FuncTy_1_args,
296                                              /*isVarArg=*/false);
297
298    mFunctionUaddOverflowCarryin = mMod->getFunction("llvm.uadd.with.overflow.carryin.i" +
299                                              std::to_string(BLOCK_SIZE));
300    if (!mFunctionUaddOverflowCarryin) {
301        mFunctionUaddOverflowCarryin = Function::Create(
302          /*Type=*/ FuncTy_1,
303          /*Linkage=*/ GlobalValue::ExternalLinkage,
304          /*Name=*/ "llvm.uadd.with.overflow.carryin.i" + std::to_string(BLOCK_SIZE), mMod); // (external, no body)
305        mFunctionUaddOverflowCarryin->setCallingConv(CallingConv::C);
306    }
307    AttributeSet mFunctionUaddOverflowCarryinPAL;
308    {
309        SmallVector<AttributeSet, 4> Attrs;
310        AttributeSet PAS;
311        {
312          AttrBuilder B;
313          B.addAttribute(Attribute::NoUnwind);
314          B.addAttribute(Attribute::ReadNone);
315          PAS = AttributeSet::get(mMod->getContext(), ~0U, B);
316        }
317
318        Attrs.push_back(PAS);
319        mFunctionUaddOverflowCarryinPAL = AttributeSet::get(mMod->getContext(), Attrs);
320    }
321    mFunctionUaddOverflowCarryin->setAttributes(mFunctionUaddOverflowCarryinPAL);
322#endif
323#endif
324
325    //Starts on process_block
326    SmallVector<AttributeSet, 4> Attrs;
327    AttributeSet PAS;
328    {
329        AttrBuilder B;
330        B.addAttribute(Attribute::ReadOnly);
331        B.addAttribute(Attribute::NoCapture);
332        PAS = AttributeSet::get(mMod->getContext(), 1U, B);
333    }
334    Attrs.push_back(PAS);
335    {
336        AttrBuilder B;
337        B.addAttribute(Attribute::NoCapture);
338        PAS = AttributeSet::get(mMod->getContext(), 2U, B);
339    }
340    Attrs.push_back(PAS);
341    {
342        AttrBuilder B;
343        B.addAttribute(Attribute::NoCapture);
344        PAS = AttributeSet::get(mMod->getContext(), 3U, B);
345    }
346    Attrs.push_back(PAS);
347    {
348        AttrBuilder B;
349        B.addAttribute(Attribute::NoUnwind);
350        B.addAttribute(Attribute::UWTable);
351        PAS = AttributeSet::get(mMod->getContext(), ~0U, B);
352    }
353    AttributeSet AttrSet = AttributeSet::get(mMod->getContext(), Attrs);
354
355    //Create the function that will be generated.
356    mFunction = mMod->getFunction("process_block");
357    if (!mFunction) {
358        mFunction = Function::Create(
359            /*Type=*/mFunctionType,
360            /*Linkage=*/GlobalValue::ExternalLinkage,
361            /*Name=*/"process_block", mMod);
362        mFunction->setCallingConv(CallingConv::C);
363    }
364    mFunction->setAttributes(AttrSet);
365}
366   
367// CarryDataNumbering
368//
369// For each PabloBlock, a contiguous CarryData area holds carry,
370// and advance values that are generated in one block for use in the
371// next.  For a given block, the carry data area contains the
372// carries, the advances and the nested data for contained blocks,
373// if any.
374// Notes:
375//   (a) an additional data entry is created for each if-statement
376//       having more than one carry or advance opreation within it.  This
377//       additional entry is a summary entry which must be nonzero to
378//       indicate that there are carry or advance bits associated with
379//       any operation within the if-structure (at any nesting level).
380//   (b) advancing by a large amount may require multiple advance entries.
381//       the number of advance entries for an operation Adv(x, n) is
382//       (n + BLOCK_SIZE - 1) / BLOCK_SIZE
383//
384// Examine precomputes some CarryNumbering and AdvanceNumbering, as
385// well as mMaxWhileDepth of while loops.
386//
387unsigned PabloCompiler::Examine(PabloBlock & blk, unsigned carryDataIndexIn) {
388    // Count local carries and advances at this level.
389    unsigned carryDataIndex = carryDataIndexIn;
390    unsigned localCarries = 0;
391    unsigned localAdvances = 0;
392    unsigned nestedCarryDataSize = 0;
393    for (Statement * stmt : blk) {
394        if (Advance * adv = dyn_cast<Advance>(stmt)) {
395            adv->setLocalAdvanceIndex(localAdvances);
396            localAdvances += (adv->getAdvanceAmount() + BLOCK_SIZE - 1) / BLOCK_SIZE;
397        }
398        else if (MatchStar * m = dyn_cast<MatchStar>(stmt)) {
399            m->setLocalCarryIndex(localCarries);
400            ++localCarries;
401        }
402        else if (ScanThru * s = dyn_cast<ScanThru>(stmt)) {
403            s->setLocalCarryIndex(localCarries);
404            ++localCarries;
405        }
406    }
407    carryDataIndex += localCarries + localAdvances;
408    for (Statement * stmt : blk) {
409        if (Call * call = dyn_cast<Call>(stmt)) {
410            mCalleeMap.insert(std::make_pair(call->getCallee(), nullptr));
411        }
412        else if (If * ifStatement = dyn_cast<If>(stmt)) {
413            ++mIfDepth;
414            const auto ifCarryDataSize = Examine(ifStatement->getBody(), carryDataIndex);
415            --mIfDepth;
416            nestedCarryDataSize += ifCarryDataSize;
417            carryDataIndex += ifCarryDataSize;
418        }
419        else if (While * whileStatement = dyn_cast<While>(stmt)) {
420            mMaxWhileDepth = std::max(mMaxWhileDepth, ++mWhileDepth);
421            const auto whileCarryDataSize = Examine(whileStatement->getBody(), carryDataIndex);
422            --mWhileDepth;
423            nestedCarryDataSize += whileCarryDataSize;
424            carryDataIndex += whileCarryDataSize;
425        }
426    }
427    blk.setCarryIndexBase(carryDataIndexIn);
428    blk.setLocalCarryCount(localCarries);
429    blk.setLocalAdvanceCount(localAdvances);
430    unsigned totalCarryDataSize = localCarries + localAdvances + nestedCarryDataSize;
431    if ((mIfDepth > 0) && (totalCarryDataSize > 1)) {
432        // Need extra space for the summary variable, always the last
433        // entry within an if block.
434        totalCarryDataSize += 1;
435    }
436    blk.setTotalCarryDataSize(totalCarryDataSize);
437    return totalCarryDataSize;
438}
439
440void PabloCompiler::DeclareCallFunctions() {
441    for (auto mapping : mCalleeMap) {
442        const String * callee = mapping.first;
443        //std::cerr << callee->str() << " to be declared\n";
444        auto ei = mExternalMap.find(callee->value());
445        if (ei != mExternalMap.end()) {
446            void * fn_ptr = ei->second;
447            //std::cerr << "Ptr found:" <<  std::hex << ((intptr_t) fn_ptr) << std::endl;
448            Value * externalValue = mMod->getOrInsertFunction(callee->value(), mBitBlockType, mBasisBitsInputPtr, NULL);
449            if (LLVM_UNLIKELY(externalValue == nullptr)) {
450                throw std::runtime_error("Could not create static method call for external function \"" + callee->to_string() + "\"");
451            }
452            mExecutionEngine->addGlobalMapping(cast<GlobalValue>(externalValue), fn_ptr);
453            mCalleeMap[callee] = externalValue;
454        }
455        else {
456            throw std::runtime_error("External function \"" + callee->to_string() + "\" not installed");
457        }
458    }
459}
460
461void PabloCompiler::compileBlock(const PabloBlock & blk) {
462    for (const Statement * statement : blk) {
463        compileStatement(statement);
464    }
465}
466
467
468
469
470void PabloCompiler::compileIf(const If * ifStatement) {       
471        //
472        //  The If-ElseZero stmt:
473        //  if <predicate:expr> then <body:stmt>* elsezero <defined:var>* endif
474        //  If the value of the predicate is nonzero, then determine the values of variables
475        //  <var>* by executing the given statements.  Otherwise, the value of the
476        //  variables are all zero.  Requirements: (a) no variable that is defined within
477        //  the body of the if may be accessed outside unless it is explicitly
478        //  listed in the variable list, (b) every variable in the defined list receives
479        //  a value within the body, and (c) the logical consequence of executing
480        //  the statements in the event that the predicate is zero is that the
481        //  values of all defined variables indeed work out to be 0.
482        //
483        //  Simple Implementation with Phi nodes:  a phi node in the if exit block
484        //  is inserted for each variable in the defined variable list.  It receives
485        //  a zero value from the ifentry block and the defined value from the if
486        //  body.
487        //
488        BasicBlock * ifEntryBlock = mBasicBlock;  // The block we are in.
489        BasicBlock * ifBodyBlock = BasicBlock::Create(mMod->getContext(), "if.body", mFunction, 0);
490        BasicBlock * ifEndBlock = BasicBlock::Create(mMod->getContext(), "if.end", mFunction, 0);
491       
492        IRBuilder<> b_entry(ifEntryBlock);
493        mBasicBlock = ifEntryBlock;
494   
495        const unsigned baseCarryDataIdx = ifStatement->getBody().getCarryIndexBase();
496        const unsigned carryDataSize = ifStatement->getBody().getTotalCarryDataSize();
497        const unsigned carrySummaryIndex = baseCarryDataIdx + carryDataSize - 1;
498       
499        Value* if_test_value = compileExpression(ifStatement->getCondition());
500        if (carryDataSize > 0) {
501            // load the summary variable
502            Value* last_if_pending_data = genCarryDataLoad(carrySummaryIndex);
503            if_test_value = b_entry.CreateOr(if_test_value, last_if_pending_data);
504        }
505        b_entry.CreateCondBr(genBitBlockAny(if_test_value), ifEndBlock, ifBodyBlock);
506
507        // Entry processing is complete, now handle the body of the if.
508        mBasicBlock = ifBodyBlock;
509        compileBlock(ifStatement -> getBody());
510
511        // If we compiled an If or a While statement, we won't be in the same basic block as before.
512        // Create the branch from the current basic block to the end block.
513        IRBuilder<> bIfBody(mBasicBlock);
514        // After the recursive compile, now insert the code to compute the summary
515        // carry over variable.
516       
517        if (carryDataSize > 1) {
518            // If there was only one carry entry, then it also serves as the summary variable.
519            // Otherwise, we need to combine entries to compute the summary.
520            Value * carry_summary = mZeroInitializer;
521            for (int c = baseCarryDataIdx; c < carrySummaryIndex; c++) {
522                int s = mCarryDataSummaryIdx[c];
523                if (s == -1) {
524                    Value* carryq_value = mCarryOutVector[c];
525                    if (carry_summary == mZeroInitializer) {
526                        carry_summary = carryq_value;
527                    }
528                    else {
529                        carry_summary = bIfBody.CreateOr(carry_summary, carryq_value);
530                    }
531                    mCarryDataSummaryIdx[c] = carrySummaryIndex;
532                }
533            }
534            genCarryDataStore(carry_summary, carrySummaryIndex);
535        }
536        bIfBody.CreateBr(ifEndBlock);
537        //End Block
538        IRBuilder<> bEnd(ifEndBlock);
539        for (const PabloAST * node : ifStatement->getDefined()) {
540            const Assign * assign = cast<Assign>(node);
541            PHINode * phi = bEnd.CreatePHI(mBitBlockType, 2, assign->getName()->value());
542            auto f = mMarkerMap.find(assign);
543            assert (f != mMarkerMap.end());
544            phi->addIncoming(mZeroInitializer, ifEntryBlock);
545            phi->addIncoming(f->second, mBasicBlock);
546            mMarkerMap[assign] = phi;
547        }
548        // Create the phi Node for the summary variable.
549        if (carryDataSize > 0) {
550            PHINode * summary_phi = bEnd.CreatePHI(mBitBlockType, 2, "summary");
551            summary_phi->addIncoming(mZeroInitializer, ifEntryBlock);
552            summary_phi->addIncoming(mCarryOutVector[carrySummaryIndex], mBasicBlock);
553            mCarryOutVector[carrySummaryIndex] = summary_phi;
554        }
555       
556        // Set the basic block to the new end block
557        mBasicBlock = ifEndBlock;
558}
559
560void PabloCompiler::compileWhile(const While * whileStatement) {
561        const unsigned baseCarryDataIdx = whileStatement->getBody().getCarryIndexBase();
562        const unsigned carryDataSize = whileStatement->getBody().getTotalCarryDataSize();
563   
564        if (mWhileDepth == 0) {
565            for (auto i = 0; i < carryDataSize; ++i) {
566                genCarryDataLoad(baseCarryDataIdx + i);
567            }
568        }
569
570        SmallVector<const Next*, 4> nextNodes;
571        for (const PabloAST * node : whileStatement->getBody()) {
572            if (isa<Next>(node)) {
573                nextNodes.push_back(cast<Next>(node));
574            }
575        }
576
577        // Compile the initial iteration statements; the calls to genCarryDataStore will update the
578        // mCarryOutVector with the appropriate values. Although we're not actually entering a new basic
579        // block yet, increment the nesting depth so that any calls to genCarryDataLoad or genCarryDataStore
580        // will refer to the previous value.
581
582        ++mWhileDepth;
583
584        compileBlock(whileStatement->getBody());
585
586        // Reset the carry queue index. Note: this ought to be changed in the future. Currently this assumes
587        // that compiling the while body twice will generate the equivalent IR. This is not necessarily true
588        // but works for now.
589
590        BasicBlock* whileCondBlock = BasicBlock::Create(mMod->getContext(), "while.cond", mFunction, 0);
591        BasicBlock* whileBodyBlock = BasicBlock::Create(mMod->getContext(), "while.body", mFunction, 0);
592        BasicBlock* whileEndBlock = BasicBlock::Create(mMod->getContext(), "while.end", mFunction, 0);
593
594        // Note: compileBlock may update the mBasicBlock pointer if the body contains nested loops. It
595        // may not be same one that we entered the function with.
596        IRBuilder<> bEntry(mBasicBlock);
597        bEntry.CreateBr(whileCondBlock);
598
599        // CONDITION BLOCK
600        IRBuilder<> bCond(whileCondBlock);
601        // generate phi nodes for any carry propogating instruction
602        std::vector<PHINode*> phiNodes(carryDataSize + nextNodes.size());
603        unsigned index = 0;
604        for (index = 0; index < carryDataSize; ++index) {
605            PHINode * phi = bCond.CreatePHI(mBitBlockType, 2);
606            phi->addIncoming(mCarryOutVector[baseCarryDataIdx + index], mBasicBlock);
607            mCarryInVector[baseCarryDataIdx + index] = mZeroInitializer; // (use phi for multi-carry mode.)
608            phiNodes[index] = phi;
609        }
610        // and for any Next nodes in the loop body
611        for (const Next * n : nextNodes) {
612            PHINode * phi = bCond.CreatePHI(mBitBlockType, 2, n->getName()->value());
613            auto f = mMarkerMap.find(n->getInitial());
614            assert (f != mMarkerMap.end());
615            phi->addIncoming(f->second, mBasicBlock);
616            mMarkerMap[n->getInitial()] = phi;
617            phiNodes[index++] = phi;
618        }
619
620        mBasicBlock = whileCondBlock;
621        bCond.CreateCondBr(genBitBlockAny(compileExpression(whileStatement->getCondition())), whileEndBlock, whileBodyBlock);
622
623        // BODY BLOCK
624        //std::cerr << "Compile loop body\n";
625        mBasicBlock = whileBodyBlock;
626        compileBlock(whileStatement->getBody());
627        // update phi nodes for any carry propogating instruction
628        IRBuilder<> bWhileBody(mBasicBlock);
629        for (index = 0; index < carryDataSize; ++index) {
630            PHINode * phi = phiNodes[index];
631            Value * carryOut = bWhileBody.CreateOr(phi, mCarryOutVector[baseCarryDataIdx + index]);
632            phi->addIncoming(carryOut, mBasicBlock);
633            mCarryOutVector[baseCarryDataIdx + index] = phi;
634        }
635       
636        // and for any Next nodes in the loop body
637        for (const Next * n : nextNodes) {
638            auto f = mMarkerMap.find(n->getInitial());
639            assert (f != mMarkerMap.end());
640            PHINode * phi = phiNodes[index++];
641            phi->addIncoming(f->second, mBasicBlock);
642            mMarkerMap[n->getInitial()] = phi;
643        }
644
645        bWhileBody.CreateBr(whileCondBlock);
646
647        // EXIT BLOCK
648        mBasicBlock = whileEndBlock;
649        if (--mWhileDepth == 0) {
650            for (index = 0; index < carryDataSize; ++index) {
651                genCarryDataStore(phiNodes[index], baseCarryDataIdx + index);
652            }
653        }
654 
655}
656
657void PabloCompiler::compileStatement(const Statement * stmt)
658{
659    IRBuilder<> b(mBasicBlock);
660    if (const Assign * assign = dyn_cast<const Assign>(stmt)) {
661        Value * expr = compileExpression(assign->getExpr());
662        if (DumpTrace) {
663            genPrintRegister(assign->getName()->to_string(), expr);
664        }
665        mMarkerMap[assign] = expr;
666        if (LLVM_UNLIKELY(assign->isOutputAssignment())) {
667            SetOutputValue(expr, assign->getOutputIndex());
668        }
669    }
670    else if (const Next * next = dyn_cast<const Next>(stmt)) {
671        Value * expr = compileExpression(next->getExpr());
672        if (TraceNext) {
673            genPrintRegister(next->getInitial()->getName()->to_string(), expr);
674        }
675        mMarkerMap[next->getInitial()] = expr;
676    }
677    else if (const If * ifStatement = dyn_cast<const If>(stmt))
678    {
679        compileIf(ifStatement);
680    }
681    else if (const While * whileStatement = dyn_cast<const While>(stmt))
682    {
683        compileWhile(whileStatement);
684    }
685    else if (const Call* call = dyn_cast<Call>(stmt)) {
686        //Call the callee once and store the result in the marker map.
687        auto mi = mMarkerMap.find(call);
688        if (mi == mMarkerMap.end()) {
689            auto ci = mCalleeMap.find(call->getCallee());
690            if (LLVM_UNLIKELY(ci == mCalleeMap.end())) {
691                throw std::runtime_error("Unexpected error locating static function for \"" + call->getCallee()->to_string() + "\"");
692            }
693            mi = mMarkerMap.insert(std::make_pair(call, b.CreateCall(ci->second, mBasisBitsAddr))).first;
694        }
695        // return mi->second;
696    }
697    else if (const And * pablo_and = dyn_cast<And>(stmt)) {
698        Value * expr = b.CreateAnd(compileExpression(pablo_and->getExpr1()), compileExpression(pablo_and->getExpr2()), "and");
699        if (DumpTrace) {
700            genPrintRegister(stmt->getName()->to_string(), expr);
701        }
702        mMarkerMap[pablo_and] = expr;
703        // return expr;
704    }
705    else if (const Or * pablo_or = dyn_cast<Or>(stmt)) {
706        Value * expr = b.CreateOr(compileExpression(pablo_or->getExpr1()), compileExpression(pablo_or->getExpr2()), "or");
707        if (DumpTrace) {
708            genPrintRegister(stmt->getName()->to_string(), expr);
709        }
710        mMarkerMap[pablo_or] = expr;
711        // return expr;
712    }
713    else if (const Xor * pablo_xor = dyn_cast<Xor>(stmt)) {
714        Value * expr = b.CreateXor(compileExpression(pablo_xor->getExpr1()), compileExpression(pablo_xor->getExpr2()), "xor");
715        mMarkerMap[pablo_xor] = expr;
716        // return expr;
717    }
718    else if (const Sel * sel = dyn_cast<Sel>(stmt)) {
719        Value* ifMask = compileExpression(sel->getCondition());
720        Value* ifTrue = b.CreateAnd(ifMask, compileExpression(sel->getTrueExpr()));
721        Value* ifFalse = b.CreateAnd(genNot(ifMask), compileExpression(sel->getFalseExpr()));
722        Value * expr = b.CreateOr(ifTrue, ifFalse);
723        if (DumpTrace) {
724            genPrintRegister(stmt->getName()->to_string(), expr);
725        }
726        mMarkerMap[sel] = expr;
727        // return expr;
728    }
729    else if (const Not * pablo_not = dyn_cast<Not>(stmt)) {
730        Value * expr = genNot(compileExpression(pablo_not->getExpr()));
731        if (DumpTrace) {
732            genPrintRegister(stmt->getName()->to_string(), expr);
733        }
734        mMarkerMap[pablo_not] = expr;
735        // return expr;
736    }
737    else if (const Advance * adv = dyn_cast<Advance>(stmt)) {
738        Value* strm_value = compileExpression(adv->getExpr());
739        int shift = adv->getAdvanceAmount();
740        unsigned advance_index = adv->getLocalAdvanceIndex();
741        Value * expr = genAdvanceWithCarry(strm_value, shift, advance_index, stmt->getParent());
742        if (DumpTrace) {
743            genPrintRegister(stmt->getName()->to_string(), expr);
744        }
745        mMarkerMap[adv] = expr;
746        // return expr;
747    }
748    else if (const MatchStar * mstar = dyn_cast<MatchStar>(stmt))
749    {
750        Value * marker = compileExpression(mstar->getMarker());
751        Value * cc = compileExpression(mstar->getCharClass());
752        Value * marker_and_cc = b.CreateAnd(marker, cc);
753        unsigned carry_index = mstar->getLocalCarryIndex();
754        Value * expr = b.CreateOr(b.CreateXor(genAddWithCarry(marker_and_cc, cc, carry_index, stmt->getParent()), cc), marker, "matchstar");
755        if (DumpTrace) {
756            genPrintRegister(stmt->getName()->to_string(), expr);
757        }
758        mMarkerMap[mstar] = expr;
759        // return expr;
760    }
761    else if (const ScanThru * sthru = dyn_cast<ScanThru>(stmt))
762    {
763        Value * marker_expr = compileExpression(sthru->getScanFrom());
764        Value * cc_expr = compileExpression(sthru->getScanThru());
765        unsigned carry_index = sthru->getLocalCarryIndex();
766        Value * expr = b.CreateAnd(genAddWithCarry(marker_expr, cc_expr, carry_index, stmt->getParent()), genNot(cc_expr), "scanthru");
767        if (DumpTrace) {
768            genPrintRegister(stmt->getName()->to_string(), expr);
769        }
770        mMarkerMap[sthru] = expr;
771        // return expr;
772    }
773    else {
774        PabloPrinter::print(stmt, std::cerr);
775        throw std::runtime_error("Unrecognized Pablo Statement! can't compile.");
776    }
777}
778
779Value * PabloCompiler::compileExpression(const PabloAST * expr) {
780    if (isa<Ones>(expr)) {
781        return mOneInitializer;
782    }
783    else if (isa<Zeroes>(expr)) {
784        return mZeroInitializer;
785    }
786    else if (const Next * next = dyn_cast<Next>(expr)) {
787        expr = next->getInitial();
788    }
789    auto f = mMarkerMap.find(expr);
790    if (f == mMarkerMap.end()) {
791        std::stringstream str;
792        str << "\"";
793        PabloPrinter::print(expr, str);
794        str << "\" was used before definition!";
795        throw std::runtime_error(str.str());
796    }
797    return f->second;
798}
799
800
801#ifdef USE_UADD_OVERFLOW
802#ifdef USE_TWO_UADD_OVERFLOW
803PabloCompiler::SumWithOverflowPack PabloCompiler::callUaddOverflow(Value* int128_e1, Value* int128_e2) {
804    std::vector<Value*> struct_res_params;
805    struct_res_params.push_back(int128_e1);
806    struct_res_params.push_back(int128_e2);
807    CallInst* struct_res = CallInst::Create(mFunctionUaddOverflow, struct_res_params, "uadd_overflow_res", mBasicBlock);
808    struct_res->setCallingConv(CallingConv::C);
809    struct_res->setTailCall(false);
810    AttributeSet struct_res_PAL;
811    struct_res->setAttributes(struct_res_PAL);
812
813    SumWithOverflowPack ret;
814
815    std::vector<unsigned> int128_sum_indices;
816    int128_sum_indices.push_back(0);
817    ret.sum = ExtractValueInst::Create(struct_res, int128_sum_indices, "sum", mBasicBlock);
818
819    std::vector<unsigned> int1_obit_indices;
820    int1_obit_indices.push_back(1);
821    ret.obit = ExtractValueInst::Create(struct_res, int1_obit_indices, "obit", mBasicBlock);
822
823    return ret;
824}
825#else
826PabloCompiler::SumWithOverflowPack PabloCompiler::callUaddOverflow(Value* int128_e1, Value* int128_e2, Value* int1_cin) {
827    std::vector<Value*> struct_res_params;
828    struct_res_params.push_back(int128_e1);
829    struct_res_params.push_back(int128_e2);
830    struct_res_params.push_back(int1_cin);
831    CallInst* struct_res = CallInst::Create(mFunctionUaddOverflowCarryin, struct_res_params, "uadd_overflow_res", mBasicBlock);
832    struct_res->setCallingConv(CallingConv::C);
833    struct_res->setTailCall(false);
834    AttributeSet struct_res_PAL;
835    struct_res->setAttributes(struct_res_PAL);
836
837    SumWithOverflowPack ret;
838
839    std::vector<unsigned> int128_sum_indices;
840    int128_sum_indices.push_back(0);
841    ret.sum = ExtractValueInst::Create(struct_res, int128_sum_indices, "sum", mBasicBlock);
842
843    std::vector<unsigned> int1_obit_indices;
844    int1_obit_indices.push_back(1);
845    ret.obit = ExtractValueInst::Create(struct_res, int1_obit_indices, "obit", mBasicBlock);
846
847    return ret;
848}
849#endif
850#endif
851
852
853Value* PabloCompiler::genAddWithCarry(Value* e1, Value* e2, unsigned localIndex, const PabloBlock * blk) {
854    IRBuilder<> b(mBasicBlock);
855
856    //CarryQ - carry in.
857    const int carryIdx = blk->getCarryIndexBase() + localIndex;
858    Value* carryq_value = genCarryDataLoad(carryIdx);
859#ifdef USE_TWO_UADD_OVERFLOW
860    //This is the ideal implementation, which uses two uadd.with.overflow
861    //The back end should be able to recognize this pattern and combine it into uadd.with.overflow.carryin
862    CastInst* int128_e1 = new BitCastInst(e1, b.getIntNTy(BLOCK_SIZE), "e1_128", mBasicBlock);
863    CastInst* int128_e2 = new BitCastInst(e2, b.getIntNTy(BLOCK_SIZE), "e2_128", mBasicBlock);
864    CastInst* int128_carryq_value = new BitCastInst(carryq_value, b.getIntNTy(BLOCK_SIZE), "carryq_128", mBasicBlock);
865
866    SumWithOverflowPack sumpack0, sumpack1;
867
868    sumpack0 = callUaddOverflow(int128_e1, int128_e2);
869    sumpack1 = callUaddOverflow(sumpack0.sum, int128_carryq_value);
870
871    Value* obit = b.CreateOr(sumpack0.obit, sumpack1.obit, "carry_bit");
872    Value* sum = b.CreateBitCast(sumpack1.sum, mBitBlockType, "ret_sum");
873
874    /*obit is the i1 carryout, zero extend and insert it into a v2i64 or v4i64 vector.*/
875    ConstantAggregateZero* const_packed_5 = ConstantAggregateZero::get(mBitBlockType);
876    ConstantInt* const_int32_6 = ConstantInt::get(mMod->getContext(), APInt(32, StringRef("0"), 10));
877    CastInst* int64_o0 = new ZExtInst(obit, IntegerType::get(mMod->getContext(), 64), "o0", mBasicBlock);
878    InsertElementInst* carry_out = InsertElementInst::Create(const_packed_5, int64_o0, const_int32_6, "carry_out", mBasicBlock);
879
880#elif defined USE_UADD_OVERFLOW
881    //use llvm.uadd.with.overflow.i128 or i256
882    CastInst* int128_e1 = new BitCastInst(e1, b.getIntNTy(BLOCK_SIZE), "e1_128", mBasicBlock);
883    CastInst* int128_e2 = new BitCastInst(e2, b.getIntNTy(BLOCK_SIZE), "e2_128", mBasicBlock);
884
885    //get i1 carryin from iBLOCK_SIZE
886    ConstantInt* const_int32_6 = ConstantInt::get(mMod->getContext(), APInt(32, StringRef("0"), 10));
887    ExtractElementInst * int64_carryq_value = ExtractElementInst::Create(carryq_value, const_int32_6, "carryq_64", mBasicBlock);
888    CastInst* int1_carryq_value = new TruncInst(int64_carryq_value, IntegerType::get(mMod->getContext(), 1), "carryq_1", mBasicBlock);
889
890    SumWithOverflowPack sumpack0;
891    sumpack0 = callUaddOverflow(int128_e1, int128_e2, int1_carryq_value);
892    Value* obit = sumpack0.obit;
893    Value* sum = b.CreateBitCast(sumpack0.sum, mBitBlockType, "sum");
894
895    /*obit is the i1 carryout, zero extend and insert it into a v2i64 or v4i64 vector.*/
896    ConstantAggregateZero* const_packed_5 = ConstantAggregateZero::get(mBitBlockType);
897    CastInst* int64_o0 = new ZExtInst(obit, IntegerType::get(mMod->getContext(), 64), "o0", mBasicBlock);
898    InsertElementInst* carry_out = InsertElementInst::Create(const_packed_5, int64_o0, const_int32_6, "carry_out", mBasicBlock);
899#elif (BLOCK_SIZE == 128)
900    //calculate carry through logical ops
901    Value* carrygen = b.CreateAnd(e1, e2, "carrygen");
902    Value* carryprop = b.CreateOr(e1, e2, "carryprop");
903    Value* digitsum = b.CreateAdd(e1, e2, "digitsum");
904    Value* partial = b.CreateAdd(digitsum, carryq_value, "partial");
905    Value* digitcarry = b.CreateOr(carrygen, b.CreateAnd(carryprop, genNot(partial)));
906    Value* mid_carry_in = genShiftLeft64(b.CreateLShr(digitcarry, 63), "mid_carry_in");
907
908    Value* sum = b.CreateAdd(partial, mid_carry_in, "sum");
909    Value* carry_out = genShiftHighbitToLow(BLOCK_SIZE, b.CreateOr(carrygen, b.CreateAnd(carryprop, genNot(sum))));
910#else
911    //BLOCK_SIZE == 256, there is no other implementation
912    static_assert(false, "Add with carry for 256-bit bitblock requires USE_UADD_OVERFLOW");
913#endif //USE_TWO_UADD_OVERFLOW
914
915    genCarryDataStore(carry_out, carryIdx);
916    return sum;
917}
918//#define CARRY_DEBUG
919Value* PabloCompiler::genCarryDataLoad(const unsigned index) {
920    assert (index < mCarryInVector.size());
921    if (mWhileDepth == 0) {
922        IRBuilder<> b(mBasicBlock);
923        mCarryInVector[index] = b.CreateAlignedLoad(b.CreateGEP(mCarryDataPtr, b.getInt64(index)), BLOCK_SIZE/8, false);
924    }
925#ifdef CARRY_DEBUG
926    genPrintRegister("carry_in_" + std::to_string(index), mCarryInVector[index]);
927#endif
928    return mCarryInVector[index];
929}
930
931void PabloCompiler::genCarryDataStore(Value* carryOut, const unsigned index ) {
932    assert (carryOut);
933    assert (index < mCarryOutVector.size());
934    if (mWhileDepth == 0) {
935        IRBuilder<> b(mBasicBlock);
936        b.CreateAlignedStore(carryOut, b.CreateGEP(mCarryDataPtr, b.getInt64(index)), BLOCK_SIZE/8, false);
937    }
938    mCarryDataSummaryIdx[index] = -1;
939#ifdef CARRY_DEBUG
940    genPrintRegister("carry_out_" + std::to_string(index), mCarryOutVector[index]);
941#endif
942    mCarryOutVector[index] = carryOut;
943    //std::cerr << "mCarryOutVector[" << index << "]]\n";
944}
945
946inline Value* PabloCompiler::genBitBlockAny(Value* test) {
947    IRBuilder<> b(mBasicBlock);
948    Value* cast_marker_value_1 = b.CreateBitCast(test, b.getIntNTy(BLOCK_SIZE));
949    return b.CreateICmpEQ(cast_marker_value_1, ConstantInt::get(b.getIntNTy(BLOCK_SIZE), 0));
950}
951
952Value * PabloCompiler::genShiftHighbitToLow(unsigned FieldWidth, Value * op) {
953    unsigned FieldCount = BLOCK_SIZE/FieldWidth;
954    IRBuilder<> b(mBasicBlock);
955    VectorType * vType = VectorType::get(IntegerType::get(mMod->getContext(), FieldWidth), FieldCount);
956    Value * v = b.CreateBitCast(op, vType);
957    return b.CreateBitCast(b.CreateLShr(v, FieldWidth - 1), mBitBlockType);
958}
959
960Value* PabloCompiler::genShiftLeft64(Value* e, const Twine &namehint) {
961    IRBuilder<> b(mBasicBlock);
962    Value* i128_val = b.CreateBitCast(e, b.getIntNTy(BLOCK_SIZE));
963    return b.CreateBitCast(b.CreateShl(i128_val, 64, namehint), mBitBlockType);
964}
965
966inline Value* PabloCompiler::genNot(Value* expr) {
967    IRBuilder<> b(mBasicBlock);
968    return b.CreateXor(expr, mOneInitializer, "not");
969}
970
971unsigned const LongAdvanceBase = 64;
972   
973Value* PabloCompiler::genAdvanceWithCarry(Value* strm_value, int shift_amount, unsigned localIndex, const PabloBlock * blk) {
974    if (shift_amount >= LongAdvanceBase) {
975        return genLongAdvanceWithCarry(strm_value, shift_amount, localIndex, blk);
976    }
977    IRBuilder<> b(mBasicBlock);
978    const auto advanceIndex = blk->getCarryIndexBase() + blk->getLocalCarryCount() + localIndex;
979    Value* result_value;
980   
981    if (shift_amount == 0) {
982        result_value = genCarryDataLoad(advanceIndex);
983        //b.CreateCall(mFunc_print_register, result_value);
984    }
985#if (BLOCK_SIZE == 128) && !defined(USE_LONG_INTEGER_SHIFT)
986    if (shift_amount == 1) {
987        Value* advanceq_value = genShiftHighbitToLow(BLOCK_SIZE, genCarryDataLoad(advanceIndex));
988        Value* srli_1_value = b.CreateLShr(strm_value, 63);
989        Value* packed_shuffle;
990        Constant* const_packed_1_elems [] = {b.getInt32(0), b.getInt32(2)};
991        Constant* const_packed_1 = ConstantVector::get(const_packed_1_elems);
992        packed_shuffle = b.CreateShuffleVector(advanceq_value, srli_1_value, const_packed_1);
993       
994        Constant* const_packed_2_elems[] = {b.getInt64(1), b.getInt64(1)};
995        Constant* const_packed_2 = ConstantVector::get(const_packed_2_elems);
996       
997        Value* shl_value = b.CreateShl(strm_value, const_packed_2);
998        result_value = b.CreateOr(shl_value, packed_shuffle, "advance");
999    }
1000    else { //if (block_shift < BLOCK_SIZE) {
1001        // This is the preferred logic, but is too slow for the general case.
1002        // We need to speed up our custom LLVM for this code.
1003        Value* advanceq_longint = b.CreateBitCast(genCarryDataLoad(advanceIndex), b.getIntNTy(BLOCK_SIZE));
1004        Value* strm_longint = b.CreateBitCast(strm_value, b.getIntNTy(BLOCK_SIZE));
1005        Value* adv_longint = b.CreateOr(b.CreateShl(strm_longint, shift_amount), b.CreateLShr(advanceq_longint, BLOCK_SIZE - shift_amount), "advance");
1006        result_value = b.CreateBitCast(adv_longint, mBitBlockType);
1007    }
1008#else
1009    Value* advanceq_longint = b.CreateBitCast(genCarryDataLoad(advanceIndex), b.getIntNTy(BLOCK_SIZE));
1010    Value* strm_longint = b.CreateBitCast(strm_value, b.getIntNTy(BLOCK_SIZE));
1011    Value* adv_longint = b.CreateOr(b.CreateShl(strm_longint, block_shift), b.CreateLShr(advanceq_longint, BLOCK_SIZE - shift_amount), "advance");
1012    result_value = b.CreateBitCast(adv_longint, mBitBlockType);
1013   
1014#endif
1015    genCarryDataStore(strm_value, advanceIndex);
1016    return result_value;
1017}
1018
1019//
1020// Generate code for long advances >= LongAdvanceBase
1021//
1022Value* PabloCompiler::genLongAdvanceWithCarry(Value* strm_value, int shift_amount, unsigned localIndex, const PabloBlock * blk) {
1023    IRBuilder<> b(mBasicBlock);
1024    int advEntries = (shift_amount - 1) / BLOCK_SIZE + 1;
1025    //int advCeil = log2ceil(advEntries);
1026    //Value * indexMask = b.getInt64(advCeil - 1);
1027    int block_shift = shift_amount % BLOCK_SIZE;
1028    const auto advanceIndex = blk->getCarryIndexBase() + blk->getLocalCarryCount() + localIndex;
1029    //Value * blockIndex = b.CreateAnd(mBlockNo, indexMask);
1030    //Value * idx2 = b.CreateAnd(b.CreateAdd(mBlockNo - b.getInt64(advEntries - 1)), indexMask);
1031    const auto storeIdx = advanceIndex;
1032    const auto loadIdx = advanceIndex + advEntries - 1;
1033    Value* result_value;
1034
1035    if (block_shift == 0) {
1036        result_value = genCarryDataLoad(loadIdx);
1037    }
1038    else if (advEntries == 1) {
1039        Value* advanceq_longint = b.CreateBitCast(genCarryDataLoad(loadIdx), b.getIntNTy(BLOCK_SIZE));
1040        Value* strm_longint = b.CreateBitCast(strm_value, b.getIntNTy(BLOCK_SIZE));
1041        Value* adv_longint = b.CreateOr(b.CreateShl(strm_longint, block_shift), b.CreateLShr(advanceq_longint, BLOCK_SIZE - block_shift), "advance");
1042        result_value = b.CreateBitCast(adv_longint, mBitBlockType);
1043    }
1044    else {
1045        // The advance is based on the two oldest bit blocks in the advance queue.
1046        Value* advanceq_longint = b.CreateBitCast(genCarryDataLoad(loadIdx), b.getIntNTy(BLOCK_SIZE));
1047        Value* strm_longint = b.CreateBitCast(genCarryDataLoad(loadIdx-1), b.getIntNTy(BLOCK_SIZE));
1048        Value* adv_longint = b.CreateOr(b.CreateShl(strm_longint, block_shift), b.CreateLShr(advanceq_longint, BLOCK_SIZE - block_shift), "longadvance");
1049        result_value = b.CreateBitCast(adv_longint, mBitBlockType);
1050    }
1051    // copy entries from previous blocks forward
1052    for (int i = loadIdx; i > storeIdx; i--) {
1053        genCarryDataStore(genCarryDataLoad(i-1), i);
1054    }
1055    genCarryDataStore(strm_value, storeIdx);
1056    return result_value;
1057}
1058   
1059void PabloCompiler::SetOutputValue(Value * marker, const unsigned index) {
1060    IRBuilder<> b(mBasicBlock);
1061    if (marker->getType()->isPointerTy()) {
1062        marker = b.CreateAlignedLoad(marker, BLOCK_SIZE/8, false);
1063    }
1064    Value* indices[] = {b.getInt64(0), b.getInt32(index)};
1065    Value* gep = b.CreateGEP(mOutputAddrPtr, indices);
1066    b.CreateAlignedStore(marker, gep, BLOCK_SIZE/8, false);
1067}
1068
1069CompiledPabloFunction::CompiledPabloFunction(size_t carryDataSize, Function * function, ExecutionEngine * executionEngine)
1070: CarryDataSize(carryDataSize)
1071, FunctionPointer(executionEngine->getPointerToFunction(function))
1072, mFunction(function)
1073, mExecutionEngine(executionEngine)
1074{
1075
1076}
1077
1078// Clean up the memory for the compiled function once we're finished using it.
1079CompiledPabloFunction::~CompiledPabloFunction() {
1080    if (mExecutionEngine) {
1081        assert (mFunction);
1082        // mExecutionEngine->freeMachineCodeForFunction(mFunction); // This function only prints a "not supported" message. Reevaluate with LLVM 3.6.
1083        delete mExecutionEngine;
1084    }
1085}
1086
1087}
Note: See TracBrowser for help on using the repository browser.