-
Notifications
You must be signed in to change notification settings - Fork 12.8k
/
RustWrapper.cpp
1578 lines (1407 loc) · 55.9 KB
/
RustWrapper.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
#include "rustllvm.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/DiagnosticPrinter.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/Instructions.h"
#include "llvm/Object/Archive.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Bitcode/BitcodeWriterPass.h"
#include "llvm/Support/Signals.h"
#include "llvm/ADT/Optional.h"
#include <iostream>
//===----------------------------------------------------------------------===
//
// This file defines alternate interfaces to core functions that are more
// readily callable by Rust's FFI.
//
//===----------------------------------------------------------------------===
using namespace llvm;
using namespace llvm::sys;
using namespace llvm::object;
// LLVMAtomicOrdering is already an enum - don't create another
// one.
static AtomicOrdering fromRust(LLVMAtomicOrdering Ordering) {
switch (Ordering) {
case LLVMAtomicOrderingNotAtomic:
return AtomicOrdering::NotAtomic;
case LLVMAtomicOrderingUnordered:
return AtomicOrdering::Unordered;
case LLVMAtomicOrderingMonotonic:
return AtomicOrdering::Monotonic;
case LLVMAtomicOrderingAcquire:
return AtomicOrdering::Acquire;
case LLVMAtomicOrderingRelease:
return AtomicOrdering::Release;
case LLVMAtomicOrderingAcquireRelease:
return AtomicOrdering::AcquireRelease;
case LLVMAtomicOrderingSequentiallyConsistent:
return AtomicOrdering::SequentiallyConsistent;
}
report_fatal_error("Invalid LLVMAtomicOrdering value!");
}
static LLVM_THREAD_LOCAL char *LastError;
// Custom error handler for fatal LLVM errors.
//
// Notably it exits the process with code 101, unlike LLVM's default of 1.
static void FatalErrorHandler(void *UserData,
const std::string& Reason,
bool GenCrashDiag) {
// Do the same thing that the default error handler does.
std::cerr << "LLVM ERROR: " << Reason << std::endl;
// Since this error handler exits the process, we have to run any cleanup that
// LLVM would run after handling the error. This might change with an LLVM
// upgrade.
sys::RunInterruptHandlers();
exit(101);
}
extern "C" void LLVMRustInstallFatalErrorHandler() {
install_fatal_error_handler(FatalErrorHandler);
}
extern "C" LLVMMemoryBufferRef
LLVMRustCreateMemoryBufferWithContentsOfFile(const char *Path) {
ErrorOr<std::unique_ptr<MemoryBuffer>> BufOr =
MemoryBuffer::getFile(Path, -1, false);
if (!BufOr) {
LLVMRustSetLastError(BufOr.getError().message().c_str());
return nullptr;
}
return wrap(BufOr.get().release());
}
extern "C" char *LLVMRustGetLastError(void) {
char *Ret = LastError;
LastError = nullptr;
return Ret;
}
extern "C" unsigned int LLVMRustGetInstructionCount(LLVMModuleRef M) {
return unwrap(M)->getInstructionCount();
}
extern "C" void LLVMRustSetLastError(const char *Err) {
free((void *)LastError);
LastError = strdup(Err);
}
extern "C" LLVMContextRef LLVMRustContextCreate(bool shouldDiscardNames) {
auto ctx = new LLVMContext();
ctx->setDiscardValueNames(shouldDiscardNames);
return wrap(ctx);
}
extern "C" void LLVMRustSetNormalizedTarget(LLVMModuleRef M,
const char *Triple) {
unwrap(M)->setTargetTriple(Triple::normalize(Triple));
}
extern "C" void LLVMRustPrintPassTimings() {
raw_fd_ostream OS(2, false); // stderr.
TimerGroup::printAll(OS);
}
extern "C" LLVMValueRef LLVMRustGetNamedValue(LLVMModuleRef M,
const char *Name) {
return wrap(unwrap(M)->getNamedValue(Name));
}
extern "C" LLVMValueRef LLVMRustGetOrInsertFunction(LLVMModuleRef M,
const char *Name,
LLVMTypeRef FunctionTy) {
return wrap(
unwrap(M)->getOrInsertFunction(Name, unwrap<FunctionType>(FunctionTy))
#if LLVM_VERSION_GE(9, 0)
.getCallee()
#endif
);
}
extern "C" LLVMValueRef
LLVMRustGetOrInsertGlobal(LLVMModuleRef M, const char *Name, size_t NameLen, LLVMTypeRef Ty) {
StringRef NameRef(Name, NameLen);
return wrap(unwrap(M)->getOrInsertGlobal(NameRef, unwrap(Ty)));
}
extern "C" LLVMValueRef
LLVMRustInsertPrivateGlobal(LLVMModuleRef M, LLVMTypeRef Ty) {
return wrap(new GlobalVariable(*unwrap(M),
unwrap(Ty),
false,
GlobalValue::PrivateLinkage,
nullptr));
}
extern "C" LLVMTypeRef LLVMRustMetadataTypeInContext(LLVMContextRef C) {
return wrap(Type::getMetadataTy(*unwrap(C)));
}
static Attribute::AttrKind fromRust(LLVMRustAttribute Kind) {
switch (Kind) {
case AlwaysInline:
return Attribute::AlwaysInline;
case ByVal:
return Attribute::ByVal;
case Cold:
return Attribute::Cold;
case InlineHint:
return Attribute::InlineHint;
case MinSize:
return Attribute::MinSize;
case Naked:
return Attribute::Naked;
case NoAlias:
return Attribute::NoAlias;
case NoCapture:
return Attribute::NoCapture;
case NoInline:
return Attribute::NoInline;
case NonNull:
return Attribute::NonNull;
case NoRedZone:
return Attribute::NoRedZone;
case NoReturn:
return Attribute::NoReturn;
case NoUnwind:
return Attribute::NoUnwind;
case OptimizeForSize:
return Attribute::OptimizeForSize;
case ReadOnly:
return Attribute::ReadOnly;
case SExt:
return Attribute::SExt;
case StructRet:
return Attribute::StructRet;
case UWTable:
return Attribute::UWTable;
case ZExt:
return Attribute::ZExt;
case InReg:
return Attribute::InReg;
case SanitizeThread:
return Attribute::SanitizeThread;
case SanitizeAddress:
return Attribute::SanitizeAddress;
case SanitizeMemory:
return Attribute::SanitizeMemory;
case NonLazyBind:
return Attribute::NonLazyBind;
case OptimizeNone:
return Attribute::OptimizeNone;
case ReturnsTwice:
return Attribute::ReturnsTwice;
}
report_fatal_error("bad AttributeKind");
}
extern "C" void LLVMRustAddCallSiteAttribute(LLVMValueRef Instr, unsigned Index,
LLVMRustAttribute RustAttr) {
CallSite Call = CallSite(unwrap<Instruction>(Instr));
Attribute Attr = Attribute::get(Call->getContext(), fromRust(RustAttr));
Call.addAttribute(Index, Attr);
}
extern "C" void LLVMRustAddAlignmentCallSiteAttr(LLVMValueRef Instr,
unsigned Index,
uint32_t Bytes) {
CallSite Call = CallSite(unwrap<Instruction>(Instr));
AttrBuilder B;
B.addAlignmentAttr(Bytes);
Call.setAttributes(Call.getAttributes().addAttributes(
Call->getContext(), Index, B));
}
extern "C" void LLVMRustAddDereferenceableCallSiteAttr(LLVMValueRef Instr,
unsigned Index,
uint64_t Bytes) {
CallSite Call = CallSite(unwrap<Instruction>(Instr));
AttrBuilder B;
B.addDereferenceableAttr(Bytes);
Call.setAttributes(Call.getAttributes().addAttributes(
Call->getContext(), Index, B));
}
extern "C" void LLVMRustAddDereferenceableOrNullCallSiteAttr(LLVMValueRef Instr,
unsigned Index,
uint64_t Bytes) {
CallSite Call = CallSite(unwrap<Instruction>(Instr));
AttrBuilder B;
B.addDereferenceableOrNullAttr(Bytes);
Call.setAttributes(Call.getAttributes().addAttributes(
Call->getContext(), Index, B));
}
extern "C" void LLVMRustAddByValCallSiteAttr(LLVMValueRef Instr, unsigned Index,
LLVMTypeRef Ty) {
CallSite Call = CallSite(unwrap<Instruction>(Instr));
#if LLVM_VERSION_GE(9, 0)
Attribute Attr = Attribute::getWithByValType(Call->getContext(), unwrap(Ty));
#else
Attribute Attr = Attribute::get(Call->getContext(), Attribute::ByVal);
#endif
Call.addAttribute(Index, Attr);
}
extern "C" void LLVMRustAddFunctionAttribute(LLVMValueRef Fn, unsigned Index,
LLVMRustAttribute RustAttr) {
Function *A = unwrap<Function>(Fn);
Attribute Attr = Attribute::get(A->getContext(), fromRust(RustAttr));
AttrBuilder B(Attr);
A->addAttributes(Index, B);
}
extern "C" void LLVMRustAddAlignmentAttr(LLVMValueRef Fn,
unsigned Index,
uint32_t Bytes) {
Function *A = unwrap<Function>(Fn);
AttrBuilder B;
B.addAlignmentAttr(Bytes);
A->addAttributes(Index, B);
}
extern "C" void LLVMRustAddDereferenceableAttr(LLVMValueRef Fn, unsigned Index,
uint64_t Bytes) {
Function *A = unwrap<Function>(Fn);
AttrBuilder B;
B.addDereferenceableAttr(Bytes);
A->addAttributes(Index, B);
}
extern "C" void LLVMRustAddDereferenceableOrNullAttr(LLVMValueRef Fn,
unsigned Index,
uint64_t Bytes) {
Function *A = unwrap<Function>(Fn);
AttrBuilder B;
B.addDereferenceableOrNullAttr(Bytes);
A->addAttributes(Index, B);
}
extern "C" void LLVMRustAddByValAttr(LLVMValueRef Fn, unsigned Index,
LLVMTypeRef Ty) {
Function *F = unwrap<Function>(Fn);
#if LLVM_VERSION_GE(9, 0)
Attribute Attr = Attribute::getWithByValType(F->getContext(), unwrap(Ty));
#else
Attribute Attr = Attribute::get(F->getContext(), Attribute::ByVal);
#endif
F->addAttribute(Index, Attr);
}
extern "C" void LLVMRustAddFunctionAttrStringValue(LLVMValueRef Fn,
unsigned Index,
const char *Name,
const char *Value) {
Function *F = unwrap<Function>(Fn);
AttrBuilder B;
B.addAttribute(Name, Value);
F->addAttributes(Index, B);
}
extern "C" void LLVMRustRemoveFunctionAttributes(LLVMValueRef Fn,
unsigned Index,
LLVMRustAttribute RustAttr) {
Function *F = unwrap<Function>(Fn);
Attribute Attr = Attribute::get(F->getContext(), fromRust(RustAttr));
AttrBuilder B(Attr);
auto PAL = F->getAttributes();
auto PALNew = PAL.removeAttributes(F->getContext(), Index, B);
F->setAttributes(PALNew);
}
// enable fpmath flag UnsafeAlgebra
extern "C" void LLVMRustSetHasUnsafeAlgebra(LLVMValueRef V) {
if (auto I = dyn_cast<Instruction>(unwrap<Value>(V))) {
I->setFast(true);
}
}
extern "C" LLVMValueRef
LLVMRustBuildAtomicLoad(LLVMBuilderRef B, LLVMValueRef Source, const char *Name,
LLVMAtomicOrdering Order) {
LoadInst *LI = new LoadInst(unwrap(Source));
LI->setAtomic(fromRust(Order));
return wrap(unwrap(B)->Insert(LI, Name));
}
extern "C" LLVMValueRef LLVMRustBuildAtomicStore(LLVMBuilderRef B,
LLVMValueRef V,
LLVMValueRef Target,
LLVMAtomicOrdering Order) {
StoreInst *SI = new StoreInst(unwrap(V), unwrap(Target));
SI->setAtomic(fromRust(Order));
return wrap(unwrap(B)->Insert(SI));
}
extern "C" LLVMValueRef
LLVMRustBuildAtomicCmpXchg(LLVMBuilderRef B, LLVMValueRef Target,
LLVMValueRef Old, LLVMValueRef Source,
LLVMAtomicOrdering Order,
LLVMAtomicOrdering FailureOrder, LLVMBool Weak) {
AtomicCmpXchgInst *ACXI = unwrap(B)->CreateAtomicCmpXchg(
unwrap(Target), unwrap(Old), unwrap(Source), fromRust(Order),
fromRust(FailureOrder));
ACXI->setWeak(Weak);
return wrap(ACXI);
}
enum class LLVMRustSynchronizationScope {
Other,
SingleThread,
CrossThread,
};
static SyncScope::ID fromRust(LLVMRustSynchronizationScope Scope) {
switch (Scope) {
case LLVMRustSynchronizationScope::SingleThread:
return SyncScope::SingleThread;
case LLVMRustSynchronizationScope::CrossThread:
return SyncScope::System;
default:
report_fatal_error("bad SynchronizationScope.");
}
}
extern "C" LLVMValueRef
LLVMRustBuildAtomicFence(LLVMBuilderRef B, LLVMAtomicOrdering Order,
LLVMRustSynchronizationScope Scope) {
return wrap(unwrap(B)->CreateFence(fromRust(Order), fromRust(Scope)));
}
enum class LLVMRustAsmDialect {
Other,
Att,
Intel,
};
static InlineAsm::AsmDialect fromRust(LLVMRustAsmDialect Dialect) {
switch (Dialect) {
case LLVMRustAsmDialect::Att:
return InlineAsm::AD_ATT;
case LLVMRustAsmDialect::Intel:
return InlineAsm::AD_Intel;
default:
report_fatal_error("bad AsmDialect.");
}
}
extern "C" LLVMValueRef LLVMRustInlineAsm(LLVMTypeRef Ty, char *AsmString,
char *Constraints,
LLVMBool HasSideEffects,
LLVMBool IsAlignStack,
LLVMRustAsmDialect Dialect) {
return wrap(InlineAsm::get(unwrap<FunctionType>(Ty), AsmString, Constraints,
HasSideEffects, IsAlignStack, fromRust(Dialect)));
}
extern "C" bool LLVMRustInlineAsmVerify(LLVMTypeRef Ty,
char *Constraints) {
return InlineAsm::Verify(unwrap<FunctionType>(Ty), Constraints);
}
extern "C" void LLVMRustAppendModuleInlineAsm(LLVMModuleRef M, const char *Asm) {
unwrap(M)->appendModuleInlineAsm(StringRef(Asm));
}
typedef DIBuilder *LLVMRustDIBuilderRef;
template <typename DIT> DIT *unwrapDIPtr(LLVMMetadataRef Ref) {
return (DIT *)(Ref ? unwrap<MDNode>(Ref) : nullptr);
}
#define DIDescriptor DIScope
#define DIArray DINodeArray
#define unwrapDI unwrapDIPtr
// These values **must** match debuginfo::DIFlags! They also *happen*
// to match LLVM, but that isn't required as we do giant sets of
// matching below. The value shouldn't be directly passed to LLVM.
enum class LLVMRustDIFlags : uint32_t {
FlagZero = 0,
FlagPrivate = 1,
FlagProtected = 2,
FlagPublic = 3,
FlagFwdDecl = (1 << 2),
FlagAppleBlock = (1 << 3),
FlagBlockByrefStruct = (1 << 4),
FlagVirtual = (1 << 5),
FlagArtificial = (1 << 6),
FlagExplicit = (1 << 7),
FlagPrototyped = (1 << 8),
FlagObjcClassComplete = (1 << 9),
FlagObjectPointer = (1 << 10),
FlagVector = (1 << 11),
FlagStaticMember = (1 << 12),
FlagLValueReference = (1 << 13),
FlagRValueReference = (1 << 14),
FlagExternalTypeRef = (1 << 15),
FlagIntroducedVirtual = (1 << 18),
FlagBitField = (1 << 19),
FlagNoReturn = (1 << 20),
// Do not add values that are not supported by the minimum LLVM
// version we support! see llvm/include/llvm/IR/DebugInfoFlags.def
};
inline LLVMRustDIFlags operator&(LLVMRustDIFlags A, LLVMRustDIFlags B) {
return static_cast<LLVMRustDIFlags>(static_cast<uint32_t>(A) &
static_cast<uint32_t>(B));
}
inline LLVMRustDIFlags operator|(LLVMRustDIFlags A, LLVMRustDIFlags B) {
return static_cast<LLVMRustDIFlags>(static_cast<uint32_t>(A) |
static_cast<uint32_t>(B));
}
inline LLVMRustDIFlags &operator|=(LLVMRustDIFlags &A, LLVMRustDIFlags B) {
return A = A | B;
}
inline bool isSet(LLVMRustDIFlags F) { return F != LLVMRustDIFlags::FlagZero; }
inline LLVMRustDIFlags visibility(LLVMRustDIFlags F) {
return static_cast<LLVMRustDIFlags>(static_cast<uint32_t>(F) & 0x3);
}
static DINode::DIFlags fromRust(LLVMRustDIFlags Flags) {
DINode::DIFlags Result = DINode::DIFlags::FlagZero;
switch (visibility(Flags)) {
case LLVMRustDIFlags::FlagPrivate:
Result |= DINode::DIFlags::FlagPrivate;
break;
case LLVMRustDIFlags::FlagProtected:
Result |= DINode::DIFlags::FlagProtected;
break;
case LLVMRustDIFlags::FlagPublic:
Result |= DINode::DIFlags::FlagPublic;
break;
default:
// The rest are handled below
break;
}
if (isSet(Flags & LLVMRustDIFlags::FlagFwdDecl)) {
Result |= DINode::DIFlags::FlagFwdDecl;
}
if (isSet(Flags & LLVMRustDIFlags::FlagAppleBlock)) {
Result |= DINode::DIFlags::FlagAppleBlock;
}
#if LLVM_VERSION_LT(10, 0)
if (isSet(Flags & LLVMRustDIFlags::FlagBlockByrefStruct)) {
Result |= DINode::DIFlags::FlagBlockByrefStruct;
}
#endif
if (isSet(Flags & LLVMRustDIFlags::FlagVirtual)) {
Result |= DINode::DIFlags::FlagVirtual;
}
if (isSet(Flags & LLVMRustDIFlags::FlagArtificial)) {
Result |= DINode::DIFlags::FlagArtificial;
}
if (isSet(Flags & LLVMRustDIFlags::FlagExplicit)) {
Result |= DINode::DIFlags::FlagExplicit;
}
if (isSet(Flags & LLVMRustDIFlags::FlagPrototyped)) {
Result |= DINode::DIFlags::FlagPrototyped;
}
if (isSet(Flags & LLVMRustDIFlags::FlagObjcClassComplete)) {
Result |= DINode::DIFlags::FlagObjcClassComplete;
}
if (isSet(Flags & LLVMRustDIFlags::FlagObjectPointer)) {
Result |= DINode::DIFlags::FlagObjectPointer;
}
if (isSet(Flags & LLVMRustDIFlags::FlagVector)) {
Result |= DINode::DIFlags::FlagVector;
}
if (isSet(Flags & LLVMRustDIFlags::FlagStaticMember)) {
Result |= DINode::DIFlags::FlagStaticMember;
}
if (isSet(Flags & LLVMRustDIFlags::FlagLValueReference)) {
Result |= DINode::DIFlags::FlagLValueReference;
}
if (isSet(Flags & LLVMRustDIFlags::FlagRValueReference)) {
Result |= DINode::DIFlags::FlagRValueReference;
}
if (isSet(Flags & LLVMRustDIFlags::FlagIntroducedVirtual)) {
Result |= DINode::DIFlags::FlagIntroducedVirtual;
}
if (isSet(Flags & LLVMRustDIFlags::FlagBitField)) {
Result |= DINode::DIFlags::FlagBitField;
}
if (isSet(Flags & LLVMRustDIFlags::FlagNoReturn)) {
Result |= DINode::DIFlags::FlagNoReturn;
}
return Result;
}
// These values **must** match debuginfo::DISPFlags! They also *happen*
// to match LLVM, but that isn't required as we do giant sets of
// matching below. The value shouldn't be directly passed to LLVM.
enum class LLVMRustDISPFlags : uint32_t {
SPFlagZero = 0,
SPFlagVirtual = 1,
SPFlagPureVirtual = 2,
SPFlagLocalToUnit = (1 << 2),
SPFlagDefinition = (1 << 3),
SPFlagOptimized = (1 << 4),
SPFlagMainSubprogram = (1 << 5),
// Do not add values that are not supported by the minimum LLVM
// version we support! see llvm/include/llvm/IR/DebugInfoFlags.def
// (In LLVM < 8, createFunction supported these as separate bool arguments.)
};
inline LLVMRustDISPFlags operator&(LLVMRustDISPFlags A, LLVMRustDISPFlags B) {
return static_cast<LLVMRustDISPFlags>(static_cast<uint32_t>(A) &
static_cast<uint32_t>(B));
}
inline LLVMRustDISPFlags operator|(LLVMRustDISPFlags A, LLVMRustDISPFlags B) {
return static_cast<LLVMRustDISPFlags>(static_cast<uint32_t>(A) |
static_cast<uint32_t>(B));
}
inline LLVMRustDISPFlags &operator|=(LLVMRustDISPFlags &A, LLVMRustDISPFlags B) {
return A = A | B;
}
inline bool isSet(LLVMRustDISPFlags F) { return F != LLVMRustDISPFlags::SPFlagZero; }
inline LLVMRustDISPFlags virtuality(LLVMRustDISPFlags F) {
return static_cast<LLVMRustDISPFlags>(static_cast<uint32_t>(F) & 0x3);
}
#if LLVM_VERSION_GE(8, 0)
static DISubprogram::DISPFlags fromRust(LLVMRustDISPFlags SPFlags) {
DISubprogram::DISPFlags Result = DISubprogram::DISPFlags::SPFlagZero;
switch (virtuality(SPFlags)) {
case LLVMRustDISPFlags::SPFlagVirtual:
Result |= DISubprogram::DISPFlags::SPFlagVirtual;
break;
case LLVMRustDISPFlags::SPFlagPureVirtual:
Result |= DISubprogram::DISPFlags::SPFlagPureVirtual;
break;
default:
// The rest are handled below
break;
}
if (isSet(SPFlags & LLVMRustDISPFlags::SPFlagLocalToUnit)) {
Result |= DISubprogram::DISPFlags::SPFlagLocalToUnit;
}
if (isSet(SPFlags & LLVMRustDISPFlags::SPFlagDefinition)) {
Result |= DISubprogram::DISPFlags::SPFlagDefinition;
}
if (isSet(SPFlags & LLVMRustDISPFlags::SPFlagOptimized)) {
Result |= DISubprogram::DISPFlags::SPFlagOptimized;
}
#if LLVM_VERSION_GE(9, 0)
if (isSet(SPFlags & LLVMRustDISPFlags::SPFlagMainSubprogram)) {
Result |= DISubprogram::DISPFlags::SPFlagMainSubprogram;
}
#endif
return Result;
}
#endif
enum class LLVMRustDebugEmissionKind {
NoDebug,
FullDebug,
LineTablesOnly,
};
static DICompileUnit::DebugEmissionKind fromRust(LLVMRustDebugEmissionKind Kind) {
switch (Kind) {
case LLVMRustDebugEmissionKind::NoDebug:
return DICompileUnit::DebugEmissionKind::NoDebug;
case LLVMRustDebugEmissionKind::FullDebug:
return DICompileUnit::DebugEmissionKind::FullDebug;
case LLVMRustDebugEmissionKind::LineTablesOnly:
return DICompileUnit::DebugEmissionKind::LineTablesOnly;
default:
report_fatal_error("bad DebugEmissionKind.");
}
}
extern "C" uint32_t LLVMRustDebugMetadataVersion() {
return DEBUG_METADATA_VERSION;
}
extern "C" uint32_t LLVMRustVersionMinor() { return LLVM_VERSION_MINOR; }
extern "C" uint32_t LLVMRustVersionMajor() { return LLVM_VERSION_MAJOR; }
extern "C" void LLVMRustAddModuleFlag(LLVMModuleRef M, const char *Name,
uint32_t Value) {
unwrap(M)->addModuleFlag(Module::Warning, Name, Value);
}
extern "C" LLVMValueRef LLVMRustMetadataAsValue(LLVMContextRef C, LLVMMetadataRef MD) {
return wrap(MetadataAsValue::get(*unwrap(C), unwrap(MD)));
}
extern "C" LLVMRustDIBuilderRef LLVMRustDIBuilderCreate(LLVMModuleRef M) {
return new DIBuilder(*unwrap(M));
}
extern "C" void LLVMRustDIBuilderDispose(LLVMRustDIBuilderRef Builder) {
delete Builder;
}
extern "C" void LLVMRustDIBuilderFinalize(LLVMRustDIBuilderRef Builder) {
Builder->finalize();
}
extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateCompileUnit(
LLVMRustDIBuilderRef Builder, unsigned Lang, LLVMMetadataRef FileRef,
const char *Producer, bool isOptimized, const char *Flags,
unsigned RuntimeVer, const char *SplitName,
LLVMRustDebugEmissionKind Kind) {
auto *File = unwrapDI<DIFile>(FileRef);
return wrap(Builder->createCompileUnit(Lang, File, Producer, isOptimized,
Flags, RuntimeVer, SplitName,
fromRust(Kind)));
}
extern "C" LLVMMetadataRef
LLVMRustDIBuilderCreateFile(LLVMRustDIBuilderRef Builder, const char *Filename,
const char *Directory) {
return wrap(Builder->createFile(Filename, Directory));
}
extern "C" LLVMMetadataRef
LLVMRustDIBuilderCreateSubroutineType(LLVMRustDIBuilderRef Builder,
LLVMMetadataRef File,
LLVMMetadataRef ParameterTypes) {
return wrap(Builder->createSubroutineType(
DITypeRefArray(unwrap<MDTuple>(ParameterTypes))));
}
extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateFunction(
LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
const char *LinkageName, LLVMMetadataRef File, unsigned LineNo,
LLVMMetadataRef Ty, unsigned ScopeLine, LLVMRustDIFlags Flags,
LLVMRustDISPFlags SPFlags, LLVMValueRef Fn, LLVMMetadataRef TParam,
LLVMMetadataRef Decl) {
DITemplateParameterArray TParams =
DITemplateParameterArray(unwrap<MDTuple>(TParam));
#if LLVM_VERSION_GE(8, 0)
DISubprogram::DISPFlags llvmSPFlags = fromRust(SPFlags);
DINode::DIFlags llvmFlags = fromRust(Flags);
#if LLVM_VERSION_LT(9, 0)
if (isSet(SPFlags & LLVMRustDISPFlags::SPFlagMainSubprogram))
llvmFlags |= DINode::DIFlags::FlagMainSubprogram;
#endif
DISubprogram *Sub = Builder->createFunction(
unwrapDI<DIScope>(Scope), Name, LinkageName, unwrapDI<DIFile>(File),
LineNo, unwrapDI<DISubroutineType>(Ty), ScopeLine, llvmFlags,
llvmSPFlags, TParams, unwrapDIPtr<DISubprogram>(Decl));
#else
bool IsLocalToUnit = isSet(SPFlags & LLVMRustDISPFlags::SPFlagLocalToUnit);
bool IsDefinition = isSet(SPFlags & LLVMRustDISPFlags::SPFlagDefinition);
bool IsOptimized = isSet(SPFlags & LLVMRustDISPFlags::SPFlagOptimized);
DINode::DIFlags llvmFlags = fromRust(Flags);
if (isSet(SPFlags & LLVMRustDISPFlags::SPFlagMainSubprogram))
llvmFlags |= DINode::DIFlags::FlagMainSubprogram;
DISubprogram *Sub = Builder->createFunction(
unwrapDI<DIScope>(Scope), Name, LinkageName, unwrapDI<DIFile>(File),
LineNo, unwrapDI<DISubroutineType>(Ty), IsLocalToUnit, IsDefinition,
ScopeLine, llvmFlags, IsOptimized, TParams,
unwrapDIPtr<DISubprogram>(Decl));
#endif
unwrap<Function>(Fn)->setSubprogram(Sub);
return wrap(Sub);
}
extern "C" LLVMMetadataRef
LLVMRustDIBuilderCreateBasicType(LLVMRustDIBuilderRef Builder, const char *Name,
uint64_t SizeInBits, uint32_t AlignInBits,
unsigned Encoding) {
return wrap(Builder->createBasicType(Name, SizeInBits, Encoding));
}
extern "C" LLVMMetadataRef LLVMRustDIBuilderCreatePointerType(
LLVMRustDIBuilderRef Builder, LLVMMetadataRef PointeeTy,
uint64_t SizeInBits, uint32_t AlignInBits, const char *Name) {
return wrap(Builder->createPointerType(unwrapDI<DIType>(PointeeTy),
SizeInBits, AlignInBits,
/* DWARFAddressSpace */ None,
Name));
}
extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateStructType(
LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
uint32_t AlignInBits, LLVMRustDIFlags Flags,
LLVMMetadataRef DerivedFrom, LLVMMetadataRef Elements,
unsigned RunTimeLang, LLVMMetadataRef VTableHolder,
const char *UniqueId) {
return wrap(Builder->createStructType(
unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNumber,
SizeInBits, AlignInBits, fromRust(Flags), unwrapDI<DIType>(DerivedFrom),
DINodeArray(unwrapDI<MDTuple>(Elements)), RunTimeLang,
unwrapDI<DIType>(VTableHolder), UniqueId));
}
extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateVariantPart(
LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
uint32_t AlignInBits, LLVMRustDIFlags Flags, LLVMMetadataRef Discriminator,
LLVMMetadataRef Elements, const char *UniqueId) {
return wrap(Builder->createVariantPart(
unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNumber,
SizeInBits, AlignInBits, fromRust(Flags), unwrapDI<DIDerivedType>(Discriminator),
DINodeArray(unwrapDI<MDTuple>(Elements)), UniqueId));
}
extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateMemberType(
LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits,
uint32_t AlignInBits, uint64_t OffsetInBits, LLVMRustDIFlags Flags,
LLVMMetadataRef Ty) {
return wrap(Builder->createMemberType(unwrapDI<DIDescriptor>(Scope), Name,
unwrapDI<DIFile>(File), LineNo,
SizeInBits, AlignInBits, OffsetInBits,
fromRust(Flags), unwrapDI<DIType>(Ty)));
}
extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateVariantMemberType(
LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope,
const char *Name, LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits,
uint32_t AlignInBits, uint64_t OffsetInBits, LLVMValueRef Discriminant,
LLVMRustDIFlags Flags, LLVMMetadataRef Ty) {
llvm::ConstantInt* D = nullptr;
if (Discriminant) {
D = unwrap<llvm::ConstantInt>(Discriminant);
}
return wrap(Builder->createVariantMemberType(unwrapDI<DIDescriptor>(Scope), Name,
unwrapDI<DIFile>(File), LineNo,
SizeInBits, AlignInBits, OffsetInBits, D,
fromRust(Flags), unwrapDI<DIType>(Ty)));
}
extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateLexicalBlock(
LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope,
LLVMMetadataRef File, unsigned Line, unsigned Col) {
return wrap(Builder->createLexicalBlock(unwrapDI<DIDescriptor>(Scope),
unwrapDI<DIFile>(File), Line, Col));
}
extern "C" LLVMMetadataRef
LLVMRustDIBuilderCreateLexicalBlockFile(LLVMRustDIBuilderRef Builder,
LLVMMetadataRef Scope,
LLVMMetadataRef File) {
return wrap(Builder->createLexicalBlockFile(unwrapDI<DIDescriptor>(Scope),
unwrapDI<DIFile>(File)));
}
extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateStaticVariable(
LLVMRustDIBuilderRef Builder, LLVMMetadataRef Context, const char *Name,
const char *LinkageName, LLVMMetadataRef File, unsigned LineNo,
LLVMMetadataRef Ty, bool IsLocalToUnit, LLVMValueRef V,
LLVMMetadataRef Decl = nullptr, uint32_t AlignInBits = 0) {
llvm::GlobalVariable *InitVal = cast<llvm::GlobalVariable>(unwrap(V));
llvm::DIExpression *InitExpr = nullptr;
if (llvm::ConstantInt *IntVal = llvm::dyn_cast<llvm::ConstantInt>(InitVal)) {
InitExpr = Builder->createConstantValueExpression(
IntVal->getValue().getSExtValue());
} else if (llvm::ConstantFP *FPVal =
llvm::dyn_cast<llvm::ConstantFP>(InitVal)) {
InitExpr = Builder->createConstantValueExpression(
FPVal->getValueAPF().bitcastToAPInt().getZExtValue());
}
llvm::DIGlobalVariableExpression *VarExpr = Builder->createGlobalVariableExpression(
unwrapDI<DIDescriptor>(Context), Name, LinkageName,
unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), IsLocalToUnit,
#if LLVM_VERSION_GE(10, 0)
/* isDefined */ true,
#endif
InitExpr, unwrapDIPtr<MDNode>(Decl),
#if LLVM_VERSION_GE(8, 0)
/* templateParams */ nullptr,
#endif
AlignInBits);
InitVal->setMetadata("dbg", VarExpr);
return wrap(VarExpr);
}
extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateVariable(
LLVMRustDIBuilderRef Builder, unsigned Tag, LLVMMetadataRef Scope,
const char *Name, LLVMMetadataRef File, unsigned LineNo,
LLVMMetadataRef Ty, bool AlwaysPreserve, LLVMRustDIFlags Flags,
unsigned ArgNo, uint32_t AlignInBits) {
if (Tag == 0x100) { // DW_TAG_auto_variable
return wrap(Builder->createAutoVariable(
unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNo,
unwrapDI<DIType>(Ty), AlwaysPreserve, fromRust(Flags), AlignInBits));
} else {
return wrap(Builder->createParameterVariable(
unwrapDI<DIDescriptor>(Scope), Name, ArgNo, unwrapDI<DIFile>(File),
LineNo, unwrapDI<DIType>(Ty), AlwaysPreserve, fromRust(Flags)));
}
}
extern "C" LLVMMetadataRef
LLVMRustDIBuilderCreateArrayType(LLVMRustDIBuilderRef Builder, uint64_t Size,
uint32_t AlignInBits, LLVMMetadataRef Ty,
LLVMMetadataRef Subscripts) {
return wrap(
Builder->createArrayType(Size, AlignInBits, unwrapDI<DIType>(Ty),
DINodeArray(unwrapDI<MDTuple>(Subscripts))));
}
extern "C" LLVMMetadataRef
LLVMRustDIBuilderGetOrCreateSubrange(LLVMRustDIBuilderRef Builder, int64_t Lo,
int64_t Count) {
return wrap(Builder->getOrCreateSubrange(Lo, Count));
}
extern "C" LLVMMetadataRef
LLVMRustDIBuilderGetOrCreateArray(LLVMRustDIBuilderRef Builder,
LLVMMetadataRef *Ptr, unsigned Count) {
Metadata **DataValue = unwrap(Ptr);
return wrap(
Builder->getOrCreateArray(ArrayRef<Metadata *>(DataValue, Count)).get());
}
extern "C" LLVMValueRef LLVMRustDIBuilderInsertDeclareAtEnd(
LLVMRustDIBuilderRef Builder, LLVMValueRef V, LLVMMetadataRef VarInfo,
int64_t *AddrOps, unsigned AddrOpsCount, LLVMValueRef DL,
LLVMBasicBlockRef InsertAtEnd) {
return wrap(Builder->insertDeclare(
unwrap(V), unwrap<DILocalVariable>(VarInfo),
Builder->createExpression(llvm::ArrayRef<int64_t>(AddrOps, AddrOpsCount)),
DebugLoc(cast<MDNode>(unwrap<MetadataAsValue>(DL)->getMetadata())),
unwrap(InsertAtEnd)));
}
extern "C" LLVMMetadataRef
LLVMRustDIBuilderCreateEnumerator(LLVMRustDIBuilderRef Builder,
const char *Name, uint64_t Val) {
return wrap(Builder->createEnumerator(Name, Val));
}
extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateEnumerationType(
LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
uint32_t AlignInBits, LLVMMetadataRef Elements,
LLVMMetadataRef ClassTy, bool IsScoped) {
return wrap(Builder->createEnumerationType(
unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNumber,
SizeInBits, AlignInBits, DINodeArray(unwrapDI<MDTuple>(Elements)),
unwrapDI<DIType>(ClassTy), "", IsScoped));
}
extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateUnionType(
LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
uint32_t AlignInBits, LLVMRustDIFlags Flags, LLVMMetadataRef Elements,
unsigned RunTimeLang, const char *UniqueId) {
return wrap(Builder->createUnionType(
unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNumber,
SizeInBits, AlignInBits, fromRust(Flags),
DINodeArray(unwrapDI<MDTuple>(Elements)), RunTimeLang, UniqueId));
}
extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateTemplateTypeParameter(
LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
LLVMMetadataRef Ty, LLVMMetadataRef File, unsigned LineNo,
unsigned ColumnNo) {
return wrap(Builder->createTemplateTypeParameter(
unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIType>(Ty)));
}
extern "C" LLVMMetadataRef
LLVMRustDIBuilderCreateNameSpace(LLVMRustDIBuilderRef Builder,
LLVMMetadataRef Scope, const char *Name,
LLVMMetadataRef File, unsigned LineNo) {
return wrap(Builder->createNameSpace(
unwrapDI<DIDescriptor>(Scope), Name,
false // ExportSymbols (only relevant for C++ anonymous namespaces)
));
}
extern "C" void
LLVMRustDICompositeTypeReplaceArrays(LLVMRustDIBuilderRef Builder,
LLVMMetadataRef CompositeTy,
LLVMMetadataRef Elements,
LLVMMetadataRef Params) {
DICompositeType *Tmp = unwrapDI<DICompositeType>(CompositeTy);
Builder->replaceArrays(Tmp, DINodeArray(unwrap<MDTuple>(Elements)),
DINodeArray(unwrap<MDTuple>(Params)));
}
extern "C" LLVMValueRef
LLVMRustDIBuilderCreateDebugLocation(LLVMContextRef ContextRef, unsigned Line,
unsigned Column, LLVMMetadataRef Scope,
LLVMMetadataRef InlinedAt) {
LLVMContext &Context = *unwrap(ContextRef);
DebugLoc debug_loc = DebugLoc::get(Line, Column, unwrapDIPtr<MDNode>(Scope),
unwrapDIPtr<MDNode>(InlinedAt));
return wrap(MetadataAsValue::get(Context, debug_loc.getAsMDNode()));
}
extern "C" int64_t LLVMRustDIBuilderCreateOpDeref() {
return dwarf::DW_OP_deref;
}
extern "C" int64_t LLVMRustDIBuilderCreateOpPlusUconst() {
return dwarf::DW_OP_plus_uconst;
}
extern "C" void LLVMRustWriteTypeToString(LLVMTypeRef Ty, RustStringRef Str) {
RawRustStringOstream OS(Str);
unwrap<llvm::Type>(Ty)->print(OS);
}
extern "C" void LLVMRustWriteValueToString(LLVMValueRef V,
RustStringRef Str) {
RawRustStringOstream OS(Str);
if (!V) {
OS << "(null)";
} else {
OS << "(";
unwrap<llvm::Value>(V)->getType()->print(OS);
OS << ":";
unwrap<llvm::Value>(V)->print(OS);
OS << ")";
}
}
// Note that the two following functions look quite similar to the
// LLVMGetSectionName function. Sadly, it appears that this function only
// returns a char* pointer, which isn't guaranteed to be null-terminated. The
// function provided by LLVM doesn't return the length, so we've created our own
// function which returns the length as well as the data pointer.
//
// For an example of this not returning a null terminated string, see
// lib/Object/COFFObjectFile.cpp in the getSectionName function. One of the
// branches explicitly creates a StringRef without a null terminator, and then
// that's returned.
inline section_iterator *unwrap(LLVMSectionIteratorRef SI) {