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

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

Carry manager bit packing partially working, but disabled by default.

File size: 34.8 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/carry_manager.h>
11#include <pablo/printer_pablos.h>
12#include <pablo/function.h>
13#include <cc/cc_namemap.hpp>
14#include <re/re_name.h>
15#include <stdexcept>
16#include <include/simd-lib/bitblock.hpp>
17#include <sstream>
18#include <IDISA/idisa_builder.h>
19#include <llvm/IR/Verifier.h>
20#include <llvm/Pass.h>
21#include <llvm/PassManager.h>
22#include <llvm/ADT/SmallVector.h>
23#include <llvm/Analysis/Passes.h>
24#include <llvm/IR/BasicBlock.h>
25#include <llvm/IR/CallingConv.h>
26#include <llvm/IR/Constants.h>
27#include <llvm/IR/DataLayout.h>
28#include <llvm/IR/DerivedTypes.h>
29#include <llvm/IR/Function.h>
30#include <llvm/IR/GlobalVariable.h>
31#include <llvm/IR/InlineAsm.h>
32#include <llvm/IR/Instructions.h>
33#include <llvm/IR/LLVMContext.h>
34#include <llvm/IR/Module.h>
35#include <llvm/Support/FormattedStream.h>
36#include <llvm/Support/MathExtras.h>
37#include <llvm/Support/Casting.h>
38#include <llvm/Support/Compiler.h>
39#include <llvm/Support/Debug.h>
40#include <llvm/Support/TargetSelect.h>
41#include <llvm/Support/Host.h>
42#include <llvm/Transforms/Scalar.h>
43#include <llvm/ExecutionEngine/ExecutionEngine.h>
44#include <llvm/ExecutionEngine/MCJIT.h>
45#include <llvm/IRReader/IRReader.h>
46#include <llvm/Bitcode/ReaderWriter.h>
47#include <llvm/Support/MemoryBuffer.h>
48#include <llvm/IR/IRBuilder.h>
49#include <llvm/Support/CommandLine.h>
50#include <llvm/ADT/Twine.h>
51#include <iostream>
52
53static cl::OptionCategory eIRDumpOptions("LLVM IR Dump Options", "These options control dumping of LLVM IR.");
54static cl::opt<bool> DumpGeneratedIR("dump-generated-IR", cl::init(false), cl::desc("Print LLVM IR generated by Pablo Compiler."), cl::cat(eIRDumpOptions));
55
56static cl::OptionCategory fTracingOptions("Run-time Tracing Options", "These options control execution traces.");
57static 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));
58static cl::opt<bool> DumpTrace("dump-trace", cl::init(false), cl::desc("Generate dynamic traces of executed assignments."), cl::cat(fTracingOptions));
59
60extern "C" {
61  void wrapped_print_register(char * regName, BitBlock bit_block) {
62      print_register<BitBlock>(regName, bit_block);
63  }
64}
65
66namespace pablo {
67
68PabloCompiler::PabloCompiler()
69: mMod(nullptr)
70, mExecutionEngine(nullptr)
71, mBuilder(nullptr)
72, mCarryManager(nullptr)
73, mCarryOffset(0)
74, mBitBlockType(VectorType::get(IntegerType::get(getGlobalContext(), 64), BLOCK_SIZE / 64))
75, iBuilder(mBitBlockType)
76, mInputType(nullptr)
77, mCarryDataPtr(nullptr)
78, mWhileDepth(0)
79, mIfDepth(0)
80, mZeroInitializer(ConstantAggregateZero::get(mBitBlockType))
81, mOneInitializer(ConstantVector::getAllOnesValue(mBitBlockType))
82, mFunction(nullptr)
83, mInputAddressPtr(nullptr)
84, mOutputAddressPtr(nullptr)
85, mMaxWhileDepth(0)
86, mPrintRegisterFunction(nullptr) {
87
88}
89
90PabloCompiler::~PabloCompiler() {
91}
92   
93
94void PabloCompiler::genPrintRegister(std::string regName, Value * bitblockValue) {
95    Constant * regNameData = ConstantDataArray::getString(mMod->getContext(), regName);
96    GlobalVariable *regStrVar = new GlobalVariable(*mMod,
97                                                   ArrayType::get(IntegerType::get(mMod->getContext(), 8), regName.length()+1),
98                                                   /*isConstant=*/ true,
99                                                   /*Linkage=*/ GlobalValue::PrivateLinkage,
100                                                   /*Initializer=*/ regNameData);
101    Value * regStrPtr = mBuilder->CreateGEP(regStrVar, {mBuilder->getInt64(0), mBuilder->getInt32(0)});
102    mBuilder->CreateCall(mPrintRegisterFunction, {regStrPtr, bitblockValue});
103}
104
105CompiledPabloFunction PabloCompiler::compile(PabloFunction & function) {
106
107    Examine(function);
108
109    InitializeNativeTarget();
110    InitializeNativeTargetAsmPrinter();
111    InitializeNativeTargetAsmParser();
112
113    Module * module = new Module("", getGlobalContext());
114
115    mMod = module;
116
117    std::string errMessage;
118    #ifdef USE_LLVM_3_5
119    EngineBuilder builder(mMod);
120    #else
121    EngineBuilder builder(std::move(std::unique_ptr<Module>(mMod)));
122    #endif
123    builder.setErrorStr(&errMessage);
124    builder.setMCPU(sys::getHostCPUName());
125    #ifdef USE_LLVM_3_5
126    builder.setUseMCJIT(true);
127    #endif
128    builder.setOptLevel(mMaxWhileDepth ? CodeGenOpt::Level::Less : CodeGenOpt::Level::None);
129    mExecutionEngine = builder.create();
130    if (mExecutionEngine == nullptr) {
131        throw std::runtime_error("Could not create ExecutionEngine: " + errMessage);
132    }
133    DeclareDebugFunctions();
134
135    auto func = compile(function, mMod);
136
137    //Display the IR that has been generated by this module.
138    if (LLVM_UNLIKELY(DumpGeneratedIR)) {
139        module->dump();
140    }
141    //Create a verifier.  The verifier will print an error message if our module is malformed in any way.
142    verifyModule(*module, &dbgs());
143
144    mExecutionEngine->finalizeObject();
145    ExecutionEngine * engine = mExecutionEngine;
146    mExecutionEngine = nullptr; // <-- pass ownership of the execution engine to the caller
147
148    return CompiledPabloFunction(func.second, func.first, engine);
149}
150
151std::pair<llvm::Function *, size_t> PabloCompiler::compile(PabloFunction & function, Module * module) {
152
153 
154    function.getEntryBlock().enumerateScopes(0);
155   
156    Examine(function);
157
158    mMod = module;
159
160    mBuilder = new IRBuilder<>(mMod->getContext());
161
162    iBuilder.initialize(mMod, mBuilder);
163
164    mCarryManager = new CarryManager(mBuilder, mBitBlockType, mZeroInitializer, mOneInitializer, &iBuilder);
165
166    GenerateFunction(function);
167
168    mBuilder->SetInsertPoint(BasicBlock::Create(mMod->getContext(), "entry", mFunction,0));
169
170    //The basis bits structure
171    for (unsigned i = 0; i != function.getNumOfParameters(); ++i) {
172        Value* indices[] = {mBuilder->getInt64(0), mBuilder->getInt32(i)};
173        Value * gep = mBuilder->CreateGEP(mInputAddressPtr, indices);
174        LoadInst * basisBit = mBuilder->CreateAlignedLoad(gep, BLOCK_SIZE/8, false, function.getParameter(i)->getName()->to_string());
175        mMarkerMap[function.getParameter(i)] = basisBit;
176        if (DumpTrace) {
177            genPrintRegister(function.getParameter(i)->getName()->to_string(), basisBit);
178        }
179    }
180     
181    PabloBlock & mainScope = function.getEntryBlock();
182
183    mCarryOffset = mCarryManager->initialize(&mainScope, mCarryDataPtr);
184   
185    //Generate the IR instructions for the function.
186   
187    compileBlock(mainScope);
188   
189    mCarryManager->leaveScope();
190   
191   
192    mCarryManager->generateBlockNoIncrement();
193
194    if (DumpTrace || TraceNext) {
195        genPrintRegister("mBlockNo", mBuilder->CreateAlignedLoad(mBuilder->CreateBitCast(mCarryManager->getBlockNoPtr(), PointerType::get(mBitBlockType, 0)), BLOCK_SIZE/8, false));
196    }
197   
198    // Write the output values out
199    for (unsigned i = 0; i != function.getNumOfResults(); ++i) {
200        assert (function.getResult(i));
201        SetOutputValue(mMarkerMap[function.getResult(i)], i);
202    }
203
204    //Terminate the block
205    ReturnInst::Create(mMod->getContext(), mBuilder->GetInsertBlock());
206
207    // Clean up
208    delete mCarryManager; mCarryManager = nullptr;
209    delete mBuilder; mBuilder = nullptr;
210    mMod = nullptr; // don't delete this. It's either owned by the ExecutionEngine or the calling function.
211
212    //Return the required size of the carry data area to the process_block function.
213    return std::make_pair(mFunction, mCarryOffset * sizeof(BitBlock));
214}
215
216inline void PabloCompiler::GenerateFunction(PabloFunction & function) {
217    mInputType = PointerType::get(StructType::get(mMod->getContext(), std::vector<Type *>(function.getNumOfParameters(), mBitBlockType)), 0);
218    Type * carryType = PointerType::get(mBitBlockType, 0);
219    Type * outputType = PointerType::get(StructType::get(mMod->getContext(), std::vector<Type *>(function.getNumOfResults(), mBitBlockType)), 0);
220    FunctionType * functionType = FunctionType::get(Type::getVoidTy(mMod->getContext()), {{mInputType, carryType, outputType}}, false);
221
222#ifdef USE_UADD_OVERFLOW
223#ifdef USE_TWO_UADD_OVERFLOW
224    // Type Definitions for llvm.uadd.with.overflow.carryin.i128 or .i256
225    std::vector<Type*>StructTy_0_fields;
226    StructTy_0_fields.push_back(IntegerType::get(mMod->getContext(), BLOCK_SIZE));
227    StructTy_0_fields.push_back(IntegerType::get(mMod->getContext(), 1));
228    StructType *StructTy_0 = StructType::get(mMod->getContext(), StructTy_0_fields, /*isPacked=*/false);
229
230    std::vector<Type*>FuncTy_1_args;
231    FuncTy_1_args.push_back(IntegerType::get(mMod->getContext(), BLOCK_SIZE));
232    FuncTy_1_args.push_back(IntegerType::get(mMod->getContext(), BLOCK_SIZE));
233    FunctionType* FuncTy_1 = FunctionType::get(
234                                              /*Result=*/StructTy_0,
235                                              /*Params=*/FuncTy_1_args,
236                                              /*isVarArg=*/false);
237
238    mFunctionUaddOverflow = mMod->getFunction("llvm.uadd.with.overflow.i" +
239                                              std::to_string(BLOCK_SIZE));
240    if (!mFunctionUaddOverflow) {
241        mFunctionUaddOverflow= Function::Create(
242          /*Type=*/ FuncTy_1,
243          /*Linkage=*/ GlobalValue::ExternalLinkage,
244          /*Name=*/ "llvm.uadd.with.overflow.i" + std::to_string(BLOCK_SIZE), mMod); // (external, no body)
245        mFunctionUaddOverflow->setCallingConv(CallingConv::C);
246    }
247    AttributeSet mFunctionUaddOverflowPAL;
248    {
249        SmallVector<AttributeSet, 4> Attrs;
250        AttributeSet PAS;
251        {
252          AttrBuilder B;
253          B.addAttribute(Attribute::NoUnwind);
254          B.addAttribute(Attribute::ReadNone);
255          PAS = AttributeSet::get(mMod->getContext(), ~0U, B);
256        }
257
258        Attrs.push_back(PAS);
259        mFunctionUaddOverflowPAL = AttributeSet::get(mMod->getContext(), Attrs);
260    }
261    mFunctionUaddOverflow->setAttributes(mFunctionUaddOverflowPAL);
262#else
263    // Type Definitions for llvm.uadd.with.overflow.carryin.i128 or .i256
264    std::vector<Type*>StructTy_0_fields;
265    StructTy_0_fields.push_back(IntegerType::get(mMod->getContext(), BLOCK_SIZE));
266    StructTy_0_fields.push_back(IntegerType::get(mMod->getContext(), 1));
267    StructType *StructTy_0 = StructType::get(mMod->getContext(), StructTy_0_fields, /*isPacked=*/false);
268
269    std::vector<Type*>FuncTy_1_args;
270    FuncTy_1_args.push_back(IntegerType::get(mMod->getContext(), BLOCK_SIZE));
271    FuncTy_1_args.push_back(IntegerType::get(mMod->getContext(), BLOCK_SIZE));
272    FuncTy_1_args.push_back(IntegerType::get(mMod->getContext(), 1));
273    FunctionType* FuncTy_1 = FunctionType::get(
274                                              /*Result=*/StructTy_0,
275                                              /*Params=*/FuncTy_1_args,
276                                              /*isVarArg=*/false);
277
278    mFunctionUaddOverflowCarryin = mMod->getFunction("llvm.uadd.with.overflow.carryin.i" +
279                                              std::to_string(BLOCK_SIZE));
280    if (!mFunctionUaddOverflowCarryin) {
281        mFunctionUaddOverflowCarryin = Function::Create(
282          /*Type=*/ FuncTy_1,
283          /*Linkage=*/ GlobalValue::ExternalLinkage,
284          /*Name=*/ "llvm.uadd.with.overflow.carryin.i" + std::to_string(BLOCK_SIZE), mMod); // (external, no body)
285        mFunctionUaddOverflowCarryin->setCallingConv(CallingConv::C);
286    }
287    AttributeSet mFunctionUaddOverflowCarryinPAL;
288    {
289        SmallVector<AttributeSet, 4> Attrs;
290        AttributeSet PAS;
291        {
292          AttrBuilder B;
293          B.addAttribute(Attribute::NoUnwind);
294          B.addAttribute(Attribute::ReadNone);
295          PAS = AttributeSet::get(mMod->getContext(), ~0U, B);
296        }
297
298        Attrs.push_back(PAS);
299        mFunctionUaddOverflowCarryinPAL = AttributeSet::get(mMod->getContext(), Attrs);
300    }
301    mFunctionUaddOverflowCarryin->setAttributes(mFunctionUaddOverflowCarryinPAL);
302#endif
303#endif
304
305    //Starts on process_block
306    SmallVector<AttributeSet, 4> Attrs;
307    Attrs.push_back(AttributeSet::get(mMod->getContext(), ~0U, { Attribute::NoUnwind, Attribute::UWTable }));
308    Attrs.push_back(AttributeSet::get(mMod->getContext(), 1U, { Attribute::ReadOnly, Attribute::NoCapture }));
309    Attrs.push_back(AttributeSet::get(mMod->getContext(), 2U, { Attribute::NoCapture }));
310    Attrs.push_back(AttributeSet::get(mMod->getContext(), 3U, { Attribute::ReadNone, Attribute::NoCapture }));
311    AttributeSet AttrSet = AttributeSet::get(mMod->getContext(), Attrs);
312
313    // Create the function that will be generated.
314    mFunction = Function::Create(functionType, GlobalValue::ExternalLinkage, function.getName()->value(), mMod);
315    mFunction->setCallingConv(CallingConv::C);
316    mFunction->setAttributes(AttrSet);
317
318    Function::arg_iterator args = mFunction->arg_begin();
319    mInputAddressPtr = args++;
320    mInputAddressPtr->setName("input");
321    mCarryDataPtr = args++;
322    mCarryDataPtr->setName("carry");
323    mOutputAddressPtr = args++;
324    mOutputAddressPtr->setName("output");
325}
326
327inline void PabloCompiler::Examine(PabloFunction & function) {
328    mWhileDepth = 0;
329    mIfDepth = 0;
330    mMaxWhileDepth = 0;
331    Examine(function.getEntryBlock());
332    if (LLVM_UNLIKELY(mWhileDepth != 0 || mIfDepth != 0)) {
333        throw std::runtime_error("Malformed Pablo AST: Unbalanced If or While nesting depth!");
334    }
335}
336
337
338void PabloCompiler::Examine(PabloBlock & block) {
339    for (Statement * stmt : block) {
340        if (If * ifStatement = dyn_cast<If>(stmt)) {
341            Examine(ifStatement->getBody());
342        }
343        else if (While * whileStatement = dyn_cast<While>(stmt)) {
344            mMaxWhileDepth = std::max(mMaxWhileDepth, ++mWhileDepth);
345            Examine(whileStatement->getBody());
346            --mWhileDepth;
347        }
348    }
349}
350
351inline void PabloCompiler::DeclareDebugFunctions() {
352    if (DumpTrace || TraceNext) {
353        //This function can be used for testing to print the contents of a register from JIT'd code to the terminal window.
354        mPrintRegisterFunction = mMod->getOrInsertFunction("wrapped_print_register", Type::getVoidTy(mMod->getContext()), Type::getInt8PtrTy(mMod->getContext()), mBitBlockType, NULL);
355        if (mExecutionEngine) mExecutionEngine->addGlobalMapping(cast<GlobalValue>(mPrintRegisterFunction), (void *)&wrapped_print_register);
356    }
357}
358
359void PabloCompiler::compileBlock(PabloBlock & block) {
360    mPabloBlock = & block;
361    for (const Statement * statement : block) {
362        compileStatement(statement);
363    }
364    mPabloBlock = block.getParent();
365}
366
367Value * PabloCompiler::genBitTest2(Value * e1, Value * e2) {
368    Type * t1 = e1->getType();
369    Type * t2 = e2->getType();
370    if (t1 == mBitBlockType) {
371        if (t2 == mBitBlockType) {
372            return iBuilder.bitblock_any(mBuilder->CreateOr(e1, e2));
373        }
374        else {
375            Value * m1 = mBuilder->CreateZExt(iBuilder.hsimd_signmask(16, e1), t2);
376            return mBuilder->CreateICmpNE(mBuilder->CreateOr(m1, e2), ConstantInt::get(t2, 0));
377        }
378    }
379    else if (t2 == mBitBlockType) {
380        Value * m2 = mBuilder->CreateZExt(iBuilder.hsimd_signmask(16, e2), t1);
381        return mBuilder->CreateICmpNE(mBuilder->CreateOr(e1, m2), ConstantInt::get(t1, 0));
382    }
383    else {
384        return mBuilder->CreateICmpNE(mBuilder->CreateOr(e1, e2), ConstantInt::get(t1, 0));
385    }
386}
387
388void PabloCompiler::compileIf(const If * ifStatement) {       
389    //
390    //  The If-ElseZero stmt:
391    //  if <predicate:expr> then <body:stmt>* elsezero <defined:var>* endif
392    //  If the value of the predicate is nonzero, then determine the values of variables
393    //  <var>* by executing the given statements.  Otherwise, the value of the
394    //  variables are all zero.  Requirements: (a) no variable that is defined within
395    //  the body of the if may be accessed outside unless it is explicitly
396    //  listed in the variable list, (b) every variable in the defined list receives
397    //  a value within the body, and (c) the logical consequence of executing
398    //  the statements in the event that the predicate is zero is that the
399    //  values of all defined variables indeed work out to be 0.
400    //
401    //  Simple Implementation with Phi nodes:  a phi node in the if exit block
402    //  is inserted for each variable in the defined variable list.  It receives
403    //  a zero value from the ifentry block and the defined value from the if
404    //  body.
405    //
406
407    BasicBlock * ifEntryBlock = mBuilder->GetInsertBlock();
408    BasicBlock * ifBodyBlock = BasicBlock::Create(mMod->getContext(), "if.body", mFunction, 0);
409    BasicBlock * ifEndBlock = BasicBlock::Create(mMod->getContext(), "if.end", mFunction, 0);
410   
411    PabloBlock & ifBody = ifStatement -> getBody();
412   
413    Value * if_test_value = compileExpression(ifStatement->getCondition());
414   
415    mCarryManager->enterScope(&ifBody);
416    if (mCarryManager->blockHasCarries()) {
417        // load the summary variable
418        Value* last_if_pending_data = mCarryManager->getCarrySummaryExpr();
419        mBuilder->CreateCondBr(genBitTest2(if_test_value, last_if_pending_data), ifBodyBlock, ifEndBlock);
420
421    }
422    else {
423        mBuilder->CreateCondBr(iBuilder.bitblock_any(if_test_value), ifBodyBlock, ifEndBlock);
424    }
425    // Entry processing is complete, now handle the body of the if.
426    mBuilder->SetInsertPoint(ifBodyBlock);
427   
428    mCarryManager->initializeCarryDataAtIfEntry();
429    compileBlock(ifBody);
430    if (mCarryManager->blockHasCarries()) {
431        mCarryManager->generateCarryOutSummaryCodeIfNeeded();
432    }
433    BasicBlock * ifBodyFinalBlock = mBuilder->GetInsertBlock();
434    mBuilder->CreateBr(ifEndBlock);
435    //End Block
436    mBuilder->SetInsertPoint(ifEndBlock);
437    for (const PabloAST * node : ifStatement->getDefined()) {
438        const Assign * assign = cast<Assign>(node);
439        PHINode * phi = mBuilder->CreatePHI(mBitBlockType, 2, assign->getName()->value());
440        auto f = mMarkerMap.find(assign);
441        assert (f != mMarkerMap.end());
442        phi->addIncoming(mZeroInitializer, ifEntryBlock);
443        phi->addIncoming(f->second, ifBodyFinalBlock);
444        mMarkerMap[assign] = phi;
445    }
446    // Create the phi Node for the summary variable, if needed.
447    mCarryManager->buildCarryDataPhisAfterIfBody(ifEntryBlock, ifBodyFinalBlock);
448    //mCarryManager->addSummaryPhiIfNeeded(ifEntryBlock, ifBodyFinalBlock);
449    mCarryManager->leaveScope();
450}
451
452void PabloCompiler::compileWhile(const While * whileStatement) {
453
454    PabloBlock & whileBody = whileStatement -> getBody();
455   
456    BasicBlock * whileEntryBlock = mBuilder->GetInsertBlock();
457    BasicBlock * whileBodyBlock = BasicBlock::Create(mMod->getContext(), "while.body", mFunction, 0);
458    BasicBlock * whileEndBlock = BasicBlock::Create(mMod->getContext(), "while.end", mFunction, 0);
459
460    mCarryManager->enterScope(&whileBody);
461    mCarryManager->ensureCarriesLoadedRecursive();
462
463    const auto & nextNodes = whileStatement->getVariants();
464    std::vector<PHINode *> nextPhis;
465    nextPhis.reserve(nextNodes.size());
466
467    // On entry to the while structure, proceed to execute the first iteration
468    // of the loop body unconditionally.   The while condition is tested at the end of
469    // the loop.
470
471    mBuilder->CreateBr(whileBodyBlock);
472    mBuilder->SetInsertPoint(whileBodyBlock);
473
474    //
475    // There are 3 sets of Phi nodes for the while loop.
476    // (1) Carry-ins: (a) incoming carry data first iterations, (b) zero thereafter
477    // (2) Carry-out accumulators: (a) zero first iteration, (b) |= carry-out of each iteration
478    // (3) Next nodes: (a) values set up before loop, (b) modified values calculated in loop.
479
480    mCarryManager->initializeCarryDataPhisAtWhileEntry(whileEntryBlock);
481
482    // for any Next nodes in the loop body, initialize to (a) pre-loop value.
483    for (const Next * n : nextNodes) {
484        PHINode * phi = mBuilder->CreatePHI(mBitBlockType, 2, n->getName()->value());
485        auto f = mMarkerMap.find(n->getInitial());
486        assert (f != mMarkerMap.end());
487        phi->addIncoming(f->second, whileEntryBlock);
488        mMarkerMap[n->getInitial()] = phi;
489        nextPhis.push_back(phi);
490    }
491
492    //
493    // Now compile the loop body proper.  Carry-out accumulated values
494    // and iterated values of Next nodes will be computed.
495    ++mWhileDepth;
496    compileBlock(whileBody);
497
498    BasicBlock * whileBodyFinalBlock = mBuilder->GetInsertBlock();
499
500    if (mCarryManager->blockHasCarries()) {
501        mCarryManager->generateCarryOutSummaryCodeIfNeeded();
502    }
503    mCarryManager->extendCarryDataPhisAtWhileBodyFinalBlock(whileBodyFinalBlock);
504
505    // Terminate the while loop body with a conditional branch back.
506    mBuilder->CreateCondBr(iBuilder.bitblock_any(compileExpression(whileStatement->getCondition())), whileBodyBlock, whileEndBlock);
507
508    // and for any Next nodes in the loop body
509    for (unsigned i = 0; i < nextNodes.size(); i++) {
510        const Next * n = nextNodes[i];
511        auto f = mMarkerMap.find(n->getExpr());
512        if (LLVM_UNLIKELY(f == mMarkerMap.end())) {
513            throw std::runtime_error("Next node expression was not compiled!");
514        }
515        nextPhis[i]->addIncoming(f->second, whileBodyFinalBlock);
516    }
517
518    mBuilder->SetInsertPoint(whileEndBlock);
519    --mWhileDepth;
520
521    mCarryManager->ensureCarriesStoredRecursive();
522    mCarryManager->leaveScope();
523}
524
525
526void PabloCompiler::compileStatement(const Statement * stmt) {
527    Value * expr = nullptr;
528    if (const Assign * assign = dyn_cast<const Assign>(stmt)) {
529        expr = compileExpression(assign->getExpression());
530    }
531    else if (const Next * next = dyn_cast<const Next>(stmt)) {
532        expr = compileExpression(next->getExpr());
533        if (TraceNext) {
534            genPrintRegister(next->getName()->to_string(), expr);
535        }
536    }
537    else if (const If * ifStatement = dyn_cast<const If>(stmt)) {
538        compileIf(ifStatement);
539        return;
540    }
541    else if (const While * whileStatement = dyn_cast<const While>(stmt)) {
542        compileWhile(whileStatement);
543        return;
544    }
545    else if (const Call* call = dyn_cast<Call>(stmt)) {
546        //Call the callee once and store the result in the marker map.
547        if (mMarkerMap.count(call) != 0) {
548            return;
549        }
550
551        const Prototype * proto = call->getPrototype();
552        const String * callee = proto->getName();
553
554        Type * inputType = StructType::get(mMod->getContext(), std::vector<Type *>{proto->getNumOfParameters(), mBitBlockType});
555        Type * carryType = mBitBlockType;
556        Type * outputType = StructType::get(mMod->getContext(), std::vector<Type *>{proto->getNumOfResults(), mBitBlockType});
557        FunctionType * functionType = FunctionType::get(Type::getVoidTy(mMod->getContext()), std::vector<Type *>{PointerType::get(inputType, 0), PointerType::get(carryType, 0), PointerType::get(outputType, 0)}, false);
558
559        //Starts on process_block
560        SmallVector<AttributeSet, 3> Attrs;
561        Attrs.push_back(AttributeSet::get(mMod->getContext(), 1U, { Attribute::ReadOnly, Attribute::NoCapture }));
562        Attrs.push_back(AttributeSet::get(mMod->getContext(), 2U, { Attribute::NoCapture }));
563        Attrs.push_back(AttributeSet::get(mMod->getContext(), 3U, { Attribute::ReadNone, Attribute::NoCapture }));
564        AttributeSet AttrSet = AttributeSet::get(mMod->getContext(), Attrs);
565
566        Function * externalFunction = cast<Function>(mMod->getOrInsertFunction(callee->value(), functionType, AttrSet));
567        if (LLVM_UNLIKELY(externalFunction == nullptr)) {
568            throw std::runtime_error("Could not create static method call for external function \"" + callee->to_string() + "\"");
569        }
570        externalFunction->setCallingConv(llvm::CallingConv::C);
571
572        if (mExecutionEngine) mExecutionEngine->addGlobalMapping(externalFunction, proto->getFunctionPtr());
573
574        // add mCarryOffset to mCarryDataPtr
575        Value * carryFramePtr = mBuilder->CreateGEP(mCarryDataPtr, mBuilder->getInt64(mCarryOffset));
576        AllocaInst * outputStruct = mBuilder->CreateAlloca(outputType);
577        mBuilder->CreateCall3(externalFunction, mInputAddressPtr, carryFramePtr, outputStruct);
578        Value * outputPtr = mBuilder->CreateGEP(outputStruct, { mBuilder->getInt32(0), mBuilder->getInt32(0) });
579        expr = mBuilder->CreateAlignedLoad(outputPtr, BLOCK_SIZE / 8, false);
580
581        mCarryOffset += (proto->getRequiredStateSpace() + (BLOCK_SIZE / 8) - 1) / (BLOCK_SIZE / 8);
582    }
583    else if (const And * pablo_and = dyn_cast<And>(stmt)) {
584        expr = mBuilder->CreateAnd(compileExpression(pablo_and->getExpr1()), compileExpression(pablo_and->getExpr2()), "and");
585    }
586    else if (const Or * pablo_or = dyn_cast<Or>(stmt)) {
587        expr = mBuilder->CreateOr(compileExpression(pablo_or->getExpr1()), compileExpression(pablo_or->getExpr2()), "or");
588    }
589    else if (const Xor * pablo_xor = dyn_cast<Xor>(stmt)) {
590        expr = mBuilder->CreateXor(compileExpression(pablo_xor->getExpr1()), compileExpression(pablo_xor->getExpr2()), "xor");
591    }
592    else if (const Sel * sel = dyn_cast<Sel>(stmt)) {
593        Value* ifMask = compileExpression(sel->getCondition());
594        Value* ifTrue = mBuilder->CreateAnd(ifMask, compileExpression(sel->getTrueExpr()));
595        Value* ifFalse = mBuilder->CreateAnd(genNot(ifMask), compileExpression(sel->getFalseExpr()));
596        expr = mBuilder->CreateOr(ifTrue, ifFalse);
597    }
598    else if (const Not * pablo_not = dyn_cast<Not>(stmt)) {
599        expr = genNot(compileExpression(pablo_not->getExpr()));
600    }
601    else if (const Advance * adv = dyn_cast<Advance>(stmt)) {
602        Value* strm_value = compileExpression(adv->getExpr());
603        int shift = adv->getAdvanceAmount();
604        unsigned advance_index = adv->getLocalAdvanceIndex();
605        expr = mCarryManager->advanceCarryInCarryOut(advance_index, shift, strm_value);
606    }
607    else if (const MatchStar * mstar = dyn_cast<MatchStar>(stmt)) {
608        Value * marker = compileExpression(mstar->getMarker());
609        Value * cc = compileExpression(mstar->getCharClass());
610        Value * marker_and_cc = mBuilder->CreateAnd(marker, cc);
611        unsigned carry_index = mstar->getLocalCarryIndex();
612        expr = mBuilder->CreateOr(mBuilder->CreateXor(genAddWithCarry(marker_and_cc, cc, carry_index), cc), marker, "matchstar");
613    }
614    else if (const ScanThru * sthru = dyn_cast<ScanThru>(stmt)) {
615        Value * marker_expr = compileExpression(sthru->getScanFrom());
616        Value * cc_expr = compileExpression(sthru->getScanThru());
617        unsigned carry_index = sthru->getLocalCarryIndex();
618        expr = mBuilder->CreateAnd(genAddWithCarry(marker_expr, cc_expr, carry_index), genNot(cc_expr), "scanthru");
619    }
620    else {
621        llvm::raw_os_ostream cerr(std::cerr);
622        PabloPrinter::print(stmt, cerr);
623        throw std::runtime_error("Unrecognized Pablo Statement! can't compile.");
624    }
625    mMarkerMap[stmt] = expr;
626    if (DumpTrace) {
627        genPrintRegister(stmt->getName()->to_string(), expr);
628    }
629   
630}
631
632Value * PabloCompiler::compileExpression(const PabloAST * expr) {
633    if (isa<Ones>(expr)) {
634        return mOneInitializer;
635    }
636    else if (isa<Zeroes>(expr)) {
637        return mZeroInitializer;
638    }
639    auto f = mMarkerMap.find(expr);
640    if (LLVM_UNLIKELY(f == mMarkerMap.end())) {
641        std::string o;
642        llvm::raw_string_ostream str(o);
643        str << "\"";
644        PabloPrinter::print(expr, str);
645        str << "\" was used before definition!";
646        throw std::runtime_error(str.str());
647    }
648    return f->second;
649}
650
651
652#ifdef USE_UADD_OVERFLOW
653#ifdef USE_TWO_UADD_OVERFLOW
654PabloCompiler::SumWithOverflowPack PabloCompiler::callUaddOverflow(Value* int128_e1, Value* int128_e2) {
655    std::vector<Value*> struct_res_params;
656    struct_res_params.push_back(int128_e1);
657    struct_res_params.push_back(int128_e2);
658    CallInst* struct_res = CallInst::Create(mFunctionUaddOverflow, struct_res_params, "uadd_overflow_res", mBasicBlock);
659    struct_res->setCallingConv(CallingConv::C);
660    struct_res->setTailCall(false);
661    AttributeSet struct_res_PAL;
662    struct_res->setAttributes(struct_res_PAL);
663
664    SumWithOverflowPack ret;
665
666    std::vector<unsigned> int128_sum_indices;
667    int128_sum_indices.push_back(0);
668    ret.sum = ExtractValueInst::Create(struct_res, int128_sum_indices, "sum", mBasicBlock);
669
670    std::vector<unsigned> int1_obit_indices;
671    int1_obit_indices.push_back(1);
672    ret.obit = ExtractValueInst::Create(struct_res, int1_obit_indices, "obit", mBasicBlock);
673
674    return ret;
675}
676#else
677PabloCompiler::SumWithOverflowPack PabloCompiler::callUaddOverflow(Value* int128_e1, Value* int128_e2, Value* int1_cin) {
678    std::vector<Value*> struct_res_params;
679    struct_res_params.push_back(int128_e1);
680    struct_res_params.push_back(int128_e2);
681    struct_res_params.push_back(int1_cin);
682    CallInst* struct_res = CallInst::Create(mFunctionUaddOverflowCarryin, struct_res_params, "uadd_overflow_res", mBasicBlock);
683    struct_res->setCallingConv(CallingConv::C);
684    struct_res->setTailCall(false);
685    AttributeSet struct_res_PAL;
686    struct_res->setAttributes(struct_res_PAL);
687
688    SumWithOverflowPack ret;
689
690    std::vector<unsigned> int128_sum_indices;
691    int128_sum_indices.push_back(0);
692    ret.sum = ExtractValueInst::Create(struct_res, int128_sum_indices, "sum", mBasicBlock);
693
694    std::vector<unsigned> int1_obit_indices;
695    int1_obit_indices.push_back(1);
696    ret.obit = ExtractValueInst::Create(struct_res, int1_obit_indices, "obit", mBasicBlock);
697
698    return ret;
699}
700#endif
701#endif
702
703
704Value* PabloCompiler::genAddWithCarry(Value* e1, Value* e2, unsigned localIndex) {
705    Value * carryq_value = mCarryManager->getCarryOpCarryIn(localIndex);
706#ifdef USE_TWO_UADD_OVERFLOW
707    //This is the ideal implementation, which uses two uadd.with.overflow
708    //The back end should be able to recognize this pattern and combine it into uadd.with.overflow.carryin
709    CastInst* int128_e1 = new BitCastInst(e1, mBuilder->getIntNTy(BLOCK_SIZE), "e1_128", mBasicBlock);
710    CastInst* int128_e2 = new BitCastInst(e2, mBuilder->getIntNTy(BLOCK_SIZE), "e2_128", mBasicBlock);
711    CastInst* int128_carryq_value = new BitCastInst(carryq_value, mBuilder->getIntNTy(BLOCK_SIZE), "carryq_128", mBasicBlock);
712
713    SumWithOverflowPack sumpack0, sumpack1;
714
715    sumpack0 = callUaddOverflow(int128_e1, int128_e2);
716    sumpack1 = callUaddOverflow(sumpack0.sum, int128_carryq_value);
717
718    Value* obit = mBuilder->CreateOr(sumpack0.obit, sumpack1.obit, "carry_bit");
719    Value* sum = mBuilder->CreateBitCast(sumpack1.sum, mBitBlockType, "ret_sum");
720
721    /*obit is the i1 carryout, zero extend and insert it into a v2i64 or v4i64 vector.*/
722    ConstantAggregateZero* const_packed_5 = ConstantAggregateZero::get(mBitBlockType);
723    ConstantInt* const_int32_6 = ConstantInt::get(mMod->getContext(), APInt(32, StringRef("0"), 10));
724    CastInst* int64_o0 = new ZExtInst(obit, IntegerType::get(mMod->getContext(), 64), "o0", mBasicBlock);
725    InsertElementInst* carry_out = InsertElementInst::Create(const_packed_5, int64_o0, const_int32_6, "carry_out", mBasicBlock);
726
727#elif defined USE_UADD_OVERFLOW
728    //use llvm.uadd.with.overflow.i128 or i256
729    CastInst* int128_e1 = new BitCastInst(e1, mBuilder->getIntNTy(BLOCK_SIZE), "e1_128", mBasicBlock);
730    CastInst* int128_e2 = new BitCastInst(e2, mBuilder->getIntNTy(BLOCK_SIZE), "e2_128", mBasicBlock);
731
732    //get i1 carryin from iBLOCK_SIZE
733    ConstantInt* const_int32_6 = ConstantInt::get(mMod->getContext(), APInt(32, StringRef("0"), 10));
734    ExtractElementInst * int64_carryq_value = ExtractElementInst::Create(carryq_value, const_int32_6, "carryq_64", mBasicBlock);
735    CastInst* int1_carryq_value = new TruncInst(int64_carryq_value, IntegerType::get(mMod->getContext(), 1), "carryq_1", mBasicBlock);
736
737    SumWithOverflowPack sumpack0;
738    sumpack0 = callUaddOverflow(int128_e1, int128_e2, int1_carryq_value);
739    Value* obit = sumpack0.obit;
740    Value* sum = mBuilder->CreateBitCast(sumpack0.sum, mBitBlockType, "sum");
741
742    /*obit is the i1 carryout, zero extend and insert it into a v2i64 or v4i64 vector.*/
743    ConstantAggregateZero* const_packed_5 = ConstantAggregateZero::get(mBitBlockType);
744    CastInst* int64_o0 = new ZExtInst(obit, IntegerType::get(mMod->getContext(), 64), "o0", mBasicBlock);
745    InsertElementInst* carry_out = InsertElementInst::Create(const_packed_5, int64_o0, const_int32_6, "carry_out", mBasicBlock);
746#elif (BLOCK_SIZE == 128)
747    //calculate carry through logical ops
748    Value* carrygen = mBuilder->CreateAnd(e1, e2, "carrygen");
749    Value* carryprop = mBuilder->CreateOr(e1, e2, "carryprop");
750    Value* digitsum = mBuilder->CreateAdd(e1, e2, "digitsum");
751    Value* partial = mBuilder->CreateAdd(digitsum, carryq_value, "partial");
752    Value* digitcarry = mBuilder->CreateOr(carrygen, mBuilder->CreateAnd(carryprop, genNot(partial)));
753    Value* mid_carry_in = genShiftLeft64(mBuilder->CreateLShr(digitcarry, 63), "mid_carry_in");
754
755    Value* sum = mBuilder->CreateAdd(partial, mid_carry_in, "sum");
756    Value* carry_out = genShiftHighbitToLow(BLOCK_SIZE, mBuilder->CreateOr(carrygen, mBuilder->CreateAnd(carryprop, genNot(sum))));
757#else
758    //BLOCK_SIZE == 256, there is no other implementation
759    static_assert(false, "Add with carry for 256-bit bitblock requires USE_UADD_OVERFLOW");
760#endif //USE_TWO_UADD_OVERFLOW
761
762    mCarryManager->setCarryOpCarryOut(localIndex, carry_out);
763    return sum;
764}
765
766Value * PabloCompiler::genShiftHighbitToLow(unsigned FieldWidth, Value * op) {
767    unsigned FieldCount = BLOCK_SIZE/FieldWidth;
768    VectorType * vType = VectorType::get(IntegerType::get(mMod->getContext(), FieldWidth), FieldCount);
769    Value * v = mBuilder->CreateBitCast(op, vType);
770    return mBuilder->CreateBitCast(mBuilder->CreateLShr(v, FieldWidth - 1), mBitBlockType);
771}
772
773Value* PabloCompiler::genShiftLeft64(Value* e, const Twine &namehint) {
774    Value* i128_val = mBuilder->CreateBitCast(e, mBuilder->getIntNTy(BLOCK_SIZE));
775    return mBuilder->CreateBitCast(mBuilder->CreateShl(i128_val, 64, namehint), mBitBlockType);
776}
777
778inline Value* PabloCompiler::genNot(Value* expr) {
779    return mBuilder->CreateXor(expr, mOneInitializer, "not");
780}
781   
782void PabloCompiler::SetOutputValue(Value * marker, const unsigned index) {
783    if (LLVM_UNLIKELY(marker == nullptr)) {
784        throw std::runtime_error("Cannot set result " + std::to_string(index) + " to Null");
785    }
786    if (LLVM_UNLIKELY(marker->getType()->isPointerTy())) {
787        marker = mBuilder->CreateAlignedLoad(marker, BLOCK_SIZE/8, false);
788    }
789    Value* indices[] = {mBuilder->getInt64(0), mBuilder->getInt32(index)};
790    Value* gep = mBuilder->CreateGEP(mOutputAddressPtr, indices);
791    mBuilder->CreateAlignedStore(marker, gep, BLOCK_SIZE/8, false);
792}
793
794CompiledPabloFunction::CompiledPabloFunction(size_t carryDataSize, Function * function, ExecutionEngine * executionEngine)
795: CarryDataSize(carryDataSize)
796, FunctionPointer(executionEngine->getPointerToFunction(function))
797, mFunction(function)
798, mExecutionEngine(executionEngine)
799{
800
801}
802
803// Clean up the memory for the compiled function once we're finished using it.
804CompiledPabloFunction::~CompiledPabloFunction() {
805    if (mExecutionEngine) {
806        assert (mFunction);
807        // mExecutionEngine->freeMachineCodeForFunction(mFunction); // This function only prints a "not supported" message. Reevaluate with LLVM 3.6.
808        delete mExecutionEngine;
809    }
810}
811
812}
Note: See TracBrowser for help on using the repository browser.