forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathYkIRWriter.cpp
1969 lines (1777 loc) · 63.4 KB
/
YkIRWriter.cpp
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
//===- YkIR/YkIRWRiter.cpp -- Yk JIT IR Serialiaser---------------------===//
//
// Converts an LLVM module into Yk's on-disk AOT IR.
//
//===-------------------------------------------------------------------===//
#include "llvm/YkIR/YkIRWriter.h"
#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/BinaryFormat/ELF.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCSectionELF.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Transforms/Yk/ControlPoint.h"
#include "llvm/Transforms/Yk/Idempotent.h"
#include "llvm/Transforms/Yk/ModuleClone.h"
using namespace llvm;
using namespace std;
// The argument index of the <numArgs> parameter of
// llvm.experimental.patchpoint.*
//
// We need this later to know where arguments to __ykrt_control_point stop, and
// where live variables to include in the stackmap entry start.
const int PPArgIdxNumTargetArgs = 3;
// Function flags.
const uint8_t YkFuncFlagOutline = 1;
const uint8_t YkFuncFlagIdempotent = 2;
#include <sstream>
namespace {
class SerialiseInstructionException {
private:
string S;
public:
SerialiseInstructionException(string S) : S(S) {}
string &what() { return S; }
};
#define YK_PROMOTE_PREFIX "__yk_promote"
#define YK_DEBUG_STR "yk_debug_str"
#define YK_IDEMPOTENT_PREFIX "__yk_idempotent_promote"
const char *SectionName = ".yk_ir";
const uint32_t Magic = 0xedd5f00d;
const uint32_t Version = 0;
enum OpCode {
OpCodeNop = 0,
OpCodeLoad,
OpCodeStore,
OpCodeAlloca,
OpCodeCall,
OpCodeBr,
OpCodeCondBr,
OpCodeICmp,
OpCodeRet,
OpCodeInsertValue,
OpCodePtrAdd,
OpCodeBinOp,
OpCodeCast,
OpCodeSwitch,
OpCodePHI,
OpCodeIndirectCall,
OpCodeSelect,
OpCodeLoadArg,
OpCodeFCmp,
OpCodePromote,
OpCodeFNeg,
OpCodeDebugStr,
OpCodePromoteIdempotent,
OpCodeUnimplemented = 255, // YKFIXME: Will eventually be deleted.
};
enum OperandKind {
OperandKindConstant = 0,
OperandKindLocal,
OperandKindGlobal,
OperandKindFunction,
OperandKindArg,
};
enum TypeKind {
TypeKindVoid = 0,
TypeKindInteger,
TypeKindPtr,
TypeKindFunction,
TypeKindStruct,
TypeKindFloat,
TypeKindUnimplemented = 255, // YKFIXME: Will eventually be deleted.
};
enum FloatKind {
FloatKindFloat,
FloatKindDouble,
};
enum CastKind {
CastKindSignExt = 0,
CastKindZeroExt = 1,
CastKindTrunc = 2,
CastKindSIToFP = 3,
CastKindFPExt = 4,
CastKindFPToSI = 5,
CastKindBitCast = 6,
CastKindPtrToInt = 7,
CastKindIntToPtr = 8,
};
// A predicate used in an integer comparison.
enum CmpPredicate {
PredEqual = 0,
PredNotEqual,
PredUnsignedGreater,
PredUnsignedGreaterEqual,
PredUnsignedLess,
PredUnsignedLessEqual,
PredSignedGreater,
PredSignedGreaterEqual,
PredSignedLess,
PredSignedLessEqual,
};
// A predicate used in a floating point comparison.
enum FCmpPredicate {
FCmpFalse = 0,
FCmpOrderedEqual,
FCmpOrderedGreater,
FCmpOrderedGreaterEqual,
FCmpOrderedLess,
FCmpOrderedLessEqual,
FCmpOrderedNotEqual,
FCmpOrdered,
FCmpUnordered,
FCmpUnorderedEqual,
FCmpUnorderedGreater,
FCmpUnorderedGreaterEqual,
FCmpUnorderedLess,
FCmpUnorderedLessEqual,
FCmpUnorderedNotEqual,
FCmpTrue,
};
// A binary operator.
enum BinOp {
BinOpAdd,
BinOpSub,
BinOpMul,
BinOpOr,
BinOpAnd,
BinOpXor,
BinOpShl,
BinOpAShr,
BinOpFAdd,
BinOpFDiv,
BinOpFMul,
BinOpFRem,
BinOpFSub,
BinOpLShr,
BinOpSDiv,
BinOpSRem,
BinOpUDiv,
BinOpURem,
};
// A constant kind
enum ConstKind {
ConstKindVal,
ConstKindUnimplemented,
};
template <class T> string toString(T *X) {
string S;
raw_string_ostream SS(S);
X->print(SS);
return S;
}
// Get the index of an element in its parent container.
template <class C, class E> size_t getIndex(C *Container, E *FindElement) {
bool Found = false;
size_t Idx = 0;
for (E &AnElement : *Container) {
if (&AnElement == FindElement) {
Found = true;
break;
}
Idx++;
}
assert(Found);
return Idx;
}
// An instruction index that uniquely identifies a Yk instruction within
// a basic block.
//
// FIXME: At some point it may be worth making type-safe index types (for
// instruction, block and function indices) and using them throughout
// the serialiser.
using InstIdx = size_t;
// An function index that uniquely identifies a Yk function within
// a module.
using FuncIdx = size_t;
// An basic block index that uniquely identifies a Yk basic block within
// a function.
using BBlockIdx = size_t;
// An instruction ID that uniquely identifies a Yk instruction within a module.
//
// We use a raw tuple here (instead of a custom struct) so that it is hashable.
using InstID = tuple<FuncIdx, BBlockIdx, InstIdx>;
// An index into the path table.
using PathIdx = size_t;
// Line-level debug information for a Yk instruction.
//
// Elements: path index, line number.
using LineInfo = tuple<PathIdx, unsigned>;
// Maps an LLVM local (the instruction that creates it) to the correspoinding Yk
// instruction index in its parent basic block.
//
// Note: The Yk basic block index is not stored because it's the same as
// the LLVM IR block index, which can be found elsewhere (see `getIndex()`).
using ValueLoweringMap = map<Instruction *, InstIdx>;
// Function lowering context.
//
// This groups together some per-function lowering bits so that they can be
// passed down through the serialiser together (and so that they can die
// together).
class FuncLowerCtxt {
// The local variable mapping for one function.
ValueLoweringMap VLMap;
// Local variable indices that require patching once we have finished
// lowwering the function.
vector<tuple<Instruction *, MCSymbol *>> InstIdxPatchUps;
public:
// Create an empty function lowering context.
FuncLowerCtxt() : VLMap(ValueLoweringMap()), InstIdxPatchUps({}){};
// Maps argument operands to LoadArg instructions.
map<Argument *, InstIdx> ArgumentMap;
// Defer (patch up later) the use-site of the (as-yet unknown) instruction
// index of the instruction `I`, which has the symbol `Sym`.
void deferInstIdx(Instruction *I, MCSymbol *Sym) {
InstIdxPatchUps.push_back({I, Sym});
}
// Fill in instruction indices that had to be deferred.
void patchUpInstIdxs(MCStreamer &OutStreamer) {
MCContext &MCtxt = OutStreamer.getContext();
for (auto &[Inst, Sym] : InstIdxPatchUps) {
InstIdx InstIdx = VLMap.at(Inst);
OutStreamer.emitAssignment(Sym, MCConstantExpr::create(InstIdx, MCtxt));
}
}
// Add/update an entry in the value lowering map.
void updateVLMap(Instruction *I, InstIdx L) { VLMap[I] = L; }
// Get the entry for `I` in the value lowering map.
//
// Raises `std::out_of_range` if not present.
InstIdx lookupInVLMap(Instruction *I) { return VLMap.at(I); }
// Determines if there's an entry for `I` in the value lowering map.
bool vlMapContains(Instruction *I) { return VLMap.count(I) == 1; }
};
// The class responsible for serialising our IR into the interpreter binary.
//
// It walks over the LLVM IR, lowering each function, block, instruction, etc.
// into a Yk IR equivalent.
//
// As it does this there are some invariants that must be maintained:
//
// - The current basic block index (BBIdx) is passed down the lowering process.
// This must be incremented each time we finish a Yk IR basic block.
//
// - Similarly for instructions. Each time we finish a Yk IR instruction,
// we must increment the current instruction index (InstIdx).
//
// - When we are done lowering an LLVM instruction that generates a value, we
// must update the `VLMap` (found inside the `FuncLowerCtxt`) with an entry
// that maps the LLVM instruction to the final Yk IR instruction in the
// lowering. If the LLVM instruction doesn't generate a value, or the LLVM
// instruction lowered to exactly zero Yk IR instructions, then there is no
// need to update the `VLMap`.
//
// These invariants are required so that when we encounter a local variable as
// an operand to an LLVM instruction, we can quickly find the corresponding Yk
// IR local variable.
class YkIRWriter {
private:
Module &M;
MCStreamer &OutStreamer;
DataLayout DL;
vector<llvm::Type *> Types;
vector<llvm::Constant *> Constants;
vector<llvm::GlobalVariable *> Globals;
// Maps a function to its index. This is not the same as the index in
// the module's function list because we skip cloned functions in
// serialisation.
std::unordered_map<llvm::Function *, size_t> FunctionIndexMap;
// File paths.
vector<string> Paths;
// Line-level debug line info for the instructions of the module.
//
// If debug info is not being compiled in, this will be empty.
map<InstID, LineInfo> LineInfos;
// The last processed `LineInfo`. Used for de-duplication.
optional<LineInfo> LastLineInfo;
// Return the index of the LLVM type `Ty`, inserting a new entry if
// necessary.
size_t typeIndex(llvm::Type *Ty) {
vector<llvm::Type *>::iterator Found =
std::find(Types.begin(), Types.end(), Ty);
if (Found != Types.end()) {
return std::distance(Types.begin(), Found);
}
// Not found. Assign it a type index.
size_t Idx = Types.size();
Types.push_back(Ty);
// If the newly-registered type is an aggregate type that contains other
// types, then assign them type indices now too.
for (llvm::Type *STy : Ty->subtypes()) {
typeIndex(STy);
}
return Idx;
}
// Return the index of the LLVM constant `C`, inserting a new entry if
// necessary.
size_t constantIndex(Constant *C) {
vector<Constant *>::iterator Found =
std::find(Constants.begin(), Constants.end(), C);
if (Found != Constants.end()) {
return std::distance(Constants.begin(), Found);
}
size_t Idx = Constants.size();
Constants.push_back(C);
return Idx;
}
// Return the index of the LLVM global `G`, inserting a new entry if
// necessary.
size_t globalIndex(GlobalVariable *G) {
vector<GlobalVariable *>::iterator Found =
std::find(Globals.begin(), Globals.end(), G);
if (Found != Globals.end()) {
return std::distance(Globals.begin(), Found);
}
size_t Idx = Globals.size();
Globals.push_back(G);
return Idx;
}
size_t functionIndex(llvm::Function *F) {
auto it = FunctionIndexMap.find(F);
if (it != FunctionIndexMap.end()) {
return it->second;
}
llvm::errs() << "Function not found in function index map: " << F->getName()
<< "\n";
llvm::report_fatal_error("Function not found in function index map");
}
// Serialises a null-terminated string.
void serialiseString(StringRef S) {
OutStreamer.emitBinaryData(S);
OutStreamer.emitInt8(0); // null terminator.
}
void serialiseOpcode(OpCode Code) { OutStreamer.emitInt8(Code); }
void serialiseOperandKind(OperandKind Kind) { OutStreamer.emitInt8(Kind); }
void serialiseTypeKind(TypeKind Kind) { OutStreamer.emitInt8(Kind); }
void serialiseConstantOperand(Instruction *Parent, llvm::Constant *C) {
serialiseOperandKind(OperandKindConstant);
OutStreamer.emitSizeT(constantIndex(C));
}
void serialiseLocalVariableOperand(Instruction *I, FuncLowerCtxt &FLCtxt) {
// operand kind:
serialiseOperandKind(OperandKindLocal);
// func_idx:
OutStreamer.emitSizeT(getIndex(&M, I->getFunction()));
// bb_idx:
OutStreamer.emitSizeT(getIndex(I->getFunction(), I->getParent()));
// inst_idx:
if (FLCtxt.vlMapContains(I)) {
InstIdx InstIdx = FLCtxt.lookupInVLMap(I);
OutStreamer.emitSizeT(InstIdx);
} else {
// It's a local variable generated by an instruction that we haven't
// serialised yet. This can happen in loop bodies where a PHI node merges
// in a variable from the end of the loop body.
//
// To work around this, we emit a dummy instruction index
// and patch it up later once it becomes known.
MCSymbol *PatchUpSym = OutStreamer.getContext().createTempSymbol();
OutStreamer.emitSymbolValue(PatchUpSym, sizeof(size_t));
FLCtxt.deferInstIdx(I, PatchUpSym);
}
}
void serialiseFunctionOperand(llvm::Function *F) {
serialiseOperandKind(OperandKindFunction);
OutStreamer.emitSizeT(functionIndex(F));
}
void serialiseBlockLabel(BasicBlock *BB) {
// Basic block indices are the same in both LLVM IR and our IR.
OutStreamer.emitSizeT(getIndex(BB->getParent(), BB));
}
void serialiseArgOperand(Argument *A, FuncLowerCtxt &FLCtxt) {
// operand kind:
serialiseOperandKind(OperandKindLocal);
// func_idx:
OutStreamer.emitSizeT(getIndex(&M, A->getParent()));
// bb_idx:
OutStreamer.emitSizeT(0);
// inst_idx:
if (FLCtxt.ArgumentMap.count(A) > 0) {
InstIdx InstIdx = FLCtxt.ArgumentMap[A];
OutStreamer.emitSizeT(InstIdx);
}
}
void serialiseGlobalOperand(GlobalVariable *G) {
serialiseOperandKind(OperandKindGlobal);
OutStreamer.emitSizeT(globalIndex(G));
}
void serialiseOperand(Instruction *Parent, FuncLowerCtxt &FLCtxt, Value *V) {
if (llvm::GlobalVariable *G = dyn_cast<llvm::GlobalVariable>(V)) {
serialiseGlobalOperand(G);
} else if (llvm::Function *F = dyn_cast<llvm::Function>(V)) {
serialiseFunctionOperand(F);
} else if (llvm::Constant *C = dyn_cast<llvm::Constant>(V)) {
serialiseConstantOperand(Parent, C);
} else if (llvm::Argument *A = dyn_cast<llvm::Argument>(V)) {
serialiseArgOperand(A, FLCtxt);
} else if (Instruction *I = dyn_cast<Instruction>(V)) {
serialiseLocalVariableOperand(I, FLCtxt);
} else {
llvm::report_fatal_error(
StringRef("attempt to serialise non-yk-operand: " + toString(V)));
}
}
void serialiseBinaryOperatorInst(llvm::BinaryOperator *I,
FuncLowerCtxt &FLCtxt, unsigned BBIdx,
unsigned &InstIdx) {
assert(I->getNumOperands() == 2);
// We don't yet support:
// - fast math flags (for float operations).
// - vector variants
if ((isa<FPMathOperator>(I) && (I->getFastMathFlags().any())) ||
I->getType()->isVectorTy()) {
serialiseUnimplementedInstruction(I, FLCtxt, BBIdx, InstIdx);
return;
}
// Note that we do nothing with the `nsw` and `nuw` (no {signed,unsigned}
// wrap), and `exact` keywords, which may generate poison values. If they
// do, the rules of deferred UB allow us to make any value we wish.
// opcode:
serialiseOpcode(OpCodeBinOp);
// left-hand side:
serialiseOperand(I, FLCtxt, I->getOperand(0));
// binary operator:
serialiseBinOperator(I->getOpcode());
// right-hand side:
serialiseOperand(I, FLCtxt, I->getOperand(1));
FLCtxt.updateVLMap(I, InstIdx);
InstIdx++;
}
// Serialise a binary operator.
void serialiseBinOperator(Instruction::BinaryOps BO) {
switch (BO) {
case Instruction::BinaryOps::Add:
OutStreamer.emitInt8(BinOp::BinOpAdd);
break;
case Instruction::BinaryOps::Sub:
OutStreamer.emitInt8(BinOp::BinOpSub);
break;
case Instruction::BinaryOps::Mul:
OutStreamer.emitInt8(BinOp::BinOpMul);
break;
case Instruction::BinaryOps::Or:
OutStreamer.emitInt8(BinOp::BinOpOr);
break;
case Instruction::BinaryOps::And:
OutStreamer.emitInt8(BinOp::BinOpAnd);
break;
case Instruction::BinaryOps::Xor:
OutStreamer.emitInt8(BinOp::BinOpXor);
break;
case Instruction::BinaryOps::Shl:
OutStreamer.emitInt8(BinOp::BinOpShl);
break;
case Instruction::BinaryOps::AShr:
OutStreamer.emitInt8(BinOp::BinOpAShr);
break;
case Instruction::BinaryOps::FAdd:
OutStreamer.emitInt8(BinOp::BinOpFAdd);
break;
case Instruction::BinaryOps::FDiv:
OutStreamer.emitInt8(BinOp::BinOpFDiv);
break;
case Instruction::BinaryOps::FMul:
OutStreamer.emitInt8(BinOp::BinOpFMul);
break;
case Instruction::BinaryOps::FRem:
OutStreamer.emitInt8(BinOp::BinOpFRem);
break;
case Instruction::BinaryOps::FSub:
OutStreamer.emitInt8(BinOp::BinOpFSub);
break;
case Instruction::BinaryOps::LShr:
OutStreamer.emitInt8(BinOp::BinOpLShr);
break;
case Instruction::BinaryOps::SDiv:
OutStreamer.emitInt8(BinOp::BinOpSDiv);
break;
case Instruction::BinaryOps::SRem:
OutStreamer.emitInt8(BinOp::BinOpSRem);
break;
case Instruction::BinaryOps::UDiv:
OutStreamer.emitInt8(BinOp::BinOpUDiv);
break;
case Instruction::BinaryOps::URem:
OutStreamer.emitInt8(BinOp::BinOpURem);
break;
default:
llvm::report_fatal_error("unknown binary operator");
}
}
void serialiseAllocaInst(AllocaInst *I, FuncLowerCtxt &FLCtxt, unsigned BBIdx,
unsigned &InstIdx) {
// We don't yet support:
// - the `inalloca` keyword.
// - non-zero address spaces.
// - dynamic alloca (because stackmaps can't handle them).
// - allocating an array with more than SIZE_MAX elements.
if ((I->isUsedWithInAlloca()) || (I->getAddressSpace() != 0) ||
(!isa<Constant>(I->getArraySize())) ||
cast<ConstantInt>(I->getArraySize())->getValue().ugt(SIZE_MAX)) {
serialiseUnimplementedInstruction(I, FLCtxt, BBIdx, InstIdx);
return;
}
// opcode:
serialiseOpcode(OpCodeAlloca);
// type to be allocated:
OutStreamer.emitSizeT(typeIndex(I->getAllocatedType()));
// number of objects to allocate
ConstantInt *CI = cast<ConstantInt>(I->getArraySize());
static_assert(sizeof(size_t) <= sizeof(uint64_t));
OutStreamer.emitSizeT(CI->getZExtValue());
// align:
OutStreamer.emitInt64(I->getAlign().value());
FLCtxt.updateVLMap(I, InstIdx);
InstIdx++;
}
void serialiseStackmapCall(CallInst *I, FuncLowerCtxt &FLCtxt) {
assert(I);
assert(I->getCalledFunction()->isIntrinsic());
assert(I->getIntrinsicID() == Intrinsic::experimental_stackmap ||
I->getIntrinsicID() == Intrinsic::experimental_patchpoint_void);
// stackmap ID:
Value *Op = I->getOperand(0);
assert(isa<ConstantInt>(Op));
uint64_t SMId = (cast<ConstantInt>(Op))->getZExtValue();
OutStreamer.emitInt64(SMId);
int Skip = 0;
if (I->getIntrinsicID() == Intrinsic::experimental_stackmap) {
// Skip the following arguments: ID, shadow.
Skip = 2;
} else if (I->getIntrinsicID() == Intrinsic::experimental_patchpoint_void) {
// Skip the following arguments: ID, shadow, target, target arguments.
Skip = 4 + cast<ConstantInt>(I->getOperand(PPArgIdxNumTargetArgs))
->getZExtValue();
}
// num_lives:
OutStreamer.emitInt32(I->arg_size() - Skip);
// lives:
for (unsigned OI = Skip; OI < I->arg_size(); OI++) {
serialiseOperand(I, FLCtxt, I->getOperand(OI));
}
}
void serialisePromotion(CallInst *I, FuncLowerCtxt &FLCtxt,
unsigned &InstIdx) {
assert(I->arg_size() == 1);
// opcode:
serialiseOpcode(OpCodePromote);
// type_idx:
OutStreamer.emitSizeT(typeIndex(I->getOperand(0)->getType()));
// value:
serialiseOperand(I, FLCtxt, I->getOperand(0));
// safepoint:
CallInst *SMI = dyn_cast<CallInst>(I->getNextNonDebugInstruction());
serialiseStackmapCall(SMI, FLCtxt);
FLCtxt.updateVLMap(I, InstIdx);
InstIdx++;
}
void serialiseIdempotentPromotion(CallInst *I, FuncLowerCtxt &FLCtxt,
unsigned &InstIdx) {
assert(I->arg_size() == 1);
// opcode:
serialiseOpcode(OpCodePromoteIdempotent);
// type_idx:
OutStreamer.emitSizeT(typeIndex(I->getOperand(0)->getType()));
// value:
serialiseOperand(I, FLCtxt, I->getOperand(0));
FLCtxt.updateVLMap(I, InstIdx);
InstIdx++;
}
void serialiseDebugStr(CallInst *I, FuncLowerCtxt &FLCtxt,
unsigned &InstIdx) {
// We expect one argument: a `char *`.
assert(I->arg_size() == 1);
assert(I->getOperand(0)->getType()->isPointerTy());
// opcode:
serialiseOpcode(OpCodeDebugStr);
// message:
serialiseOperand(I, FLCtxt, I->getOperand(0));
FLCtxt.updateVLMap(I, InstIdx);
InstIdx++;
}
void serialiseIndirectCallInst(CallInst *I, FuncLowerCtxt &FLCtxt,
unsigned BBIdx, unsigned &InstIdx) {
serialiseOpcode(OpCodeIndirectCall);
// function type:
OutStreamer.emitSizeT(typeIndex(I->getFunctionType()));
// callee (operand):
serialiseOperand(I, FLCtxt, I->getCalledOperand());
// num_args:
// (this includes static and varargs arguments)
OutStreamer.emitInt32(I->arg_size());
// args:
for (unsigned OI = 0; OI < I->arg_size(); OI++) {
serialiseOperand(I, FLCtxt, I->getOperand(OI));
}
// If the return type is non-void, then this defines a local.
if (!I->getType()->isVoidTy()) {
FLCtxt.updateVLMap(I, InstIdx);
}
InstIdx++;
}
void serialiseCallInst(CallInst *I, FuncLowerCtxt &FLCtxt, unsigned BBIdx,
unsigned &InstIdx) {
// Tail calls:
//
// - The `tail` keyword is ignorable and merely means that the call *could*
// be tail called, should an appropriate calling convention be used for
// the call. It's safe for us to ignore this because we check the calling
// convention of the call separately below.
//
// - The `notail` keyword just means don't add `tail` or `musttail`. I
// think this has no consequences for us.
//
// - `musttail` is tricky. It means "it is semantically incorrect to NOT
// tail call codegen this". I don't even know what this means for an
// inlining tracer, so let's just reject it for now.
if (I->isMustTailCall()) {
serialiseUnimplementedInstruction(I, FLCtxt, BBIdx, InstIdx);
}
// We don't support some parameter attributes yet.
AttributeList Attrs = I->getAttributes();
for (unsigned AI = 0; AI < I->arg_size(); AI++) {
for (auto &Attr : Attrs.getParamAttrs(AI)) {
// `nonull`, `noundef`, `nounwind` and `dereferencable` are used a lot.
// I think for our purposes they can be safely ignored.
if (((Attr.getKindAsEnum() == Attribute::NonNull) ||
(Attr.getKindAsEnum() == Attribute::NoUndef) ||
(Attr.getKindAsEnum() == Attribute::NoUnwind) ||
(Attr.getKindAsEnum() == Attribute::Dereferenceable))) {
continue;
}
// "indicates that the annotated function will always return at least a
// given number of bytes (or null)" -- not relevant for Yk at this
// time.
if (Attr.getKindAsEnum() == Attribute::AllocSize) {
continue;
}
if (Attr.getKindAsEnum() == Attribute::Alignment) {
// Following what we do with loads/stores, we accept any alignment
// value greater-than or equal-to the size of the object.
//
// FIXME: explicitly encode the alignment requirements into the IR
// and let the JIT codegen deal with it.
if (I->getParamAlign(AI) >=
DL.getTypeAllocSize(I->getArgOperand(AI)->getType())) {
continue;
}
}
serialiseUnimplementedInstruction(I, FLCtxt, BBIdx, InstIdx);
return;
}
}
// We don't support ANY return value attributes yet.
if (Attrs.getRetAttrs().getNumAttributes() > 0) {
serialiseUnimplementedInstruction(I, FLCtxt, BBIdx, InstIdx);
return;
}
// We don't support some function attributes.
//
// Note that although we haven't thought about unwinding, if we reject any
// call to a function that isn't `nounwind` we are unable to lower much at
// all (including the call to the control point). So for now we have to
// accept calls to functions that might unwind.
AttributeSet FnAttrs = Attrs.getFnAttrs();
for (auto &Attr : FnAttrs) {
// - `cold` can be ignored.
// - `nounwind` has no consequences for us at the moment.
if (Attr.isEnumAttribute() &&
((Attr.getKindAsEnum() == Attribute::Cold) ||
(Attr.getKindAsEnum() == Attribute::NoUnwind))) {
continue;
}
// Anything else, we've not thought about.
serialiseUnimplementedInstruction(I, FLCtxt, BBIdx, InstIdx);
return;
}
// In addition, we don't support:
//
// - fast math flags
// - Non-C calling conventions.
// - operand bundles
// - non-zero address spaces
//
// Note: address spaces are blanket handled elsewhere in serialiseInst().
if ((isa<FPMathOperator>(I) && I->getFastMathFlags().any()) ||
(I->getCallingConv() != CallingConv::C) || I->hasOperandBundles()) {
serialiseUnimplementedInstruction(I, FLCtxt, BBIdx, InstIdx);
return;
}
if (I->isInlineAsm()) {
// For now we omit calls to empty inline asm blocks.
//
// These are pretty much always present in yk unit tests to block
// optimisations.
// if (!(cast<InlineAsm>(Callee)->getAsmString().empty())) {
if (!(cast<InlineAsm>(I->getCalledOperand())->getAsmString().empty())) {
// Non-empty asm block. We can't ignore it.
serialiseUnimplementedInstruction(I, FLCtxt, BBIdx, InstIdx);
}
return;
}
if (I->isIndirectCall()) {
serialiseIndirectCallInst(I, FLCtxt, BBIdx, InstIdx);
return;
}
// Stackmap calls are serialised on-demand by folding them into the `call`
// or `condbr` instruction which they belong to.
if (I->getCalledFunction()->isIntrinsic() &&
I->getIntrinsicID() == Intrinsic::experimental_stackmap) {
return;
}
// Calls to functions that promote runtime values are given their own
// bytecodes so that they can more be easily identified.
if (I->getCalledFunction()->getName().startswith(YK_PROMOTE_PREFIX)) {
serialisePromotion(I, FLCtxt, InstIdx);
return;
}
if (I->getCalledFunction()->getName().startswith(YK_IDEMPOTENT_PREFIX)) {
serialiseIdempotentPromotion(I, FLCtxt, InstIdx);
return;
}
if (I->getCalledFunction()->getName() == YK_DEBUG_STR) {
serialiseDebugStr(I, FLCtxt, InstIdx);
return;
}
// FIXME: Note that this assertion can fail if you do a direct call without
// the correct type annotation at the call site.
//
// e.g. for a functiion:
//
// define i32 @f(i32, ...)
//
// if you do:
//
// call i32 @f(1i32, 2i32);
//
// instead of:
//
// call i32 (i32, ...) @f(1i32, 2i32);
assert(I->getCalledFunction());
serialiseOpcode(OpCodeCall);
// callee:
OutStreamer.emitSizeT(functionIndex(I->getCalledFunction()));
// num_args:
// (this includes static and varargs arguments)
OutStreamer.emitInt32(I->arg_size());
// args:
for (unsigned OI = 0; OI < I->arg_size(); OI++) {
serialiseOperand(I, FLCtxt, I->getOperand(OI));
}
bool IsCtrlPointCall = I->getCalledFunction()->getName() == CP_PPNAME;
if (!I->getCalledFunction()->isDeclaration() || IsCtrlPointCall) {
// The next instruction will be the stackmap entry
// has_safepoint = 1:
OutStreamer.emitInt8(1);
CallInst *SMI = nullptr;
// The control point is special. We use a patchpoint to perform the
// call, so the stackmap is associated with the patchpoint itself.
//
// We'd love to be able to do the same for ALL calls that need a
// stackmap, but patchpoints can only return void or i64, which isn't
// general enough for any given call we may encounter in the IR.
//
// For non-control-point calls, we instead place a stackmap instruction
// after the call and rely on a pass (FixStackmapsSpillReloads) to "patch
// up" the MIR later. This is necessary because we want the live
// locations at the point of the call, but when you place stackmap
// instruction after the call, you don't generally get that: LLVM often
// inserts instructions between the call and the stackmap instruction
// which is (for us, undesirably) reflected in the stackmap entry.
if (IsCtrlPointCall) {
SMI = dyn_cast<CallInst>(I);
} else {
SMI = dyn_cast<CallInst>(I->getNextNonDebugInstruction());
}
serialiseStackmapCall(SMI, FLCtxt);
} else {
// has_safepoint = 0:
OutStreamer.emitInt8(0);
}
// If the return type is non-void, then this defines a local.
if (!I->getType()->isVoidTy()) {
FLCtxt.updateVLMap(I, InstIdx);
}
InstIdx++;
}
void serialiseBranchInst(BranchInst *I, FuncLowerCtxt &FLCtxt, unsigned BBIdx,
unsigned &InstIdx) {
// We split LLVM's `br` into two Yk IR instructions: one for unconditional
// branching, another for conidtional branching.
if (!I->isConditional()) {
// We don't serialise the branch target for unconditional branches because
// traces will guide us.
//
// opcode:
serialiseOpcode(OpCodeBr);
// successor:
serialiseBlockLabel(I->getSuccessor(0));
} else {
// opcode:
serialiseOpcode(OpCodeCondBr);
// We DO need operands for conditional branches, so that we can build
// guards.
//
// cond:
serialiseOperand(I, FLCtxt, I->getCondition());
// true_bb:
serialiseBlockLabel(I->getSuccessor(0));
// false_bb:
serialiseBlockLabel(I->getSuccessor(1));
CallInst *SMI = dyn_cast<CallInst>(I->getPrevNonDebugInstruction());
serialiseStackmapCall(SMI, FLCtxt);
}
InstIdx++;
}
void serialiseLoadInst(LoadInst *I, FuncLowerCtxt &FLCtxt, unsigned BBIdx,
unsigned &InstIdx) {
// We don't yet support:
// - atomic loads
// - loads from exotic address spaces
// - potentially misaligned loads
//
// FIXME: About misaligned loads, when a load is aligned `N`, this is a hard
// guarantee to the code generator that at runtime, the pointer is aligned
// to N bytes. The codegen uses this to decide whether or not to split the
// operation into multiple loads (in order to avoid a memory access
// straddling an alignment boundary on a CPU that disallows such things).
//
// For now we let through only loads with an alignment greater-than or
// equal-to the size of the type of the data being loaded. Such cases are
// trivially safe, since the codegen will never have to face an unaligned
// load for these.
//
// Eventually we will have to encode the alignment of the load into our IR
// and have the trace code generator split up the loads where necessary.
// The same will have to be done for store instructions.
if ((I->getOrdering() != AtomicOrdering::NotAtomic) ||
(I->getPointerAddressSpace() != 0) ||
(I->getAlign() < DL.getTypeAllocSize(I->getType()))) {
serialiseUnimplementedInstruction(I, FLCtxt, BBIdx, InstIdx);
return;
}
// opcode:
serialiseOpcode(OpCodeLoad);
// ptr:
serialiseOperand(I, FLCtxt, I->getPointerOperand());
// type_idx:
OutStreamer.emitSizeT(typeIndex(I->getType()));
// volatile:
OutStreamer.emitInt8(I->isVolatile());
FLCtxt.updateVLMap(I, InstIdx);
InstIdx++;
}
void serialiseStoreInst(StoreInst *I, FuncLowerCtxt &FLCtxt, unsigned BBIdx,
unsigned &InstIdx) {
// We don't yet support:
// - atomic store
// - stores into exotic address spaces
// - potentially misaligned stores
//
// See the comment in `serialiseLoadInst()` for context on misaligned memory
// accesses.
if ((I->getOrdering() != AtomicOrdering::NotAtomic) ||
(I->getPointerAddressSpace() != 0) ||
(I->getAlign() <
DL.getTypeAllocSize(I->getValueOperand()->getType()))) {
serialiseUnimplementedInstruction(I, FLCtxt, BBIdx, InstIdx);
return;
}
// opcode:
serialiseOpcode(OpCodeStore);
// value:
serialiseOperand(I, FLCtxt, I->getValueOperand());
// ptr:
serialiseOperand(I, FLCtxt, I->getPointerOperand());
// volatile:
OutStreamer.emitInt8(I->isVolatile());