This repository has been archived by the owner on Mar 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 153
/
readerir.cpp
4453 lines (3759 loc) · 152 KB
/
readerir.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
//===---- lib/MSILReader/readerir.cpp ---------------------------*- C++ -*-===//
//
// LLILC
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief Convert from MSIL bytecode to LLVM IR.
///
//===----------------------------------------------------------------------===//
#include "readerir.h"
#include "imeta.h"
#include "newvstate.h"
#include "llvm/ADT/Triple.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/Support/Debug.h" // for dbgs()
#include "llvm/Support/raw_ostream.h" // for errs()
#include "llvm/Support/ConvertUTF.h" // for ConvertUTF16toUTF8
#include <cstdlib>
#include <new>
using namespace llvm;
#pragma region READER STACK MODEL
//===----------------------------------------------------------------------===//
//
// MSIL Reader Stack
//
//===----------------------------------------------------------------------===//
GenStack::GenStack(uint32_t MaxStack, ReaderBase *Rdr) {
Reader = Rdr;
Stack.reserve(MaxStack);
}
void GenStack::push(IRNode *NewVal) {
ASSERT(NewVal != nullptr);
ASSERT(GenIR::isValidStackType(NewVal));
Stack.push_back(NewVal);
}
IRNode *GenStack::pop() {
ASSERTM(size() > 0, "stack underflow");
if (size() == 0)
LLILCJit::fatal(CORJIT_BADCODE);
IRNode* result = Stack.back();
Stack.pop_back();
return result;
}
void GenStack::assertEmpty() { ASSERT(empty()); }
#if !defined(NODEBUG)
void GenStack::print() {
dbgs() << "{GenStack dump, Top first, size = " << size() << '\n';
int32_t I = 0;
for (auto N : *this) {
dbgs() << "[" << I++ << "]: ";
Reader->dbPrintIRNode(N);
}
dbgs() << "}\n";
}
#endif
ReaderStack *GenStack::copy() {
GenStack *Copy;
void *Buffer = Reader->getTempMemory(sizeof(GenStack));
Copy = new (Buffer)GenStack(Stack.capacity() + 1, Reader);
for (auto Value : *this) {
Copy->push(Value);
}
return Copy;
}
ReaderStack *GenIR::createStack(uint32_t MaxStack, ReaderBase *Reader) {
void *Buffer = Reader->getTempMemory(sizeof(GenStack));
// extra 16 should reduce frequency of reallocation when inlining / jmp
return new (Buffer)GenStack(MaxStack + 16, Reader);
}
#pragma endregion
#pragma region EH REGION BUILDER
//===----------------------------------------------------------------------===//
//
// MSIL Reader EH Region Builder
//
//===----------------------------------------------------------------------===//
struct EHRegion {
public:
EHRegion *Parent;
EHRegionList *Children;
uint32_t StartMsilOffset;
uint32_t EndMsilOffset;
ReaderBaseNS::RegionKind Kind;
};
struct EHRegionList {
public:
EHRegion *Region;
EHRegionList *NextRegionList;
};
EHRegion *GenIR::rgnAllocateRegion() {
// TODO: Using ProcMemory here.
// Do we really want these Region objects to persist?
return (EHRegion *)getProcMemory(sizeof(EHRegion));
}
EHRegionList *GenIR::rgnAllocateRegionList() {
// TODO: Using ProcMemory here.
// Do we really want these Region objects to persist?
return (EHRegionList *)getProcMemory(sizeof(EHRegionList));
}
EHRegionList *rgnListGetNext(EHRegionList *RegionList) {
return RegionList->NextRegionList;
}
void rgnListSetNext(EHRegionList *RegionList, EHRegionList *Next) {
RegionList->NextRegionList = Next;
}
EHRegion *rgnListGetRgn(EHRegionList *RegionList) { return RegionList->Region; }
void rgnListSetRgn(EHRegionList *RegionList, EHRegion *Region) {
RegionList->Region = Region;
}
ReaderBaseNS::RegionKind rgnGetRegionType(EHRegion *Region) {
return Region->Kind;
}
void rgnSetRegionType(EHRegion *Region, ReaderBaseNS::RegionKind Type) {
Region->Kind = Type;
}
uint32_t rgnGetStartMSILOffset(EHRegion *Region) {
return Region->StartMsilOffset;
}
void rgnSetStartMSILOffset(EHRegion *Region, uint32_t Offset) {
Region->StartMsilOffset = Offset;
}
uint32_t rgnGetEndMSILOffset(EHRegion *Region) { return Region->EndMsilOffset; }
void rgnSetEndMSILOffset(EHRegion *Region, uint32_t Offset) {
Region->EndMsilOffset = Offset;
}
IRNode *rgnGetHead(EHRegion *Region) { return nullptr; }
void rgnSetHead(EHRegion *Region, IRNode *Head) { return; }
IRNode *rgnGetLast(EHRegion *Region) { return nullptr; }
void rgnSetLast(EHRegion *Region, IRNode *Last) { return; }
bool rgnGetIsLive(EHRegion *Region) { return false; }
void rgnSetIsLive(EHRegion *Region, bool Live) { return; }
void rgnSetParent(EHRegion *Region, EHRegion *Parent) {
Region->Parent = Parent;
}
EHRegion *rgnGetParent(EHRegion *Region) { return Region->Parent; }
void rgnSetChildList(EHRegion *Region, EHRegionList *Children) {
Region->Children = Children;
}
EHRegionList *rgnGetChildList(EHRegion *Region) { return Region->Children; }
bool rgnGetHasNonLocalFlow(EHRegion *Region) { return false; }
void rgnSetHasNonLocalFlow(EHRegion *Region, bool NonLocalFlow) { return; }
IRNode *rgnGetEndOfClauses(EHRegion *Region) { return nullptr; }
void rgnSetEndOfClauses(EHRegion *Region, IRNode *Node) { return; }
IRNode *rgnGetTryBodyEnd(EHRegion *Region) { return nullptr; }
void rgnSetTryBodyEnd(EHRegion *Region, IRNode *Node) { return; }
ReaderBaseNS::TryKind rgnGetTryType(EHRegion *Region) {
return ReaderBaseNS::TryKind::TRY_None;
}
void rgnSetTryType(EHRegion *Region, ReaderBaseNS::TryKind Type) { return; }
int rgnGetTryCanonicalExitOffset(EHRegion *TryRegion) { return 0; }
void rgnSetTryCanonicalExitOffset(EHRegion *TryRegion, int32_t Offset) {
return;
}
EHRegion *rgnGetExceptFilterRegion(EHRegion *Region) { return nullptr; }
void rgnSetExceptFilterRegion(EHRegion *Region, EHRegion *FilterRegion) {
return;
}
EHRegion *rgnGetExceptTryRegion(EHRegion *Region) { return nullptr; }
void rgnSetExceptTryRegion(EHRegion *Region, EHRegion *TryRegion) { return; }
bool rgnGetExceptUsesExCode(EHRegion *Region) { return false; }
void rgnSetExceptUsesExCode(EHRegion *Region, bool UsesExceptionCode) {
return;
}
EHRegion *rgnGetFilterTryRegion(EHRegion *Region) { return nullptr; }
void rgnSetFilterTryRegion(EHRegion *Region, EHRegion *TryRegion) { return; }
EHRegion *rgnGetFilterHandlerRegion(EHRegion *Region) { return nullptr; }
void rgnSetFilterHandlerRegion(EHRegion *Region, EHRegion *Handler) { return; }
EHRegion *rgnGetFinallyTryRegion(EHRegion *FinallyRegion) { return nullptr; }
void rgnSetFinallyTryRegion(EHRegion *FinallyRegion, EHRegion *TryRegion) {
return;
}
bool rgnGetFinallyEndIsReachable(EHRegion *FinallyRegion) { return false; }
void rgnSetFinallyEndIsReachable(EHRegion *FinallyRegion, bool IsReachable) {
return;
}
EHRegion *rgnGetFaultTryRegion(EHRegion *FaultRegion) { return nullptr; }
void rgnSetFaultTryRegion(EHRegion *FaultRegion, EHRegion *TryRegion) {
return;
}
EHRegion *rgnGetCatchTryRegion(EHRegion *CatchRegion) { return nullptr; }
void rgnSetCatchTryRegion(EHRegion *CatchRegion, EHRegion *TryRegion) {
return;
}
mdToken rgnGetCatchClassToken(EHRegion *CatchRegion) { return 0; }
void rgnSetCatchClassToken(EHRegion *CatchRegion, mdToken Token) { return; }
#pragma endregion
#pragma region MEMORY ALLOCATION
//===----------------------------------------------------------------------===//
//
// MSIL Reader memory allocation helpers
//
//===----------------------------------------------------------------------===//
// Get memory that will be freed at end of reader
void *GenIR::getTempMemory(size_t NumBytes) { return calloc(1, NumBytes); }
// Get memory that will persist after the reader
void *GenIR::getProcMemory(size_t NumBytes) { return calloc(1, NumBytes); }
#pragma endregion
#pragma region READER PASSES
//===----------------------------------------------------------------------===//
//
// MSIL Reader Passes
//
//===----------------------------------------------------------------------===//
void GenIR::readerPrePass(uint8_t *Buffer, uint32_t NumBytes) {
Triple PT(Triple::normalize(LLVM_DEFAULT_TARGET_TRIPLE));
if (PT.isArch16Bit()) {
TargetPointerSizeInBits = 16;
} else if (PT.isArch32Bit()) {
TargetPointerSizeInBits = 32;
} else if (PT.isArch64Bit()) {
TargetPointerSizeInBits = 64;
} else {
ASSERTNR(UNREACHED);
}
CORINFO_METHOD_HANDLE MethodHandle = JitContext->MethodInfo->ftn;
Function = getFunction(MethodHandle);
// Capture low-level info about the return type for use in Return.
CORINFO_SIG_INFO Sig;
getMethodSig(MethodHandle, &Sig);
ReturnCorType = Sig.retType;
EntryBlock = BasicBlock::Create(*JitContext->LLVMContext, "entry", Function);
LLVMBuilder = new IRBuilder<>(*this->JitContext->LLVMContext);
LLVMBuilder->SetInsertPoint(EntryBlock);
// Note numArgs may exceed the IL argument count when there
// are hidden args like the varargs cookie or type descriptor.
// Since we add these hidden args to the function's type, we can use the
// type's argument count to get the right number here.
uint32_t NumArgs = Function->getFunctionType()->getFunctionNumParams();
ASSERT(NumArgs >= JitContext->MethodInfo->args.totalILArgs());
uint32_t NumLocals = JitContext->MethodInfo->locals.numArgs;
LocalVars.resize(NumLocals);
LocalVarCorTypes.resize(NumLocals);
Arguments.resize(NumArgs);
ArgumentCorTypes.resize(NumArgs);
HasThis = JitContext->MethodInfo->args.hasThis();
HasTypeParameter = JitContext->MethodInfo->args.hasTypeArg();
HasVarargsToken = JitContext->MethodInfo->args.isVarArg();
KeepGenericContextAlive = false;
initParamsAndAutos(NumArgs, NumLocals);
// Take note of the current insertion point in case we need
// to add more allocas later.
if (EntryBlock->empty()) {
TempInsertionPoint = nullptr;
} else {
TempInsertionPoint = &EntryBlock->back();
}
Function::arg_iterator Args = Function->arg_begin();
Value *CurrentArg;
int32_t I;
for (CurrentArg = Args++, I = 0; CurrentArg != Function->arg_end();
CurrentArg = Args++, I++) {
if (CurrentArg->getType()->isStructTy()) {
// LLVM doesn't use the same calling convention as other .Net jits
// for structs, and we want to be able to select jits per-method
// so we need them to interoperate.
throw NotYetImplementedException("Struct parameter");
}
makeStoreNonNull(CurrentArg, Arguments[I], false);
}
// Check for special cases where the Jit needs to do extra work.
const uint32_t MethodFlags = getCurrentMethodAttribs();
const uint32_t JitFlags = JitContext->Flags;
// TODO: support for synchronized methods
if (MethodFlags & CORINFO_FLG_SYNCH) {
throw NotYetImplementedException("synchronized method");
}
// TODO: support for JustMyCode hook
if ((JitFlags & CORJIT_FLG_DEBUG_CODE) &&
!(JitFlags & CORJIT_FLG_IL_STUB)) {
bool IsIndirect = false;
void * DebugHandle =
getJustMyCodeHandle(getCurrentMethodHandle(), &IsIndirect);
if (DebugHandle != nullptr) {
throw NotYetImplementedException("just my code hook");
}
}
// TODO: support for secret parameter for shared IL stubs
if ((JitFlags & CORJIT_FLG_IL_STUB) &&
(JitFlags & CORJIT_FLG_PUBLISH_SECRET_PARAM)) {
throw NotYetImplementedException("publish secret param");
}
// TODO: Insert class initialization check if necessary
CorInfoInitClassResult InitResult =
initClass(nullptr, getCurrentMethodHandle(), getCurrentContext());
const bool InitClass = InitResult & CORINFO_INITCLASS_USE_HELPER;
if (InitClass) {
throw NotYetImplementedException("init class");
}
}
void GenIR::readerMiddlePass() { return; }
void GenIR::readerPostPass(bool IsImportOnly) {
// If the generic context must be kept live,
// insert the necessary code to make it so.
Value *ContextAddress = nullptr;
if (KeepGenericContextAlive) {
CorInfoOptions Options = JitContext->MethodInfo->options;
if (Options & CORINFO_GENERICS_CTXT_FROM_THIS) {
ASSERT(HasThis);
ContextAddress = Arguments[0];
throw NotYetImplementedException("keep alive generic context: this");
} else {
ASSERT(Options & (CORINFO_GENERICS_CTXT_FROM_METHODDESC |
CORINFO_GENERICS_CTXT_FROM_METHODTABLE));
ASSERT(HasTypeParameter);
ContextAddress = Arguments[HasThis ? (HasVarargsToken ? 2 : 1) : 0];
throw NotYetImplementedException("keep alive generic context: !this");
}
}
// Cleanup the memory we've been using.
delete LLVMBuilder;
}
#pragma endregion
#pragma region UTILITIES
//===----------------------------------------------------------------------===//
//
// MSIL Reader Utilities
//
//===----------------------------------------------------------------------===//
// Translate an ArgOrdinal (from MSIL) into an in index
// into the Arguments array.
uint32_t GenIR::argOrdinalToArgIndex(uint32_t ArgOrdinal) {
bool MightNeedShift = !HasThis || ArgOrdinal > 0;
if (MightNeedShift) {
uint32_t Delta = (HasTypeParameter ? 1 : 0) + (HasVarargsToken ? 1 : 0);
return ArgOrdinal + Delta;
}
return ArgOrdinal;
}
// Translate an index into the Arguments array into
// the ordinal used in MSIL.
uint32_t GenIR::argIndexToArgOrdinal(uint32_t ArgIndex) {
bool MightNeedShift = !HasThis || ArgIndex > 0;
if (MightNeedShift) {
uint32_t Delta = (HasTypeParameter ? 1 : 0) + (HasVarargsToken ? 1 : 0);
ASSERT(ArgIndex >= Delta);
return ArgIndex - Delta;
}
return ArgIndex;
}
void GenIR::createSym(uint32_t Num, bool IsAuto, CorInfoType CorType,
CORINFO_CLASS_HANDLE Class, bool IsPinned,
ReaderSpecialSymbolType SymType) {
// Give the symbol a plausible name.
//
// The user names for args and locals are stored in the PDB,
// not in the metadata, so we can't directly access it via the jit interface.
const char *SymName = IsAuto ? "loc" : "arg";
bool UseNumber = false;
uint32_t Number = Num;
switch (SymType) {
case ReaderSpecialSymbolType::Reader_ThisPtr:
ASSERT(HasThis);
SymName = "this";
break;
case ReaderSpecialSymbolType::Reader_InstParam:
ASSERT(HasTypeParameter);
SymName = "$TypeArg";
break;
case ReaderSpecialSymbolType::Reader_VarArgsToken:
ASSERT(HasVarargsToken);
SymName = "$VarargsToken";
HasVarargsToken = true;
break;
default:
UseNumber = true;
if (!IsAuto) {
Number = argIndexToArgOrdinal(Num);
}
break;
}
Type *LLVMType = this->getType(CorType, Class);
AllocaInst *AllocaInst = LLVMBuilder->CreateAlloca(
LLVMType, nullptr,
UseNumber ? Twine(SymName) + Twine(Number) : Twine(SymName));
if (IsAuto) {
LocalVars[Num] = AllocaInst;
LocalVarCorTypes[Num] = CorType;
} else {
Arguments[Num] = AllocaInst;
ArgumentCorTypes[Num] = CorType;
}
}
Function *GenIR::getFunction(CORINFO_METHOD_HANDLE MethodHandle) {
Module *M = JitContext->CurrentModule;
FunctionType *Ty = getFunctionType(MethodHandle);
llvm::Function *F = Function::Create(Ty, Function::ExternalLinkage,
M->getModuleIdentifier(), M);
ASSERT(Ty == F->getFunctionType());
// Use "param" for these initial parameter values. Numbering here
// is strictly positional (hence includes implicit parameters).
uint32_t N = 0;
for (Function::arg_iterator Args = F->arg_begin(); Args != F->arg_end();
Args++) {
Args->setName(Twine("param") + Twine(N++));
}
return F;
}
// Return true if this IR node is a reference to the
// original this pointer passed to the method. Can
// conservatively return false.
bool GenIR::objIsThis(IRNode *Obj) { return false; }
// Create a new temporary with the indicated type.
Instruction *GenIR::createTemporary(Type *Ty) {
// Put the alloca for this temporary into the entry block so
// the temporary uses can appear anywhere.
IRBuilder<>::InsertPoint IP = LLVMBuilder->saveIP();
if (TempInsertionPoint == nullptr) {
// There are no local, param or temp allocas in the entry block, so set
// the insertion point to the first point in the block.
LLVMBuilder->SetInsertPoint(EntryBlock->getFirstInsertionPt());
} else {
// There are local, param or temp allocas. TempInsertionPoint refers to
// the last of them. Set the insertion point to the next instruction since
// the builder will insert new instructions before the insertion point.
LLVMBuilder->SetInsertPoint(TempInsertionPoint->getNextNode());
}
AllocaInst *AllocaInst = LLVMBuilder->CreateAlloca(Ty);
// Update the end of the alloca range.
TempInsertionPoint = AllocaInst;
LLVMBuilder->restoreIP(IP);
return AllocaInst;
}
// Get the value of the unmodified this object.
IRNode *GenIR::thisObj() {
ASSERT(HasThis);
Function::arg_iterator Args = Function->arg_begin();
Value *UnmodifiedThis = Args++;
return (IRNode *)UnmodifiedThis;
}
// Get the value of the varargs token (aka argList).
IRNode *GenIR::argList() {
ASSERT(HasVarargsToken);
Function::arg_iterator Args = Function->arg_begin();
if (HasThis) {
Args++;
}
Value *ArgList = Args++;
return (IRNode *)ArgList;
}
// Get the value of the instantiation parameter (aka type parameter).
IRNode *GenIR::instParam() {
ASSERT(HasTypeParameter);
Function::arg_iterator Args = Function->arg_begin();
if (HasThis) {
Args++;
}
if (HasVarargsToken) {
Args++;
}
Value *TypeParameter = Args++;
return (IRNode *)TypeParameter;
}
#pragma endregion
#pragma region DIAGNOSTICS
//===----------------------------------------------------------------------===//
//
// MSIL Reader Diagnostics
//
//===----------------------------------------------------------------------===//
// Notify client of alignment problem
void GenIR::verifyStaticAlignment(void *FieldAddress, CorInfoType CorType,
uint32_t MinClassAlign) {
bool AlignmentError;
const char *TypeName;
AlignmentError = false;
switch (CorType) {
case CORINFO_TYPE_DOUBLE:
TypeName = "CORINFO_TYPE_DOUBLE";
goto ALIGN_8;
case CORINFO_TYPE_STRING:
TypeName = "CORINFO_TYPE_STRING";
goto ALIGN_8;
case CORINFO_TYPE_PTR:
TypeName = "CORINFO_TYPE_PTR";
goto ALIGN_8;
case CORINFO_TYPE_BYREF:
TypeName = "CORINFO_TYPE_BYREF";
goto ALIGN_8;
case CORINFO_TYPE_REFANY:
TypeName = "CORINFO_TYPE_REFANY";
goto RESOLVE_ALIGNMENT_BY_SIZE;
case CORINFO_TYPE_VALUECLASS:
TypeName = "CORINFO_TYPE_VALUECLASS";
goto RESOLVE_ALIGNMENT_BY_SIZE;
RESOLVE_ALIGNMENT_BY_SIZE:
switch (MinClassAlign) {
case 1:
goto ALIGN_1;
case 2:
goto ALIGN_2;
case 4:
goto ALIGN_4;
case 8:
goto ALIGN_8;
default:
ASSERTNR(UNREACHED);
break;
}
case CORINFO_TYPE_CLASS:
TypeName = "CORINFO_TYPE_CLASS";
goto ALIGN_8;
ALIGN_8:
// Require 8-byte alignment
AlignmentError = ((7 & (uintptr_t)FieldAddress) != 0);
break;
case CORINFO_TYPE_INT:
TypeName = "CORINFO_TYPE_INT";
goto ALIGN_4;
case CORINFO_TYPE_UINT:
TypeName = "CORINFO_TYPE_UINT";
goto ALIGN_4;
case CORINFO_TYPE_LONG:
TypeName = "CORINFO_TYPE_LONG";
goto ALIGN_8;
case CORINFO_TYPE_NATIVEINT:
TypeName = "CORINFO_TYPE_NATIVEINT";
goto ALIGN_8;
case CORINFO_TYPE_NATIVEUINT:
TypeName = "CORINFO_TYPE_NATIVEUINT";
goto ALIGN_8;
case CORINFO_TYPE_ULONG:
TypeName = "CORINFO_TYPE_ULONG";
goto ALIGN_8;
case CORINFO_TYPE_FLOAT:
TypeName = "CORINFO_TYPE_FLOAT";
goto ALIGN_4;
ALIGN_4:
// Require 4-byte alignment
AlignmentError = ((3 & (uintptr_t)FieldAddress) != 0);
break;
case CORINFO_TYPE_SHORT:
TypeName = "CORINFO_TYPE_SHORT";
goto ALIGN_2;
case CORINFO_TYPE_USHORT:
TypeName = "CORINFO_TYPE_USHORT";
goto ALIGN_2;
case CORINFO_TYPE_CHAR: // unicode
TypeName = "CORINFO_TYPE_CHAR";
goto ALIGN_2;
ALIGN_2:
// Require 2-byte alignment
AlignmentError = ((1 & (uintptr_t)FieldAddress) != 0);
break;
case CORINFO_TYPE_BOOL:
TypeName = "CORINFO_TYPE_BOOL";
goto ALIGN_1;
case CORINFO_TYPE_BYTE:
TypeName = "CORINFO_TYPE_BYTE";
goto ALIGN_1;
case CORINFO_TYPE_UBYTE:
TypeName = "CORINFO_TYPE_UBYTE";
goto ALIGN_1;
ALIGN_1:
default:
// Require 1-byte alignment - no constraints.
break;
}
// TODO: the commented out parts depend on debug code
// which we haven't ported.
#if defined(_DEBUG)
if (AlignmentError /*&& ifdb(DB_UNALIGNEDSTATICASSERT)*/) {
/*dbgs() << format
("Warning - unaligned static field found at address, type:%s, "
"value 0x%I64x\n", typeName, fieldAddress);
if ((corInfoType == CORINFO_TYPE_VALUECLASS) ||
(corInfoType == CORINFO_TYPE_REFANY)) {
dbgs() << format("minClassAlign: %d\n", minClassAlign);
}*/
ASSERT(UNREACHED);
}
#endif
}
void ReaderBase::debugError(const char *Filename, unsigned Linenumber,
const char *S) {
assert(0);
// TODO
// if (s) JitContext->JitInfo->doAssert(Filename, Linenumber, S);
// ASSERTNR(UNREACHED);
}
// Fatal error, reader cannot continue.
void ReaderBase::fatal(int ErrNum) { LLILCJit::fatal(LLILCJIT_FATAL_ERROR); }
#pragma endregion
#pragma region TYPES
//===----------------------------------------------------------------------===//
//
// MSIL READER CLR and LLVM Type Support
//
//===----------------------------------------------------------------------===//
Type *GenIR::getType(CorInfoType CorType, CORINFO_CLASS_HANDLE ClassHandle,
bool GetRefClassFields) {
LLVMContext &LLVMContext = *this->JitContext->LLVMContext;
switch (CorType) {
case CorInfoType::CORINFO_TYPE_UNDEF:
return nullptr;
case CorInfoType::CORINFO_TYPE_VOID:
return Type::getVoidTy(LLVMContext);
case CorInfoType::CORINFO_TYPE_BOOL:
case CorInfoType::CORINFO_TYPE_BYTE:
case CorInfoType::CORINFO_TYPE_UBYTE:
return Type::getInt8Ty(LLVMContext);
case CorInfoType::CORINFO_TYPE_SHORT:
case CorInfoType::CORINFO_TYPE_USHORT:
case CorInfoType::CORINFO_TYPE_CHAR:
return Type::getInt16Ty(LLVMContext);
case CorInfoType::CORINFO_TYPE_INT:
case CorInfoType::CORINFO_TYPE_UINT:
return Type::getInt32Ty(LLVMContext);
case CorInfoType::CORINFO_TYPE_LONG:
case CorInfoType::CORINFO_TYPE_ULONG:
return Type::getInt64Ty(LLVMContext);
case CorInfoType::CORINFO_TYPE_NATIVEINT:
case CorInfoType::CORINFO_TYPE_NATIVEUINT:
return Type::getIntNTy(LLVMContext, TargetPointerSizeInBits);
case CorInfoType::CORINFO_TYPE_FLOAT:
return Type::getFloatTy(LLVMContext);
case CorInfoType::CORINFO_TYPE_DOUBLE:
return Type::getDoubleTy(LLVMContext);
case CorInfoType::CORINFO_TYPE_CLASS:
ASSERT(ClassHandle != nullptr);
return getClassType(ClassHandle, true, GetRefClassFields);
case CorInfoType::CORINFO_TYPE_VALUECLASS:
case CorInfoType::CORINFO_TYPE_REFANY: {
ASSERT(ClassHandle != nullptr);
return getClassType(ClassHandle, false, true);
}
case CorInfoType::CORINFO_TYPE_PTR:
case CorInfoType::CORINFO_TYPE_BYREF: {
ASSERT(ClassHandle != 0);
bool IsPtr = (CorType == CorInfoType::CORINFO_TYPE_PTR);
Type *ClassType = nullptr;
CORINFO_CLASS_HANDLE ChildClassHandle = nullptr;
CorInfoType ChildCorType = getChildType(ClassHandle, &ChildClassHandle);
// LLVM does not allow void*, so use char* instead.
if (ChildCorType == CORINFO_TYPE_VOID) {
ASSERT(IsPtr);
ClassType = getType(CORINFO_TYPE_CHAR, nullptr);
} else if (ChildCorType == CORINFO_TYPE_UNDEF) {
// Presumably a value class...?
ClassType = getType(CORINFO_TYPE_VALUECLASS, ClassHandle);
} else {
ClassType = getType(ChildCorType, ChildClassHandle);
}
// Byrefs are reported as potential GC pointers.
if (IsPtr) {
return getUnmanagedPointerType(ClassType);
} else {
return getManagedPointerType(ClassType);
}
}
case CorInfoType::CORINFO_TYPE_STRING: // Not used, should remove
// CORINFO_TYPE_VAR is for a generic type variable.
// Generic type variables only appear when the JIT is doing
// verification (not NOT compilation) of generic code
// for the EE, in which case we're running
// the JIT in "import only" mode.
case CorInfoType::CORINFO_TYPE_VAR:
default:
throw NotYetImplementedException("unexpected CorInfoType in GetType");
}
}
// Map this class handle into an LLVM type.
//
// Classes are modelled via LLVM structs. Fields in a class
// correspond to .Net fields. We make the LLVM layout
// match the EE's layout here by accounting for the vtable
// and any internal padding.
//
// Note there may be some inter-element padding that
// is not accounted for here (eg array of value classes).
// We also do not model things like the preheader so overall
// size is accurate only for value classes.
//
// If GetRefClassFields is false, then we won't fill in the
// field information for ref classes. This is used to avoid
// getting trapped in cycles in the type reference graph.
Type *GenIR::getClassType(CORINFO_CLASS_HANDLE ClassHandle, bool IsRefClass,
bool GetRefClassFields) {
// Check if we've already created a type for this class handle.
Type *ResultTy = nullptr;
StructType *StructTy = nullptr;
uint32_t ArrayRank = getArrayRank(ClassHandle);
bool IsArray = ArrayRank > 0;
CORINFO_CLASS_HANDLE ArrayElementHandle = nullptr;
CorInfoType ArrayElementType = CorInfoType::CORINFO_TYPE_UNDEF;
// Two different handles can identify the same array: the actual array handle
// and the handle of its MethodTable. Because of that we have a separate map
// for arrays with <element type, element handle, array rank> tuple as key.
if (IsArray) {
ArrayElementType = getChildType(ClassHandle, &ArrayElementHandle);
auto MapElement = ArrayTypeMap->find(
std::make_tuple(ArrayElementType, ArrayElementHandle, ArrayRank));
if (MapElement != ArrayTypeMap->end()) {
ResultTy = MapElement->second;
}
} else {
auto MapElement = ClassTypeMap->find(ClassHandle);
if (MapElement != ClassTypeMap->end()) {
ResultTy = MapElement->second;
}
}
if (ResultTy != nullptr) {
// See if we can just return this result.
bool CanReturnCachedType = true;
if (IsRefClass) {
// ResultTy should be ptr-to struct.
ASSERT(ResultTy->isPointerTy());
Type *ReferentTy = cast<PointerType>(ResultTy)->getPointerElementType();
ASSERT(ReferentTy->isStructTy());
StructTy = cast<StructType>(ReferentTy);
// If we need fields and don't have them yet, we
// can't return the cached type without doing some
// work to finish it off.
if (GetRefClassFields && StructTy->isOpaque()) {
CanReturnCachedType = false;
}
} else {
// Value classes should be structs and all filled in
ASSERT(ResultTy->isStructTy());
ASSERT(!cast<StructType>(ResultTy)->isOpaque());
}
if (CanReturnCachedType) {
return ResultTy;
}
}
// Cache the context and data layout.
LLVMContext &LLVMContext = *JitContext->LLVMContext;
const DataLayout *DataLayout = JitContext->EE->getDataLayout();
// We need to fill in or create a new type for this class.
if (StructTy == nullptr) {
// Need to create one ... add it to the map now so it's
// there if we make a recursive request.
StructTy = StructType::create(LLVMContext);
ResultTy =
IsRefClass ? (Type *)getManagedPointerType(StructTy) : (Type *)StructTy;
if (IsArray) {
(*ArrayTypeMap)[std::make_tuple(ArrayElementType, ArrayElementHandle,
ArrayRank)] = ResultTy;
} else {
(*ClassTypeMap)[ClassHandle] = ResultTy;
}
// Fetch the name of this type for use in dumps.
// Note some constructed types like arrays may not have names.
int32_t NameSize = 0;
const bool IncludeNamespace = true;
const bool FullInst = false;
const bool IncludeAssembly = false;
// We are using appendClassName instead of getClassName because
// getClassName omits namespaces from some types (e.g., nested classes).
// We may still get the same name for two different structs because
// two classes with the same fully-qualified names may live in different
// assemblies. In that case StructType->setName will append a unique suffix
// to the conflicting name.
NameSize = appendClassName(nullptr, &NameSize, ClassHandle,
IncludeNamespace, FullInst, IncludeAssembly);
if (NameSize > 0) {
// Add one for terminating null.
int32_t BufferLength = NameSize + 1;
int32_t BufferRemaining = BufferLength;
char16_t *WideCharBuffer = new char16_t[BufferLength];
char16_t *BufferPtrToChange = WideCharBuffer;
appendClassName(&BufferPtrToChange, &BufferRemaining, ClassHandle,
IncludeNamespace, FullInst, IncludeAssembly);
ASSERT(BufferRemaining == 1);
// Note that this is a worst-case estimate.
size_t UTF8Size = (NameSize * UNI_MAX_UTF8_BYTES_PER_CODE_POINT) + 1;
UTF8 *ClassName = new UTF8[UTF8Size];
UTF8 *UTF8Start = ClassName;
const UTF16 *UTF16Start = (UTF16 *)WideCharBuffer;
ConversionResult Result =
ConvertUTF16toUTF8(&UTF16Start, &UTF16Start[NameSize + 1], &UTF8Start,
&UTF8Start[UTF8Size], strictConversion);
if (Result == conversionOK) {
ASSERT((size_t)(&WideCharBuffer[BufferLength] -
(const char16_t *)UTF16Start) == 0);
StructTy->setName((char *)ClassName);
}
delete[] ClassName;
delete[] WideCharBuffer;
}
}
// Bail out if we just want a placeholder for a ref class.
// We will fill in details later.
if (IsRefClass && !GetRefClassFields) {
return ResultTy;
}
// We want to build up a description of the fields in
// this type, including those from parent classes. We are
// going to "inject" parent class fields into this type.
// .Net only allows single inheritance so we know that
// parent class's layout forms a prefix for this class's layout.
//
// Note getClassNumInstanceFields includes fields from
// all ancestor classes. We'll need to subtract those out to figure
// out how many fields this class uniquely contributes.
const uint32_t NumFields = getClassNumInstanceFields(ClassHandle);
std::vector<Type *> Fields;
uint32_t ByteOffset = 0;
uint32_t NumParentFields = 0;
// Look for cases that require special handling.
bool IsString = false;
bool IsUnion = false;
bool IsObject = false;
bool IsTypedByref = false;
CORINFO_CLASS_HANDLE ObjectClassHandle =
getBuiltinClass(CorInfoClassId::CLASSID_SYSTEM_OBJECT);
CORINFO_CLASS_HANDLE StringClassHandle =
getBuiltinClass(CorInfoClassId::CLASSID_STRING);
CORINFO_CLASS_HANDLE TypedByrefClassHandle =
getBuiltinClass(CorInfoClassId::CLASSID_TYPED_BYREF);
if (ClassHandle == ObjectClassHandle) {
IsObject = true;
} else if (ClassHandle == StringClassHandle) {
IsString = true;
} else if (ClassHandle == TypedByrefClassHandle) {
IsTypedByref = true;
} else {
uint32_t ClassAttributes = getClassAttribs(ClassHandle);
if ((ClassAttributes & CORINFO_FLG_ARRAY) != 0) {
ASSERT(IsArray);
}
if ((ClassAttributes & CORINFO_FLG_OVERLAPPING_FIELDS) != 0) {
IsUnion = true;
}
}
// Keep track of any ref classes that we deferred
// examining in detail, so we can come back to them
// when this class is filled in.
std::vector<CORINFO_CLASS_HANDLE> DeferredDetailClasses;
// System.Object is a special case, it has no explicit
// fields but we need to account for the vtable slot.
if (IsObject) {
ASSERT(NumFields == 0);
ASSERT(IsRefClass);
// Vtable is an array of pointer-sized things.
Type *VtableSlotTy =
Type::getIntNPtrTy(LLVMContext, TargetPointerSizeInBits);
Type *VtableTy = ArrayType::get(VtableSlotTy, 0);
Type *VtablePtrTy = VtableTy->getPointerTo();