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

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

Fix for access to carry/advance summary variables

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