1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 #include "llvm/IR/DebugInfoMetadata.h"
13 #include "llvm/IR/DiagnosticInfo.h"
14 #include "llvm/IR/DiagnosticPrinter.h"
15 #include "llvm/IR/Instructions.h"
16 #include "llvm/Object/Archive.h"
17 #include "llvm/Object/ObjectFile.h"
18 #include "llvm/Bitcode/BitcodeWriterPass.h"
20 #include "llvm/IR/CallSite.h"
22 #if LLVM_VERSION_GE(5, 0)
23 #include "llvm/ADT/Optional.h"
28 //===----------------------------------------------------------------------===
30 // This file defines alternate interfaces to core functions that are more
31 // readily callable by Rust's FFI.
33 //===----------------------------------------------------------------------===
36 using namespace llvm::sys;
37 using namespace llvm::object;
39 // LLVMAtomicOrdering is already an enum - don't create another
41 static AtomicOrdering fromRust(LLVMAtomicOrdering Ordering) {
43 case LLVMAtomicOrderingNotAtomic:
44 return AtomicOrdering::NotAtomic;
45 case LLVMAtomicOrderingUnordered:
46 return AtomicOrdering::Unordered;
47 case LLVMAtomicOrderingMonotonic:
48 return AtomicOrdering::Monotonic;
49 case LLVMAtomicOrderingAcquire:
50 return AtomicOrdering::Acquire;
51 case LLVMAtomicOrderingRelease:
52 return AtomicOrdering::Release;
53 case LLVMAtomicOrderingAcquireRelease:
54 return AtomicOrdering::AcquireRelease;
55 case LLVMAtomicOrderingSequentiallyConsistent:
56 return AtomicOrdering::SequentiallyConsistent;
59 report_fatal_error("Invalid LLVMAtomicOrdering value!");
62 static LLVM_THREAD_LOCAL char *LastError;
64 extern "C" LLVMMemoryBufferRef
65 LLVMRustCreateMemoryBufferWithContentsOfFile(const char *Path) {
66 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOr =
67 MemoryBuffer::getFile(Path, -1, false);
69 LLVMRustSetLastError(BufOr.getError().message().c_str());
72 return wrap(BufOr.get().release());
75 extern "C" char *LLVMRustGetLastError(void) {
76 char *Ret = LastError;
81 extern "C" void LLVMRustSetLastError(const char *Err) {
82 free((void *)LastError);
83 LastError = strdup(Err);
86 extern "C" LLVMContextRef LLVMRustContextCreate(bool shouldDiscardNames) {
87 auto ctx = new LLVMContext();
88 ctx->setDiscardValueNames(shouldDiscardNames);
92 extern "C" void LLVMRustSetNormalizedTarget(LLVMModuleRef M,
94 unwrap(M)->setTargetTriple(Triple::normalize(Triple));
97 extern "C" void LLVMRustPrintPassTimings() {
98 raw_fd_ostream OS(2, false); // stderr.
99 TimerGroup::printAll(OS);
102 extern "C" LLVMValueRef LLVMRustGetNamedValue(LLVMModuleRef M,
104 return wrap(unwrap(M)->getNamedValue(Name));
107 extern "C" LLVMValueRef LLVMRustGetOrInsertFunction(LLVMModuleRef M,
109 LLVMTypeRef FunctionTy) {
111 unwrap(M)->getOrInsertFunction(Name, unwrap<FunctionType>(FunctionTy)));
114 extern "C" LLVMValueRef
115 LLVMRustGetOrInsertGlobal(LLVMModuleRef M, const char *Name, LLVMTypeRef Ty) {
116 return wrap(unwrap(M)->getOrInsertGlobal(Name, unwrap(Ty)));
119 extern "C" LLVMTypeRef LLVMRustMetadataTypeInContext(LLVMContextRef C) {
120 return wrap(Type::getMetadataTy(*unwrap(C)));
123 static Attribute::AttrKind fromRust(LLVMRustAttribute Kind) {
126 return Attribute::AlwaysInline;
128 return Attribute::ByVal;
130 return Attribute::Cold;
132 return Attribute::InlineHint;
134 return Attribute::MinSize;
136 return Attribute::Naked;
138 return Attribute::NoAlias;
140 return Attribute::NoCapture;
142 return Attribute::NoInline;
144 return Attribute::NonNull;
146 return Attribute::NoRedZone;
148 return Attribute::NoReturn;
150 return Attribute::NoUnwind;
151 case OptimizeForSize:
152 return Attribute::OptimizeForSize;
154 return Attribute::ReadOnly;
156 return Attribute::SExt;
158 return Attribute::StructRet;
160 return Attribute::UWTable;
162 return Attribute::ZExt;
164 return Attribute::InReg;
166 return Attribute::SanitizeThread;
167 case SanitizeAddress:
168 return Attribute::SanitizeAddress;
170 return Attribute::SanitizeMemory;
172 report_fatal_error("bad AttributeKind");
175 extern "C" void LLVMRustAddCallSiteAttribute(LLVMValueRef Instr, unsigned Index,
176 LLVMRustAttribute RustAttr) {
177 CallSite Call = CallSite(unwrap<Instruction>(Instr));
178 Attribute Attr = Attribute::get(Call->getContext(), fromRust(RustAttr));
179 #if LLVM_VERSION_GE(5, 0)
180 Call.addAttribute(Index, Attr);
183 Call.setAttributes(Call.getAttributes().addAttributes(
184 Call->getContext(), Index,
185 AttributeSet::get(Call->getContext(), Index, B)));
189 extern "C" void LLVMRustAddAlignmentCallSiteAttr(LLVMValueRef Instr,
192 CallSite Call = CallSite(unwrap<Instruction>(Instr));
194 B.addAlignmentAttr(Bytes);
195 #if LLVM_VERSION_GE(5, 0)
196 Call.setAttributes(Call.getAttributes().addAttributes(
197 Call->getContext(), Index, B));
199 Call.setAttributes(Call.getAttributes().addAttributes(
200 Call->getContext(), Index,
201 AttributeSet::get(Call->getContext(), Index, B)));
205 extern "C" void LLVMRustAddDereferenceableCallSiteAttr(LLVMValueRef Instr,
208 CallSite Call = CallSite(unwrap<Instruction>(Instr));
210 B.addDereferenceableAttr(Bytes);
211 #if LLVM_VERSION_GE(5, 0)
212 Call.setAttributes(Call.getAttributes().addAttributes(
213 Call->getContext(), Index, B));
215 Call.setAttributes(Call.getAttributes().addAttributes(
216 Call->getContext(), Index,
217 AttributeSet::get(Call->getContext(), Index, B)));
221 extern "C" void LLVMRustAddDereferenceableOrNullCallSiteAttr(LLVMValueRef Instr,
224 CallSite Call = CallSite(unwrap<Instruction>(Instr));
226 B.addDereferenceableOrNullAttr(Bytes);
227 #if LLVM_VERSION_GE(5, 0)
228 Call.setAttributes(Call.getAttributes().addAttributes(
229 Call->getContext(), Index, B));
231 Call.setAttributes(Call.getAttributes().addAttributes(
232 Call->getContext(), Index,
233 AttributeSet::get(Call->getContext(), Index, B)));
237 extern "C" void LLVMRustAddFunctionAttribute(LLVMValueRef Fn, unsigned Index,
238 LLVMRustAttribute RustAttr) {
239 Function *A = unwrap<Function>(Fn);
240 Attribute Attr = Attribute::get(A->getContext(), fromRust(RustAttr));
242 #if LLVM_VERSION_GE(5, 0)
243 A->addAttributes(Index, B);
245 A->addAttributes(Index, AttributeSet::get(A->getContext(), Index, B));
249 extern "C" void LLVMRustAddAlignmentAttr(LLVMValueRef Fn,
252 Function *A = unwrap<Function>(Fn);
254 B.addAlignmentAttr(Bytes);
255 #if LLVM_VERSION_GE(5, 0)
256 A->addAttributes(Index, B);
258 A->addAttributes(Index, AttributeSet::get(A->getContext(), Index, B));
262 extern "C" void LLVMRustAddDereferenceableAttr(LLVMValueRef Fn, unsigned Index,
264 Function *A = unwrap<Function>(Fn);
266 B.addDereferenceableAttr(Bytes);
267 #if LLVM_VERSION_GE(5, 0)
268 A->addAttributes(Index, B);
270 A->addAttributes(Index, AttributeSet::get(A->getContext(), Index, B));
274 extern "C" void LLVMRustAddDereferenceableOrNullAttr(LLVMValueRef Fn,
277 Function *A = unwrap<Function>(Fn);
279 B.addDereferenceableOrNullAttr(Bytes);
280 #if LLVM_VERSION_GE(5, 0)
281 A->addAttributes(Index, B);
283 A->addAttributes(Index, AttributeSet::get(A->getContext(), Index, B));
287 extern "C" void LLVMRustAddFunctionAttrStringValue(LLVMValueRef Fn,
291 Function *F = unwrap<Function>(Fn);
293 B.addAttribute(Name, Value);
294 #if LLVM_VERSION_GE(5, 0)
295 F->addAttributes(Index, B);
297 F->addAttributes(Index, AttributeSet::get(F->getContext(), Index, B));
301 extern "C" void LLVMRustRemoveFunctionAttributes(LLVMValueRef Fn,
303 LLVMRustAttribute RustAttr) {
304 Function *F = unwrap<Function>(Fn);
305 Attribute Attr = Attribute::get(F->getContext(), fromRust(RustAttr));
307 auto PAL = F->getAttributes();
308 #if LLVM_VERSION_GE(5, 0)
309 auto PALNew = PAL.removeAttributes(F->getContext(), Index, B);
311 const AttributeSet PALNew = PAL.removeAttributes(
312 F->getContext(), Index, AttributeSet::get(F->getContext(), Index, B));
314 F->setAttributes(PALNew);
317 // enable fpmath flag UnsafeAlgebra
318 extern "C" void LLVMRustSetHasUnsafeAlgebra(LLVMValueRef V) {
319 if (auto I = dyn_cast<Instruction>(unwrap<Value>(V))) {
320 #if LLVM_VERSION_GE(6, 0)
323 I->setHasUnsafeAlgebra(true);
328 extern "C" LLVMValueRef
329 LLVMRustBuildAtomicLoad(LLVMBuilderRef B, LLVMValueRef Source, const char *Name,
330 LLVMAtomicOrdering Order) {
331 LoadInst *LI = new LoadInst(unwrap(Source), 0);
332 LI->setAtomic(fromRust(Order));
333 return wrap(unwrap(B)->Insert(LI, Name));
336 extern "C" LLVMValueRef LLVMRustBuildAtomicStore(LLVMBuilderRef B,
339 LLVMAtomicOrdering Order) {
340 StoreInst *SI = new StoreInst(unwrap(V), unwrap(Target));
341 SI->setAtomic(fromRust(Order));
342 return wrap(unwrap(B)->Insert(SI));
345 extern "C" LLVMValueRef
346 LLVMRustBuildAtomicCmpXchg(LLVMBuilderRef B, LLVMValueRef Target,
347 LLVMValueRef Old, LLVMValueRef Source,
348 LLVMAtomicOrdering Order,
349 LLVMAtomicOrdering FailureOrder, LLVMBool Weak) {
350 AtomicCmpXchgInst *ACXI = unwrap(B)->CreateAtomicCmpXchg(
351 unwrap(Target), unwrap(Old), unwrap(Source), fromRust(Order),
352 fromRust(FailureOrder));
357 enum class LLVMRustSynchronizationScope {
363 #if LLVM_VERSION_GE(5, 0)
364 static SyncScope::ID fromRust(LLVMRustSynchronizationScope Scope) {
366 case LLVMRustSynchronizationScope::SingleThread:
367 return SyncScope::SingleThread;
368 case LLVMRustSynchronizationScope::CrossThread:
369 return SyncScope::System;
371 report_fatal_error("bad SynchronizationScope.");
375 static SynchronizationScope fromRust(LLVMRustSynchronizationScope Scope) {
377 case LLVMRustSynchronizationScope::SingleThread:
379 case LLVMRustSynchronizationScope::CrossThread:
382 report_fatal_error("bad SynchronizationScope.");
387 extern "C" LLVMValueRef
388 LLVMRustBuildAtomicFence(LLVMBuilderRef B, LLVMAtomicOrdering Order,
389 LLVMRustSynchronizationScope Scope) {
390 return wrap(unwrap(B)->CreateFence(fromRust(Order), fromRust(Scope)));
393 enum class LLVMRustAsmDialect {
399 static InlineAsm::AsmDialect fromRust(LLVMRustAsmDialect Dialect) {
401 case LLVMRustAsmDialect::Att:
402 return InlineAsm::AD_ATT;
403 case LLVMRustAsmDialect::Intel:
404 return InlineAsm::AD_Intel;
406 report_fatal_error("bad AsmDialect.");
410 extern "C" LLVMValueRef LLVMRustInlineAsm(LLVMTypeRef Ty, char *AsmString,
412 LLVMBool HasSideEffects,
413 LLVMBool IsAlignStack,
414 LLVMRustAsmDialect Dialect) {
415 return wrap(InlineAsm::get(unwrap<FunctionType>(Ty), AsmString, Constraints,
416 HasSideEffects, IsAlignStack, fromRust(Dialect)));
419 extern "C" void LLVMRustAppendModuleInlineAsm(LLVMModuleRef M, const char *Asm) {
420 unwrap(M)->appendModuleInlineAsm(StringRef(Asm));
423 typedef DIBuilder *LLVMRustDIBuilderRef;
425 #if LLVM_VERSION_LT(5, 0)
426 typedef struct LLVMOpaqueMetadata *LLVMMetadataRef;
429 DEFINE_ISA_CONVERSION_FUNCTIONS(Metadata, LLVMMetadataRef)
431 inline Metadata **unwrap(LLVMMetadataRef *Vals) {
432 return reinterpret_cast<Metadata **>(Vals);
437 template <typename DIT> DIT *unwrapDIPtr(LLVMMetadataRef Ref) {
438 return (DIT *)(Ref ? unwrap<MDNode>(Ref) : nullptr);
441 #define DIDescriptor DIScope
442 #define DIArray DINodeArray
443 #define unwrapDI unwrapDIPtr
445 // These values **must** match debuginfo::DIFlags! They also *happen*
446 // to match LLVM, but that isn't required as we do giant sets of
447 // matching below. The value shouldn't be directly passed to LLVM.
448 enum class LLVMRustDIFlags : uint32_t {
453 FlagFwdDecl = (1 << 2),
454 FlagAppleBlock = (1 << 3),
455 FlagBlockByrefStruct = (1 << 4),
456 FlagVirtual = (1 << 5),
457 FlagArtificial = (1 << 6),
458 FlagExplicit = (1 << 7),
459 FlagPrototyped = (1 << 8),
460 FlagObjcClassComplete = (1 << 9),
461 FlagObjectPointer = (1 << 10),
462 FlagVector = (1 << 11),
463 FlagStaticMember = (1 << 12),
464 FlagLValueReference = (1 << 13),
465 FlagRValueReference = (1 << 14),
466 FlagExternalTypeRef = (1 << 15),
467 FlagIntroducedVirtual = (1 << 18),
468 FlagBitField = (1 << 19),
469 FlagNoReturn = (1 << 20),
470 FlagMainSubprogram = (1 << 21),
471 // Do not add values that are not supported by the minimum LLVM
472 // version we support! see llvm/include/llvm/IR/DebugInfoFlags.def
475 inline LLVMRustDIFlags operator&(LLVMRustDIFlags A, LLVMRustDIFlags B) {
476 return static_cast<LLVMRustDIFlags>(static_cast<uint32_t>(A) &
477 static_cast<uint32_t>(B));
480 inline LLVMRustDIFlags operator|(LLVMRustDIFlags A, LLVMRustDIFlags B) {
481 return static_cast<LLVMRustDIFlags>(static_cast<uint32_t>(A) |
482 static_cast<uint32_t>(B));
485 inline LLVMRustDIFlags &operator|=(LLVMRustDIFlags &A, LLVMRustDIFlags B) {
489 inline bool isSet(LLVMRustDIFlags F) { return F != LLVMRustDIFlags::FlagZero; }
491 inline LLVMRustDIFlags visibility(LLVMRustDIFlags F) {
492 return static_cast<LLVMRustDIFlags>(static_cast<uint32_t>(F) & 0x3);
495 static DINode::DIFlags fromRust(LLVMRustDIFlags Flags) {
496 DINode::DIFlags Result = DINode::DIFlags::FlagZero;
498 switch (visibility(Flags)) {
499 case LLVMRustDIFlags::FlagPrivate:
500 Result |= DINode::DIFlags::FlagPrivate;
502 case LLVMRustDIFlags::FlagProtected:
503 Result |= DINode::DIFlags::FlagProtected;
505 case LLVMRustDIFlags::FlagPublic:
506 Result |= DINode::DIFlags::FlagPublic;
509 // The rest are handled below
513 if (isSet(Flags & LLVMRustDIFlags::FlagFwdDecl)) {
514 Result |= DINode::DIFlags::FlagFwdDecl;
516 if (isSet(Flags & LLVMRustDIFlags::FlagAppleBlock)) {
517 Result |= DINode::DIFlags::FlagAppleBlock;
519 if (isSet(Flags & LLVMRustDIFlags::FlagBlockByrefStruct)) {
520 Result |= DINode::DIFlags::FlagBlockByrefStruct;
522 if (isSet(Flags & LLVMRustDIFlags::FlagVirtual)) {
523 Result |= DINode::DIFlags::FlagVirtual;
525 if (isSet(Flags & LLVMRustDIFlags::FlagArtificial)) {
526 Result |= DINode::DIFlags::FlagArtificial;
528 if (isSet(Flags & LLVMRustDIFlags::FlagExplicit)) {
529 Result |= DINode::DIFlags::FlagExplicit;
531 if (isSet(Flags & LLVMRustDIFlags::FlagPrototyped)) {
532 Result |= DINode::DIFlags::FlagPrototyped;
534 if (isSet(Flags & LLVMRustDIFlags::FlagObjcClassComplete)) {
535 Result |= DINode::DIFlags::FlagObjcClassComplete;
537 if (isSet(Flags & LLVMRustDIFlags::FlagObjectPointer)) {
538 Result |= DINode::DIFlags::FlagObjectPointer;
540 if (isSet(Flags & LLVMRustDIFlags::FlagVector)) {
541 Result |= DINode::DIFlags::FlagVector;
543 if (isSet(Flags & LLVMRustDIFlags::FlagStaticMember)) {
544 Result |= DINode::DIFlags::FlagStaticMember;
546 if (isSet(Flags & LLVMRustDIFlags::FlagLValueReference)) {
547 Result |= DINode::DIFlags::FlagLValueReference;
549 if (isSet(Flags & LLVMRustDIFlags::FlagRValueReference)) {
550 Result |= DINode::DIFlags::FlagRValueReference;
552 #if LLVM_VERSION_LE(4, 0)
553 if (isSet(Flags & LLVMRustDIFlags::FlagExternalTypeRef)) {
554 Result |= DINode::DIFlags::FlagExternalTypeRef;
557 if (isSet(Flags & LLVMRustDIFlags::FlagIntroducedVirtual)) {
558 Result |= DINode::DIFlags::FlagIntroducedVirtual;
560 if (isSet(Flags & LLVMRustDIFlags::FlagBitField)) {
561 Result |= DINode::DIFlags::FlagBitField;
563 if (isSet(Flags & LLVMRustDIFlags::FlagNoReturn)) {
564 Result |= DINode::DIFlags::FlagNoReturn;
566 if (isSet(Flags & LLVMRustDIFlags::FlagMainSubprogram)) {
567 Result |= DINode::DIFlags::FlagMainSubprogram;
573 extern "C" uint32_t LLVMRustDebugMetadataVersion() {
574 return DEBUG_METADATA_VERSION;
577 extern "C" uint32_t LLVMRustVersionMinor() { return LLVM_VERSION_MINOR; }
579 extern "C" uint32_t LLVMRustVersionMajor() { return LLVM_VERSION_MAJOR; }
581 extern "C" void LLVMRustAddModuleFlag(LLVMModuleRef M, const char *Name,
583 unwrap(M)->addModuleFlag(Module::Warning, Name, Value);
586 extern "C" LLVMValueRef LLVMRustMetadataAsValue(LLVMContextRef C, LLVMMetadataRef MD) {
587 return wrap(MetadataAsValue::get(*unwrap(C), unwrap(MD)));
590 extern "C" LLVMRustDIBuilderRef LLVMRustDIBuilderCreate(LLVMModuleRef M) {
591 return new DIBuilder(*unwrap(M));
594 extern "C" void LLVMRustDIBuilderDispose(LLVMRustDIBuilderRef Builder) {
598 extern "C" void LLVMRustDIBuilderFinalize(LLVMRustDIBuilderRef Builder) {
602 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateCompileUnit(
603 LLVMRustDIBuilderRef Builder, unsigned Lang, LLVMMetadataRef FileRef,
604 const char *Producer, bool isOptimized, const char *Flags,
605 unsigned RuntimeVer, const char *SplitName) {
606 auto *File = unwrapDI<DIFile>(FileRef);
608 return wrap(Builder->createCompileUnit(Lang, File, Producer, isOptimized,
609 Flags, RuntimeVer, SplitName));
612 extern "C" LLVMMetadataRef
613 LLVMRustDIBuilderCreateFile(LLVMRustDIBuilderRef Builder, const char *Filename,
614 const char *Directory) {
615 return wrap(Builder->createFile(Filename, Directory));
618 extern "C" LLVMMetadataRef
619 LLVMRustDIBuilderCreateSubroutineType(LLVMRustDIBuilderRef Builder,
620 LLVMMetadataRef File,
621 LLVMMetadataRef ParameterTypes) {
622 return wrap(Builder->createSubroutineType(
623 DITypeRefArray(unwrap<MDTuple>(ParameterTypes))));
626 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateFunction(
627 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
628 const char *LinkageName, LLVMMetadataRef File, unsigned LineNo,
629 LLVMMetadataRef Ty, bool IsLocalToUnit, bool IsDefinition,
630 unsigned ScopeLine, LLVMRustDIFlags Flags, bool IsOptimized,
631 LLVMValueRef Fn, LLVMMetadataRef TParam, LLVMMetadataRef Decl) {
632 DITemplateParameterArray TParams =
633 DITemplateParameterArray(unwrap<MDTuple>(TParam));
634 DISubprogram *Sub = Builder->createFunction(
635 unwrapDI<DIScope>(Scope), Name, LinkageName, unwrapDI<DIFile>(File),
636 LineNo, unwrapDI<DISubroutineType>(Ty), IsLocalToUnit, IsDefinition,
637 ScopeLine, fromRust(Flags), IsOptimized, TParams,
638 unwrapDIPtr<DISubprogram>(Decl));
639 unwrap<Function>(Fn)->setSubprogram(Sub);
643 extern "C" LLVMMetadataRef
644 LLVMRustDIBuilderCreateBasicType(LLVMRustDIBuilderRef Builder, const char *Name,
645 uint64_t SizeInBits, uint32_t AlignInBits,
647 return wrap(Builder->createBasicType(Name, SizeInBits, Encoding));
650 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreatePointerType(
651 LLVMRustDIBuilderRef Builder, LLVMMetadataRef PointeeTy,
652 uint64_t SizeInBits, uint32_t AlignInBits, const char *Name) {
653 return wrap(Builder->createPointerType(unwrapDI<DIType>(PointeeTy),
654 SizeInBits, AlignInBits,
655 #if LLVM_VERSION_GE(5, 0)
656 /* DWARFAddressSpace */ None,
661 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateStructType(
662 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
663 LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
664 uint32_t AlignInBits, LLVMRustDIFlags Flags,
665 LLVMMetadataRef DerivedFrom, LLVMMetadataRef Elements,
666 unsigned RunTimeLang, LLVMMetadataRef VTableHolder,
667 const char *UniqueId) {
668 return wrap(Builder->createStructType(
669 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNumber,
670 SizeInBits, AlignInBits, fromRust(Flags), unwrapDI<DIType>(DerivedFrom),
671 DINodeArray(unwrapDI<MDTuple>(Elements)), RunTimeLang,
672 unwrapDI<DIType>(VTableHolder), UniqueId));
675 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateMemberType(
676 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
677 LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits,
678 uint32_t AlignInBits, uint64_t OffsetInBits, LLVMRustDIFlags Flags,
679 LLVMMetadataRef Ty) {
680 return wrap(Builder->createMemberType(unwrapDI<DIDescriptor>(Scope), Name,
681 unwrapDI<DIFile>(File), LineNo,
682 SizeInBits, AlignInBits, OffsetInBits,
683 fromRust(Flags), unwrapDI<DIType>(Ty)));
686 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateLexicalBlock(
687 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope,
688 LLVMMetadataRef File, unsigned Line, unsigned Col) {
689 return wrap(Builder->createLexicalBlock(unwrapDI<DIDescriptor>(Scope),
690 unwrapDI<DIFile>(File), Line, Col));
693 extern "C" LLVMMetadataRef
694 LLVMRustDIBuilderCreateLexicalBlockFile(LLVMRustDIBuilderRef Builder,
695 LLVMMetadataRef Scope,
696 LLVMMetadataRef File) {
697 return wrap(Builder->createLexicalBlockFile(unwrapDI<DIDescriptor>(Scope),
698 unwrapDI<DIFile>(File)));
701 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateStaticVariable(
702 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Context, const char *Name,
703 const char *LinkageName, LLVMMetadataRef File, unsigned LineNo,
704 LLVMMetadataRef Ty, bool IsLocalToUnit, LLVMValueRef V,
705 LLVMMetadataRef Decl = nullptr, uint32_t AlignInBits = 0) {
706 llvm::GlobalVariable *InitVal = cast<llvm::GlobalVariable>(unwrap(V));
708 llvm::DIExpression *InitExpr = nullptr;
709 if (llvm::ConstantInt *IntVal = llvm::dyn_cast<llvm::ConstantInt>(InitVal)) {
710 InitExpr = Builder->createConstantValueExpression(
711 IntVal->getValue().getSExtValue());
712 } else if (llvm::ConstantFP *FPVal =
713 llvm::dyn_cast<llvm::ConstantFP>(InitVal)) {
714 InitExpr = Builder->createConstantValueExpression(
715 FPVal->getValueAPF().bitcastToAPInt().getZExtValue());
718 llvm::DIGlobalVariableExpression *VarExpr = Builder->createGlobalVariableExpression(
719 unwrapDI<DIDescriptor>(Context), Name, LinkageName,
720 unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), IsLocalToUnit,
721 InitExpr, unwrapDIPtr<MDNode>(Decl), AlignInBits);
723 InitVal->setMetadata("dbg", VarExpr);
725 return wrap(VarExpr);
728 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateVariable(
729 LLVMRustDIBuilderRef Builder, unsigned Tag, LLVMMetadataRef Scope,
730 const char *Name, LLVMMetadataRef File, unsigned LineNo,
731 LLVMMetadataRef Ty, bool AlwaysPreserve, LLVMRustDIFlags Flags,
732 unsigned ArgNo, uint32_t AlignInBits) {
733 if (Tag == 0x100) { // DW_TAG_auto_variable
734 return wrap(Builder->createAutoVariable(
735 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNo,
736 unwrapDI<DIType>(Ty), AlwaysPreserve, fromRust(Flags), AlignInBits));
738 return wrap(Builder->createParameterVariable(
739 unwrapDI<DIDescriptor>(Scope), Name, ArgNo, unwrapDI<DIFile>(File),
740 LineNo, unwrapDI<DIType>(Ty), AlwaysPreserve, fromRust(Flags)));
744 extern "C" LLVMMetadataRef
745 LLVMRustDIBuilderCreateArrayType(LLVMRustDIBuilderRef Builder, uint64_t Size,
746 uint32_t AlignInBits, LLVMMetadataRef Ty,
747 LLVMMetadataRef Subscripts) {
749 Builder->createArrayType(Size, AlignInBits, unwrapDI<DIType>(Ty),
750 DINodeArray(unwrapDI<MDTuple>(Subscripts))));
753 extern "C" LLVMMetadataRef
754 LLVMRustDIBuilderCreateVectorType(LLVMRustDIBuilderRef Builder, uint64_t Size,
755 uint32_t AlignInBits, LLVMMetadataRef Ty,
756 LLVMMetadataRef Subscripts) {
758 Builder->createVectorType(Size, AlignInBits, unwrapDI<DIType>(Ty),
759 DINodeArray(unwrapDI<MDTuple>(Subscripts))));
762 extern "C" LLVMMetadataRef
763 LLVMRustDIBuilderGetOrCreateSubrange(LLVMRustDIBuilderRef Builder, int64_t Lo,
765 return wrap(Builder->getOrCreateSubrange(Lo, Count));
768 extern "C" LLVMMetadataRef
769 LLVMRustDIBuilderGetOrCreateArray(LLVMRustDIBuilderRef Builder,
770 LLVMMetadataRef *Ptr, unsigned Count) {
771 Metadata **DataValue = unwrap(Ptr);
773 Builder->getOrCreateArray(ArrayRef<Metadata *>(DataValue, Count)).get());
776 extern "C" LLVMValueRef LLVMRustDIBuilderInsertDeclareAtEnd(
777 LLVMRustDIBuilderRef Builder, LLVMValueRef V, LLVMMetadataRef VarInfo,
778 int64_t *AddrOps, unsigned AddrOpsCount, LLVMValueRef DL,
779 LLVMBasicBlockRef InsertAtEnd) {
780 return wrap(Builder->insertDeclare(
781 unwrap(V), unwrap<DILocalVariable>(VarInfo),
782 Builder->createExpression(llvm::ArrayRef<int64_t>(AddrOps, AddrOpsCount)),
783 DebugLoc(cast<MDNode>(unwrap<MetadataAsValue>(DL)->getMetadata())),
784 unwrap(InsertAtEnd)));
787 extern "C" LLVMMetadataRef
788 LLVMRustDIBuilderCreateEnumerator(LLVMRustDIBuilderRef Builder,
789 const char *Name, uint64_t Val) {
790 return wrap(Builder->createEnumerator(Name, Val));
793 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateEnumerationType(
794 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
795 LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
796 uint32_t AlignInBits, LLVMMetadataRef Elements,
797 LLVMMetadataRef ClassTy) {
798 return wrap(Builder->createEnumerationType(
799 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNumber,
800 SizeInBits, AlignInBits, DINodeArray(unwrapDI<MDTuple>(Elements)),
801 unwrapDI<DIType>(ClassTy)));
804 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateUnionType(
805 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
806 LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
807 uint32_t AlignInBits, LLVMRustDIFlags Flags, LLVMMetadataRef Elements,
808 unsigned RunTimeLang, const char *UniqueId) {
809 return wrap(Builder->createUnionType(
810 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNumber,
811 SizeInBits, AlignInBits, fromRust(Flags),
812 DINodeArray(unwrapDI<MDTuple>(Elements)), RunTimeLang, UniqueId));
815 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateTemplateTypeParameter(
816 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
817 LLVMMetadataRef Ty, LLVMMetadataRef File, unsigned LineNo,
819 return wrap(Builder->createTemplateTypeParameter(
820 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIType>(Ty)));
823 extern "C" LLVMMetadataRef
824 LLVMRustDIBuilderCreateNameSpace(LLVMRustDIBuilderRef Builder,
825 LLVMMetadataRef Scope, const char *Name,
826 LLVMMetadataRef File, unsigned LineNo) {
827 return wrap(Builder->createNameSpace(
828 unwrapDI<DIDescriptor>(Scope), Name
829 #if LLVM_VERSION_LT(5, 0)
831 unwrapDI<DIFile>(File), LineNo
833 #if LLVM_VERSION_GE(4, 0)
835 false // ExportSymbols (only relevant for C++ anonymous namespaces)
841 LLVMRustDICompositeTypeSetTypeArray(LLVMRustDIBuilderRef Builder,
842 LLVMMetadataRef CompositeTy,
843 LLVMMetadataRef TyArray) {
844 DICompositeType *Tmp = unwrapDI<DICompositeType>(CompositeTy);
845 Builder->replaceArrays(Tmp, DINodeArray(unwrap<MDTuple>(TyArray)));
848 extern "C" LLVMValueRef
849 LLVMRustDIBuilderCreateDebugLocation(LLVMContextRef ContextRef, unsigned Line,
850 unsigned Column, LLVMMetadataRef Scope,
851 LLVMMetadataRef InlinedAt) {
852 LLVMContext &Context = *unwrap(ContextRef);
854 DebugLoc debug_loc = DebugLoc::get(Line, Column, unwrapDIPtr<MDNode>(Scope),
855 unwrapDIPtr<MDNode>(InlinedAt));
857 return wrap(MetadataAsValue::get(Context, debug_loc.getAsMDNode()));
860 extern "C" int64_t LLVMRustDIBuilderCreateOpDeref() {
861 return dwarf::DW_OP_deref;
864 extern "C" int64_t LLVMRustDIBuilderCreateOpPlusUconst() {
865 #if LLVM_VERSION_GE(5, 0)
866 return dwarf::DW_OP_plus_uconst;
868 // older LLVM used `plus` to behave like `plus_uconst`.
869 return dwarf::DW_OP_plus;
873 extern "C" void LLVMRustWriteTypeToString(LLVMTypeRef Ty, RustStringRef Str) {
874 RawRustStringOstream OS(Str);
875 unwrap<llvm::Type>(Ty)->print(OS);
878 extern "C" void LLVMRustWriteValueToString(LLVMValueRef V,
880 RawRustStringOstream OS(Str);
885 unwrap<llvm::Value>(V)->getType()->print(OS);
887 unwrap<llvm::Value>(V)->print(OS);
892 // Note that the two following functions look quite similar to the
893 // LLVMGetSectionName function. Sadly, it appears that this function only
894 // returns a char* pointer, which isn't guaranteed to be null-terminated. The
895 // function provided by LLVM doesn't return the length, so we've created our own
896 // function which returns the length as well as the data pointer.
898 // For an example of this not returning a null terminated string, see
899 // lib/Object/COFFObjectFile.cpp in the getSectionName function. One of the
900 // branches explicitly creates a StringRef without a null terminator, and then
903 inline section_iterator *unwrap(LLVMSectionIteratorRef SI) {
904 return reinterpret_cast<section_iterator *>(SI);
907 extern "C" size_t LLVMRustGetSectionName(LLVMSectionIteratorRef SI,
910 if (std::error_code EC = (*unwrap(SI))->getName(Ret))
911 report_fatal_error(EC.message());
916 // LLVMArrayType function does not support 64-bit ElementCount
917 extern "C" LLVMTypeRef LLVMRustArrayType(LLVMTypeRef ElementTy,
918 uint64_t ElementCount) {
919 return wrap(ArrayType::get(unwrap(ElementTy), ElementCount));
922 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Twine, LLVMTwineRef)
924 extern "C" void LLVMRustWriteTwineToString(LLVMTwineRef T, RustStringRef Str) {
925 RawRustStringOstream OS(Str);
926 unwrap(T)->print(OS);
929 extern "C" void LLVMRustUnpackOptimizationDiagnostic(
930 LLVMDiagnosticInfoRef DI, RustStringRef PassNameOut,
931 LLVMValueRef *FunctionOut, unsigned* Line, unsigned* Column,
932 RustStringRef FilenameOut, RustStringRef MessageOut) {
933 // Undefined to call this not on an optimization diagnostic!
934 llvm::DiagnosticInfoOptimizationBase *Opt =
935 static_cast<llvm::DiagnosticInfoOptimizationBase *>(unwrap(DI));
937 RawRustStringOstream PassNameOS(PassNameOut);
938 PassNameOS << Opt->getPassName();
939 *FunctionOut = wrap(&Opt->getFunction());
941 RawRustStringOstream FilenameOS(FilenameOut);
942 #if LLVM_VERSION_GE(5,0)
943 DiagnosticLocation loc = Opt->getLocation();
945 *Line = loc.getLine();
946 *Column = loc.getColumn();
947 FilenameOS << loc.getFilename();
950 const DebugLoc &loc = Opt->getDebugLoc();
952 *Line = loc.getLine();
953 *Column = loc.getCol();
954 FilenameOS << cast<DIScope>(loc.getScope())->getFilename();
958 RawRustStringOstream MessageOS(MessageOut);
959 MessageOS << Opt->getMsg();
963 LLVMRustUnpackInlineAsmDiagnostic(LLVMDiagnosticInfoRef DI, unsigned *CookieOut,
964 LLVMTwineRef *MessageOut,
965 LLVMValueRef *InstructionOut) {
966 // Undefined to call this not on an inline assembly diagnostic!
967 llvm::DiagnosticInfoInlineAsm *IA =
968 static_cast<llvm::DiagnosticInfoInlineAsm *>(unwrap(DI));
970 *CookieOut = IA->getLocCookie();
971 *MessageOut = wrap(&IA->getMsgStr());
972 *InstructionOut = wrap(IA->getInstruction());
975 extern "C" void LLVMRustWriteDiagnosticInfoToString(LLVMDiagnosticInfoRef DI,
977 RawRustStringOstream OS(Str);
978 DiagnosticPrinterRawOStream DP(OS);
979 unwrap(DI)->print(DP);
982 enum class LLVMRustDiagnosticKind {
986 DebugMetadataVersion,
989 OptimizationRemarkMissed,
990 OptimizationRemarkAnalysis,
991 OptimizationRemarkAnalysisFPCommute,
992 OptimizationRemarkAnalysisAliasing,
993 OptimizationRemarkOther,
998 static LLVMRustDiagnosticKind toRust(DiagnosticKind Kind) {
1001 return LLVMRustDiagnosticKind::InlineAsm;
1003 return LLVMRustDiagnosticKind::StackSize;
1004 case DK_DebugMetadataVersion:
1005 return LLVMRustDiagnosticKind::DebugMetadataVersion;
1006 case DK_SampleProfile:
1007 return LLVMRustDiagnosticKind::SampleProfile;
1008 case DK_OptimizationRemark:
1009 return LLVMRustDiagnosticKind::OptimizationRemark;
1010 case DK_OptimizationRemarkMissed:
1011 return LLVMRustDiagnosticKind::OptimizationRemarkMissed;
1012 case DK_OptimizationRemarkAnalysis:
1013 return LLVMRustDiagnosticKind::OptimizationRemarkAnalysis;
1014 case DK_OptimizationRemarkAnalysisFPCommute:
1015 return LLVMRustDiagnosticKind::OptimizationRemarkAnalysisFPCommute;
1016 case DK_OptimizationRemarkAnalysisAliasing:
1017 return LLVMRustDiagnosticKind::OptimizationRemarkAnalysisAliasing;
1019 return LLVMRustDiagnosticKind::PGOProfile;
1021 return (Kind >= DK_FirstRemark && Kind <= DK_LastRemark)
1022 ? LLVMRustDiagnosticKind::OptimizationRemarkOther
1023 : LLVMRustDiagnosticKind::Other;
1027 extern "C" LLVMRustDiagnosticKind
1028 LLVMRustGetDiagInfoKind(LLVMDiagnosticInfoRef DI) {
1029 return toRust((DiagnosticKind)unwrap(DI)->getKind());
1031 // This is kept distinct from LLVMGetTypeKind, because when
1032 // a new type kind is added, the Rust-side enum must be
1033 // updated or UB will result.
1034 extern "C" LLVMTypeKind LLVMRustGetTypeKind(LLVMTypeRef Ty) {
1035 switch (unwrap(Ty)->getTypeID()) {
1036 case Type::VoidTyID:
1037 return LLVMVoidTypeKind;
1038 case Type::HalfTyID:
1039 return LLVMHalfTypeKind;
1040 case Type::FloatTyID:
1041 return LLVMFloatTypeKind;
1042 case Type::DoubleTyID:
1043 return LLVMDoubleTypeKind;
1044 case Type::X86_FP80TyID:
1045 return LLVMX86_FP80TypeKind;
1046 case Type::FP128TyID:
1047 return LLVMFP128TypeKind;
1048 case Type::PPC_FP128TyID:
1049 return LLVMPPC_FP128TypeKind;
1050 case Type::LabelTyID:
1051 return LLVMLabelTypeKind;
1052 case Type::MetadataTyID:
1053 return LLVMMetadataTypeKind;
1054 case Type::IntegerTyID:
1055 return LLVMIntegerTypeKind;
1056 case Type::FunctionTyID:
1057 return LLVMFunctionTypeKind;
1058 case Type::StructTyID:
1059 return LLVMStructTypeKind;
1060 case Type::ArrayTyID:
1061 return LLVMArrayTypeKind;
1062 case Type::PointerTyID:
1063 return LLVMPointerTypeKind;
1064 case Type::VectorTyID:
1065 return LLVMVectorTypeKind;
1066 case Type::X86_MMXTyID:
1067 return LLVMX86_MMXTypeKind;
1068 case Type::TokenTyID:
1069 return LLVMTokenTypeKind;
1071 report_fatal_error("Unhandled TypeID.");
1074 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(SMDiagnostic, LLVMSMDiagnosticRef)
1076 extern "C" void LLVMRustSetInlineAsmDiagnosticHandler(
1077 LLVMContextRef C, LLVMContext::InlineAsmDiagHandlerTy H, void *CX) {
1078 unwrap(C)->setInlineAsmDiagnosticHandler(H, CX);
1081 extern "C" void LLVMRustWriteSMDiagnosticToString(LLVMSMDiagnosticRef D,
1082 RustStringRef Str) {
1083 RawRustStringOstream OS(Str);
1084 unwrap(D)->print("", OS);
1087 extern "C" LLVMValueRef LLVMRustBuildCleanupPad(LLVMBuilderRef B,
1088 LLVMValueRef ParentPad,
1090 LLVMValueRef *LLArgs,
1092 Value **Args = unwrap(LLArgs);
1093 if (ParentPad == nullptr) {
1094 Type *Ty = Type::getTokenTy(unwrap(B)->getContext());
1095 ParentPad = wrap(Constant::getNullValue(Ty));
1097 return wrap(unwrap(B)->CreateCleanupPad(
1098 unwrap(ParentPad), ArrayRef<Value *>(Args, ArgCount), Name));
1101 extern "C" LLVMValueRef LLVMRustBuildCleanupRet(LLVMBuilderRef B,
1102 LLVMValueRef CleanupPad,
1103 LLVMBasicBlockRef UnwindBB) {
1104 CleanupPadInst *Inst = cast<CleanupPadInst>(unwrap(CleanupPad));
1105 return wrap(unwrap(B)->CreateCleanupRet(Inst, unwrap(UnwindBB)));
1108 extern "C" LLVMValueRef
1109 LLVMRustBuildCatchPad(LLVMBuilderRef B, LLVMValueRef ParentPad,
1110 unsigned ArgCount, LLVMValueRef *LLArgs, const char *Name) {
1111 Value **Args = unwrap(LLArgs);
1112 return wrap(unwrap(B)->CreateCatchPad(
1113 unwrap(ParentPad), ArrayRef<Value *>(Args, ArgCount), Name));
1116 extern "C" LLVMValueRef LLVMRustBuildCatchRet(LLVMBuilderRef B,
1118 LLVMBasicBlockRef BB) {
1119 return wrap(unwrap(B)->CreateCatchRet(cast<CatchPadInst>(unwrap(Pad)),
1123 extern "C" LLVMValueRef LLVMRustBuildCatchSwitch(LLVMBuilderRef B,
1124 LLVMValueRef ParentPad,
1125 LLVMBasicBlockRef BB,
1126 unsigned NumHandlers,
1128 if (ParentPad == nullptr) {
1129 Type *Ty = Type::getTokenTy(unwrap(B)->getContext());
1130 ParentPad = wrap(Constant::getNullValue(Ty));
1132 return wrap(unwrap(B)->CreateCatchSwitch(unwrap(ParentPad), unwrap(BB),
1133 NumHandlers, Name));
1136 extern "C" void LLVMRustAddHandler(LLVMValueRef CatchSwitchRef,
1137 LLVMBasicBlockRef Handler) {
1138 Value *CatchSwitch = unwrap(CatchSwitchRef);
1139 cast<CatchSwitchInst>(CatchSwitch)->addHandler(unwrap(Handler));
1142 extern "C" OperandBundleDef *LLVMRustBuildOperandBundleDef(const char *Name,
1143 LLVMValueRef *Inputs,
1144 unsigned NumInputs) {
1145 return new OperandBundleDef(Name, makeArrayRef(unwrap(Inputs), NumInputs));
1148 extern "C" void LLVMRustFreeOperandBundleDef(OperandBundleDef *Bundle) {
1152 extern "C" LLVMValueRef LLVMRustBuildCall(LLVMBuilderRef B, LLVMValueRef Fn,
1153 LLVMValueRef *Args, unsigned NumArgs,
1154 OperandBundleDef *Bundle,
1156 unsigned Len = Bundle ? 1 : 0;
1157 ArrayRef<OperandBundleDef> Bundles = makeArrayRef(Bundle, Len);
1158 return wrap(unwrap(B)->CreateCall(
1159 unwrap(Fn), makeArrayRef(unwrap(Args), NumArgs), Bundles, Name));
1162 extern "C" LLVMValueRef
1163 LLVMRustBuildInvoke(LLVMBuilderRef B, LLVMValueRef Fn, LLVMValueRef *Args,
1164 unsigned NumArgs, LLVMBasicBlockRef Then,
1165 LLVMBasicBlockRef Catch, OperandBundleDef *Bundle,
1167 unsigned Len = Bundle ? 1 : 0;
1168 ArrayRef<OperandBundleDef> Bundles = makeArrayRef(Bundle, Len);
1169 return wrap(unwrap(B)->CreateInvoke(unwrap(Fn), unwrap(Then), unwrap(Catch),
1170 makeArrayRef(unwrap(Args), NumArgs),
1174 extern "C" void LLVMRustPositionBuilderAtStart(LLVMBuilderRef B,
1175 LLVMBasicBlockRef BB) {
1176 auto Point = unwrap(BB)->getFirstInsertionPt();
1177 unwrap(B)->SetInsertPoint(unwrap(BB), Point);
1180 extern "C" void LLVMRustSetComdat(LLVMModuleRef M, LLVMValueRef V,
1182 Triple TargetTriple(unwrap(M)->getTargetTriple());
1183 GlobalObject *GV = unwrap<GlobalObject>(V);
1184 if (!TargetTriple.isOSBinFormatMachO()) {
1185 GV->setComdat(unwrap(M)->getOrInsertComdat(Name));
1189 extern "C" void LLVMRustUnsetComdat(LLVMValueRef V) {
1190 GlobalObject *GV = unwrap<GlobalObject>(V);
1191 GV->setComdat(nullptr);
1194 enum class LLVMRustLinkage {
1195 ExternalLinkage = 0,
1196 AvailableExternallyLinkage = 1,
1197 LinkOnceAnyLinkage = 2,
1198 LinkOnceODRLinkage = 3,
1201 AppendingLinkage = 6,
1202 InternalLinkage = 7,
1204 ExternalWeakLinkage = 9,
1208 static LLVMRustLinkage toRust(LLVMLinkage Linkage) {
1210 case LLVMExternalLinkage:
1211 return LLVMRustLinkage::ExternalLinkage;
1212 case LLVMAvailableExternallyLinkage:
1213 return LLVMRustLinkage::AvailableExternallyLinkage;
1214 case LLVMLinkOnceAnyLinkage:
1215 return LLVMRustLinkage::LinkOnceAnyLinkage;
1216 case LLVMLinkOnceODRLinkage:
1217 return LLVMRustLinkage::LinkOnceODRLinkage;
1218 case LLVMWeakAnyLinkage:
1219 return LLVMRustLinkage::WeakAnyLinkage;
1220 case LLVMWeakODRLinkage:
1221 return LLVMRustLinkage::WeakODRLinkage;
1222 case LLVMAppendingLinkage:
1223 return LLVMRustLinkage::AppendingLinkage;
1224 case LLVMInternalLinkage:
1225 return LLVMRustLinkage::InternalLinkage;
1226 case LLVMPrivateLinkage:
1227 return LLVMRustLinkage::PrivateLinkage;
1228 case LLVMExternalWeakLinkage:
1229 return LLVMRustLinkage::ExternalWeakLinkage;
1230 case LLVMCommonLinkage:
1231 return LLVMRustLinkage::CommonLinkage;
1233 report_fatal_error("Invalid LLVMRustLinkage value!");
1237 static LLVMLinkage fromRust(LLVMRustLinkage Linkage) {
1239 case LLVMRustLinkage::ExternalLinkage:
1240 return LLVMExternalLinkage;
1241 case LLVMRustLinkage::AvailableExternallyLinkage:
1242 return LLVMAvailableExternallyLinkage;
1243 case LLVMRustLinkage::LinkOnceAnyLinkage:
1244 return LLVMLinkOnceAnyLinkage;
1245 case LLVMRustLinkage::LinkOnceODRLinkage:
1246 return LLVMLinkOnceODRLinkage;
1247 case LLVMRustLinkage::WeakAnyLinkage:
1248 return LLVMWeakAnyLinkage;
1249 case LLVMRustLinkage::WeakODRLinkage:
1250 return LLVMWeakODRLinkage;
1251 case LLVMRustLinkage::AppendingLinkage:
1252 return LLVMAppendingLinkage;
1253 case LLVMRustLinkage::InternalLinkage:
1254 return LLVMInternalLinkage;
1255 case LLVMRustLinkage::PrivateLinkage:
1256 return LLVMPrivateLinkage;
1257 case LLVMRustLinkage::ExternalWeakLinkage:
1258 return LLVMExternalWeakLinkage;
1259 case LLVMRustLinkage::CommonLinkage:
1260 return LLVMCommonLinkage;
1262 report_fatal_error("Invalid LLVMRustLinkage value!");
1265 extern "C" LLVMRustLinkage LLVMRustGetLinkage(LLVMValueRef V) {
1266 return toRust(LLVMGetLinkage(V));
1269 extern "C" void LLVMRustSetLinkage(LLVMValueRef V,
1270 LLVMRustLinkage RustLinkage) {
1271 LLVMSetLinkage(V, fromRust(RustLinkage));
1274 // Returns true if both high and low were successfully set. Fails in case constant wasn’t any of
1275 // the common sizes (1, 8, 16, 32, 64, 128 bits)
1276 extern "C" bool LLVMRustConstInt128Get(LLVMValueRef CV, bool sext, uint64_t *high, uint64_t *low)
1278 auto C = unwrap<llvm::ConstantInt>(CV);
1279 if (C->getBitWidth() > 128) { return false; }
1282 AP = C->getValue().sextOrSelf(128);
1284 AP = C->getValue().zextOrSelf(128);
1286 *low = AP.getLoBits(64).getZExtValue();
1287 *high = AP.getHiBits(64).getZExtValue();
1291 enum class LLVMRustVisibility {
1297 static LLVMRustVisibility toRust(LLVMVisibility Vis) {
1299 case LLVMDefaultVisibility:
1300 return LLVMRustVisibility::Default;
1301 case LLVMHiddenVisibility:
1302 return LLVMRustVisibility::Hidden;
1303 case LLVMProtectedVisibility:
1304 return LLVMRustVisibility::Protected;
1306 report_fatal_error("Invalid LLVMRustVisibility value!");
1309 static LLVMVisibility fromRust(LLVMRustVisibility Vis) {
1311 case LLVMRustVisibility::Default:
1312 return LLVMDefaultVisibility;
1313 case LLVMRustVisibility::Hidden:
1314 return LLVMHiddenVisibility;
1315 case LLVMRustVisibility::Protected:
1316 return LLVMProtectedVisibility;
1318 report_fatal_error("Invalid LLVMRustVisibility value!");
1321 extern "C" LLVMRustVisibility LLVMRustGetVisibility(LLVMValueRef V) {
1322 return toRust(LLVMGetVisibility(V));
1325 // Oh hey, a binding that makes sense for once? (because LLVM’s own do not)
1326 extern "C" LLVMValueRef LLVMRustBuildIntCast(LLVMBuilderRef B, LLVMValueRef Val,
1327 LLVMTypeRef DestTy, bool isSigned) {
1328 return wrap(unwrap(B)->CreateIntCast(unwrap(Val), unwrap(DestTy), isSigned, ""));
1331 extern "C" void LLVMRustSetVisibility(LLVMValueRef V,
1332 LLVMRustVisibility RustVisibility) {
1333 LLVMSetVisibility(V, fromRust(RustVisibility));
1336 struct LLVMRustModuleBuffer {
1340 extern "C" LLVMRustModuleBuffer*
1341 LLVMRustModuleBufferCreate(LLVMModuleRef M) {
1342 auto Ret = llvm::make_unique<LLVMRustModuleBuffer>();
1344 raw_string_ostream OS(Ret->data);
1346 legacy::PassManager PM;
1347 PM.add(createBitcodeWriterPass(OS));
1351 return Ret.release();
1355 LLVMRustModuleBufferFree(LLVMRustModuleBuffer *Buffer) {
1359 extern "C" const void*
1360 LLVMRustModuleBufferPtr(const LLVMRustModuleBuffer *Buffer) {
1361 return Buffer->data.data();
1365 LLVMRustModuleBufferLen(const LLVMRustModuleBuffer *Buffer) {
1366 return Buffer->data.length();
1370 LLVMRustModuleCost(LLVMModuleRef M) {
1371 auto f = unwrap(M)->functions();
1372 return std::distance(std::begin(f), std::end(f));
1375 // Vector reductions:
1376 #if LLVM_VERSION_GE(5, 0)
1377 extern "C" LLVMValueRef
1378 LLVMRustBuildVectorReduceFAdd(LLVMBuilderRef B, LLVMValueRef Acc, LLVMValueRef Src) {
1379 return wrap(unwrap(B)->CreateFAddReduce(unwrap(Acc),unwrap(Src)));
1381 extern "C" LLVMValueRef
1382 LLVMRustBuildVectorReduceFMul(LLVMBuilderRef B, LLVMValueRef Acc, LLVMValueRef Src) {
1383 return wrap(unwrap(B)->CreateFMulReduce(unwrap(Acc),unwrap(Src)));
1385 extern "C" LLVMValueRef
1386 LLVMRustBuildVectorReduceAdd(LLVMBuilderRef B, LLVMValueRef Src) {
1387 return wrap(unwrap(B)->CreateAddReduce(unwrap(Src)));
1389 extern "C" LLVMValueRef
1390 LLVMRustBuildVectorReduceMul(LLVMBuilderRef B, LLVMValueRef Src) {
1391 return wrap(unwrap(B)->CreateMulReduce(unwrap(Src)));
1393 extern "C" LLVMValueRef
1394 LLVMRustBuildVectorReduceAnd(LLVMBuilderRef B, LLVMValueRef Src) {
1395 return wrap(unwrap(B)->CreateAndReduce(unwrap(Src)));
1397 extern "C" LLVMValueRef
1398 LLVMRustBuildVectorReduceOr(LLVMBuilderRef B, LLVMValueRef Src) {
1399 return wrap(unwrap(B)->CreateOrReduce(unwrap(Src)));
1401 extern "C" LLVMValueRef
1402 LLVMRustBuildVectorReduceXor(LLVMBuilderRef B, LLVMValueRef Src) {
1403 return wrap(unwrap(B)->CreateXorReduce(unwrap(Src)));
1405 extern "C" LLVMValueRef
1406 LLVMRustBuildVectorReduceMin(LLVMBuilderRef B, LLVMValueRef Src, bool IsSigned) {
1407 return wrap(unwrap(B)->CreateIntMinReduce(unwrap(Src), IsSigned));
1409 extern "C" LLVMValueRef
1410 LLVMRustBuildVectorReduceMax(LLVMBuilderRef B, LLVMValueRef Src, bool IsSigned) {
1411 return wrap(unwrap(B)->CreateIntMaxReduce(unwrap(Src), IsSigned));
1413 extern "C" LLVMValueRef
1414 LLVMRustBuildVectorReduceFMin(LLVMBuilderRef B, LLVMValueRef Src, bool NoNaN) {
1415 return wrap(unwrap(B)->CreateFPMinReduce(unwrap(Src), NoNaN));
1417 extern "C" LLVMValueRef
1418 LLVMRustBuildVectorReduceFMax(LLVMBuilderRef B, LLVMValueRef Src, bool NoNaN) {
1419 return wrap(unwrap(B)->CreateFPMaxReduce(unwrap(Src), NoNaN));
1424 extern "C" LLVMValueRef
1425 LLVMRustBuildVectorReduceFAdd(LLVMBuilderRef, LLVMValueRef, LLVMValueRef) {
1428 extern "C" LLVMValueRef
1429 LLVMRustBuildVectorReduceFMul(LLVMBuilderRef, LLVMValueRef, LLVMValueRef) {
1432 extern "C" LLVMValueRef
1433 LLVMRustBuildVectorReduceAdd(LLVMBuilderRef, LLVMValueRef) {
1436 extern "C" LLVMValueRef
1437 LLVMRustBuildVectorReduceMul(LLVMBuilderRef, LLVMValueRef) {
1440 extern "C" LLVMValueRef
1441 LLVMRustBuildVectorReduceAnd(LLVMBuilderRef, LLVMValueRef) {
1444 extern "C" LLVMValueRef
1445 LLVMRustBuildVectorReduceOr(LLVMBuilderRef, LLVMValueRef) {
1448 extern "C" LLVMValueRef
1449 LLVMRustBuildVectorReduceXor(LLVMBuilderRef, LLVMValueRef) {
1452 extern "C" LLVMValueRef
1453 LLVMRustBuildVectorReduceMin(LLVMBuilderRef, LLVMValueRef, bool) {
1456 extern "C" LLVMValueRef
1457 LLVMRustBuildVectorReduceMax(LLVMBuilderRef, LLVMValueRef, bool) {
1460 extern "C" LLVMValueRef
1461 LLVMRustBuildVectorReduceFMin(LLVMBuilderRef, LLVMValueRef, bool) {
1464 extern "C" LLVMValueRef
1465 LLVMRustBuildVectorReduceFMax(LLVMBuilderRef, LLVMValueRef, bool) {
1470 #if LLVM_VERSION_LT(4, 0)
1471 extern "C" LLVMValueRef
1472 LLVMBuildExactUDiv(LLVMBuilderRef B, LLVMValueRef LHS,
1473 LLVMValueRef RHS, const char *Name) {
1474 return wrap(unwrap(B)->CreateExactUDiv(unwrap(LHS), unwrap(RHS), Name));
1478 #if LLVM_VERSION_GE(6, 0)
1479 extern "C" LLVMValueRef
1480 LLVMRustBuildMinNum(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS) {
1481 return wrap(unwrap(B)->CreateMinNum(unwrap(LHS),unwrap(RHS)));
1483 extern "C" LLVMValueRef
1484 LLVMRustBuildMaxNum(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS) {
1485 return wrap(unwrap(B)->CreateMaxNum(unwrap(LHS),unwrap(RHS)));
1488 extern "C" LLVMValueRef
1489 LLVMRustBuildMinNum(LLVMBuilderRef, LLVMValueRef, LLVMValueRef) {
1492 extern "C" LLVMValueRef
1493 LLVMRustBuildMaxNum(LLVMBuilderRef, LLVMValueRef, LLVMValueRef) {