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

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

Added optional CMake command -DDISABLE_PREGENERATED_UCD_FUNCTIONS.

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