aboutsummaryrefslogtreecommitdiffstats
path: root/yql/essentials/minikql/codegen/codegen_ut.cpp
blob: f0443f1a897416801c74fcfb2fed46bdd7e4ff1f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
#include <yql/essentials/minikql/codegen/codegen.h>

#include <codegen_ut_llvm_deps.h> // Y_IGNORE

#include <library/cpp/testing/unittest/registar.h>
#include <library/cpp/resource/resource.h>

using namespace NYql::NCodegen;
using namespace llvm;

extern "C" int mul(int x, int y) {
    return x * y;
}

extern "C" int sum(int x, int y) {
    return x + y;
}

namespace {

struct T128 {
    ui64 Lo;
    ui64 Hi;

    T128(ui64 x)
        : Lo(x)
        , Hi(0)
    {}

    bool operator==(const T128& other) const {
        return Lo == other.Lo && Hi == other.Hi;
    }
};

Function *CreateFibFunction(Module &M, LLVMContext &Context) {
    const auto funcType = FunctionType::get(Type::getInt32Ty(Context), {Type::getInt32Ty(Context)}, false);

    // Create the fib function and insert it into module M. This function is said
    // to return an int and take an int parameter.
    Function *FibF = cast<Function>(M.getOrInsertFunction("fib", funcType).getCallee());

    // Add a basic block to the function.
    BasicBlock *BB = BasicBlock::Create(Context, "EntryBlock", FibF);

    // Get pointers to the constants.
    Value *One = ConstantInt::get(Type::getInt32Ty(Context), 1);
    Value *Two = ConstantInt::get(Type::getInt32Ty(Context), 2);

    // Get pointer to the integer argument of the add1 function...
    auto ArgX = FibF->arg_begin();   // Get the arg.
    ArgX->setName("AnArg");            // Give it a nice symbolic name for fun.

                                        // Create the true_block.
    BasicBlock *RetBB = BasicBlock::Create(Context, "return", FibF);
    // Create an exit block.
    BasicBlock* RecurseBB = BasicBlock::Create(Context, "recurse", FibF);

    // Create the "if (arg <= 2) goto exitbb"
    Value *CondInst = CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_SLE, &*ArgX, Two, "cond", BB);
    BranchInst::Create(RetBB, RecurseBB, CondInst, BB);

    // Create: ret int 1
    ReturnInst::Create(Context, One, RetBB);

    // create fib(x-1)
    Value *Sub = BinaryOperator::CreateSub(&*ArgX, One, "arg", RecurseBB);
    CallInst *CallFibX1 = CallInst::Create(FibF, Sub, "fibx1", RecurseBB);
    CallFibX1->setTailCall();

    // create fib(x-2)
    Sub = BinaryOperator::CreateSub(&*ArgX, Two, "arg", RecurseBB);
    CallInst *CallFibX2 = CallInst::Create(FibF, Sub, "fibx2", RecurseBB);
    CallFibX2->setTailCall();


    // fib(x-1)+fib(x-2)
    Value *Sum = BinaryOperator::CreateAdd(CallFibX1, CallFibX2,
        "addresult", RecurseBB);

    // Create the return instruction and add it to the basic block
    ReturnInst::Create(Context, Sum, RecurseBB);

    return FibF;
}

Function *CreateBadFibFunction(Module &M, LLVMContext &Context) {
    const auto funcType = FunctionType::get(Type::getInt32Ty(Context), {Type::getInt32Ty(Context)}, false);

    // Create the fib function and insert it into module M. This function is said
    // to return an int and take an int parameter.
    Function *FibF = cast<Function>(M.getOrInsertFunction("bad_fib", funcType).getCallee());

    BasicBlock *BB = BasicBlock::Create(Context, "EntryBlock", FibF);

    // Get pointers to the constants.
    Value *One = ConstantInt::get(Type::getInt64Ty(Context), 1);

    ReturnInst::Create(Context, One, BB);
    return FibF;
}

Function *CreateMulFunction(Module &M, LLVMContext &Context) {
    const auto funcType = FunctionType::get(Type::getInt32Ty(Context), {Type::getInt32Ty(Context), Type::getInt32Ty(Context)}, false);

    Function *MulF = cast<Function>(M.getOrInsertFunction("mul", funcType).getCallee());

    // Add a basic block to the function.
    BasicBlock *BB = BasicBlock::Create(Context, "EntryBlock", MulF);
    auto args = MulF->arg_begin();
    auto ArgX = args;   // Get the arg 1.
    ArgX->setName("x");
    auto ArgY = ++args;   // Get the arg 2.
    ArgY->setName("y");

    // arg1 * arg2
    Value *Mul = BinaryOperator::CreateMul(&*ArgX, &*ArgY, "res", BB);

    // Create the return instruction and add it to the basic block
    ReturnInst::Create(Context, Mul, BB);

    return MulF;
}

Function *CreateUseNativeFunction(Module &M, LLVMContext &Context) {
    const auto funcType = FunctionType::get(Type::getInt32Ty(Context), {Type::getInt32Ty(Context), Type::getInt32Ty(Context)}, false);

    Function *func = cast<Function>(M.getOrInsertFunction("add", funcType).getCallee());

    // Add a basic block to the function.
    BasicBlock *BB = BasicBlock::Create(Context, "EntryBlock", func);
    auto args = func->arg_begin();
    auto ArgX = args;   // Get the arg 1.
    ArgX->setName("x");
    auto ArgY = ++args;   // Get the arg 2.
    ArgY->setName("y");

    Function* func_mul = M.getFunction("mul");
    if (!func_mul) {
        func_mul = Function::Create(
        /*Type=*/FunctionType::get(Type::getInt32Ty(Context), {Type::getInt32Ty(Context), Type::getInt32Ty(Context)}, false),
        /*Linkage=*/GlobalValue::ExternalLinkage,
        /*Name=*/"mul", &M); // (external, no body)
        func_mul->setCallingConv(CallingConv::C);
    }

    // arg1 * arg2
    Value *Mul = CallInst::Create(func_mul, {&*ArgX, &*ArgY}, "res", BB);

    // Create the return instruction and add it to the basic block
    ReturnInst::Create(Context, Mul, BB);
    return func;
}

Function *CreateUseExternalFromGeneratedFunction(Module& main, LLVMContext &Context) {
    const auto funcType = FunctionType::get(Type::getInt32Ty(Context), {Type::getInt32Ty(Context), Type::getInt32Ty(Context), Type::getInt32Ty(Context)}, false);

    Function *func = cast<Function>(main.getOrInsertFunction("sum_sqr_3", funcType).getCallee());

    // Add a basic block to the function.
    BasicBlock *BB = BasicBlock::Create(Context, "EntryBlock", func);
    auto args = func->arg_begin();
    auto ArgX = args;   // Get the arg 1.
    ArgX->setName("x");
    auto ArgY = ++args;   // Get the arg 2.
    ArgY->setName("y");
    auto ArgZ = ++args;   // Get the arg 3.
    ArgZ->setName("z");

    Function* sum_sqr = main.getFunction("sum_sqr");

    Value *tmp = CallInst::Create(sum_sqr, {&*ArgX, &*ArgY}, "tmp", BB);
    Value *res = CallInst::Create(sum_sqr, {&*ArgZ, tmp}, "res", BB);

    // Create the return instruction and add it to the basic block
    ReturnInst::Create(Context, res, BB);
    return func;
}

Function *CreateUseExternalFromGeneratedFunction128(const ICodegen::TPtr& codegen, bool ir) {
    Module& main = codegen->GetModule();
    LLVMContext &Context = codegen->GetContext();
    auto typeInt128 = Type::getInt128Ty(Context);
    auto pointerInt128 = PointerType::getUnqual(typeInt128);
    const auto funcType = codegen->GetEffectiveTarget() != NYql::NCodegen::ETarget::Windows ?
        FunctionType::get(typeInt128, {typeInt128, typeInt128, typeInt128}, false):
        FunctionType::get(Type::getVoidTy(Context), {pointerInt128, pointerInt128, pointerInt128, pointerInt128}, false);

    Function *func = cast<Function>(main.getOrInsertFunction("sum_sqr_3", funcType).getCallee());

    auto args = func->arg_begin();

    // Add a basic block to the function.
    BasicBlock *BB = BasicBlock::Create(Context, "EntryBlock", func);
    llvm::Argument* retArg = nullptr;
    if (codegen->GetEffectiveTarget() == NYql::NCodegen::ETarget::Windows) {
        retArg = &*args++;
        retArg->addAttr(Attribute::StructRet);
        retArg->addAttr(Attribute::NoAlias);
    }

    auto ArgX = args++;   // Get the arg 1.
    ArgX->setName("x");
    auto ArgY = args++;   // Get the arg 2.
    ArgY->setName("y");
    auto ArgZ = args++;   // Get the arg 3.
    ArgZ->setName("z");

    const auto type = FunctionType::get(Type::getVoidTy(Context), { pointerInt128, pointerInt128, pointerInt128 }, false);
    const auto sum_sqr = main.getOrInsertFunction(ir ? "sum_sqr_128_ir" : "sum_sqr_128", type);

    if (codegen->GetEffectiveTarget() == NYql::NCodegen::ETarget::Windows) {
        Value* tmp1 = new AllocaInst(typeInt128, 0U, nullptr, llvm::Align(16), "tmp1", BB);
        Value* tmp2 = new AllocaInst(typeInt128, 0U, nullptr, llvm::Align(16), "tmp2", BB);
        CallInst::Create(sum_sqr, { &*tmp1, &*ArgX, &*ArgY }, "", BB);
        CallInst::Create(sum_sqr, { &*tmp2, &*ArgZ, &*tmp1 }, "", BB);
        auto res = new LoadInst(typeInt128, tmp2, "load_res", BB);
        new StoreInst(res, retArg, BB);
        // Create the return instruction and add it to the basic block
        ReturnInst::Create(Context, BB);
    } else {
        Value* tmp1 = new AllocaInst(typeInt128, 0U, nullptr, llvm::Align(16), "tmp1", BB);
        Value* tmp2 = new AllocaInst(typeInt128, 0U, nullptr, llvm::Align(16), "tmp2", BB);
        Value* argXPtr = new AllocaInst(typeInt128, 0U, nullptr, llvm::Align(16), "argXptr", BB);
        Value* argYPtr = new AllocaInst(typeInt128, 0U, nullptr, llvm::Align(16), "argYptr", BB);
        Value* argZPtr = new AllocaInst(typeInt128, 0U, nullptr, llvm::Align(16), "argZptr", BB);
        new StoreInst(&*ArgX, argXPtr, BB);
        new StoreInst(&*ArgY, argYPtr, BB);
        new StoreInst(&*ArgZ, argZPtr, BB);

        CallInst::Create(sum_sqr, { &*tmp1, &*argXPtr, &*argYPtr }, "", BB);
        CallInst::Create(sum_sqr, { &*tmp2, &*argZPtr, &*tmp1 }, "", BB);
        auto res = new LoadInst(typeInt128, tmp2, "load_res", BB);

        // Create the return instruction and add it to the basic block
        ReturnInst::Create(Context, res, BB);
    }
    return func;
}

}

#if !defined(_ubsan_enabled_) && !defined(HAVE_VALGRIND)
Y_UNIT_TEST_SUITE(TCodegenTests) {

    Y_UNIT_TEST(FibNative) {
        auto codegen = ICodegen::Make(ETarget::Native);
        auto func = CreateFibFunction(codegen->GetModule(), codegen->GetContext());
        codegen->Verify();
        codegen->Compile();
        typedef int(*TFunc)(int);
        auto funcPtr = (TFunc)codegen->GetPointerToFunction(func);
        UNIT_ASSERT_VALUES_EQUAL(funcPtr(24), 46368);
    }

    Y_UNIT_TEST(FibCurrentOS) {
        auto codegen = ICodegen::Make(ETarget::CurrentOS);
        auto func = CreateFibFunction(codegen->GetModule(), codegen->GetContext());
        codegen->Verify();
        codegen->Compile();
        typedef int(*TFunc)(int);
        auto funcPtr = (TFunc)codegen->GetPointerToFunction(func);
        UNIT_ASSERT_VALUES_EQUAL(funcPtr(24), 46368);
    }

    Y_UNIT_TEST(BadFib) {
        auto codegen = ICodegen::Make(ETarget::Native);
        auto func = CreateBadFibFunction(codegen->GetModule(), codegen->GetContext());
        Y_UNUSED(func);
        UNIT_ASSERT_EXCEPTION(codegen->Verify(), yexception);
    }

    Y_UNIT_TEST(FibFromBitCode) {
        auto codegen = ICodegen::Make(ETarget::Native);
        auto bitcode = NResource::Find("/llvm_bc/Funcs");
        codegen->LoadBitCode(bitcode, "Funcs");
        auto func = codegen->GetModule().getFunction("fib");
        codegen->Verify();
        codegen->ExportSymbol(func);
        codegen->Compile();
        typedef int(*TFunc)(int);
        auto funcPtr = (TFunc)codegen->GetPointerToFunction(func);
        UNIT_ASSERT_VALUES_EQUAL(funcPtr(24), 46368);
    }

    Y_UNIT_TEST(LinkWithNativeFunction) {
        auto codegen = ICodegen::Make(ETarget::Native);
        auto bitcode = NResource::Find("/llvm_bc/Funcs");
        codegen->LoadBitCode(bitcode, "Funcs");
        auto func = codegen->GetModule().getFunction("sum_sqr");
        codegen->AddGlobalMapping("mul", (void*)&sum);
        codegen->ExportSymbol(func);
        codegen->Verify();
        codegen->Compile();
        typedef int(*TFunc)(int, int);
        auto funcPtr = (TFunc)codegen->GetPointerToFunction(func);
        UNIT_ASSERT_VALUES_EQUAL(funcPtr(3, 4), 14);
    }

    Y_UNIT_TEST(LinkWithGeneratedFunction) {
        auto codegen = ICodegen::Make(ETarget::Native);
        auto mulFunc = CreateMulFunction(codegen->GetModule(), codegen->GetContext());
        Y_UNUSED(mulFunc);
        auto bitcode = NResource::Find("/llvm_bc/Funcs");
        codegen->LoadBitCode(bitcode, "Funcs");
        auto func = codegen->GetModule().getFunction("sum_sqr");
        codegen->ExportSymbol(func);
        codegen->Verify();
        codegen->Compile();
        typedef int(*TFunc)(int, int);
        auto funcPtr = (TFunc)codegen->GetPointerToFunction(func);
        UNIT_ASSERT_VALUES_EQUAL(funcPtr(3, 4), 25);
    }

    Y_UNIT_TEST(ReuseExternalCode) {
        auto codegen = ICodegen::Make(ETarget::Native);
        auto bitcode = NResource::Find("/llvm_bc/Funcs");
        codegen->LoadBitCode(bitcode, "Funcs");
        auto func = codegen->GetModule().getFunction("sum_sqr2");
        codegen->ExportSymbol(func);
        codegen->Verify();
        codegen->Compile();
        typedef int(*TFunc)(int, int);
        auto funcPtr = (TFunc)codegen->GetPointerToFunction(func);
        UNIT_ASSERT_VALUES_EQUAL(funcPtr(3, 4), 25);
    }

    Y_UNIT_TEST(UseObjectReference) {
        auto codegen = ICodegen::Make(ETarget::Native);
        auto bitcode = NResource::Find("/llvm_bc/Funcs");
        codegen->LoadBitCode(bitcode, "Funcs");
        auto func = codegen->GetModule().getFunction("str_size");
        codegen->ExportSymbol(func);
        codegen->Verify();
        codegen->Compile();
        typedef size_t(*TFunc)(const std::string&);
        auto funcPtr = (TFunc)codegen->GetPointerToFunction(func);
        const std::string hw("Hello World!");
        UNIT_ASSERT_VALUES_EQUAL(funcPtr(hw), 12);
    }

    Y_UNIT_TEST(UseNativeFromGeneratedFunction) {
        auto codegen = ICodegen::Make(ETarget::Native);
        auto func = CreateUseNativeFunction(codegen->GetModule(), codegen->GetContext());
        codegen->AddGlobalMapping("mul", (void*)&mul);
        codegen->ExportSymbol(func);
        codegen->Verify();
        codegen->Compile();
        typedef int(*TFunc)(int, int);
        auto funcPtr = (TFunc)codegen->GetPointerToFunction(func);
        UNIT_ASSERT_VALUES_EQUAL(funcPtr(3, 4), 12);
    }

    Y_UNIT_TEST(UseExternalFromGeneratedFunction) {
        auto codegen = ICodegen::Make(ETarget::Native);
        auto bitcode = NResource::Find("/llvm_bc/Funcs");
        codegen->LoadBitCode(bitcode, "Funcs");
        auto func = CreateUseExternalFromGeneratedFunction(codegen->GetModule(), codegen->GetContext());
        codegen->ExportSymbol(func);
        codegen->AddGlobalMapping("mul", (void*)&mul);
        codegen->Verify();
        codegen->Compile();
        typedef int(*TFunc)(int, int, int);
        auto funcPtr = (TFunc)codegen->GetPointerToFunction(func);
        UNIT_ASSERT_VALUES_EQUAL(funcPtr(7, 4, 8), 4289);
    }

    Y_UNIT_TEST(UseExternalFromGeneratedFunction_128bit_Compiled) {
        auto codegen = ICodegen::Make(ETarget::Native);
        auto bitcode = NResource::Find("/llvm_bc/Funcs");
        codegen->LoadBitCode(bitcode, "Funcs");
        auto func = CreateUseExternalFromGeneratedFunction128(codegen, false);
        codegen->ExportSymbol(func);
        codegen->Verify();
        codegen->Compile();
        TStringStream str;
        codegen->ShowGeneratedFunctions(&str);
#ifdef _win_
        typedef T128 (*TFunc)(T128, T128, T128);
        auto funcPtr = (TFunc)codegen->GetPointerToFunction(func);
        UNIT_ASSERT(funcPtr(T128(7), T128(4), T128(8)) == T128(4289));
#else
        typedef unsigned __int128(*TFunc)(__int128, __int128, __int128);
        auto funcPtr = (TFunc)codegen->GetPointerToFunction(func);
        UNIT_ASSERT(funcPtr(7, 4, 8) == 4289);
#endif
#if !defined(_asan_enabled_) && !defined(_msan_enabled_) && !defined(_tsan_enabled_) && !defined(_hardening_enabled_)
        if (str.Str().Contains("call")) {
            UNIT_FAIL("Expected inline, disasm:\n" + str.Str());
        }
#endif
    }

    Y_UNIT_TEST(UseExternalFromGeneratedFunction_128bit_Bitcode) {
        auto codegen = ICodegen::Make(ETarget::Native);
        auto bitcode = NResource::Find("/llvm_bc/Funcs");
        codegen->LoadBitCode(bitcode, "Funcs");
        auto func = CreateUseExternalFromGeneratedFunction128(codegen, true);
        codegen->ExportSymbol(func);
        codegen->Verify();
        codegen->Compile();
        TStringStream str;
        codegen->ShowGeneratedFunctions(&str);
#ifdef _win_
        typedef T128(*TFunc)(T128, T128, T128);
        auto funcPtr = (TFunc)codegen->GetPointerToFunction(func);
        UNIT_ASSERT(funcPtr(T128(7), T128(4), T128(8)) == T128(4289));
#else
        typedef unsigned __int128(*TFunc)(__int128, __int128, __int128);
        auto funcPtr = (TFunc)codegen->GetPointerToFunction(func);
        UNIT_ASSERT(funcPtr(7, 4, 8) == 4289);
#endif
#if !defined(_asan_enabled_) && !defined(_msan_enabled_) && !defined(_tsan_enabled_)
        if (str.Str().Contains("call")) {
            UNIT_FAIL("Expected inline, disasm:\n" + str.Str());
        }
#endif
    }
}

#endif