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

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

Simplified While structure. Next nodes are in the AST again but are treated like independent variable assignments; they're only associated with their original Assign by including them in the While instruction.

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