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

Last change on this file since 4589 was 4589, checked in by nmedfort, 4 years ago

Possible fix for -dump-trace

File size: 46.2 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 - 1));
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            if (LLVM_UNLIKELY(f == mMarkerMap.end())) {
502                throw std::runtime_error("Fatal error during compileIf: could not find \"" + assign->getName()->to_string() + "\" in the marker map.");
503            }
504            phi->addIncoming(mZeroInitializer, ifEntryBlock);
505            phi->addIncoming(f->second, mBasicBlock);
506            mMarkerMap[assign] = phi;
507        }
508        // Create the phi Node for the summary variable, if needed.
509        if (cd.summaryNeededInParentBlock()) {
510            PHINode * summary_phi = bEnd.CreatePHI(mBitBlockType, 2, "summary");
511            summary_phi->addIncoming(mZeroInitializer, ifEntryBlock);
512            summary_phi->addIncoming(mCarryOutVector[carrySummaryIndex], mBasicBlock);
513            mCarryOutVector[carrySummaryIndex] = summary_phi;
514        }
515       
516        // Set the basic block to the new end block
517        mBasicBlock = ifEndBlock;
518}
519
520void PabloCompiler::compileWhile(const While * whileStatement) {
521        const PabloBlockCarryData & cd = whileStatement -> getBody().carryData;
522        const unsigned baseCarryDataIdx = cd.getBlockCarryDataIndex();
523        const unsigned carryDataSize = cd.getTotalCarryDataSize();
524   
525        if (mWhileDepth == 0) {
526            for (auto i = 0; i < carryDataSize; ++i) {
527                genCarryDataLoad(baseCarryDataIdx + i);
528            }
529        }
530
531        SmallVector<const Next*, 4> nextNodes;
532        SmallVector<PHINode *, 4> nextPhis;
533        for (const PabloAST * node : whileStatement->getBody()) {
534            if (isa<Next>(node)) {
535                nextNodes.push_back(cast<Next>(node));
536            }
537        }
538
539        // Compile the initial iteration statements; the calls to genCarryDataStore will update the
540        // mCarryOutVector with the appropriate values. Although we're not actually entering a new basic
541        // block yet, increment the nesting depth so that any calls to genCarryDataLoad or genCarryDataStore
542        // will refer to the previous value.
543
544        ++mWhileDepth;
545
546        compileBlock(whileStatement->getBody());
547        // Reset the carry queue index. Note: this ought to be changed in the future. Currently this assumes
548        // that compiling the while body twice will generate the equivalent IR. This is not necessarily true
549        // but works for now.
550
551        BasicBlock* whileCondBlock = BasicBlock::Create(mMod->getContext(), "while.cond", mFunction, 0);
552        BasicBlock* whileBodyBlock = BasicBlock::Create(mMod->getContext(), "while.body", mFunction, 0);
553        BasicBlock* whileEndBlock = BasicBlock::Create(mMod->getContext(), "while.end", mFunction, 0);
554
555        // Note: compileBlock may update the mBasicBlock pointer if the body contains nested loops. It
556        // may not be same one that we entered the function with.
557        IRBuilder<> bEntry(mBasicBlock);
558#ifdef WHILE_MULTI_CARRY
559        Value * secondCarryFramePtr = bEntry.CreateGEP(mCarryFramePtr, bEntry.getInt64(WHILEBODYCARRYTOTALSIZE));
560        mCarryFramePtr = secondCarryFramePtr;
561#endif       
562
563        bEntry.CreateBr(whileCondBlock);
564
565        // CONDITION BLOCK
566        IRBuilder<> bCond(whileCondBlock);
567        // generate phi nodes for any carry propogating instruction
568        std::vector<PHINode*> phiNodes(carryDataSize);
569        unsigned index = 0;
570        for (index = 0; index < carryDataSize; ++index) {
571            PHINode * phi = bCond.CreatePHI(mBitBlockType, 2);
572            phi->addIncoming(mCarryOutVector[baseCarryDataIdx + index], mBasicBlock);
573            mCarryInVector[baseCarryDataIdx + index] = mZeroInitializer; // (use phi for multi-carry mode.)
574            phiNodes[index] = phi;
575        }
576        // and for any Next nodes in the loop body
577        for (const Next * n : nextNodes) {
578            PHINode * phi = bCond.CreatePHI(mBitBlockType, 2, n->getName()->value());
579            auto f = mMarkerMap.find(n->getInitial());
580            assert (f != mMarkerMap.end());
581            phi->addIncoming(f->second, mBasicBlock);
582            mMarkerMap[n->getInitial()] = phi;
583            nextPhis.push_back(phi);
584        }
585#ifdef WHILE_MULTI_CARRY
586        //  CarryFramePtr
587        PHINode * carryFramePtrPhi = bCond.CreatePHI(mBitBlockType, 2, "CarryFramePtr");
588        carryFramePtrPhi->addIncoming(mCarryFramePtr, mBasicBlock);
589        mCarryFramePtr = carryFramePtrPhi;
590#endif       
591        mBasicBlock = whileCondBlock;
592        bCond.CreateCondBr(genBitBlockAny(compileExpression(whileStatement->getCondition())), whileEndBlock, whileBodyBlock);
593
594        // BODY BLOCK
595        //std::cerr << "Compile loop body\n";
596        mBasicBlock = whileBodyBlock;
597        compileBlock(whileStatement->getBody());
598       
599        // update phi nodes for any carry propogating instruction
600        IRBuilder<> bWhileBody(mBasicBlock);
601        for (index = 0; index < carryDataSize; ++index) {
602            PHINode * phi = phiNodes[index];
603            Value * carryOut = bWhileBody.CreateOr(phi, mCarryOutVector[baseCarryDataIdx + index]);
604            phi->addIncoming(carryOut, mBasicBlock);
605            mCarryOutVector[baseCarryDataIdx + index] = phi;
606        }
607       
608        // and for any Next nodes in the loop body
609        for (int i = 0; i < nextNodes.size(); i++) {
610            const Next * n = nextNodes[i];
611            auto f = mMarkerMap.find(n->getInitial());
612            assert (f != mMarkerMap.end());
613            PHINode * phi = nextPhis[i];
614            phi->addIncoming(f->second, mBasicBlock);
615            mMarkerMap[n->getInitial()] = phi;
616        }
617#ifdef WHILE_MULTI_CARRY
618        Value * nextCarryFramePtr = bWhileBody.CreateGEP(mCarryFramePtr, bWhileBody.getInt64(WHILEBODYCARRYTOTALSIZE));
619        carryFramePtrPhi->addIncoming(nextCarryFramePtr, mBasicBlock);
620#endif       
621        bWhileBody.CreateBr(whileCondBlock);
622
623        // EXIT BLOCK
624        mBasicBlock = whileEndBlock;
625        if (--mWhileDepth == 0) {
626            for (index = 0; index < carryDataSize; ++index) {
627                genCarryDataStore(phiNodes[index], baseCarryDataIdx + index);
628            }
629        }
630 
631}
632
633void PabloCompiler::compileStatement(const Statement * stmt)
634{
635    IRBuilder<> b(mBasicBlock);
636    if (const Assign * assign = dyn_cast<const Assign>(stmt)) {
637        Value * expr = compileExpression(assign->getExpr());
638        if (DumpTrace) {
639            genPrintRegister(assign->getName()->to_string(), expr);
640        }
641        mMarkerMap[assign] = expr;
642        if (LLVM_UNLIKELY(assign->isOutputAssignment())) {
643            SetOutputValue(expr, assign->getOutputIndex());
644        }
645    }
646    else if (const Next * next = dyn_cast<const Next>(stmt)) {
647        Value * expr = compileExpression(next->getExpr());
648        if (TraceNext) {
649            genPrintRegister(next->getInitial()->getName()->to_string(), expr);
650        }
651        mMarkerMap[next->getInitial()] = expr;
652    }
653    else if (const If * ifStatement = dyn_cast<const If>(stmt))
654    {
655        compileIf(ifStatement);
656    }
657    else if (const While * whileStatement = dyn_cast<const While>(stmt))
658    {
659        compileWhile(whileStatement);
660    }
661    else if (const Call* call = dyn_cast<Call>(stmt)) {
662        //Call the callee once and store the result in the marker map.
663        auto mi = mMarkerMap.find(call);
664        if (mi == mMarkerMap.end()) {
665            auto ci = mCalleeMap.find(call->getCallee());
666            if (LLVM_UNLIKELY(ci == mCalleeMap.end())) {
667                throw std::runtime_error("Unexpected error locating static function for \"" + call->getCallee()->to_string() + "\"");
668            }
669            mi = mMarkerMap.insert(std::make_pair(call, b.CreateCall(ci->second, mBasisBitsAddr))).first;
670        }
671        // return mi->second;
672    }
673    else if (const And * pablo_and = dyn_cast<And>(stmt)) {
674        Value * expr = b.CreateAnd(compileExpression(pablo_and->getExpr1()), compileExpression(pablo_and->getExpr2()), "and");
675        if (DumpTrace) {
676            genPrintRegister(stmt->getName()->to_string(), expr);
677        }
678        mMarkerMap[pablo_and] = expr;
679        // return expr;
680    }
681    else if (const Or * pablo_or = dyn_cast<Or>(stmt)) {
682        Value * expr = b.CreateOr(compileExpression(pablo_or->getExpr1()), compileExpression(pablo_or->getExpr2()), "or");
683        if (DumpTrace) {
684            genPrintRegister(stmt->getName()->to_string(), expr);
685        }
686        mMarkerMap[pablo_or] = expr;
687        // return expr;
688    }
689    else if (const Xor * pablo_xor = dyn_cast<Xor>(stmt)) {
690        Value * expr = b.CreateXor(compileExpression(pablo_xor->getExpr1()), compileExpression(pablo_xor->getExpr2()), "xor");
691        mMarkerMap[pablo_xor] = expr;
692        // return expr;
693    }
694    else if (const Sel * sel = dyn_cast<Sel>(stmt)) {
695        Value* ifMask = compileExpression(sel->getCondition());
696        Value* ifTrue = b.CreateAnd(ifMask, compileExpression(sel->getTrueExpr()));
697        Value* ifFalse = b.CreateAnd(genNot(ifMask), compileExpression(sel->getFalseExpr()));
698        Value * expr = b.CreateOr(ifTrue, ifFalse);
699        if (DumpTrace) {
700            genPrintRegister(stmt->getName()->to_string(), expr);
701        }
702        mMarkerMap[sel] = expr;
703        // return expr;
704    }
705    else if (const Not * pablo_not = dyn_cast<Not>(stmt)) {
706        Value * expr = genNot(compileExpression(pablo_not->getExpr()));
707        if (DumpTrace) {
708            genPrintRegister(stmt->getName()->to_string(), expr);
709        }
710        mMarkerMap[pablo_not] = expr;
711        // return expr;
712    }
713    else if (const Advance * adv = dyn_cast<Advance>(stmt)) {
714        Value* strm_value = compileExpression(adv->getExpr());
715        int shift = adv->getAdvanceAmount();
716        unsigned advance_index = adv->getLocalAdvanceIndex();
717        Value * expr = genAdvanceWithCarry(strm_value, shift, advance_index, stmt->getParent());
718        if (DumpTrace) {
719            genPrintRegister(stmt->getName()->to_string(), expr);
720        }
721        mMarkerMap[adv] = expr;
722        // return expr;
723    }
724    else if (const MatchStar * mstar = dyn_cast<MatchStar>(stmt))
725    {
726        Value * marker = compileExpression(mstar->getMarker());
727        Value * cc = compileExpression(mstar->getCharClass());
728        Value * marker_and_cc = b.CreateAnd(marker, cc);
729        unsigned carry_index = mstar->getLocalCarryIndex();
730        Value * expr = b.CreateOr(b.CreateXor(genAddWithCarry(marker_and_cc, cc, carry_index, stmt->getParent()), cc), marker, "matchstar");
731        if (DumpTrace) {
732            genPrintRegister(stmt->getName()->to_string(), expr);
733        }
734        mMarkerMap[mstar] = expr;
735        // return expr;
736    }
737    else if (const ScanThru * sthru = dyn_cast<ScanThru>(stmt))
738    {
739        Value * marker_expr = compileExpression(sthru->getScanFrom());
740        Value * cc_expr = compileExpression(sthru->getScanThru());
741        unsigned carry_index = sthru->getLocalCarryIndex();
742        Value * expr = b.CreateAnd(genAddWithCarry(marker_expr, cc_expr, carry_index, stmt->getParent()), genNot(cc_expr), "scanthru");
743        if (DumpTrace) {
744            genPrintRegister(stmt->getName()->to_string(), expr);
745        }
746        mMarkerMap[sthru] = expr;
747        // return expr;
748    }
749    else {
750        llvm::raw_os_ostream cerr(std::cerr);
751        PabloPrinter::print(stmt, cerr);
752        throw std::runtime_error("Unrecognized Pablo Statement! can't compile.");
753    }
754}
755
756Value * PabloCompiler::compileExpression(const PabloAST * expr) {
757    if (isa<Ones>(expr)) {
758        return mOneInitializer;
759    }
760    else if (isa<Zeroes>(expr)) {
761        return mZeroInitializer;
762    }
763    else if (const Next * next = dyn_cast<Next>(expr)) {
764        expr = next->getInitial();
765    }
766    auto f = mMarkerMap.find(expr);
767    if (f == mMarkerMap.end()) {
768        std::string o;
769        llvm::raw_string_ostream str(o);
770        str << "\"";
771        PabloPrinter::print(expr, str);
772        str << "\" was used before definition!";
773        throw std::runtime_error(str.str());
774    }
775    return f->second;
776}
777
778
779#ifdef USE_UADD_OVERFLOW
780#ifdef USE_TWO_UADD_OVERFLOW
781PabloCompiler::SumWithOverflowPack PabloCompiler::callUaddOverflow(Value* int128_e1, Value* int128_e2) {
782    std::vector<Value*> struct_res_params;
783    struct_res_params.push_back(int128_e1);
784    struct_res_params.push_back(int128_e2);
785    CallInst* struct_res = CallInst::Create(mFunctionUaddOverflow, struct_res_params, "uadd_overflow_res", mBasicBlock);
786    struct_res->setCallingConv(CallingConv::C);
787    struct_res->setTailCall(false);
788    AttributeSet struct_res_PAL;
789    struct_res->setAttributes(struct_res_PAL);
790
791    SumWithOverflowPack ret;
792
793    std::vector<unsigned> int128_sum_indices;
794    int128_sum_indices.push_back(0);
795    ret.sum = ExtractValueInst::Create(struct_res, int128_sum_indices, "sum", mBasicBlock);
796
797    std::vector<unsigned> int1_obit_indices;
798    int1_obit_indices.push_back(1);
799    ret.obit = ExtractValueInst::Create(struct_res, int1_obit_indices, "obit", mBasicBlock);
800
801    return ret;
802}
803#else
804PabloCompiler::SumWithOverflowPack PabloCompiler::callUaddOverflow(Value* int128_e1, Value* int128_e2, Value* int1_cin) {
805    std::vector<Value*> struct_res_params;
806    struct_res_params.push_back(int128_e1);
807    struct_res_params.push_back(int128_e2);
808    struct_res_params.push_back(int1_cin);
809    CallInst* struct_res = CallInst::Create(mFunctionUaddOverflowCarryin, struct_res_params, "uadd_overflow_res", mBasicBlock);
810    struct_res->setCallingConv(CallingConv::C);
811    struct_res->setTailCall(false);
812    AttributeSet struct_res_PAL;
813    struct_res->setAttributes(struct_res_PAL);
814
815    SumWithOverflowPack ret;
816
817    std::vector<unsigned> int128_sum_indices;
818    int128_sum_indices.push_back(0);
819    ret.sum = ExtractValueInst::Create(struct_res, int128_sum_indices, "sum", mBasicBlock);
820
821    std::vector<unsigned> int1_obit_indices;
822    int1_obit_indices.push_back(1);
823    ret.obit = ExtractValueInst::Create(struct_res, int1_obit_indices, "obit", mBasicBlock);
824
825    return ret;
826}
827#endif
828#endif
829
830
831Value* PabloCompiler::genAddWithCarry(Value* e1, Value* e2, unsigned localIndex, const PabloBlock * blk) {
832    IRBuilder<> b(mBasicBlock);
833    const PabloBlockCarryData & cd = blk->carryData;
834    const unsigned carryIdx = cd.carryOpCarryDataOffset(localIndex);
835    Value* carryq_value = genCarryDataLoad(carryIdx);
836#ifdef USE_TWO_UADD_OVERFLOW
837    //This is the ideal implementation, which uses two uadd.with.overflow
838    //The back end should be able to recognize this pattern and combine it into uadd.with.overflow.carryin
839    CastInst* int128_e1 = new BitCastInst(e1, b.getIntNTy(BLOCK_SIZE), "e1_128", mBasicBlock);
840    CastInst* int128_e2 = new BitCastInst(e2, b.getIntNTy(BLOCK_SIZE), "e2_128", mBasicBlock);
841    CastInst* int128_carryq_value = new BitCastInst(carryq_value, b.getIntNTy(BLOCK_SIZE), "carryq_128", mBasicBlock);
842
843    SumWithOverflowPack sumpack0, sumpack1;
844
845    sumpack0 = callUaddOverflow(int128_e1, int128_e2);
846    sumpack1 = callUaddOverflow(sumpack0.sum, int128_carryq_value);
847
848    Value* obit = b.CreateOr(sumpack0.obit, sumpack1.obit, "carry_bit");
849    Value* sum = b.CreateBitCast(sumpack1.sum, mBitBlockType, "ret_sum");
850
851    /*obit is the i1 carryout, zero extend and insert it into a v2i64 or v4i64 vector.*/
852    ConstantAggregateZero* const_packed_5 = ConstantAggregateZero::get(mBitBlockType);
853    ConstantInt* const_int32_6 = ConstantInt::get(mMod->getContext(), APInt(32, StringRef("0"), 10));
854    CastInst* int64_o0 = new ZExtInst(obit, IntegerType::get(mMod->getContext(), 64), "o0", mBasicBlock);
855    InsertElementInst* carry_out = InsertElementInst::Create(const_packed_5, int64_o0, const_int32_6, "carry_out", mBasicBlock);
856
857#elif defined USE_UADD_OVERFLOW
858    //use llvm.uadd.with.overflow.i128 or i256
859    CastInst* int128_e1 = new BitCastInst(e1, b.getIntNTy(BLOCK_SIZE), "e1_128", mBasicBlock);
860    CastInst* int128_e2 = new BitCastInst(e2, b.getIntNTy(BLOCK_SIZE), "e2_128", mBasicBlock);
861
862    //get i1 carryin from iBLOCK_SIZE
863    ConstantInt* const_int32_6 = ConstantInt::get(mMod->getContext(), APInt(32, StringRef("0"), 10));
864    ExtractElementInst * int64_carryq_value = ExtractElementInst::Create(carryq_value, const_int32_6, "carryq_64", mBasicBlock);
865    CastInst* int1_carryq_value = new TruncInst(int64_carryq_value, IntegerType::get(mMod->getContext(), 1), "carryq_1", mBasicBlock);
866
867    SumWithOverflowPack sumpack0;
868    sumpack0 = callUaddOverflow(int128_e1, int128_e2, int1_carryq_value);
869    Value* obit = sumpack0.obit;
870    Value* sum = b.CreateBitCast(sumpack0.sum, mBitBlockType, "sum");
871
872    /*obit is the i1 carryout, zero extend and insert it into a v2i64 or v4i64 vector.*/
873    ConstantAggregateZero* const_packed_5 = ConstantAggregateZero::get(mBitBlockType);
874    CastInst* int64_o0 = new ZExtInst(obit, IntegerType::get(mMod->getContext(), 64), "o0", mBasicBlock);
875    InsertElementInst* carry_out = InsertElementInst::Create(const_packed_5, int64_o0, const_int32_6, "carry_out", mBasicBlock);
876#elif (BLOCK_SIZE == 128)
877    //calculate carry through logical ops
878    Value* carrygen = b.CreateAnd(e1, e2, "carrygen");
879    Value* carryprop = b.CreateOr(e1, e2, "carryprop");
880    Value* digitsum = b.CreateAdd(e1, e2, "digitsum");
881    Value* partial = b.CreateAdd(digitsum, carryq_value, "partial");
882    Value* digitcarry = b.CreateOr(carrygen, b.CreateAnd(carryprop, genNot(partial)));
883    Value* mid_carry_in = genShiftLeft64(b.CreateLShr(digitcarry, 63), "mid_carry_in");
884
885    Value* sum = b.CreateAdd(partial, mid_carry_in, "sum");
886    Value* carry_out = genShiftHighbitToLow(BLOCK_SIZE, b.CreateOr(carrygen, b.CreateAnd(carryprop, genNot(sum))));
887#else
888    //BLOCK_SIZE == 256, there is no other implementation
889    static_assert(false, "Add with carry for 256-bit bitblock requires USE_UADD_OVERFLOW");
890#endif //USE_TWO_UADD_OVERFLOW
891
892    genCarryDataStore(carry_out, carryIdx);
893    return sum;
894}
895//#define CARRY_DEBUG
896Value* PabloCompiler::genCarryDataLoad(const unsigned index) {
897    assert (index < mCarryInVector.size());
898    if (mWhileDepth == 0) {
899        IRBuilder<> b(mBasicBlock);
900        mCarryInVector[index] = b.CreateAlignedLoad(b.CreateGEP(mCarryDataPtr, b.getInt64(index)), BLOCK_SIZE/8, false);
901    }
902#ifdef CARRY_DEBUG
903    std::cerr << "genCarryDataLoad " << index << std::endl;
904    genPrintRegister("carry_in_" + std::to_string(index), mCarryInVector[index]);
905#endif
906    return mCarryInVector[index];
907}
908
909void PabloCompiler::genCarryDataStore(Value* carryOut, const unsigned index ) {
910    assert (carryOut);
911    assert (index < mCarryOutVector.size());
912    if (mWhileDepth == 0) {
913        IRBuilder<> b(mBasicBlock);
914        b.CreateAlignedStore(carryOut, b.CreateGEP(mCarryDataPtr, b.getInt64(index)), BLOCK_SIZE/8, false);
915    }
916    mCarryDataSummaryIdx[index] = -1;
917    mCarryOutVector[index] = carryOut;
918#ifdef CARRY_DEBUG
919    std::cerr << "genCarryDataStore " << index << std::endl;
920    genPrintRegister("carry_out_" + std::to_string(index), mCarryOutVector[index]);
921#endif
922    //std::cerr << "mCarryOutVector[" << index << "]]\n";
923}
924
925inline Value* PabloCompiler::genBitBlockAny(Value* test) {
926    IRBuilder<> b(mBasicBlock);
927    Value* cast_marker_value_1 = b.CreateBitCast(test, b.getIntNTy(BLOCK_SIZE));
928    return b.CreateICmpEQ(cast_marker_value_1, ConstantInt::get(b.getIntNTy(BLOCK_SIZE), 0));
929}
930
931Value * PabloCompiler::genShiftHighbitToLow(unsigned FieldWidth, Value * op) {
932    unsigned FieldCount = BLOCK_SIZE/FieldWidth;
933    IRBuilder<> b(mBasicBlock);
934    VectorType * vType = VectorType::get(IntegerType::get(mMod->getContext(), FieldWidth), FieldCount);
935    Value * v = b.CreateBitCast(op, vType);
936    return b.CreateBitCast(b.CreateLShr(v, FieldWidth - 1), mBitBlockType);
937}
938
939Value* PabloCompiler::genShiftLeft64(Value* e, const Twine &namehint) {
940    IRBuilder<> b(mBasicBlock);
941    Value* i128_val = b.CreateBitCast(e, b.getIntNTy(BLOCK_SIZE));
942    return b.CreateBitCast(b.CreateShl(i128_val, 64, namehint), mBitBlockType);
943}
944
945inline Value* PabloCompiler::genNot(Value* expr) {
946    IRBuilder<> b(mBasicBlock);
947    return b.CreateXor(expr, mOneInitializer, "not");
948}
949
950Value* PabloCompiler::genAdvanceWithCarry(Value* strm_value, int shift_amount, unsigned localIndex, const PabloBlock * blk) {
951    if (shift_amount >= LongAdvanceBase) {
952        return genLongAdvanceWithCarry(strm_value, shift_amount, localIndex, blk);
953    }
954    else if (shift_amount == 1) {
955        return genUnitAdvanceWithCarry(strm_value, localIndex, blk);
956    }
957    IRBuilder<> b(mBasicBlock);
958    const PabloBlockCarryData & cd = blk->carryData;
959    const auto advanceIndex = cd.shortAdvanceCarryDataOffset(localIndex);
960    Value* result_value;
961   
962    if (shift_amount == 0) {
963        result_value = genCarryDataLoad(advanceIndex);
964    }
965    else {
966        Value* advanceq_longint = b.CreateBitCast(genCarryDataLoad(advanceIndex), b.getIntNTy(BLOCK_SIZE));
967        Value* strm_longint = b.CreateBitCast(strm_value, b.getIntNTy(BLOCK_SIZE));
968        Value* adv_longint = b.CreateOr(b.CreateShl(strm_longint, shift_amount), b.CreateLShr(advanceq_longint, BLOCK_SIZE - shift_amount), "advance");
969        result_value = b.CreateBitCast(adv_longint, mBitBlockType);
970    }
971    genCarryDataStore(strm_value, advanceIndex);
972    return result_value;
973}
974                   
975Value* PabloCompiler::genUnitAdvanceWithCarry(Value* strm_value, unsigned localIndex, const PabloBlock * blk) {
976    IRBuilder<> b(mBasicBlock);
977    const PabloBlockCarryData & cd = blk->carryData;
978    const auto advanceIndex = cd.unitAdvanceCarryDataOffset(localIndex);
979    Value* result_value;
980   
981#if (BLOCK_SIZE == 128) && !defined(USE_LONG_INTEGER_SHIFT)
982    Value* advanceq_value = genShiftHighbitToLow(BLOCK_SIZE, genCarryDataLoad(advanceIndex));
983    Value* srli_1_value = b.CreateLShr(strm_value, 63);
984    Value* packed_shuffle;
985    Constant* const_packed_1_elems [] = {b.getInt32(0), b.getInt32(2)};
986    Constant* const_packed_1 = ConstantVector::get(const_packed_1_elems);
987    packed_shuffle = b.CreateShuffleVector(advanceq_value, srli_1_value, const_packed_1);
988   
989    Constant* const_packed_2_elems[] = {b.getInt64(1), b.getInt64(1)};
990    Constant* const_packed_2 = ConstantVector::get(const_packed_2_elems);
991   
992    Value* shl_value = b.CreateShl(strm_value, const_packed_2);
993    result_value = b.CreateOr(shl_value, packed_shuffle, "advance");
994#else
995    Value* advanceq_longint = b.CreateBitCast(genCarryDataLoad(advanceIndex), b.getIntNTy(BLOCK_SIZE));
996    Value* strm_longint = b.CreateBitCast(strm_value, b.getIntNTy(BLOCK_SIZE));
997    Value* adv_longint = b.CreateOr(b.CreateShl(strm_longint, 1), b.CreateLShr(advanceq_longint, BLOCK_SIZE - 1), "advance");
998    result_value = b.CreateBitCast(adv_longint, mBitBlockType);
999   
1000#endif
1001    genCarryDataStore(strm_value, advanceIndex);
1002    return result_value;
1003}
1004                   
1005                    //
1006// Generate code for long advances >= LongAdvanceBase
1007//
1008Value* PabloCompiler::genLongAdvanceWithCarry(Value* strm_value, int shift_amount, unsigned localIndex, const PabloBlock * blk) {
1009    IRBuilder<> b(mBasicBlock);
1010    const PabloBlockCarryData & cd = blk->carryData;
1011    const unsigned block_shift = shift_amount % BLOCK_SIZE;
1012    const unsigned advanceEntries = cd.longAdvanceEntries(shift_amount);
1013    const unsigned bufsize = cd.longAdvanceBufferSize(shift_amount);
1014
1015    Value * indexMask = b.getInt64(bufsize - 1);  // A mask to implement circular buffer indexing
1016    Value * advBaseIndex = b.getInt64(cd.longAdvanceCarryDataOffset(localIndex));
1017    Value * storeIndex = b.CreateAdd(b.CreateAnd(mBlockNo, indexMask), advBaseIndex);
1018    Value * loadIndex = b.CreateAdd(b.CreateAnd(b.CreateSub(mBlockNo, b.getInt64(advanceEntries)), indexMask), advBaseIndex);
1019    Value * storePtr = b.CreateGEP(mCarryDataPtr, storeIndex);
1020    Value * loadPtr = b.CreateGEP(mCarryDataPtr, loadIndex);
1021    Value* result_value;
1022
1023    if (block_shift == 0) {
1024        result_value = b.CreateAlignedLoad(loadPtr, BLOCK_SIZE/8);
1025    }
1026    else if (advanceEntries == 1) {
1027        Value* advanceq_longint = b.CreateBitCast(b.CreateAlignedLoad(loadPtr, BLOCK_SIZE/8), b.getIntNTy(BLOCK_SIZE));
1028        Value* strm_longint = b.CreateBitCast(strm_value, b.getIntNTy(BLOCK_SIZE));
1029        Value* adv_longint = b.CreateOr(b.CreateShl(strm_longint, block_shift), b.CreateLShr(advanceq_longint, BLOCK_SIZE - block_shift), "advance");
1030        result_value = b.CreateBitCast(adv_longint, mBitBlockType);
1031    }
1032    else {
1033        // The advance is based on the two oldest bit blocks in the advance buffer.
1034        // The buffer is maintained as a circular buffer of size bufsize.
1035        // Indexes within the buffer are computed by bitwise and with the indexMask.
1036        Value * loadIndex2 = b.CreateAdd(b.CreateAnd(b.CreateSub(mBlockNo, b.getInt64(advanceEntries-1)), indexMask), advBaseIndex);
1037        Value * loadPtr2 = b.CreateGEP(mCarryDataPtr, loadIndex2);
1038        Value* advanceq_longint = b.CreateBitCast(b.CreateAlignedLoad(loadPtr, BLOCK_SIZE/8), b.getIntNTy(BLOCK_SIZE));
1039        //genPrintRegister("advanceq_longint", b.CreateBitCast(advanceq_longint, mBitBlockType));
1040        Value* strm_longint = b.CreateBitCast(b.CreateAlignedLoad(loadPtr2, BLOCK_SIZE/8), b.getIntNTy(BLOCK_SIZE));
1041        //genPrintRegister("strm_longint", b.CreateBitCast(strm_longint, mBitBlockType));
1042        Value* adv_longint = b.CreateOr(b.CreateShl(strm_longint, block_shift), b.CreateLShr(advanceq_longint, BLOCK_SIZE - block_shift), "longadvance");
1043        result_value = b.CreateBitCast(adv_longint, mBitBlockType);
1044    }
1045    b.CreateAlignedStore(strm_value, storePtr, BLOCK_SIZE/8);
1046    return result_value;
1047}
1048   
1049void PabloCompiler::SetOutputValue(Value * marker, const unsigned index) {
1050    IRBuilder<> b(mBasicBlock);
1051    if (marker->getType()->isPointerTy()) {
1052        marker = b.CreateAlignedLoad(marker, BLOCK_SIZE/8, false);
1053    }
1054    Value* indices[] = {b.getInt64(0), b.getInt32(index)};
1055    Value* gep = b.CreateGEP(mOutputAddrPtr, indices);
1056    b.CreateAlignedStore(marker, gep, BLOCK_SIZE/8, false);
1057}
1058
1059CompiledPabloFunction::CompiledPabloFunction(size_t carryDataSize, Function * function, ExecutionEngine * executionEngine)
1060: CarryDataSize(carryDataSize)
1061, FunctionPointer(executionEngine->getPointerToFunction(function))
1062, mFunction(function)
1063, mExecutionEngine(executionEngine)
1064{
1065
1066}
1067
1068// Clean up the memory for the compiled function once we're finished using it.
1069CompiledPabloFunction::~CompiledPabloFunction() {
1070    if (mExecutionEngine) {
1071        assert (mFunction);
1072        // mExecutionEngine->freeMachineCodeForFunction(mFunction); // This function only prints a "not supported" message. Reevaluate with LLVM 3.6.
1073        delete mExecutionEngine;
1074    }
1075}
1076
1077}
Note: See TracBrowser for help on using the repository browser.