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

Last change on this file since 4276 was 4276, checked in by nmedfort, 5 years ago

Created an "insertion friendly" Pablo AST structure similar to LLVM; fixed engine builder bug when creating a unicode class.

File size: 34.7 KB
Line 
1/*
2 *  Copyright (c) 2014 International Characters.
3 *  This software is licensed to the public under the Open Software License 3.0.
4 *  icgrep is a trademark of International Characters.
5 */
6
7/*
8 *  Copyright (c) 2014 International Characters.
9 *  This software is licensed to the public under the Open Software License 3.0.
10 *  icgrep is a trademark of International Characters.
11 */
12
13#include <pablo/pablo_compiler.h>
14#include <pablo/codegenstate.h>
15#include <pablo/printer_pablos.h>
16#include <cc/cc_namemap.hpp>
17#include <re/re_name.h>
18#include <stdexcept>
19#include <include/simd-lib/bitblock.hpp>
20
21#ifdef USE_LLVM_3_4
22#include <llvm/Analysis/Verifier.h>
23#include <llvm/Assembly/PrintModulePass.h>
24#include <llvm/Linker.h>
25#endif
26#ifdef USE_LLVM_3_5
27#include <llvm/IR/Verifier.h>
28#endif
29
30#include <llvm/Pass.h>
31#include <llvm/PassManager.h>
32#include <llvm/ADT/SmallVector.h>
33#include <llvm/Analysis/Passes.h>
34#include <llvm/IR/BasicBlock.h>
35#include <llvm/IR/CallingConv.h>
36#include <llvm/IR/Constants.h>
37#include <llvm/IR/DataLayout.h>
38#include <llvm/IR/DerivedTypes.h>
39#include <llvm/IR/Function.h>
40#include <llvm/IR/GlobalVariable.h>
41#include <llvm/IR/InlineAsm.h>
42#include <llvm/IR/Instructions.h>
43#include <llvm/IR/LLVMContext.h>
44#include <llvm/IR/Module.h>
45#include <llvm/Support/FormattedStream.h>
46#include <llvm/Support/MathExtras.h>
47#include <llvm/Support/Casting.h>
48#include <llvm/Support/Debug.h>
49#include <llvm/Support/TargetSelect.h>
50#include <llvm/Support/Host.h>
51#include <llvm/Transforms/Scalar.h>
52#include <llvm/ExecutionEngine/ExecutionEngine.h>
53#include <llvm/ExecutionEngine/MCJIT.h>
54#include <llvm/IRReader/IRReader.h>
55#include <llvm/Bitcode/ReaderWriter.h>
56#include <llvm/Support/MemoryBuffer.h>
57#include <llvm/IR/IRBuilder.h>
58
59//#define DUMP_GENERATED_IR
60//#define DUMP_OPTIMIZED_IR
61
62extern "C" {
63  void wrapped_print_register(BitBlock bit_block) {
64      print_register<BitBlock>("", bit_block);
65  }
66}
67
68#define CREATE_GENERAL_CODE_CATEGORY(SUFFIX) \
69SUFFIX * f##SUFFIX = nullptr; \
70extern "C" { \
71    BitBlock __get_category_##SUFFIX(Basis_bits &basis_bits) { \
72        if (f##SUFFIX == nullptr) f##SUFFIX = new SUFFIX(); \
73        Struct_##SUFFIX output; \
74        f##SUFFIX->do_block(basis_bits, output); \
75        return output.cc; \
76    } \
77}
78
79CREATE_GENERAL_CODE_CATEGORY(Cc)
80CREATE_GENERAL_CODE_CATEGORY(Cf)
81CREATE_GENERAL_CODE_CATEGORY(Cn)
82CREATE_GENERAL_CODE_CATEGORY(Co)
83CREATE_GENERAL_CODE_CATEGORY(Cs)
84CREATE_GENERAL_CODE_CATEGORY(Ll)
85CREATE_GENERAL_CODE_CATEGORY(Lm)
86CREATE_GENERAL_CODE_CATEGORY(Lo)
87CREATE_GENERAL_CODE_CATEGORY(Lt)
88CREATE_GENERAL_CODE_CATEGORY(Lu)
89CREATE_GENERAL_CODE_CATEGORY(Mc)
90CREATE_GENERAL_CODE_CATEGORY(Me)
91CREATE_GENERAL_CODE_CATEGORY(Mn)
92CREATE_GENERAL_CODE_CATEGORY(Nd)
93CREATE_GENERAL_CODE_CATEGORY(Nl)
94CREATE_GENERAL_CODE_CATEGORY(No)
95CREATE_GENERAL_CODE_CATEGORY(Pc)
96CREATE_GENERAL_CODE_CATEGORY(Pd)
97CREATE_GENERAL_CODE_CATEGORY(Pe)
98CREATE_GENERAL_CODE_CATEGORY(Pf)
99CREATE_GENERAL_CODE_CATEGORY(Pi)
100CREATE_GENERAL_CODE_CATEGORY(Po)
101CREATE_GENERAL_CODE_CATEGORY(Ps)
102CREATE_GENERAL_CODE_CATEGORY(Sc)
103CREATE_GENERAL_CODE_CATEGORY(Sk)
104CREATE_GENERAL_CODE_CATEGORY(Sm)
105CREATE_GENERAL_CODE_CATEGORY(So)
106CREATE_GENERAL_CODE_CATEGORY(Zl)
107CREATE_GENERAL_CODE_CATEGORY(Zp)
108CREATE_GENERAL_CODE_CATEGORY(Zs)
109
110#undef CREATE_GENERAL_CODE_CATEGORY
111
112namespace pablo {
113
114PabloCompiler::PabloCompiler(const std::vector<Var*> & basisBits)
115: mBasisBits(basisBits)
116, mMod(new Module("icgrep", getGlobalContext()))
117, mBasicBlock(nullptr)
118, mExecutionEngine(nullptr)
119, mBitBlockType(VectorType::get(IntegerType::get(mMod->getContext(), 64), BLOCK_SIZE / 64))
120, mBasisBitsInputPtr(nullptr)
121, mCarryQueueIdx(0)
122, mCarryQueuePtr(nullptr)
123, mNestingDepth(0)
124, mCarryQueueSize(0)
125, mZeroInitializer(ConstantAggregateZero::get(mBitBlockType))
126, mOneInitializer(ConstantVector::getAllOnesValue(mBitBlockType))
127, mFunctionType(nullptr)
128, mFunction(nullptr)
129, mBasisBitsAddr(nullptr)
130, mOutputAddrPtr(nullptr)
131, mMaxNestingDepth(0)
132{
133    //Create the jit execution engine.up
134    InitializeNativeTarget();
135    InitializeNativeTargetAsmPrinter();
136    InitializeNativeTargetAsmParser();
137    DefineTypes();
138    DeclareFunctions();
139}
140
141PabloCompiler::~PabloCompiler()
142{
143    delete mMod;
144    delete fPs;
145    delete fNl;
146    delete fNo;
147    delete fLo;
148    delete fLl;
149    delete fLm;
150    delete fNd;
151    delete fPc;
152    delete fLt;
153    delete fLu;
154    delete fPf;
155    delete fPd;
156    delete fPe;
157    delete fPi;
158    delete fPo;
159    delete fMe;
160    delete fMc;
161    delete fMn;
162    delete fSk;
163    delete fSo;
164    delete fSm;
165    delete fSc;
166    delete fZl;
167    delete fCo;
168    delete fCn;
169    delete fCc;
170    delete fCf;
171    delete fCs;
172    delete fZp;
173    delete fZs;
174
175}
176
177LLVM_Gen_RetVal PabloCompiler::compile(PabloBlock & pb)
178{
179    mNestingDepth = 0;
180    mMaxNestingDepth = 0;
181    mCarryQueueSize = 0;
182    Examine(pb.statements());
183    mCarryQueueVector.resize(mCarryQueueSize);
184
185    std::string errMessage;
186    EngineBuilder builder(mMod);
187    builder.setErrorStr(&errMessage);
188    builder.setMCPU(sys::getHostCPUName());
189    builder.setUseMCJIT(true);
190    builder.setOptLevel(mMaxNestingDepth > 1 ? CodeGenOpt::Level::Less : CodeGenOpt::Level::None);
191    mExecutionEngine = builder.create();
192    if (mExecutionEngine == nullptr) {
193        throw std::runtime_error("Could not create ExecutionEngine: " + errMessage);
194    }
195
196    if (!mCalleeMap.empty()) {
197        DeclareCallFunctions();
198    }
199
200    Function::arg_iterator args = mFunction->arg_begin();
201    mBasisBitsAddr = args++;
202    mBasisBitsAddr->setName("basis_bits");
203    mCarryQueuePtr = args++;
204    mCarryQueuePtr->setName("carry_q");
205    mOutputAddrPtr = args++;
206    mOutputAddrPtr->setName("output");
207
208    //Create the carry queue.
209    mCarryQueueIdx = 0;
210    mNestingDepth = 0;
211    mMaxNestingDepth = 0;
212    mBasicBlock = BasicBlock::Create(mMod->getContext(), "parabix_entry", mFunction,0);
213
214    //The basis bits structure
215    for (unsigned i = 0; i != mBasisBits.size(); ++i) {
216        IRBuilder<> b(mBasicBlock);
217        Value* indices[] = {b.getInt64(0), b.getInt32(i)};
218        const String * const name = mBasisBits[i]->getName();
219        Value * gep = b.CreateGEP(mBasisBitsAddr, indices);
220        LoadInst * basisBit = b.CreateAlignedLoad(gep, BLOCK_SIZE/8, false, name->str());
221        mMarkerMap.insert(std::make_pair(name, basisBit));
222    }
223
224    //Generate the IR instructions for the function.
225    compileStatements(pb.statements());
226
227    assert (mCarryQueueIdx == mCarryQueueSize);
228    assert (mNestingDepth == 0);
229    //Terminate the block
230    ReturnInst::Create(mMod->getContext(), mBasicBlock);
231
232    //Un-comment this line in order to display the IR that has been generated by this module.
233    #ifdef DUMP_GENERATED_IR
234    mMod->dump();
235    #endif
236
237    //Create a verifier.  The verifier will print an error message if our module is malformed in any way.
238    #ifdef USE_LLVM_3_5
239    verifyModule(*mMod, &dbgs());
240    #endif
241    #ifdef USE_LLVM_3_4
242    verifyModule(*mMod, PrintMessageAction);
243    #endif
244
245    //Use the pass manager to run optimizations on the function.
246    FunctionPassManager fpm(mMod);
247 #ifdef USE_LLVM_3_5
248    mMod->setDataLayout(mExecutionEngine->getDataLayout());
249    // Set up the optimizer pipeline.  Start with registering info about how the target lays out data structures.
250    fpm.add(new DataLayoutPass(mMod));
251#endif
252
253#ifdef USE_LLVM_3_4
254    fpm.add(new DataLayout(*mExecutionEngine->getDataLayout()));
255#endif
256
257    fpm.add(createCorrelatedValuePropagationPass());
258    fpm.add(createEarlyCSEPass());
259    fpm.add(createInstructionCombiningPass());    //Simple peephole optimizations and bit-twiddling.
260    fpm.add(createReassociatePass());             //Reassociate expressions.
261    fpm.add(createGVNPass());                     //Eliminate common subexpressions.   
262
263    fpm.doInitialization();
264
265    fpm.run(*mFunction);
266
267#ifdef DUMP_OPTIMIZED_IR
268    mMod->dump();
269#endif
270    mExecutionEngine->finalizeObject();
271
272    LLVM_Gen_RetVal retVal;
273    //Return the required size of the carry queue and a pointer to the process_block function.
274    retVal.carry_q_size = mCarryQueueSize;
275    retVal.process_block_fptr = mExecutionEngine->getPointerToFunction(mFunction);
276
277    return retVal;
278}
279
280void PabloCompiler::DefineTypes()
281{
282    StructType * structBasisBits = mMod->getTypeByName("struct.Basis_bits");
283    if (structBasisBits == nullptr) {
284        structBasisBits = StructType::create(mMod->getContext(), "struct.Basis_bits");
285    }
286    std::vector<Type*>StructTy_struct_Basis_bits_fields;
287    for (int i = 0; i != mBasisBits.size(); i++)
288    {
289        StructTy_struct_Basis_bits_fields.push_back(mBitBlockType);
290    }
291    if (structBasisBits->isOpaque()) {
292        structBasisBits->setBody(StructTy_struct_Basis_bits_fields, /*isPacked=*/false);
293    }
294    mBasisBitsInputPtr = PointerType::get(structBasisBits, 0);
295
296    std::vector<Type*>functionTypeArgs;
297    functionTypeArgs.push_back(mBasisBitsInputPtr);
298
299    //The carry q array.
300    //A pointer to the BitBlock vector.
301    functionTypeArgs.push_back(PointerType::get(mBitBlockType, 0));
302
303    //The output structure.
304    StructType * outputStruct = mMod->getTypeByName("struct.Output");
305    if (!outputStruct) {
306        outputStruct = StructType::create(mMod->getContext(), "struct.Output");
307    }
308    if (outputStruct->isOpaque()) {
309        std::vector<Type*>fields;
310        fields.push_back(mBitBlockType);
311        fields.push_back(mBitBlockType);
312        outputStruct->setBody(fields, /*isPacked=*/false);
313    }
314    PointerType* outputStructPtr = PointerType::get(outputStruct, 0);
315
316    //The &output parameter.
317    functionTypeArgs.push_back(outputStructPtr);
318
319    mFunctionType = FunctionType::get(
320     /*Result=*/Type::getVoidTy(mMod->getContext()),
321     /*Params=*/functionTypeArgs,
322     /*isVarArg=*/false);
323}
324
325void PabloCompiler::DeclareFunctions()
326{
327    //This function can be used for testing to print the contents of a register from JIT'd code to the terminal window.
328    //mFunc_print_register = mMod->getOrInsertFunction("wrapped_print_register", Type::getVoidTy(getGlobalContext()), mXi64Vect, NULL);
329    //mExecutionEngine->addGlobalMapping(cast<GlobalValue>(mFunc_print_register), (void *)&wrapped_print_register);
330    // to call->  b.CreateCall(mFunc_print_register, unicode_category);
331
332#ifdef USE_UADD_OVERFLOW
333    // Type Definitions for llvm.uadd.with.overflow.carryin.i128 or .i256
334    std::vector<Type*>StructTy_0_fields;
335    StructTy_0_fields.push_back(IntegerType::get(mMod->getContext(), BLOCK_SIZE));
336    StructTy_0_fields.push_back(IntegerType::get(mMod->getContext(), 1));
337    StructType *StructTy_0 = StructType::get(mMod->getContext(), StructTy_0_fields, /*isPacked=*/false);
338
339    std::vector<Type*>FuncTy_1_args;
340    FuncTy_1_args.push_back(IntegerType::get(mMod->getContext(), BLOCK_SIZE));
341    FuncTy_1_args.push_back(IntegerType::get(mMod->getContext(), BLOCK_SIZE));
342    FuncTy_1_args.push_back(IntegerType::get(mMod->getContext(), 1));
343    FunctionType* FuncTy_1 = FunctionType::get(
344                                              /*Result=*/StructTy_0,
345                                              /*Params=*/FuncTy_1_args,
346                                              /*isVarArg=*/false);
347
348    mFunctionUaddOverflow = mMod->getFunction("llvm.uadd.with.overflow.carryin.i" + 
349                                              std::to_string(BLOCK_SIZE));
350    if (!mFunctionUaddOverflow) {
351        mFunctionUaddOverflow = Function::Create(
352          /*Type=*/ FuncTy_1,
353          /*Linkage=*/ GlobalValue::ExternalLinkage,
354          /*Name=*/ "llvm.uadd.with.overflow.carryin.i" + std::to_string(BLOCK_SIZE), mMod); // (external, no body)
355        mFunctionUaddOverflow->setCallingConv(CallingConv::C);
356    }
357    AttributeSet mFunctionUaddOverflowPAL;
358    {
359        SmallVector<AttributeSet, 4> Attrs;
360        AttributeSet PAS;
361        {
362          AttrBuilder B;
363          B.addAttribute(Attribute::NoUnwind);
364          B.addAttribute(Attribute::ReadNone);
365          PAS = AttributeSet::get(mMod->getContext(), ~0U, B);
366        }
367
368        Attrs.push_back(PAS);
369        mFunctionUaddOverflowPAL = AttributeSet::get(mMod->getContext(), Attrs);
370    }
371    mFunctionUaddOverflow->setAttributes(mFunctionUaddOverflowPAL);
372#endif
373
374    //Starts on process_block
375    SmallVector<AttributeSet, 4> Attrs;
376    AttributeSet PAS;
377    {
378        AttrBuilder B;
379        B.addAttribute(Attribute::ReadOnly);
380        B.addAttribute(Attribute::NoCapture);
381        PAS = AttributeSet::get(mMod->getContext(), 1U, B);
382    }
383    Attrs.push_back(PAS);
384    {
385        AttrBuilder B;
386        B.addAttribute(Attribute::NoCapture);
387        PAS = AttributeSet::get(mMod->getContext(), 2U, B);
388    }
389    Attrs.push_back(PAS);
390    {
391        AttrBuilder B;
392        B.addAttribute(Attribute::NoCapture);
393        PAS = AttributeSet::get(mMod->getContext(), 3U, B);
394    }
395    Attrs.push_back(PAS);
396    {
397        AttrBuilder B;
398        B.addAttribute(Attribute::NoUnwind);
399        B.addAttribute(Attribute::UWTable);
400        PAS = AttributeSet::get(mMod->getContext(), ~0U, B);
401    }
402    AttributeSet AttrSet = AttributeSet::get(mMod->getContext(), Attrs);
403
404    //Create the function that will be generated.
405    mFunction = mMod->getFunction("process_block");
406    if (!mFunction) {
407        mFunction = Function::Create(
408            /*Type=*/mFunctionType,
409            /*Linkage=*/GlobalValue::ExternalLinkage,
410            /*Name=*/"process_block", mMod);
411        mFunction->setCallingConv(CallingConv::C);
412    }
413    mFunction->setAttributes(AttrSet);
414}
415
416void PabloCompiler::Examine(StatementList & stmts) {
417    for (Statement * stmt : stmts) {
418        if (Assign * assign = dyn_cast<Assign>(stmt)) {
419            Examine(assign->getExpr());
420        }
421        if (Next * next = dyn_cast<Next>(stmt)) {
422            Examine(next->getExpr());
423        }
424        else if (If * ifStatement = dyn_cast<If>(stmt)) {
425            const auto preIfCarryCount = mCarryQueueSize;
426            Examine(ifStatement->getCondition());
427            mMaxNestingDepth = std::max(mMaxNestingDepth, ++mNestingDepth);
428            Examine(ifStatement->getBody());
429            --mNestingDepth;
430            ifStatement->setInclusiveCarryCount(mCarryQueueSize - preIfCarryCount);
431        }
432        else if (While * whileStatement = dyn_cast<While>(stmt)) {
433            const auto preWhileCarryCount = mCarryQueueSize;
434            Examine(whileStatement->getCondition());
435            mMaxNestingDepth = std::max(mMaxNestingDepth, ++mNestingDepth);
436            Examine(whileStatement->getBody());
437            --mNestingDepth;
438            whileStatement->setInclusiveCarryCount(mCarryQueueSize - preWhileCarryCount);
439        }
440    }
441}
442
443void PabloCompiler::Examine(PabloAST *expr)
444{
445    if (Call * call = dyn_cast<Call>(expr)) {
446        mCalleeMap.insert(std::make_pair(call->getCallee(), nullptr));
447    }
448    else if (And * pablo_and = dyn_cast<And>(expr)) {
449        Examine(pablo_and->getExpr1());
450        Examine(pablo_and->getExpr2());
451    }
452    else if (Or * pablo_or = dyn_cast<Or>(expr)) {
453        Examine(pablo_or->getExpr1());
454        Examine(pablo_or->getExpr2());
455    }
456    else if (Sel * pablo_sel = dyn_cast<Sel>(expr)) {
457        Examine(pablo_sel->getCondition());
458        Examine(pablo_sel->getTrueExpr());
459        Examine(pablo_sel->getFalseExpr());
460    }
461    else if (Not * pablo_not = dyn_cast<Not>(expr)) {
462        Examine(pablo_not->getExpr());
463    }
464    else if (Advance * adv = dyn_cast<Advance>(expr)) {
465        ++mCarryQueueSize;
466        Examine(adv->getExpr());
467    }
468    else if (MatchStar * mstar = dyn_cast<MatchStar>(expr)) {
469        ++mCarryQueueSize;
470        Examine(mstar->getMarker());
471        Examine(mstar->getCharClass());
472    }
473    else if (ScanThru * sthru = dyn_cast<ScanThru>(expr)) {
474        ++mCarryQueueSize;
475        Examine(sthru->getScanFrom());
476        Examine(sthru->getScanThru());
477    }
478}
479
480void PabloCompiler::DeclareCallFunctions() {
481    for (auto mapping : mCalleeMap) {
482        const String * callee = mapping.first;
483        void * callee_ptr = nullptr;
484        #define CHECK_GENERAL_CODE_CATEGORY(SUFFIX) \
485            if (callee->str() == #SUFFIX) { \
486                callee_ptr = (void*)&__get_category_##SUFFIX; \
487            } else
488        CHECK_GENERAL_CODE_CATEGORY(Cc)
489        CHECK_GENERAL_CODE_CATEGORY(Cf)
490        CHECK_GENERAL_CODE_CATEGORY(Cn)
491        CHECK_GENERAL_CODE_CATEGORY(Co)
492        CHECK_GENERAL_CODE_CATEGORY(Cs)
493        CHECK_GENERAL_CODE_CATEGORY(Ll)
494        CHECK_GENERAL_CODE_CATEGORY(Lm)
495        CHECK_GENERAL_CODE_CATEGORY(Lo)
496        CHECK_GENERAL_CODE_CATEGORY(Lt)
497        CHECK_GENERAL_CODE_CATEGORY(Lu)
498        CHECK_GENERAL_CODE_CATEGORY(Mc)
499        CHECK_GENERAL_CODE_CATEGORY(Me)
500        CHECK_GENERAL_CODE_CATEGORY(Mn)
501        CHECK_GENERAL_CODE_CATEGORY(Nd)
502        CHECK_GENERAL_CODE_CATEGORY(Nl)
503        CHECK_GENERAL_CODE_CATEGORY(No)
504        CHECK_GENERAL_CODE_CATEGORY(Pc)
505        CHECK_GENERAL_CODE_CATEGORY(Pd)
506        CHECK_GENERAL_CODE_CATEGORY(Pe)
507        CHECK_GENERAL_CODE_CATEGORY(Pf)
508        CHECK_GENERAL_CODE_CATEGORY(Pi)
509        CHECK_GENERAL_CODE_CATEGORY(Po)
510        CHECK_GENERAL_CODE_CATEGORY(Ps)
511        CHECK_GENERAL_CODE_CATEGORY(Sc)
512        CHECK_GENERAL_CODE_CATEGORY(Sk)
513        CHECK_GENERAL_CODE_CATEGORY(Sm)
514        CHECK_GENERAL_CODE_CATEGORY(So)
515        CHECK_GENERAL_CODE_CATEGORY(Zl)
516        CHECK_GENERAL_CODE_CATEGORY(Zp)
517        CHECK_GENERAL_CODE_CATEGORY(Zs)
518        // OTHERWISE ...
519        throw std::runtime_error("Unknown unicode category \"" + callee->str() + "\"");
520        #undef CHECK_GENERAL_CODE_CATEGORY
521        Value * unicodeCategory = mMod->getOrInsertFunction("__get_category_" + callee->str(), mBitBlockType, mBasisBitsInputPtr, NULL);
522        if (unicodeCategory == nullptr) {
523            throw std::runtime_error("Could not create static method call for unicode category \"" + callee->str() + "\"");
524        }
525        mExecutionEngine->addGlobalMapping(cast<GlobalValue>(unicodeCategory), callee_ptr);
526        mCalleeMap[callee] = unicodeCategory;
527    }
528}
529
530Value * PabloCompiler::compileStatements(const StatementList & stmts) {
531    Value * retVal = nullptr;
532    for (const PabloAST * statement : stmts) {
533        retVal = compileStatement(statement);
534    }
535    return retVal;
536}
537
538Value * PabloCompiler::compileStatement(const PabloAST * stmt)
539{
540    Value * retVal = nullptr;
541    if (const Assign * assign = dyn_cast<const Assign>(stmt))
542    {
543        Value* expr = compileExpression(assign->getExpr());
544        mMarkerMap[assign->getName()] = expr;
545        if (unlikely(assign->isOutputAssignment())) {
546            SetOutputValue(expr, assign->getOutputIndex());
547        }
548        retVal = expr;
549    }
550    if (const Next * next = dyn_cast<const Next>(stmt))
551    {
552        Value* expr = compileExpression(next->getExpr());
553        mMarkerMap[next->getName()] = expr;
554        retVal = expr;
555    }
556    else if (const If * ifstmt = dyn_cast<const If>(stmt))
557    {
558        BasicBlock * ifEntryBlock = mBasicBlock;
559        BasicBlock * ifBodyBlock = BasicBlock::Create(mMod->getContext(), "if.body", mFunction, 0);
560        BasicBlock * ifEndBlock = BasicBlock::Create(mMod->getContext(), "if.end", mFunction, 0);
561
562        int if_start_idx = mCarryQueueIdx;
563
564        Value* if_test_value = compileExpression(ifstmt->getCondition());
565
566        /* Generate the statements into the if body block, and also determine the
567           final carry index.  */
568
569        IRBuilder<> bIfBody(ifBodyBlock);
570        mBasicBlock = ifBodyBlock;
571
572        ++mNestingDepth;
573
574        Value *  returnMarker = compileStatements(ifstmt->getBody());
575
576        int if_end_idx = mCarryQueueIdx;
577        if (if_start_idx < if_end_idx + 1) {
578            // Have at least two internal carries.   Accumulate and store.
579            int if_accum_idx = mCarryQueueIdx++;
580
581            Value* if_carry_accum_value = genCarryInLoad(if_start_idx);
582
583            for (int c = if_start_idx+1; c < if_end_idx; c++)
584            {
585                Value* carryq_value = genCarryInLoad(c);
586                if_carry_accum_value = bIfBody.CreateOr(carryq_value, if_carry_accum_value);
587            }
588            genCarryOutStore(if_carry_accum_value, if_accum_idx);
589
590        }
591        bIfBody.CreateBr(ifEndBlock);
592
593        IRBuilder<> b_entry(ifEntryBlock);
594        mBasicBlock = ifEntryBlock;
595        if (if_start_idx < if_end_idx) {
596            // Have at least one internal carry.
597            int if_accum_idx = mCarryQueueIdx - 1;
598            Value* last_if_pending_carries = genCarryInLoad(if_accum_idx);
599            if_test_value = b_entry.CreateOr(if_test_value, last_if_pending_carries);
600        }
601        b_entry.CreateCondBr(genBitBlockAny(if_test_value), ifEndBlock, ifBodyBlock);
602
603        mBasicBlock = ifEndBlock;
604        --mNestingDepth;
605
606        retVal = returnMarker;
607    }
608    else if (const While * whileStatement = dyn_cast<const While>(stmt))
609    {
610        const auto baseCarryQueueIdx = mCarryQueueIdx;
611        if (mNestingDepth == 0) {
612            for (auto i = 0; i != whileStatement->getInclusiveCarryCount(); ++i) {
613                genCarryInLoad(baseCarryQueueIdx + i);
614            }
615        }       
616
617        SmallVector<const Next*, 4> nextNodes;
618        for (const PabloAST * node : whileStatement->getBody()) {
619            if (isa<Next>(node)) {
620                nextNodes.push_back(cast<Next>(node));
621            }
622        }
623
624        // Compile the initial iteration statements; the calls to genCarryOutStore will update the
625        // mCarryQueueVector with the appropriate values. Although we're not actually entering a new basic
626        // block yet, increment the nesting depth so that any calls to genCarryInLoad or genCarryOutStore
627        // will refer to the previous value.       
628
629        ++mNestingDepth;
630
631        compileStatements(whileStatement->getBody());
632       
633        // Reset the carry queue index. Note: this ought to be changed in the future. Currently this assumes
634        // that compiling the while body twice will generate the equivalent IR. This is not necessarily true
635        // but works for now.
636        mCarryQueueIdx = baseCarryQueueIdx;
637
638        BasicBlock* whileCondBlock = BasicBlock::Create(mMod->getContext(), "while.cond", mFunction, 0);
639        BasicBlock* whileBodyBlock = BasicBlock::Create(mMod->getContext(), "while.body", mFunction, 0);
640        BasicBlock* whileEndBlock = BasicBlock::Create(mMod->getContext(), "while.end", mFunction, 0);
641
642        // Note: compileStatements may update the mBasicBlock pointer if the body contains nested loops. It
643        // may not be same one that we entered the function with.
644        IRBuilder<> bEntry(mBasicBlock);
645        bEntry.CreateBr(whileCondBlock);
646
647        // CONDITION BLOCK
648        IRBuilder<> bCond(whileCondBlock);
649        // generate phi nodes for any carry propogating instruction
650        std::vector<PHINode*> phiNodes(whileStatement->getInclusiveCarryCount() + nextNodes.size());
651        unsigned index = 0;
652        for (index = 0; index != whileStatement->getInclusiveCarryCount(); ++index) {
653            PHINode * phi = bCond.CreatePHI(mBitBlockType, 2);
654            phi->addIncoming(mCarryQueueVector[baseCarryQueueIdx + index], mBasicBlock);
655            mCarryQueueVector[baseCarryQueueIdx + index] = mZeroInitializer; // (use phi for multi-carry mode.)
656            phiNodes[index] = phi;
657        }
658        // and for any Next nodes in the loop body
659        for (const Next * n : nextNodes) {
660            PHINode * phi = bCond.CreatePHI(mBitBlockType, 2, n->getName()->str());
661            auto f = mMarkerMap.find(n->getName());
662            assert (f != mMarkerMap.end());
663            phi->addIncoming(f->second, mBasicBlock);
664            mMarkerMap[n->getName()] = phi;
665            phiNodes[index++] = phi;
666        }
667
668        mBasicBlock = whileCondBlock;
669        bCond.CreateCondBr(genBitBlockAny(compileExpression(whileStatement->getCondition())), whileEndBlock, whileBodyBlock);
670
671        // BODY BLOCK
672        mBasicBlock = whileBodyBlock;
673        retVal = compileStatements(whileStatement->getBody());
674        // update phi nodes for any carry propogating instruction
675        IRBuilder<> bWhileBody(mBasicBlock);
676        for (index = 0; index != whileStatement->getInclusiveCarryCount(); ++index) {
677            Value * carryOut = bWhileBody.CreateOr(phiNodes[index], mCarryQueueVector[baseCarryQueueIdx + index]);
678            PHINode * phi = phiNodes[index];
679            phi->addIncoming(carryOut, mBasicBlock);
680            mCarryQueueVector[baseCarryQueueIdx + index] = phi;
681        }
682        // and for any Next nodes in the loop body
683        for (const Next * n : nextNodes) {
684            auto f = mMarkerMap.find(n->getName());
685            assert (f != mMarkerMap.end());
686            PHINode * phi = phiNodes[index++];
687            phi->addIncoming(f->second, mBasicBlock);
688            mMarkerMap[n->getName()] = phi;
689        }
690
691        bWhileBody.CreateBr(whileCondBlock);
692
693        // EXIT BLOCK
694        mBasicBlock = whileEndBlock;   
695        if (--mNestingDepth == 0) {
696            for (index = 0; index != whileStatement->getInclusiveCarryCount(); ++index) {
697                genCarryOutStore(phiNodes[index], baseCarryQueueIdx + index);
698            }
699        }
700    }
701    return retVal;
702}
703
704Value * PabloCompiler::compileExpression(const PabloAST * expr)
705{
706    Value * retVal = nullptr;
707    IRBuilder<> b(mBasicBlock);
708    if (isa<Ones>(expr)) {
709        retVal = mOneInitializer;
710    }
711    else if (isa<Zeroes>(expr)) {
712        retVal = mZeroInitializer;
713    }
714    else if (const Call* call = dyn_cast<Call>(expr)) {
715        //Call the callee once and store the result in the marker map.
716        auto mi = mMarkerMap.find(call->getCallee());
717        if (mi == mMarkerMap.end()) {
718            auto ci = mCalleeMap.find(call->getCallee());
719            if (ci == mCalleeMap.end()) {
720                throw std::runtime_error("Unexpected error locating static function for \"" + call->getCallee()->str() + "\"");
721            }
722            mi = mMarkerMap.insert(std::make_pair(call->getCallee(), b.CreateCall(ci->second, mBasisBitsAddr))).first;
723        }
724        retVal = mi->second;
725    }
726    else if (const Var * var = dyn_cast<Var>(expr))
727    {
728        auto f = mMarkerMap.find(var->getName());
729        assert (f != mMarkerMap.end());
730        retVal = f->second;
731    }
732    else if (const And * pablo_and = dyn_cast<And>(expr))
733    {
734        retVal = b.CreateAnd(compileExpression(pablo_and->getExpr1()), compileExpression(pablo_and->getExpr2()), "and");
735    }
736    else if (const Or * pablo_or = dyn_cast<Or>(expr))
737    {
738        retVal = b.CreateOr(compileExpression(pablo_or->getExpr1()), compileExpression(pablo_or->getExpr2()), "or");
739    }
740    else if (const Sel * sel = dyn_cast<Sel>(expr))
741    {
742        Value* ifMask = compileExpression(sel->getCondition());
743        Value* ifTrue = b.CreateAnd(ifMask, compileExpression(sel->getTrueExpr()));
744        Value* ifFalse = b.CreateAnd(genNot(ifMask), compileExpression(sel->getFalseExpr()));
745        retVal = b.CreateOr(ifTrue, ifFalse);
746    }
747    else if (const Not * pablo_not = dyn_cast<Not>(expr))
748    {
749        retVal = genNot(compileExpression(pablo_not->getExpr()));
750    }
751    else if (const Advance * adv = dyn_cast<Advance>(expr))
752    {
753        Value* strm_value = compileExpression(adv->getExpr());
754        int shift = adv->getAdvanceAmount();
755        retVal = genAdvanceWithCarry(strm_value, shift);
756    }
757    else if (const MatchStar * mstar = dyn_cast<MatchStar>(expr))
758    {
759        Value* marker = compileExpression(mstar->getMarker());
760        Value* cc = compileExpression(mstar->getCharClass());
761        Value* marker_and_cc = b.CreateAnd(marker, cc);
762        retVal = b.CreateOr(b.CreateXor(genAddWithCarry(marker_and_cc, cc), cc), marker, "matchstar");
763    }
764    else if (const ScanThru * sthru = dyn_cast<ScanThru>(expr))
765    {
766        Value* marker_expr = compileExpression(sthru->getScanFrom());
767        Value* cc_expr = compileExpression(sthru->getScanThru());
768        retVal = b.CreateAnd(genAddWithCarry(marker_expr, cc_expr), genNot(cc_expr), "scanthru");
769    }
770    return retVal;
771}
772
773#ifdef USE_UADD_OVERFLOW
774PabloCompiler::SumWithOverflowPack PabloCompiler::callUaddOverflow(Value* int128_e1, Value* int128_e2, Value* int1_cin) {
775    std::vector<Value*> struct_res_params;
776    struct_res_params.push_back(int128_e1);
777    struct_res_params.push_back(int128_e2);
778    struct_res_params.push_back(int1_cin);
779    CallInst* struct_res = CallInst::Create(mFunctionUaddOverflow, struct_res_params, "uadd_overflow_res", mBasicBlock);
780    struct_res->setCallingConv(CallingConv::C);
781    struct_res->setTailCall(false);
782    AttributeSet struct_res_PAL;
783    struct_res->setAttributes(struct_res_PAL);
784
785    SumWithOverflowPack ret;
786
787    std::vector<unsigned> int128_sum_indices;
788    int128_sum_indices.push_back(0);
789    ret.sum = ExtractValueInst::Create(struct_res, int128_sum_indices, "sum", mBasicBlock);
790
791    std::vector<unsigned> int1_obit_indices;
792    int1_obit_indices.push_back(1);
793    ret.obit = ExtractValueInst::Create(struct_res, int1_obit_indices, "obit", mBasicBlock);
794
795    return ret;
796}
797#endif
798
799Value* PabloCompiler::genAddWithCarry(Value* e1, Value* e2) {
800    IRBuilder<> b(mBasicBlock);
801
802    //CarryQ - carry in.
803    const int carryIdx = mCarryQueueIdx++;
804    Value* carryq_value = genCarryInLoad(carryIdx);
805
806#ifdef USE_UADD_OVERFLOW
807    //use llvm.uadd.with.overflow.i128 or i256
808    ConstantInt* const_int32_6 = ConstantInt::get(mMod->getContext(), APInt(32, StringRef("0"), 10));
809    CastInst* int128_e1 = new BitCastInst(e1, IntegerType::get(mMod->getContext(), BLOCK_SIZE), "e1_128", mBasicBlock);
810    CastInst* int128_e2 = new BitCastInst(e2, IntegerType::get(mMod->getContext(), BLOCK_SIZE), "e2_128", mBasicBlock);
811    ExtractElementInst * int64_carryq_value = ExtractElementInst::Create(carryq_value, const_int32_6, "carryq_64", mBasicBlock);
812    CastInst* int1_carryq_value = new TruncInst(int64_carryq_value, IntegerType::get(mMod->getContext(), 1), "carryq_1", mBasicBlock);
813    SumWithOverflowPack sumpack0;
814    sumpack0 = callUaddOverflow(int128_e1, int128_e2, int1_carryq_value);
815    Value* obit = sumpack0.obit;
816    Value* sum = b.CreateBitCast(sumpack0.sum, mBitBlockType, "sum");
817    /*obit is the i1 carryout, zero extend and insert it into a v2i64 or v4i64 vector.*/
818    ConstantAggregateZero* const_packed_5 = ConstantAggregateZero::get(mBitBlockType);
819    CastInst* int64_o0 = new ZExtInst(obit, IntegerType::get(mMod->getContext(), 64), "o0", mBasicBlock);
820    InsertElementInst* carry_out = InsertElementInst::Create(const_packed_5, int64_o0, const_int32_6, "carry_out", mBasicBlock);
821#else
822    //calculate carry through logical ops
823    Value* carrygen = b.CreateAnd(e1, e2, "carrygen");
824    Value* carryprop = b.CreateOr(e1, e2, "carryprop");
825    Value* digitsum = b.CreateAdd(e1, e2, "digitsum");
826    Value* partial = b.CreateAdd(digitsum, carryq_value, "partial");
827    Value* digitcarry = b.CreateOr(carrygen, b.CreateAnd(carryprop, genNot(partial)));
828    Value* mid_carry_in = genShiftLeft64(b.CreateLShr(digitcarry, 63), "mid_carry_in");
829
830    Value* sum = b.CreateAdd(partial, mid_carry_in, "sum");
831    Value* carry_out = genShiftHighbitToLow(b.CreateOr(carrygen, b.CreateAnd(carryprop, genNot(sum))), "carry_out");
832#endif
833    genCarryOutStore(carry_out, carryIdx);
834    return sum;
835}
836
837Value* PabloCompiler::genCarryInLoad(const unsigned index) {   
838    assert (index < mCarryQueueVector.size());
839    if (mNestingDepth == 0) {
840        IRBuilder<> b(mBasicBlock);
841        mCarryQueueVector[index] = b.CreateAlignedLoad(b.CreateGEP(mCarryQueuePtr, b.getInt64(index)), BLOCK_SIZE/8, false);
842    }
843    return mCarryQueueVector[index];
844}
845
846void PabloCompiler::genCarryOutStore(Value* carryOut, const unsigned index ) {
847    assert (carryOut);
848    assert (index < mCarryQueueVector.size());
849    if (mNestingDepth == 0) {       
850        IRBuilder<> b(mBasicBlock);
851        b.CreateAlignedStore(carryOut, b.CreateGEP(mCarryQueuePtr, b.getInt64(index)), BLOCK_SIZE/8, false);
852    }
853    mCarryQueueVector[index] = carryOut;
854}
855
856inline Value* PabloCompiler::genBitBlockAny(Value* test) {
857    IRBuilder<> b(mBasicBlock);
858    Value* cast_marker_value_1 = b.CreateBitCast(test, IntegerType::get(mMod->getContext(), BLOCK_SIZE));
859    return b.CreateICmpEQ(cast_marker_value_1, ConstantInt::get(IntegerType::get(mMod->getContext(), BLOCK_SIZE), 0));
860}
861
862Value* PabloCompiler::genShiftHighbitToLow(Value* e, const Twine &namehint) {
863    IRBuilder<> b(mBasicBlock);
864    Value* i128_val = b.CreateBitCast(e, IntegerType::get(mMod->getContext(), BLOCK_SIZE));
865    return b.CreateBitCast(b.CreateLShr(i128_val, BLOCK_SIZE - 1, namehint), mBitBlockType);
866}
867
868Value* PabloCompiler::genShiftLeft64(Value* e, const Twine &namehint) {
869    IRBuilder<> b(mBasicBlock);
870    Value* i128_val = b.CreateBitCast(e, IntegerType::get(mMod->getContext(), BLOCK_SIZE));
871    return b.CreateBitCast(b.CreateShl(i128_val, 64, namehint), mBitBlockType);
872}
873
874inline Value* PabloCompiler::genNot(Value* expr) {
875    IRBuilder<> b(mBasicBlock);
876    return b.CreateXor(expr, mOneInitializer, "not");
877}
878
879Value* PabloCompiler::genAdvanceWithCarry(Value* strm_value, int shift_amount) {
880
881    IRBuilder<> b(mBasicBlock);
882#if (BLOCK_SIZE == 128)
883    const auto carryIdx = mCarryQueueIdx++;
884    if (shift_amount == 1) {
885        Value* carryq_value = genCarryInLoad(carryIdx);
886        Value* srli_1_value = b.CreateLShr(strm_value, 63);
887        Value* packed_shuffle;
888        Constant* const_packed_1_elems [] = {b.getInt32(0), b.getInt32(2)};
889        Constant* const_packed_1 = ConstantVector::get(const_packed_1_elems);
890        packed_shuffle = b.CreateShuffleVector(carryq_value, srli_1_value, const_packed_1);
891
892        Constant* const_packed_2_elems[] = {b.getInt64(1), b.getInt64(1)};
893        Constant* const_packed_2 = ConstantVector::get(const_packed_2_elems);
894
895        Value* shl_value = b.CreateShl(strm_value, const_packed_2);
896        Value* result_value = b.CreateOr(shl_value, packed_shuffle, "advance");
897
898        Value* carry_out = genShiftHighbitToLow(strm_value, "carry_out");
899        //CarryQ - carry out:
900        genCarryOutStore(carry_out, carryIdx);
901           
902        return result_value;
903    }
904    else if (shift_amount < 64) {
905        // This is the preferred logic, but is too slow for the general case.   
906        // We need to speed up our custom LLVM for this code.
907        Value* carryq_longint = b.CreateBitCast(genCarryInLoad(carryIdx), IntegerType::get(mMod->getContext(), BLOCK_SIZE));
908        Value* strm_longint = b.CreateBitCast(strm_value, IntegerType::get(mMod->getContext(), BLOCK_SIZE));
909        Value* adv_longint = b.CreateOr(b.CreateShl(strm_longint, shift_amount), carryq_longint, "advance");
910    Value* result_value = b.CreateBitCast(adv_longint, mBitBlockType);
911    Value* carry_out = b.CreateBitCast(b.CreateLShr(strm_longint, BLOCK_SIZE - shift_amount, "advance_out"), mBitBlockType);
912        //CarryQ - carry out:
913        genCarryOutStore(carry_out, carryIdx);
914           
915        return result_value;
916    }
917    else {//if (shift_amount >= 64) {
918        throw std::runtime_error("Shift amount >= 64 in Advance is currently unsupported.");
919    }
920#endif
921
922#if (BLOCK_SIZE == 256)
923    return genAddWithCarry(strm_value, strm_value);
924#endif
925
926}
927
928void PabloCompiler::SetOutputValue(Value * marker, const unsigned index) {
929    IRBuilder<> b(mBasicBlock);
930    if (marker->getType()->isPointerTy()) {
931        marker = b.CreateAlignedLoad(marker, BLOCK_SIZE/8, false);
932    }
933    Value* indices[] = {b.getInt64(0), b.getInt32(index)};
934    Value* gep = b.CreateGEP(mOutputAddrPtr, indices);
935    b.CreateAlignedStore(marker, gep, BLOCK_SIZE/8, false);
936}
937
938}
Note: See TracBrowser for help on using the repository browser.