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

Last change on this file since 4401 was 4401, checked in by cameron, 5 years ago

Optimized system for carry/advance summary variables

File size: 44.1 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] = baseCarryQueueIdx + ifCarryCount;
596                }
597
598            }
599            // Note that the limit in the following uses -1, because
600            // last entry of the advance queue is for the summary variable.
601            for (int c = baseAdvanceQueueIdx; c < baseAdvanceQueueIdx + ifAdvanceCount - 1; c++)
602            {
603                int s = mAdvanceQueueSummaryIdx[c];
604                if (s == -1 ) {
605                    Value* advance_q_value = mAdvanceQueueVector[c];
606                    carry_summary = bIfBody.CreateOr(advance_q_value, carry_summary);
607                    mAdvanceQueueSummaryIdx[c] = baseAdvanceQueueIdx + ifAdvanceCount - 1;
608                }
609            }
610            genAdvanceOutStore(carry_summary, mAdvanceQueueIdx++); //baseAdvanceQueueIdx + ifAdvanceCount - 1);
611        }
612        bIfBody.CreateBr(ifEndBlock);
613        //End Block
614        IRBuilder<> bEnd(ifEndBlock);
615        for (const Assign * a : ifStatement->getDefined()) {
616            PHINode * phi = bEnd.CreatePHI(mBitBlockType, 2, a->getName()->str());
617            auto f = mMarkerMap.find(a->getName());
618            assert (f != mMarkerMap.end());
619            phi->addIncoming(mZeroInitializer, ifEntryBlock);
620            phi->addIncoming(f->second, mBasicBlock);
621            mMarkerMap[a->getName()] = phi;
622        }
623        // Set the basic block to the new end block
624        mBasicBlock = ifEndBlock;
625    }
626    else if (const While * whileStatement = dyn_cast<const While>(stmt))
627    {
628        const auto baseCarryQueueIdx = mCarryQueueIdx;
629        const auto baseAdvanceQueueIdx = mAdvanceQueueIdx;
630        if (mNestingDepth == 0) {
631            for (auto i = 0; i != whileStatement->getInclusiveCarryCount(); ++i) {
632                genCarryInLoad(baseCarryQueueIdx + i);
633            }
634            for (auto i = 0; i != whileStatement->getInclusiveAdvanceCount(); ++i) {
635                genAdvanceInLoad(baseAdvanceQueueIdx + i);
636            }
637        }
638
639        SmallVector<const Next*, 4> nextNodes;
640        for (const PabloAST * node : whileStatement->getBody()) {
641            if (isa<Next>(node)) {
642                nextNodes.push_back(cast<Next>(node));
643            }
644        }
645
646        // Compile the initial iteration statements; the calls to genCarryOutStore will update the
647        // mCarryQueueVector with the appropriate values. Although we're not actually entering a new basic
648        // block yet, increment the nesting depth so that any calls to genCarryInLoad or genCarryOutStore
649        // will refer to the previous value.
650
651        ++mNestingDepth;
652
653        compileStatements(whileStatement->getBody());
654
655        // Reset the carry queue index. Note: this ought to be changed in the future. Currently this assumes
656        // that compiling the while body twice will generate the equivalent IR. This is not necessarily true
657        // but works for now.
658        mCarryQueueIdx = baseCarryQueueIdx;
659        mAdvanceQueueIdx = baseAdvanceQueueIdx;
660
661        BasicBlock* whileCondBlock = BasicBlock::Create(mMod->getContext(), "while.cond", mFunction, 0);
662        BasicBlock* whileBodyBlock = BasicBlock::Create(mMod->getContext(), "while.body", mFunction, 0);
663        BasicBlock* whileEndBlock = BasicBlock::Create(mMod->getContext(), "while.end", mFunction, 0);
664
665        // Note: compileStatements may update the mBasicBlock pointer if the body contains nested loops. It
666        // may not be same one that we entered the function with.
667        IRBuilder<> bEntry(mBasicBlock);
668        bEntry.CreateBr(whileCondBlock);
669
670        // CONDITION BLOCK
671        IRBuilder<> bCond(whileCondBlock);
672        // generate phi nodes for any carry propogating instruction
673        int whileCarryCount = whileStatement->getInclusiveCarryCount();
674        int whileAdvanceCount = whileStatement->getInclusiveAdvanceCount();
675        std::vector<PHINode*> phiNodes(whileCarryCount + whileAdvanceCount + nextNodes.size());
676        unsigned index = 0;
677        for (index = 0; index != whileCarryCount; ++index) {
678            PHINode * phi = bCond.CreatePHI(mBitBlockType, 2);
679            phi->addIncoming(mCarryQueueVector[baseCarryQueueIdx + index], mBasicBlock);
680            mCarryQueueVector[baseCarryQueueIdx + index] = mZeroInitializer; // (use phi for multi-carry mode.)
681            phiNodes[index] = phi;
682        }
683        for (int i = 0; i != whileAdvanceCount; ++i) {
684            PHINode * phi = bCond.CreatePHI(mBitBlockType, 2);
685            phi->addIncoming(mAdvanceQueueVector[baseAdvanceQueueIdx + i], mBasicBlock);
686            mAdvanceQueueVector[baseAdvanceQueueIdx + i] = mZeroInitializer; // (use phi for multi-carry mode.)
687            phiNodes[index++] = phi;
688        }
689        // and for any Next nodes in the loop body
690        for (const Next * n : nextNodes) {
691            PHINode * phi = bCond.CreatePHI(mBitBlockType, 2, n->getName()->str());
692            auto f = mMarkerMap.find(n->getName());
693            assert (f != mMarkerMap.end());
694            phi->addIncoming(f->second, mBasicBlock);
695            mMarkerMap[n->getName()] = phi;
696            phiNodes[index++] = phi;
697        }
698
699        mBasicBlock = whileCondBlock;
700        bCond.CreateCondBr(genBitBlockAny(compileExpression(whileStatement->getCondition())), whileEndBlock, whileBodyBlock);
701
702        // BODY BLOCK
703        mBasicBlock = whileBodyBlock;
704        compileStatements(whileStatement->getBody());
705        // update phi nodes for any carry propogating instruction
706        IRBuilder<> bWhileBody(mBasicBlock);
707        for (index = 0; index != whileStatement->getInclusiveCarryCount(); ++index) {
708            Value * carryOut = bWhileBody.CreateOr(phiNodes[index], mCarryQueueVector[baseCarryQueueIdx + index]);
709            PHINode * phi = phiNodes[index];
710            phi->addIncoming(carryOut, mBasicBlock);
711            mCarryQueueVector[baseCarryQueueIdx + index] = phi;
712        }
713        for (int i = 0; i != whileAdvanceCount; ++i) {
714            Value * advOut = bWhileBody.CreateOr(phiNodes[index], mAdvanceQueueVector[baseAdvanceQueueIdx + i]);
715            PHINode * phi = phiNodes[index++];
716            phi->addIncoming(advOut, mBasicBlock);
717            mAdvanceQueueVector[baseAdvanceQueueIdx + i] = phi;
718        }
719        // and for any Next nodes in the loop body
720        for (const Next * n : nextNodes) {
721            auto f = mMarkerMap.find(n->getName());
722            assert (f != mMarkerMap.end());
723            PHINode * phi = phiNodes[index++];
724            phi->addIncoming(f->second, mBasicBlock);
725            mMarkerMap[n->getName()] = phi;
726        }
727
728        bWhileBody.CreateBr(whileCondBlock);
729
730        // EXIT BLOCK
731        mBasicBlock = whileEndBlock;
732        if (--mNestingDepth == 0) {
733            for (index = 0; index != whileCarryCount; ++index) {
734                genCarryOutStore(phiNodes[index], baseCarryQueueIdx + index);
735            }
736            for (index = 0; index != whileAdvanceCount; ++index) {
737                genAdvanceOutStore(phiNodes[whileCarryCount + index], baseAdvanceQueueIdx + index);
738            }
739        }
740    }
741}
742
743Value * PabloCompiler::compileExpression(const PabloAST * expr)
744{
745    IRBuilder<> b(mBasicBlock);
746    if (isa<Ones>(expr)) {
747        return mOneInitializer;
748    }
749    else if (isa<Zeroes>(expr)) {
750        return mZeroInitializer;
751    }
752    else if (const Call* call = dyn_cast<Call>(expr)) {
753        //Call the callee once and store the result in the marker map.
754        auto mi = mMarkerMap.find(call->getCallee());
755        if (mi == mMarkerMap.end()) {
756            auto ci = mCalleeMap.find(call->getCallee());
757            if (LLVM_UNLIKELY(ci == mCalleeMap.end())) {
758                throw std::runtime_error("Unexpected error locating static function for \"" + call->getCallee()->str() + "\"");
759            }
760            mi = mMarkerMap.insert(std::make_pair(call->getCallee(), b.CreateCall(ci->second, mBasisBitsAddr))).first;
761        }
762        return mi->second;
763    }
764    else if (const Var * var = dyn_cast<Var>(expr))
765    {
766        auto f = mMarkerMap.find(var->getName());
767        if (LLVM_UNLIKELY(f == mMarkerMap.end())) {
768            throw std::runtime_error((var->getName()->str()) + " used before creation.");
769        }
770        return f->second;
771    }
772    else if (const And * pablo_and = dyn_cast<And>(expr))
773    {
774        return b.CreateAnd(compileExpression(pablo_and->getExpr1()), compileExpression(pablo_and->getExpr2()), "and");
775    }
776    else if (const Or * pablo_or = dyn_cast<Or>(expr))
777    {
778        return b.CreateOr(compileExpression(pablo_or->getExpr1()), compileExpression(pablo_or->getExpr2()), "or");
779    }
780    else if (const Xor * pablo_xor = dyn_cast<Xor>(expr))
781    {
782        return b.CreateXor(compileExpression(pablo_xor->getExpr1()), compileExpression(pablo_xor->getExpr2()), "xor");
783    }
784    else if (const Sel * sel = dyn_cast<Sel>(expr))
785    {
786        Value* ifMask = compileExpression(sel->getCondition());
787        Value* ifTrue = b.CreateAnd(ifMask, compileExpression(sel->getTrueExpr()));
788        Value* ifFalse = b.CreateAnd(genNot(ifMask), compileExpression(sel->getFalseExpr()));
789        return b.CreateOr(ifTrue, ifFalse);
790    }
791    else if (const Not * pablo_not = dyn_cast<Not>(expr))
792    {
793        return genNot(compileExpression(pablo_not->getExpr()));
794    }
795    else if (const Advance * adv = dyn_cast<Advance>(expr))
796    {
797        Value* strm_value = compileExpression(adv->getExpr());
798        int shift = adv->getAdvanceAmount();
799        return genAdvanceWithCarry(strm_value, shift);
800    }
801    else if (const MatchStar * mstar = dyn_cast<MatchStar>(expr))
802    {
803        Value* marker = compileExpression(mstar->getMarker());
804        Value* cc = compileExpression(mstar->getCharClass());
805        Value* marker_and_cc = b.CreateAnd(marker, cc);
806        return b.CreateOr(b.CreateXor(genAddWithCarry(marker_and_cc, cc), cc), marker, "matchstar");
807    }
808    else if (const ScanThru * sthru = dyn_cast<ScanThru>(expr))
809    {
810        Value* marker_expr = compileExpression(sthru->getScanFrom());
811        Value* cc_expr = compileExpression(sthru->getScanThru());
812        return b.CreateAnd(genAddWithCarry(marker_expr, cc_expr), genNot(cc_expr), "scanthru");
813    }
814    else {
815        throw std::runtime_error("Unrecognized Pablo expression type; can't compile.");
816    }
817
818}
819
820#ifdef USE_UADD_OVERFLOW
821#ifdef USE_TWO_UADD_OVERFLOW
822PabloCompiler::SumWithOverflowPack PabloCompiler::callUaddOverflow(Value* int128_e1, Value* int128_e2) {
823    std::vector<Value*> struct_res_params;
824    struct_res_params.push_back(int128_e1);
825    struct_res_params.push_back(int128_e2);
826    CallInst* struct_res = CallInst::Create(mFunctionUaddOverflow, struct_res_params, "uadd_overflow_res", mBasicBlock);
827    struct_res->setCallingConv(CallingConv::C);
828    struct_res->setTailCall(false);
829    AttributeSet struct_res_PAL;
830    struct_res->setAttributes(struct_res_PAL);
831
832    SumWithOverflowPack ret;
833
834    std::vector<unsigned> int128_sum_indices;
835    int128_sum_indices.push_back(0);
836    ret.sum = ExtractValueInst::Create(struct_res, int128_sum_indices, "sum", mBasicBlock);
837
838    std::vector<unsigned> int1_obit_indices;
839    int1_obit_indices.push_back(1);
840    ret.obit = ExtractValueInst::Create(struct_res, int1_obit_indices, "obit", mBasicBlock);
841
842    return ret;
843}
844#else
845PabloCompiler::SumWithOverflowPack PabloCompiler::callUaddOverflow(Value* int128_e1, Value* int128_e2, Value* int1_cin) {
846    std::vector<Value*> struct_res_params;
847    struct_res_params.push_back(int128_e1);
848    struct_res_params.push_back(int128_e2);
849    struct_res_params.push_back(int1_cin);
850    CallInst* struct_res = CallInst::Create(mFunctionUaddOverflowCarryin, struct_res_params, "uadd_overflow_res", mBasicBlock);
851    struct_res->setCallingConv(CallingConv::C);
852    struct_res->setTailCall(false);
853    AttributeSet struct_res_PAL;
854    struct_res->setAttributes(struct_res_PAL);
855
856    SumWithOverflowPack ret;
857
858    std::vector<unsigned> int128_sum_indices;
859    int128_sum_indices.push_back(0);
860    ret.sum = ExtractValueInst::Create(struct_res, int128_sum_indices, "sum", mBasicBlock);
861
862    std::vector<unsigned> int1_obit_indices;
863    int1_obit_indices.push_back(1);
864    ret.obit = ExtractValueInst::Create(struct_res, int1_obit_indices, "obit", mBasicBlock);
865
866    return ret;
867}
868#endif
869#endif
870
871Value* PabloCompiler::genAddWithCarry(Value* e1, Value* e2) {
872    IRBuilder<> b(mBasicBlock);
873
874    //CarryQ - carry in.
875    const int carryIdx = mCarryQueueIdx++;
876    Value* carryq_value = genCarryInLoad(carryIdx);
877#ifdef USE_TWO_UADD_OVERFLOW
878    //This is the ideal implementation, which uses two uadd.with.overflow
879    //The back end should be able to recognize this pattern and combine it into uadd.with.overflow.carryin
880    CastInst* int128_e1 = new BitCastInst(e1, IntegerType::get(mMod->getContext(), BLOCK_SIZE), "e1_128", mBasicBlock);
881    CastInst* int128_e2 = new BitCastInst(e2, IntegerType::get(mMod->getContext(), BLOCK_SIZE), "e2_128", mBasicBlock);
882    CastInst* int128_carryq_value = new BitCastInst(carryq_value, IntegerType::get(mMod->getContext(), BLOCK_SIZE), "carryq_128", mBasicBlock);
883
884    SumWithOverflowPack sumpack0, sumpack1;
885
886    sumpack0 = callUaddOverflow(int128_e1, int128_e2);
887    sumpack1 = callUaddOverflow(sumpack0.sum, int128_carryq_value);
888
889    Value* obit = b.CreateOr(sumpack0.obit, sumpack1.obit, "carry_bit");
890    Value* sum = b.CreateBitCast(sumpack1.sum, mBitBlockType, "ret_sum");
891
892    /*obit is the i1 carryout, zero extend and insert it into a v2i64 or v4i64 vector.*/
893    ConstantAggregateZero* const_packed_5 = ConstantAggregateZero::get(mBitBlockType);
894    ConstantInt* const_int32_6 = ConstantInt::get(mMod->getContext(), APInt(32, StringRef("0"), 10));
895    CastInst* int64_o0 = new ZExtInst(obit, IntegerType::get(mMod->getContext(), 64), "o0", mBasicBlock);
896    InsertElementInst* carry_out = InsertElementInst::Create(const_packed_5, int64_o0, const_int32_6, "carry_out", mBasicBlock);
897
898#elif defined USE_UADD_OVERFLOW
899    //use llvm.uadd.with.overflow.i128 or i256
900    CastInst* int128_e1 = new BitCastInst(e1, IntegerType::get(mMod->getContext(), BLOCK_SIZE), "e1_128", mBasicBlock);
901    CastInst* int128_e2 = new BitCastInst(e2, IntegerType::get(mMod->getContext(), BLOCK_SIZE), "e2_128", mBasicBlock);
902
903    //get i1 carryin from iBLOCK_SIZE
904    ConstantInt* const_int32_6 = ConstantInt::get(mMod->getContext(), APInt(32, StringRef("0"), 10));
905    ExtractElementInst * int64_carryq_value = ExtractElementInst::Create(carryq_value, const_int32_6, "carryq_64", mBasicBlock);
906    CastInst* int1_carryq_value = new TruncInst(int64_carryq_value, IntegerType::get(mMod->getContext(), 1), "carryq_1", mBasicBlock);
907
908    SumWithOverflowPack sumpack0;
909    sumpack0 = callUaddOverflow(int128_e1, int128_e2, int1_carryq_value);
910    Value* obit = sumpack0.obit;
911    Value* sum = b.CreateBitCast(sumpack0.sum, mBitBlockType, "sum");
912
913    /*obit is the i1 carryout, zero extend and insert it into a v2i64 or v4i64 vector.*/
914    ConstantAggregateZero* const_packed_5 = ConstantAggregateZero::get(mBitBlockType);
915    CastInst* int64_o0 = new ZExtInst(obit, IntegerType::get(mMod->getContext(), 64), "o0", mBasicBlock);
916    InsertElementInst* carry_out = InsertElementInst::Create(const_packed_5, int64_o0, const_int32_6, "carry_out", mBasicBlock);
917#elif (BLOCK_SIZE == 128)
918    //calculate carry through logical ops
919    Value* carrygen = b.CreateAnd(e1, e2, "carrygen");
920    Value* carryprop = b.CreateOr(e1, e2, "carryprop");
921    Value* digitsum = b.CreateAdd(e1, e2, "digitsum");
922    Value* partial = b.CreateAdd(digitsum, carryq_value, "partial");
923    Value* digitcarry = b.CreateOr(carrygen, b.CreateAnd(carryprop, genNot(partial)));
924    Value* mid_carry_in = genShiftLeft64(b.CreateLShr(digitcarry, 63), "mid_carry_in");
925
926    Value* sum = b.CreateAdd(partial, mid_carry_in, "sum");
927    Value* carry_out = genShiftHighbitToLow(b.CreateOr(carrygen, b.CreateAnd(carryprop, genNot(sum))), "carry_out");
928#else
929    //BLOCK_SIZE == 256, there is no other implementation
930    static_assert(false, "Add with carry for 256-bit bitblock requires USE_UADD_OVERFLOW");
931#endif //USE_TWO_UADD_OVERFLOW
932
933    genCarryOutStore(carry_out, carryIdx);
934    return sum;
935}
936
937Value* PabloCompiler::genCarryInLoad(const unsigned index) {
938    assert (index < mCarryQueueVector.size());
939    if (mNestingDepth == 0) {
940        IRBuilder<> b(mBasicBlock);
941        mCarryQueueVector[index] = b.CreateAlignedLoad(b.CreateGEP(mCarryQueuePtr, b.getInt64(index)), BLOCK_SIZE/8, false);
942    }
943    return mCarryQueueVector[index];
944}
945
946void PabloCompiler::genCarryOutStore(Value* carryOut, const unsigned index ) {
947    assert (carryOut);
948    assert (index < mCarryQueueVector.size());
949    if (mNestingDepth == 0) {
950        IRBuilder<> b(mBasicBlock);
951        b.CreateAlignedStore(carryOut, b.CreateGEP(mCarryQueuePtr, b.getInt64(index)), BLOCK_SIZE/8, false);
952    }
953    mCarryQueueSummaryIdx[index] = -1;
954    mCarryQueueVector[index] = carryOut;
955}
956
957Value* PabloCompiler::genAdvanceInLoad(const unsigned index) {
958    assert (index < mAdvanceQueueVector.size());
959    if (mNestingDepth == 0) {
960        IRBuilder<> b(mBasicBlock);
961        mAdvanceQueueVector[index] = b.CreateAlignedLoad(b.CreateGEP(mAdvanceQueuePtr, b.getInt64(index)), BLOCK_SIZE/8, false);
962    }
963    return mAdvanceQueueVector[index];
964}
965
966void PabloCompiler::genAdvanceOutStore(Value* advanceOut, const unsigned index ) {
967    assert (advanceOut);
968    assert (index < mAdvanceQueueVector.size());
969    if (mNestingDepth == 0) {
970        IRBuilder<> b(mBasicBlock);
971        b.CreateAlignedStore(advanceOut, b.CreateGEP(mAdvanceQueuePtr, b.getInt64(index)), BLOCK_SIZE/8, false);
972    }
973    mAdvanceQueueSummaryIdx[index] = -1;
974    mAdvanceQueueVector[index] = advanceOut;
975}
976
977inline Value* PabloCompiler::genBitBlockAny(Value* test) {
978    IRBuilder<> b(mBasicBlock);
979    Value* cast_marker_value_1 = b.CreateBitCast(test, IntegerType::get(mMod->getContext(), BLOCK_SIZE));
980    return b.CreateICmpEQ(cast_marker_value_1, ConstantInt::get(IntegerType::get(mMod->getContext(), BLOCK_SIZE), 0));
981}
982
983Value* PabloCompiler::genShiftHighbitToLow(Value* e, const Twine &namehint) {
984    IRBuilder<> b(mBasicBlock);
985    Value* i128_val = b.CreateBitCast(e, IntegerType::get(mMod->getContext(), BLOCK_SIZE));
986    return b.CreateBitCast(b.CreateLShr(i128_val, BLOCK_SIZE - 1, namehint), mBitBlockType);
987}
988
989Value* PabloCompiler::genShiftLeft64(Value* e, const Twine &namehint) {
990    IRBuilder<> b(mBasicBlock);
991    Value* i128_val = b.CreateBitCast(e, IntegerType::get(mMod->getContext(), BLOCK_SIZE));
992    return b.CreateBitCast(b.CreateShl(i128_val, 64, namehint), mBitBlockType);
993}
994
995inline Value* PabloCompiler::genNot(Value* expr) {
996    IRBuilder<> b(mBasicBlock);
997    return b.CreateXor(expr, mOneInitializer, "not");
998}
999
1000Value* PabloCompiler::genAdvanceWithCarry(Value* strm_value, int shift_amount) {
1001
1002    IRBuilder<> b(mBasicBlock);
1003
1004    const auto advanceIdx = mAdvanceQueueIdx++;
1005#ifdef USE_LONG_INTEGER_SHIFT
1006    Value* advanceq_longint = b.CreateBitCast(genAdvanceInLoad(advanceIdx), IntegerType::get(mMod->getContext(), BLOCK_SIZE));
1007    Value* strm_longint = b.CreateBitCast(strm_value, IntegerType::get(mMod->getContext(), BLOCK_SIZE));
1008    Value* adv_longint = b.CreateOr(b.CreateShl(strm_longint, shift_amount), b.CreateLShr(advanceq_longint, BLOCK_SIZE - shift_amount), "advance");
1009    Value* result_value = b.CreateBitCast(adv_longint, mBitBlockType);
1010    genAdvanceOutStore(strm_value, advanceIdx);
1011
1012    return result_value;
1013#elif (BLOCK_SIZE == 128)
1014    if (shift_amount == 1) {
1015        Value* advanceq_value = genShiftHighbitToLow(genAdvanceInLoad(advanceIdx));
1016        Value* srli_1_value = b.CreateLShr(strm_value, 63);
1017        Value* packed_shuffle;
1018        Constant* const_packed_1_elems [] = {b.getInt32(0), b.getInt32(2)};
1019        Constant* const_packed_1 = ConstantVector::get(const_packed_1_elems);
1020        packed_shuffle = b.CreateShuffleVector(advanceq_value, srli_1_value, const_packed_1);
1021
1022        Constant* const_packed_2_elems[] = {b.getInt64(1), b.getInt64(1)};
1023        Constant* const_packed_2 = ConstantVector::get(const_packed_2_elems);
1024
1025        Value* shl_value = b.CreateShl(strm_value, const_packed_2);
1026        Value* result_value = b.CreateOr(shl_value, packed_shuffle, "advance");
1027
1028        //CarryQ - carry out:
1029        genAdvanceOutStore(strm_value, advanceIdx);
1030
1031        return result_value;
1032    }
1033    else if (shift_amount < 64) {
1034        // This is the preferred logic, but is too slow for the general case.
1035        // We need to speed up our custom LLVM for this code.
1036        Value* advanceq_longint = b.CreateBitCast(genAdvanceInLoad(advanceIdx), IntegerType::get(mMod->getContext(), BLOCK_SIZE));
1037        Value* strm_longint = b.CreateBitCast(strm_value, IntegerType::get(mMod->getContext(), BLOCK_SIZE));
1038        Value* adv_longint = b.CreateOr(b.CreateShl(strm_longint, shift_amount), b.CreateLShr(advanceq_longint, BLOCK_SIZE - shift_amount), "advance");
1039        Value* result_value = b.CreateBitCast(adv_longint, mBitBlockType);
1040        genAdvanceOutStore(strm_value, advanceIdx);
1041
1042        return result_value;
1043    }
1044    else {//if (shift_amount >= 64) {
1045        throw std::runtime_error("Shift amount >= 64 in Advance is currently unsupported.");
1046    }
1047#else
1048    //BLOCK_SIZE == 256
1049    static_assert(false, "Advance with carry on 256-bit bitblock requires long integer shifts (USE_LONG_INTEGER_SHIFT).");
1050#endif //USE_LONG_INTEGER_SHIFT
1051}
1052
1053void PabloCompiler::SetOutputValue(Value * marker, const unsigned index) {
1054    IRBuilder<> b(mBasicBlock);
1055    if (marker->getType()->isPointerTy()) {
1056        marker = b.CreateAlignedLoad(marker, BLOCK_SIZE/8, false);
1057    }
1058    Value* indices[] = {b.getInt64(0), b.getInt32(index)};
1059    Value* gep = b.CreateGEP(mOutputAddrPtr, indices);
1060    b.CreateAlignedStore(marker, gep, BLOCK_SIZE/8, false);
1061}
1062
1063}
Note: See TracBrowser for help on using the repository browser.