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

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

Decouple phi processing for while carries vs. next nodes

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