-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathIRGen.cpp
More file actions
1093 lines (968 loc) · 40.7 KB
/
Copy pathIRGen.cpp
File metadata and controls
1093 lines (968 loc) · 40.7 KB
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "IRGen.hpp"
#include "Context.hpp"
#include "GIL/InstVisitor.hpp"
#include "IRGenGlobal.hpp"
#include "Mangling.hpp"
#include "TypeLowering.hpp"
#include <llvm/IR/DIBuilder.h>
#include <llvm/IR/DebugInfoMetadata.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Verifier.h>
namespace glu::irgen {
/// @brief IRGenImpl is the implementation of the IRGen visitor.
/// It inherits from glu::gil::InstVisitor and provides the necessary methods
/// to visit different instruction types in the GIL intermediate representation.
/// This class is used to generate LLVM IR from GIL instructions.
struct IRGenVisitor : public glu::gil::InstVisitor<IRGenVisitor> {
Context ctx;
llvm::IRBuilder<> builder;
TypeLowering typeLowering;
DebugTypeLowering debugTypeLowering;
gil::Module *gilModule;
// Helpers
IRGenGlobal globalVarGen;
// State
llvm::Function *f = nullptr;
llvm::BasicBlock *bb = nullptr;
llvm::DenseMap<gil::Value, llvm::Value *> valueMap;
llvm::DenseMap<glu::gil::Function *, llvm::Function *> _functionMap;
llvm::DICompileUnit *diCompileUnit = nullptr;
// Maps GIL BasicBlocks to LLVM BasicBlocks
llvm::DenseMap<glu::gil::BasicBlock *, llvm::BasicBlock *> basicBlockMap;
// Maps GIL BasicBlock arguments to their PHI nodes
llvm::DenseMap<gil::Value, llvm::PHINode *> phiNodeMap;
IRGenVisitor(
llvm::Module &module, SourceManager *sm, glu::gil::Module *gilModule
)
: ctx(module, sm)
, builder(ctx.ctx)
, typeLowering(ctx.ctx)
, debugTypeLowering(ctx, typeLowering)
, gilModule(gilModule)
, globalVarGen(ctx, typeLowering)
{
}
// MARK: Create Function
llvm::Function *createOrGetFunction(glu::gil::Function *fn)
{
auto it = _functionMap.find(fn);
if (it != _functionMap.end()) {
return it->second;
}
// Source loc
SourceLocation loc = SourceLocation::invalid;
if (fn->getDecl()) {
loc = fn->getDecl()->getLocation();
}
// Convert GIL function to LLVM function
auto *funcType = translateType(fn->getType());
std::string linkageName = fn->getName().str();
if (fn->getDecl() == nullptr) {
// No mangling for functions without an AST node
// Unless it's a global initializer:
for (auto &global : gilModule->getGlobals()) {
if (global.getInitializer() == fn) {
linkageName
= mangleGlobalVariableInitFunction(global.getDecl());
loc = global.getDecl()->getLocation();
break;
}
}
} else if (fn->getDecl()->hasAttribute(
ast::AttributeKind::NoManglingKind
)) {
// No mangling for functions marked as such
} else if (auto *linkageAttr = fn->getDecl()->getAttribute(
ast::AttributeKind::LinkageNameKind
)) {
// Use the specified linkage name
auto *literal
= llvm::dyn_cast<ast::LiteralExpr>(linkageAttr->getParameter());
assert(literal && "linkage_name parameter should be a literal");
assert(
std::holds_alternative<llvm::StringRef>(literal->getValue())
&& "linkage_name parameter should be a string literal"
);
linkageName = std::get<llvm::StringRef>(literal->getValue()).str();
} else {
linkageName = mangleFunctionName(fn->getDecl());
}
auto linkage = llvm::Function::ExternalLinkage;
if (fn->getDecl()
&& fn->getDecl()->hasAttribute(ast::AttributeKind::InlineKind)) {
// Inline functions should have linkonce_odr linkage
linkage = llvm::Function::LinkOnceODRLinkage;
} else if (fn->getDecl() && fn->getDecl()->isPrivate()
&& !fn->getDecl()->hasAttribute(
ast::AttributeKind::NoManglingKind
)
&& !fn->getDecl()->hasAttribute(
ast::AttributeKind::LinkageNameKind
)) {
// Private functions should have internal linkage, unless marked as
// no_mangling
linkage = llvm::Function::InternalLinkage;
}
auto *llvmFunction = llvm::Function::Create(
funcType, linkage, linkageName, ctx.outModule
);
// Create debug info for the function if source manager is available
if (ctx.sm && loc.isValid()) {
llvm::DIFile *file = ctx.createDIFile(loc);
auto bodyloc = SourceLocation::invalid;
if (fn->getDecl() && fn->getDecl()->getBody()) {
bodyloc = fn->getDecl()->getBody()->getLocation();
}
llvmFunction->setSubprogram(ctx.dib.createFunction(
diCompileUnit, fn->getName(), linkageName, file,
ctx.sm->getSpellingLineNumber(loc),
debugTypeLowering.visitFunctionTy(fn->getType()),
ctx.sm->getSpellingLineNumber(bodyloc), llvm::DINode::FlagZero,
fn->getBasicBlockCount() ? llvm::DISubprogram::SPFlagDefinition
: llvm::DISubprogram::SPFlagZero
));
}
_functionMap.insert({ fn, llvmFunction });
return llvmFunction;
}
// - MARK: Visitor Callbacks
void beforeVisitModule([[maybe_unused]] glu::gil::Module *mod)
{
if (ctx.sm) {
diCompileUnit = ctx.dib.createCompileUnit(
llvm::dwarf::DW_LANG_C,
ctx.createDIFile(
ctx.sm->getLocForStartOfFile(ctx.sm->getMainFileID())
),
"Glu Compiler",
/*isOptimized=*/false,
/*Flags=*/"",
/*RuntimeVersion=*/0
);
}
}
void beforeVisitGlobal(glu::gil::Global *global)
{
// Generate the global variable
if (global->getInitializer() == nullptr) {
globalVarGen.generateGlobal(global, nullptr);
} else {
globalVarGen.generateGlobal(
global, createOrGetFunction(global->getInitializer())
);
}
}
void beforeVisitFunction(glu::gil::Function *fn)
{
assert(!f && "Callbacks should be called in the right order");
if (!fn->getBasicBlockCount()) {
return; // Just a forward declaration, no body to generate
}
f = createOrGetFunction(fn);
// Set names for function arguments and map them to GIL values
auto argCount = fn->getEntryBlock()->getArgumentCount();
auto llvmArgIt = f->arg_begin();
for (size_t i = 0; i < argCount; ++i, ++llvmArgIt) {
// TODO: GIL Function should be able to have argument names
valueMap[fn->getEntryBlock()->getArgument(i)] = &*llvmArgIt;
}
}
void afterVisitFunction([[maybe_unused]] glu::gil::Function *fn)
{
if (!fn->getBasicBlockCount()) {
return; // Ignore forward declarations
}
assert(f && "Callbacks should be called in the right order");
f = nullptr;
valueMap.clear();
basicBlockMap.clear();
phiNodeMap.clear();
}
void beforeVisitBasicBlock(glu::gil::BasicBlock *block)
{
assert(!bb && "Callbacks should be called in the right order");
bb = getOrCreateLLVMBasicBlock(block);
builder.SetInsertPoint(bb);
// Create PHI nodes for basic block arguments
if (!bb->isEntryBlock()) {
for (size_t i = 0; i < block->getArgumentCount(); ++i) {
gil::Value bbArg = block->getArgument(i);
getOrCreatePHINode(bbArg, bb);
}
}
}
void afterVisitBasicBlock([[maybe_unused]] glu::gil::BasicBlock *block)
{
assert(bb && "Callbacks should be called in the right order");
bb = nullptr;
}
void beforeVisitInst(glu::gil::InstBase *inst)
{
glu::SourceLocation const &loc = inst->getLocation();
if (ctx.sm && loc.isValid()) {
llvm::DIScope *scope
= builder.GetInsertBlock()->getParent()->getSubprogram();
llvm::DILocation *diLoc = llvm::DILocation::get(
ctx.ctx, ctx.sm->getSpellingLineNumber(loc),
ctx.sm->getSpellingColumnNumber(loc), scope
);
builder.SetCurrentDebugLocation(diLoc);
} else {
builder.SetCurrentDebugLocation(nullptr);
}
}
void afterVisitInst([[maybe_unused]] glu::gil::InstBase *inst)
{
builder.SetCurrentDebugLocation(nullptr);
}
// - MARK: Value Translation
llvm::Value *translateValue(gil::Value &value)
{
// Check if the value is already translated
auto it = valueMap.find(value);
if (it != valueMap.end()) {
return it->second; // Return the existing LLVM value
}
// Create an empty PHI as a placeholder
return valueMap[value]
= builder.CreatePHI(translateType(value.getType()), 0);
}
void mapValue(gil::Value value, llvm::Value *llvmValue)
{
// Map the GIL value to the LLVM value
auto it = valueMap.find(value);
if (it != valueMap.end()) {
assert(
llvm::isa<llvm::PHINode>(it->second)
&& "Existing value must be an empty PHI node temporary"
);
it->second->replaceAllUsesWith(llvmValue); // Replace existing uses
llvm::cast<llvm::PHINode>(it->second)
->eraseFromParent(); // Remove old value
it->second = llvmValue; // Update existing mapping
} else {
valueMap[value] = llvmValue; // Create new mapping
}
}
llvm::Type *translateType(gil::Type type)
{
return typeLowering.visit(type.getType());
}
llvm::FunctionType *translateType(types::FunctionTy *type)
{
return typeLowering.visitFunctionTy(type);
}
// - MARK: Terminator Instructions
void visitUnreachableInst([[maybe_unused]] glu::gil::UnreachableInst *inst)
{
builder.CreateUnreachable();
}
void visitReturnInst(glu::gil::ReturnInst *inst)
{
if (inst->getValue() == gil::Value::getEmptyKey()) {
builder.CreateRetVoid();
} else {
builder.CreateRet(translateValue(inst->getValue()));
}
}
void visitBrInst(glu::gil::BrInst *inst)
{
auto *dest = inst->getDestination();
llvm::BasicBlock *destBB = getOrCreateLLVMBasicBlock(dest);
if (inst->hasBranchArgs()) {
// Handle PHI nodes for basic block arguments
handleBasicBlockArguments(dest, inst->getArgs(), destBB);
}
builder.CreateBr(destBB);
}
void visitCondBrInst(glu::gil::CondBrInst *inst)
{
auto condition = inst->getCondition();
llvm::Value *condValue = translateValue(condition);
auto *thenBlock = inst->getThenBlock();
auto *elseBlock = inst->getElseBlock();
llvm::BasicBlock *thenBB = getOrCreateLLVMBasicBlock(thenBlock);
llvm::BasicBlock *elseBB = getOrCreateLLVMBasicBlock(elseBlock);
// Handle PHI nodes for both branches
if (inst->hasBranchArgs()) {
handleBasicBlockArguments(thenBlock, inst->getThenArgs(), thenBB);
handleBasicBlockArguments(elseBlock, inst->getElseArgs(), elseBB);
}
builder.CreateCondBr(condValue, thenBB, elseBB);
}
// - MARK: Constant Instructions
void visitIntegerLiteralInst(glu::gil::IntegerLiteralInst *inst)
{
// Create an LLVM integer constant
assert(
llvm::isa<glu::types::BoolTy>(inst->getType().getType())
|| (llvm::isa<glu::types::IntTy>(inst->getType().getType())
&& llvm::cast<glu::types::IntTy>(inst->getType().getType())
->getBitWidth()
== inst->getValue().getBitWidth())
&& "Integer literal type and value bit width mismatch"
);
llvm::Value *value = llvm::ConstantInt::get(ctx.ctx, inst->getValue());
mapValue(inst->getResult(0), value);
}
void visitFloatLiteralInst(glu::gil::FloatLiteralInst *inst)
{
// Create an LLVM floating point constant
auto ty = llvm::cast<glu::types::FloatTy>(inst->getType().getType());
llvm::Type *llvmType = typeLowering.visitFloatTy(ty);
llvm::Value *value = llvm::ConstantFP::get(llvmType, inst->getValue());
mapValue(inst->getResult(0), value);
}
void visitStringLiteralInst(glu::gil::StringLiteralInst *inst)
{
// Create a global string constant
llvm::Value *value = builder.CreateGlobalString(inst->getValue());
auto strType = inst->getType().getType();
if (auto ptrTy = llvm::dyn_cast<glu::types::PointerTy>(strType)) {
if (llvm::isa<glu::types::CharTy>(ptrTy->getPointee())) {
mapValue(inst->getResult(0), value);
return;
} else {
assert(false && "String literal type must be a char pointer");
}
} else if (auto structTy
= llvm::dyn_cast<glu::types::StructTy>(strType)) {
if (structTy->getName() == "String") {
// Create a global string constant for the data
// Get length of the string
int length = inst->getValue().size();
// Find or create the createConstantString function
llvm::Function *createFn
= ctx.outModule.getFunction("glu_createConstantString");
if (!createFn) {
llvm::Type *charPtrTy = llvm::PointerType::get(ctx.ctx, 0);
llvm::Type *intTy = llvm::Type::getInt32Ty(ctx.ctx);
llvm::Type *stringTy = typeLowering.visitStructTy(structTy);
llvm::FunctionType *fnTy = llvm::FunctionType::get(
stringTy, { charPtrTy, intTy }, false
);
createFn = llvm::Function::Create(
fnTy, llvm::Function::ExternalLinkage,
"glu_createConstantString", ctx.outModule
);
}
// Call glu_createConstantString(dataPtr, length)
llvm::Value *lengthVal = llvm::ConstantInt::get(
llvm::Type::getInt32Ty(ctx.ctx), length
);
llvm::Value *stringStruct
= builder.CreateCall(createFn, { value, lengthVal });
mapValue(inst->getResult(0), stringStruct);
} else {
assert(false && "Invalid string literal type");
}
} else if (llvm::isa<glu::types::CharTy>(strType)) {
char c = inst->getValue().front();
llvm::Value *charValue
= llvm::ConstantInt::get(llvm::Type::getInt8Ty(ctx.ctx), c);
mapValue(inst->getResult(0), charValue);
} else {
assert(false && "Invalid string literal type");
}
}
void visitFunctionPtrInst(glu::gil::FunctionPtrInst *inst)
{
llvm::Function *llvmFunction = createOrGetFunction(inst->getFunction());
mapValue(inst->getResult(0), llvmFunction);
}
void visitGlobalPtrInst(glu::gil::GlobalPtrInst *inst)
{
gil::Global *globalVar = inst->getGlobal();
// First call the accessor function if it exists
if (llvm::Function *accessor = globalVarGen.getAccessor(globalVar)) {
builder.CreateCall(accessor);
}
llvm::GlobalVariable *llvmGlobal = globalVarGen.getStorage(globalVar);
mapValue(inst->getResult(0), llvmGlobal);
}
void visitEnumVariantInst(glu::gil::EnumVariantInst *inst)
{
// Enum variants are represented as integer constants
auto member = inst->getMember();
auto enumTy
= llvm::cast<glu::types::EnumTy>(member.getParent().getType());
// Get the variant index by name
auto variantIndexOpt = enumTy->getFieldIndex(member.getName());
assert(variantIndexOpt.has_value() && "Enum variant not found");
uint32_t variantIndex = static_cast<uint32_t>(variantIndexOpt.value());
llvm::Type *enumLLVMTy = typeLowering.visitEnumTy(enumTy);
llvm::Value *value = llvm::ConstantInt::get(enumLLVMTy, variantIndex);
mapValue(inst->getResult(0), value);
}
// - MARK: Memory Instructions
void visitAllocaInst(glu::gil::AllocaInst *inst)
{
// Get the pointee type that we're allocating
llvm::Type *pointeeType = translateType(inst->getPointeeType());
// Save current insertion point
auto savedIP = builder.saveIP();
// Set insertion point to the start of the entry block
llvm::BasicBlock &entry = f->getEntryBlock();
builder.SetInsertPoint(&entry, entry.begin());
// Create an alloca instruction at the start of the entry block
llvm::Value *allocaValue = builder.CreateAlloca(pointeeType);
// Apply custom alignment if the type is a struct with alignment
// attribute
if (auto *structTy
= llvm::dyn_cast<types::StructTy>(inst->getPointeeType().getType()
)) {
if (structTy->getAlignment() > 0) {
llvm::cast<llvm::AllocaInst>(allocaValue)
->setAlignment(llvm::Align(structTy->getAlignment()));
} else if (structTy->isPacked()) {
// Packed structs without explicit alignment use align 1
llvm::cast<llvm::AllocaInst>(allocaValue)
->setAlignment(llvm::Align(1));
}
}
// Restore previous insertion point
builder.restoreIP(savedIP);
mapValue(inst->getResult(0), allocaValue);
}
void visitLoadInst(glu::gil::LoadInst *inst)
{
// Get the pointer value to load from
auto ptrValue = inst->getValue();
llvm::Value *ptr = translateValue(ptrValue);
// Get the type to load by looking at the result type
llvm::Type *loadType = translateType(inst->getResultType(0));
// Create a load instruction
llvm::LoadInst *loadedValue = builder.CreateLoad(loadType, ptr);
// Apply custom alignment if the type is a struct with alignment
// attribute
if (auto *structTy
= llvm::dyn_cast<types::StructTy>(inst->getResultType(0).getType()
)) {
if (structTy->getAlignment() > 0) {
loadedValue->setAlignment(
llvm::Align(structTy->getAlignment())
);
} else if (structTy->isPacked()) {
// Packed structs without explicit alignment use align 1
loadedValue->setAlignment(llvm::Align(1));
}
}
mapValue(inst->getResult(0), loadedValue);
}
void visitStoreInst(glu::gil::StoreInst *inst)
{
// Get the source value and destination pointer
auto sourceValue = inst->getSource();
auto destValue = inst->getDest();
llvm::Value *source = translateValue(sourceValue);
llvm::Value *destPtr = translateValue(destValue);
// Create a store instruction
llvm::StoreInst *storeInst = builder.CreateStore(source, destPtr);
// Apply custom alignment if the source type is a struct with alignment
// attribute
if (auto *structTy
= llvm::dyn_cast<types::StructTy>(sourceValue.getType().getType()
)) {
if (structTy->getAlignment() > 0) {
storeInst->setAlignment(llvm::Align(structTy->getAlignment()));
} else if (structTy->isPacked()) {
// Packed structs without explicit alignment use align 1
storeInst->setAlignment(llvm::Align(1));
}
}
// StoreInst has no result to map
}
// - MARK: Call Instruction
void visitBuiltinCallInst(glu::gil::CallInst *inst)
{
auto callee = inst->getFunctionOrNull();
assert(callee && "Built-in calls must have a named function");
auto builtin = callee->getDecl()->getBuiltinKind();
assert(
builtin != ast::BuiltinKind::None && "Function must be a built-in"
);
llvm::SmallVector<llvm::Value *, 8> args;
args.reserve(inst->getArgs().size());
for (auto arg : inst->getArgs()) {
args.push_back(translateValue(arg));
}
llvm::Value *result = nullptr;
// Handle specific built-in functions
if (callee->getDecl()->getName() == "builtin_add") {
assert(
args.size() == 2 && "builtin_add expects exactly two arguments"
);
if (llvm::isa<types::FloatTy>(inst->getArgs()[0].getType().getType()
)) {
result = builder.CreateFAdd(args[0], args[1]);
} else {
result = builder.CreateAdd(args[0], args[1]);
}
} else if (callee->getDecl()->getName() == "builtin_sub") {
assert(
args.size() == 2 && "builtin_sub expects exactly two arguments"
);
if (llvm::isa<types::FloatTy>(inst->getArgs()[0].getType().getType()
)) {
result = builder.CreateFSub(args[0], args[1]);
} else {
result = builder.CreateSub(args[0], args[1]);
}
} else if (callee->getDecl()->getName() == "builtin_mul") {
assert(
args.size() == 2 && "builtin_mul expects exactly two arguments"
);
if (llvm::isa<types::FloatTy>(inst->getArgs()[0].getType().getType()
)) {
result = builder.CreateFMul(args[0], args[1]);
} else {
result = builder.CreateMul(args[0], args[1]);
}
} else if (callee->getDecl()->getName() == "builtin_div") {
assert(
args.size() == 2 && "builtin_div expects exactly two arguments"
);
if (llvm::isa<types::FloatTy>(inst->getArgs()[0].getType().getType()
)) {
result = builder.CreateFDiv(args[0], args[1]);
} else if (types::IntTy *intTy = llvm::dyn_cast<types::IntTy>(
inst->getArgs()[0].getType().getType()
)) {
if (intTy->isSigned()) {
result = builder.CreateSDiv(args[0], args[1]);
} else {
result = builder.CreateUDiv(args[0], args[1]);
}
}
} else if (callee->getDecl()->getName() == "builtin_mod") {
assert(
args.size() == 2 && "builtin_mod expects exactly two arguments"
);
if (types::IntTy *intTy = llvm::dyn_cast<types::IntTy>(
inst->getArgs()[0].getType().getType()
)) {
if (intTy->isSigned()) {
result = builder.CreateSRem(args[0], args[1]);
} else {
result = builder.CreateURem(args[0], args[1]);
}
} else {
assert(false && "builtin_mod expects integer arguments");
}
} else if (callee->getDecl()->getName() == "builtin_eq") {
assert(
args.size() == 2 && "builtin_eq expects exactly two arguments"
);
if (llvm::isa<types::FloatTy>(inst->getArgs()[0].getType().getType()
)) {
result = builder.CreateFCmpOEQ(args[0], args[1]);
} else {
result = builder.CreateICmpEQ(args[0], args[1]);
}
} else if (callee->getDecl()->getName() == "builtin_lt") {
assert(
args.size() == 2 && "builtin_lt expects exactly two arguments"
);
if (types::IntTy *intTy = llvm::dyn_cast<types::IntTy>(
inst->getArgs()[0].getType().getType()
)) {
if (intTy->isSigned()) {
result = builder.CreateICmpSLT(args[0], args[1]);
} else {
result = builder.CreateICmpULT(args[0], args[1]);
}
} else {
result = builder.CreateFCmpOLT(args[0], args[1]);
}
} else if (callee->getDecl()->getName() == "builtin_gt") {
assert(
args.size() == 2 && "builtin_gt expects exactly two arguments"
);
if (types::IntTy *intTy = llvm::dyn_cast<types::IntTy>(
inst->getArgs()[0].getType().getType()
)) {
if (intTy->isSigned()) {
result = builder.CreateICmpSGT(args[0], args[1]);
} else {
result = builder.CreateICmpUGT(args[0], args[1]);
}
} else {
result = builder.CreateFCmpOGT(args[0], args[1]);
}
} else if (callee->getDecl()->getName() == "builtin_le") {
assert(
args.size() == 2 && "builtin_le expects exactly two arguments"
);
if (types::IntTy *intTy = llvm::dyn_cast<types::IntTy>(
inst->getArgs()[0].getType().getType()
)) {
if (intTy->isSigned()) {
result = builder.CreateICmpSLE(args[0], args[1]);
} else {
result = builder.CreateICmpULE(args[0], args[1]);
}
} else {
result = builder.CreateFCmpOLE(args[0], args[1]);
}
} else if (callee->getDecl()->getName() == "builtin_ge") {
assert(
args.size() == 2 && "builtin_ge expects exactly two arguments"
);
if (types::IntTy *intTy = llvm::dyn_cast<types::IntTy>(
inst->getArgs()[0].getType().getType()
)) {
if (intTy->isSigned()) {
result = builder.CreateICmpSGE(args[0], args[1]);
} else {
result = builder.CreateICmpUGE(args[0], args[1]);
}
} else {
result = builder.CreateFCmpOGE(args[0], args[1]);
}
} else if (callee->getDecl()->getName() == "builtin_and") {
assert(
args.size() == 2 && "builtin_and expects exactly two arguments"
);
result = builder.CreateAnd(args[0], args[1]);
} else if (callee->getDecl()->getName() == "builtin_or") {
assert(
args.size() == 2 && "builtin_or expects exactly two arguments"
);
result = builder.CreateOr(args[0], args[1]);
} else if (callee->getDecl()->getName() == "builtin_xor") {
assert(
args.size() == 2 && "builtin_xor expects exactly two arguments"
);
result = builder.CreateXor(args[0], args[1]);
} else if (callee->getDecl()->getName() == "builtin_shl") {
assert(
args.size() == 2 && "builtin_shl expects exactly two arguments"
);
result = builder.CreateShl(args[0], args[1]);
} else if (callee->getDecl()->getName() == "builtin_shr") {
assert(
args.size() == 2 && "builtin_shr expects exactly two arguments"
);
if (types::IntTy *intTy = llvm::dyn_cast<types::IntTy>(
inst->getArgs()[0].getType().getType()
)) {
if (intTy->isSigned()) {
result = builder.CreateAShr(args[0], args[1]);
} else {
result = builder.CreateLShr(args[0], args[1]);
}
} else {
assert(false && "builtin_shr expects integer arguments");
}
} else if (callee->getDecl()->getName() == "builtin_compl") {
assert(
args.size() == 1 && "builtin_compl expects exactly one argument"
);
result = builder.CreateNot(args[0]);
} else {
assert(false && "Unhandled built-in function");
}
// Map the result if there is one
if (inst->getResultCount() > 0) {
mapValue(inst->getResult(0), result);
}
}
void visitCallInst(glu::gil::CallInst *inst)
{
if (inst->getFunctionOrNull()
&& inst->getFunctionOrNull()->getDecl()->isBuiltin()) {
// Handle built-in functions separately
visitBuiltinCallInst(inst);
return;
}
// Prepare the arguments
llvm::SmallVector<llvm::Value *, 8> args;
args.reserve(inst->getArgs().size());
for (auto arg : inst->getArgs()) {
args.push_back(translateValue(arg));
}
llvm::CallInst *callInst;
if (auto callee = inst->getFunctionOrNull()) {
// Create a call to a named function
callInst = builder.CreateCall(createOrGetFunction(callee), args);
} else if (auto functionPtr = inst->getFunctionPtrValue()) {
// Create a call to a function pointer
auto ptrTy = llvm::dyn_cast<glu::types::PointerTy>(
functionPtr->getType().getType()
);
assert(
ptrTy && "Expected a pointer type for function pointer call"
);
auto funcTy
= llvm::dyn_cast<glu::types::FunctionTy>(ptrTy->getPointee());
assert(
funcTy
&& "Expected a function type as pointee for function pointer"
);
callInst = builder.CreateCall(
translateType(funcTy), translateValue(*functionPtr), args
);
} else {
assert(
false
&& "CallInst must have either a function or a function pointer"
);
}
// Map the result if there is one
if (inst->getResultCount() > 0) {
mapValue(inst->getResult(0), callInst);
}
}
// - MARK: Debug Instruction
void visitDebugInst(glu::gil::DebugInst *inst)
{
if (!ctx.sm) {
return; // No debug info generation without a source manager
}
auto *fn = inst->getParent()->getParent()->getDecl();
auto value = inst->getValue();
llvm::Value *llvmValue = translateValue(value);
auto *valueType
= llvm::dyn_cast<types::PointerTy>(value.getType().getType());
if (!fn || inst->getLocation().isInvalid() || !valueType) {
// No debug info without a valid function or location
// We also currently only support pointers to allocas (dbg.declare)
return;
}
llvm::DILocalVariable *diVar = nullptr;
// If the variable is a valid function argument, create a parameter
// variable
auto *subprogram = f->getSubprogram();
auto file = ctx.createDIFile(inst->getLocation());
auto line = ctx.sm->getSpellingLineNumber(inst->getLocation());
auto type = debugTypeLowering.visit(valueType->getPointee());
if (inst->getBindingType() == gil::DebugBindingType::Arg) {
auto argNo = fn->getParamIndex(inst->getName());
if (argNo) {
diVar = ctx.dib.createParameterVariable(
subprogram, inst->getName(), *argNo + 1, file, line, type
);
}
}
if (!diVar) {
diVar = ctx.dib.createAutoVariable(
subprogram, inst->getName(), file, line, type
);
}
ctx.dib.insertDeclare(
llvmValue, diVar,
ctx.dib.createExpression(), // No expression
builder.getCurrentDebugLocation(), bb
);
}
// - MARK: Conversion Instructions
// Template implementation that can handle different method signatures
// Template specialization for CreateZExt which has an extra parameter
template <auto MethodPtr>
void processConversionInstT(glu::gil::ConversionInst *inst)
{
auto operand = inst->getOperand();
llvm::Value *srcValue = translateValue(operand);
llvm::Type *targetType = translateType(inst->getDestType());
llvm::Value *result = (builder.*MethodPtr)(srcValue, targetType, "");
mapValue(inst->getResult(0), result);
}
// Specialization for CreateZExt which has a different signature
template <>
void processConversionInstT<&llvm::IRBuilderBase::CreateZExt>(
glu::gil::ConversionInst *inst
)
{
auto operand = inst->getOperand();
llvm::Value *srcValue = translateValue(operand);
llvm::Type *targetType = translateType(inst->getDestType());
llvm::Value *result
= builder.CreateZExt(srcValue, targetType, "", false);
mapValue(inst->getResult(0), result);
}
// Macro to define visit methods for conversion instructions using the
// template
#define DEFINE_CONVERSION_VISIT(InstClass, BuilderMethod) \
void visit##InstClass(glu::gil::InstClass *inst) \
{ \
processConversionInstT<&llvm::IRBuilderBase::BuilderMethod>(inst); \
}
DEFINE_CONVERSION_VISIT(CastIntToPtrInst, CreateIntToPtr)
DEFINE_CONVERSION_VISIT(CastPtrToIntInst, CreatePtrToInt)
DEFINE_CONVERSION_VISIT(BitcastInst, CreateBitCast)
DEFINE_CONVERSION_VISIT(IntTruncInst, CreateTrunc)
DEFINE_CONVERSION_VISIT(IntSextInst, CreateSExt)
DEFINE_CONVERSION_VISIT(IntZextInst, CreateZExt)
DEFINE_CONVERSION_VISIT(FloatTruncInst, CreateFPTrunc)
DEFINE_CONVERSION_VISIT(FloatExtInst, CreateFPExt)
#undef DEFINE_CONVERSION_VISIT
void visitFloatToIntInst(glu::gil::FloatToIntInst *inst)
{
auto operand = inst->getOperand();
llvm::Value *srcValue = translateValue(operand);
llvm::Type *targetType = translateType(inst->getDestType());
// Check if target type is signed or unsigned
auto *intTy = llvm::cast<types::IntTy>(inst->getDestType().getType());
llvm::Value *result;
if (intTy->isSigned()) {
result = builder.CreateFPToSI(srcValue, targetType, "");
} else {
result = builder.CreateFPToUI(srcValue, targetType, "");
}
mapValue(inst->getResult(0), result);
}
void visitIntToFloatInst(glu::gil::IntToFloatInst *inst)
{
auto operand = inst->getOperand();
llvm::Value *srcValue = translateValue(operand);
llvm::Type *targetType = translateType(inst->getDestType());
// Check if source type is signed or unsigned
auto *intTy = llvm::cast<types::IntTy>(operand.getType().getType());
llvm::Value *result;
if (intTy->isSigned()) {
result = builder.CreateSIToFP(srcValue, targetType, "");
} else {
result = builder.CreateUIToFP(srcValue, targetType, "");
}
mapValue(inst->getResult(0), result);
}
// - MARK: Aggregate Instructions
// Helper function to get field index from struct type and member name
uint32_t getStructFieldIndexOrAssert(
glu::types::StructTy *structTy, llvm::StringRef fieldName
)
{
auto fieldIndexOpt = structTy->getFieldIndex(fieldName);
assert(fieldIndexOpt.has_value() && "Field not found in struct");
return static_cast<uint32_t>(fieldIndexOpt.value());
}
void visitStructExtractInst(glu::gil::StructExtractInst *inst)
{
auto structValue = inst->getStructValue();
llvm::Value *structVal = translateValue(structValue);
auto member = inst->getMember();
auto structTy
= llvm::cast<glu::types::StructTy>(structValue.getType().getType());
uint32_t fieldIndex
= getStructFieldIndexOrAssert(structTy, member.getName());
llvm::Value *result = builder.CreateExtractValue(structVal, fieldIndex);
mapValue(inst->getResult(0), result);
}
void visitStructCreateInst(glu::gil::StructCreateInst *inst)
{
llvm::Type *structType = translateType(inst->getStruct());
llvm::Value *structVal = llvm::UndefValue::get(structType);
auto fieldValues = inst->getMembers();
for (size_t i = 0; i < fieldValues.size(); ++i) {
gil::Value fieldValue = fieldValues[i]; // Copy to non-const
llvm::Value *fieldVal = translateValue(fieldValue);
structVal = builder.CreateInsertValue(
structVal, fieldVal, static_cast<uint32_t>(i)
);
}
mapValue(inst->getResult(0), structVal);
}
void visitStructDestructureInst(glu::gil::StructDestructureInst *inst)
{
auto structValue = inst->getStructValue();
llvm::Value *structVal = translateValue(structValue);
auto structTy
= llvm::cast<glu::types::StructTy>(structValue.getType().getType());
size_t fieldCount = structTy->getFieldCount();
// Extract each field and map to results
for (size_t i = 0; i < fieldCount; ++i) {
llvm::Value *fieldVal = builder.CreateExtractValue(
structVal, static_cast<uint32_t>(i)
);
mapValue(inst->getResult(i), fieldVal);
}
}
void visitStructFieldPtrInst(glu::gil::StructFieldPtrInst *inst)
{
auto structValue = inst->getStructValue();
llvm::Value *structPtr = translateValue(structValue);
auto member = inst->getMember();
auto structTy
= llvm::cast<glu::types::StructTy>(member.getParent().getType());
uint32_t fieldIndex
= getStructFieldIndexOrAssert(structTy, member.getName());
// Create GEP instruction to get field pointer
llvm::Value *indices[] = {
llvm::ConstantInt::get(llvm::Type::getInt32Ty(ctx.ctx), 0),
llvm::ConstantInt::get(llvm::Type::getInt32Ty(ctx.ctx), fieldIndex)
};