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 LLVMRustDIBuilderGetOrCreateSubrange(LLVMRustDIBuilderRef Builder, int64_t Lo,
756 return wrap(Builder->getOrCreateSubrange(Lo, Count));
759 extern "C" LLVMMetadataRef
760 LLVMRustDIBuilderGetOrCreateArray(LLVMRustDIBuilderRef Builder,
761 LLVMMetadataRef *Ptr, unsigned Count) {
762 Metadata **DataValue = unwrap(Ptr);
764 Builder->getOrCreateArray(ArrayRef<Metadata *>(DataValue, Count)).get());
767 extern "C" LLVMValueRef LLVMRustDIBuilderInsertDeclareAtEnd(
768 LLVMRustDIBuilderRef Builder, LLVMValueRef V, LLVMMetadataRef VarInfo,
769 int64_t *AddrOps, unsigned AddrOpsCount, LLVMValueRef DL,
770 LLVMBasicBlockRef InsertAtEnd) {
771 return wrap(Builder->insertDeclare(
772 unwrap(V), unwrap<DILocalVariable>(VarInfo),
773 Builder->createExpression(llvm::ArrayRef<int64_t>(AddrOps, AddrOpsCount)),
774 DebugLoc(cast<MDNode>(unwrap<MetadataAsValue>(DL)->getMetadata())),
775 unwrap(InsertAtEnd)));
778 extern "C" LLVMMetadataRef
779 LLVMRustDIBuilderCreateEnumerator(LLVMRustDIBuilderRef Builder,
780 const char *Name, uint64_t Val) {
781 return wrap(Builder->createEnumerator(Name, Val));
784 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateEnumerationType(
785 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
786 LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
787 uint32_t AlignInBits, LLVMMetadataRef Elements,
788 LLVMMetadataRef ClassTy) {
789 return wrap(Builder->createEnumerationType(
790 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNumber,
791 SizeInBits, AlignInBits, DINodeArray(unwrapDI<MDTuple>(Elements)),
792 unwrapDI<DIType>(ClassTy)));
795 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateUnionType(
796 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
797 LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
798 uint32_t AlignInBits, LLVMRustDIFlags Flags, LLVMMetadataRef Elements,
799 unsigned RunTimeLang, const char *UniqueId) {
800 return wrap(Builder->createUnionType(
801 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNumber,
802 SizeInBits, AlignInBits, fromRust(Flags),
803 DINodeArray(unwrapDI<MDTuple>(Elements)), RunTimeLang, UniqueId));
806 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateTemplateTypeParameter(
807 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
808 LLVMMetadataRef Ty, LLVMMetadataRef File, unsigned LineNo,
810 return wrap(Builder->createTemplateTypeParameter(
811 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIType>(Ty)));
814 extern "C" LLVMMetadataRef
815 LLVMRustDIBuilderCreateNameSpace(LLVMRustDIBuilderRef Builder,
816 LLVMMetadataRef Scope, const char *Name,
817 LLVMMetadataRef File, unsigned LineNo) {
818 return wrap(Builder->createNameSpace(
819 unwrapDI<DIDescriptor>(Scope), Name
820 #if LLVM_VERSION_LT(5, 0)
822 unwrapDI<DIFile>(File), LineNo
824 #if LLVM_VERSION_GE(4, 0)
826 false // ExportSymbols (only relevant for C++ anonymous namespaces)
832 LLVMRustDICompositeTypeSetTypeArray(LLVMRustDIBuilderRef Builder,
833 LLVMMetadataRef CompositeTy,
834 LLVMMetadataRef TyArray) {
835 DICompositeType *Tmp = unwrapDI<DICompositeType>(CompositeTy);
836 Builder->replaceArrays(Tmp, DINodeArray(unwrap<MDTuple>(TyArray)));
839 extern "C" LLVMValueRef
840 LLVMRustDIBuilderCreateDebugLocation(LLVMContextRef ContextRef, unsigned Line,
841 unsigned Column, LLVMMetadataRef Scope,
842 LLVMMetadataRef InlinedAt) {
843 LLVMContext &Context = *unwrap(ContextRef);
845 DebugLoc debug_loc = DebugLoc::get(Line, Column, unwrapDIPtr<MDNode>(Scope),
846 unwrapDIPtr<MDNode>(InlinedAt));
848 return wrap(MetadataAsValue::get(Context, debug_loc.getAsMDNode()));
851 extern "C" int64_t LLVMRustDIBuilderCreateOpDeref() {
852 return dwarf::DW_OP_deref;
855 extern "C" int64_t LLVMRustDIBuilderCreateOpPlusUconst() {
856 #if LLVM_VERSION_GE(5, 0)
857 return dwarf::DW_OP_plus_uconst;
859 // older LLVM used `plus` to behave like `plus_uconst`.
860 return dwarf::DW_OP_plus;
864 extern "C" void LLVMRustWriteTypeToString(LLVMTypeRef Ty, RustStringRef Str) {
865 RawRustStringOstream OS(Str);
866 unwrap<llvm::Type>(Ty)->print(OS);
869 extern "C" void LLVMRustWriteValueToString(LLVMValueRef V,
871 RawRustStringOstream OS(Str);
876 unwrap<llvm::Value>(V)->getType()->print(OS);
878 unwrap<llvm::Value>(V)->print(OS);
883 // Note that the two following functions look quite similar to the
884 // LLVMGetSectionName function. Sadly, it appears that this function only
885 // returns a char* pointer, which isn't guaranteed to be null-terminated. The
886 // function provided by LLVM doesn't return the length, so we've created our own
887 // function which returns the length as well as the data pointer.
889 // For an example of this not returning a null terminated string, see
890 // lib/Object/COFFObjectFile.cpp in the getSectionName function. One of the
891 // branches explicitly creates a StringRef without a null terminator, and then
894 inline section_iterator *unwrap(LLVMSectionIteratorRef SI) {
895 return reinterpret_cast<section_iterator *>(SI);
898 extern "C" size_t LLVMRustGetSectionName(LLVMSectionIteratorRef SI,
901 if (std::error_code EC = (*unwrap(SI))->getName(Ret))
902 report_fatal_error(EC.message());
907 // LLVMArrayType function does not support 64-bit ElementCount
908 extern "C" LLVMTypeRef LLVMRustArrayType(LLVMTypeRef ElementTy,
909 uint64_t ElementCount) {
910 return wrap(ArrayType::get(unwrap(ElementTy), ElementCount));
913 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Twine, LLVMTwineRef)
915 extern "C" void LLVMRustWriteTwineToString(LLVMTwineRef T, RustStringRef Str) {
916 RawRustStringOstream OS(Str);
917 unwrap(T)->print(OS);
920 extern "C" void LLVMRustUnpackOptimizationDiagnostic(
921 LLVMDiagnosticInfoRef DI, RustStringRef PassNameOut,
922 LLVMValueRef *FunctionOut, unsigned* Line, unsigned* Column,
923 RustStringRef FilenameOut, RustStringRef MessageOut) {
924 // Undefined to call this not on an optimization diagnostic!
925 llvm::DiagnosticInfoOptimizationBase *Opt =
926 static_cast<llvm::DiagnosticInfoOptimizationBase *>(unwrap(DI));
928 RawRustStringOstream PassNameOS(PassNameOut);
929 PassNameOS << Opt->getPassName();
930 *FunctionOut = wrap(&Opt->getFunction());
932 RawRustStringOstream FilenameOS(FilenameOut);
933 #if LLVM_VERSION_GE(5,0)
934 DiagnosticLocation loc = Opt->getLocation();
936 *Line = loc.getLine();
937 *Column = loc.getColumn();
938 FilenameOS << loc.getFilename();
941 const DebugLoc &loc = Opt->getDebugLoc();
943 *Line = loc.getLine();
944 *Column = loc.getCol();
945 FilenameOS << cast<DIScope>(loc.getScope())->getFilename();
949 RawRustStringOstream MessageOS(MessageOut);
950 MessageOS << Opt->getMsg();
954 LLVMRustUnpackInlineAsmDiagnostic(LLVMDiagnosticInfoRef DI, unsigned *CookieOut,
955 LLVMTwineRef *MessageOut,
956 LLVMValueRef *InstructionOut) {
957 // Undefined to call this not on an inline assembly diagnostic!
958 llvm::DiagnosticInfoInlineAsm *IA =
959 static_cast<llvm::DiagnosticInfoInlineAsm *>(unwrap(DI));
961 *CookieOut = IA->getLocCookie();
962 *MessageOut = wrap(&IA->getMsgStr());
963 *InstructionOut = wrap(IA->getInstruction());
966 extern "C" void LLVMRustWriteDiagnosticInfoToString(LLVMDiagnosticInfoRef DI,
968 RawRustStringOstream OS(Str);
969 DiagnosticPrinterRawOStream DP(OS);
970 unwrap(DI)->print(DP);
973 enum class LLVMRustDiagnosticKind {
977 DebugMetadataVersion,
980 OptimizationRemarkMissed,
981 OptimizationRemarkAnalysis,
982 OptimizationRemarkAnalysisFPCommute,
983 OptimizationRemarkAnalysisAliasing,
984 OptimizationRemarkOther,
990 static LLVMRustDiagnosticKind toRust(DiagnosticKind Kind) {
993 return LLVMRustDiagnosticKind::InlineAsm;
995 return LLVMRustDiagnosticKind::StackSize;
996 case DK_DebugMetadataVersion:
997 return LLVMRustDiagnosticKind::DebugMetadataVersion;
998 case DK_SampleProfile:
999 return LLVMRustDiagnosticKind::SampleProfile;
1000 case DK_OptimizationRemark:
1001 return LLVMRustDiagnosticKind::OptimizationRemark;
1002 case DK_OptimizationRemarkMissed:
1003 return LLVMRustDiagnosticKind::OptimizationRemarkMissed;
1004 case DK_OptimizationRemarkAnalysis:
1005 return LLVMRustDiagnosticKind::OptimizationRemarkAnalysis;
1006 case DK_OptimizationRemarkAnalysisFPCommute:
1007 return LLVMRustDiagnosticKind::OptimizationRemarkAnalysisFPCommute;
1008 case DK_OptimizationRemarkAnalysisAliasing:
1009 return LLVMRustDiagnosticKind::OptimizationRemarkAnalysisAliasing;
1011 return LLVMRustDiagnosticKind::PGOProfile;
1013 return LLVMRustDiagnosticKind::Linker;
1015 return (Kind >= DK_FirstRemark && Kind <= DK_LastRemark)
1016 ? LLVMRustDiagnosticKind::OptimizationRemarkOther
1017 : LLVMRustDiagnosticKind::Other;
1021 extern "C" LLVMRustDiagnosticKind
1022 LLVMRustGetDiagInfoKind(LLVMDiagnosticInfoRef DI) {
1023 return toRust((DiagnosticKind)unwrap(DI)->getKind());
1025 // This is kept distinct from LLVMGetTypeKind, because when
1026 // a new type kind is added, the Rust-side enum must be
1027 // updated or UB will result.
1028 extern "C" LLVMTypeKind LLVMRustGetTypeKind(LLVMTypeRef Ty) {
1029 switch (unwrap(Ty)->getTypeID()) {
1030 case Type::VoidTyID:
1031 return LLVMVoidTypeKind;
1032 case Type::HalfTyID:
1033 return LLVMHalfTypeKind;
1034 case Type::FloatTyID:
1035 return LLVMFloatTypeKind;
1036 case Type::DoubleTyID:
1037 return LLVMDoubleTypeKind;
1038 case Type::X86_FP80TyID:
1039 return LLVMX86_FP80TypeKind;
1040 case Type::FP128TyID:
1041 return LLVMFP128TypeKind;
1042 case Type::PPC_FP128TyID:
1043 return LLVMPPC_FP128TypeKind;
1044 case Type::LabelTyID:
1045 return LLVMLabelTypeKind;
1046 case Type::MetadataTyID:
1047 return LLVMMetadataTypeKind;
1048 case Type::IntegerTyID:
1049 return LLVMIntegerTypeKind;
1050 case Type::FunctionTyID:
1051 return LLVMFunctionTypeKind;
1052 case Type::StructTyID:
1053 return LLVMStructTypeKind;
1054 case Type::ArrayTyID:
1055 return LLVMArrayTypeKind;
1056 case Type::PointerTyID:
1057 return LLVMPointerTypeKind;
1058 case Type::VectorTyID:
1059 return LLVMVectorTypeKind;
1060 case Type::X86_MMXTyID:
1061 return LLVMX86_MMXTypeKind;
1062 case Type::TokenTyID:
1063 return LLVMTokenTypeKind;
1065 report_fatal_error("Unhandled TypeID.");
1068 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(SMDiagnostic, LLVMSMDiagnosticRef)
1070 extern "C" void LLVMRustSetInlineAsmDiagnosticHandler(
1071 LLVMContextRef C, LLVMContext::InlineAsmDiagHandlerTy H, void *CX) {
1072 unwrap(C)->setInlineAsmDiagnosticHandler(H, CX);
1075 extern "C" void LLVMRustWriteSMDiagnosticToString(LLVMSMDiagnosticRef D,
1076 RustStringRef Str) {
1077 RawRustStringOstream OS(Str);
1078 unwrap(D)->print("", OS);
1081 extern "C" LLVMValueRef LLVMRustBuildCleanupPad(LLVMBuilderRef B,
1082 LLVMValueRef ParentPad,
1084 LLVMValueRef *LLArgs,
1086 Value **Args = unwrap(LLArgs);
1087 if (ParentPad == nullptr) {
1088 Type *Ty = Type::getTokenTy(unwrap(B)->getContext());
1089 ParentPad = wrap(Constant::getNullValue(Ty));
1091 return wrap(unwrap(B)->CreateCleanupPad(
1092 unwrap(ParentPad), ArrayRef<Value *>(Args, ArgCount), Name));
1095 extern "C" LLVMValueRef LLVMRustBuildCleanupRet(LLVMBuilderRef B,
1096 LLVMValueRef CleanupPad,
1097 LLVMBasicBlockRef UnwindBB) {
1098 CleanupPadInst *Inst = cast<CleanupPadInst>(unwrap(CleanupPad));
1099 return wrap(unwrap(B)->CreateCleanupRet(Inst, unwrap(UnwindBB)));
1102 extern "C" LLVMValueRef
1103 LLVMRustBuildCatchPad(LLVMBuilderRef B, LLVMValueRef ParentPad,
1104 unsigned ArgCount, LLVMValueRef *LLArgs, const char *Name) {
1105 Value **Args = unwrap(LLArgs);
1106 return wrap(unwrap(B)->CreateCatchPad(
1107 unwrap(ParentPad), ArrayRef<Value *>(Args, ArgCount), Name));
1110 extern "C" LLVMValueRef LLVMRustBuildCatchRet(LLVMBuilderRef B,
1112 LLVMBasicBlockRef BB) {
1113 return wrap(unwrap(B)->CreateCatchRet(cast<CatchPadInst>(unwrap(Pad)),
1117 extern "C" LLVMValueRef LLVMRustBuildCatchSwitch(LLVMBuilderRef B,
1118 LLVMValueRef ParentPad,
1119 LLVMBasicBlockRef BB,
1120 unsigned NumHandlers,
1122 if (ParentPad == nullptr) {
1123 Type *Ty = Type::getTokenTy(unwrap(B)->getContext());
1124 ParentPad = wrap(Constant::getNullValue(Ty));
1126 return wrap(unwrap(B)->CreateCatchSwitch(unwrap(ParentPad), unwrap(BB),
1127 NumHandlers, Name));
1130 extern "C" void LLVMRustAddHandler(LLVMValueRef CatchSwitchRef,
1131 LLVMBasicBlockRef Handler) {
1132 Value *CatchSwitch = unwrap(CatchSwitchRef);
1133 cast<CatchSwitchInst>(CatchSwitch)->addHandler(unwrap(Handler));
1136 extern "C" OperandBundleDef *LLVMRustBuildOperandBundleDef(const char *Name,
1137 LLVMValueRef *Inputs,
1138 unsigned NumInputs) {
1139 return new OperandBundleDef(Name, makeArrayRef(unwrap(Inputs), NumInputs));
1142 extern "C" void LLVMRustFreeOperandBundleDef(OperandBundleDef *Bundle) {
1146 extern "C" LLVMValueRef LLVMRustBuildCall(LLVMBuilderRef B, LLVMValueRef Fn,
1147 LLVMValueRef *Args, unsigned NumArgs,
1148 OperandBundleDef *Bundle,
1150 unsigned Len = Bundle ? 1 : 0;
1151 ArrayRef<OperandBundleDef> Bundles = makeArrayRef(Bundle, Len);
1152 return wrap(unwrap(B)->CreateCall(
1153 unwrap(Fn), makeArrayRef(unwrap(Args), NumArgs), Bundles, Name));
1156 extern "C" LLVMValueRef
1157 LLVMRustBuildInvoke(LLVMBuilderRef B, LLVMValueRef Fn, LLVMValueRef *Args,
1158 unsigned NumArgs, LLVMBasicBlockRef Then,
1159 LLVMBasicBlockRef Catch, OperandBundleDef *Bundle,
1161 unsigned Len = Bundle ? 1 : 0;
1162 ArrayRef<OperandBundleDef> Bundles = makeArrayRef(Bundle, Len);
1163 return wrap(unwrap(B)->CreateInvoke(unwrap(Fn), unwrap(Then), unwrap(Catch),
1164 makeArrayRef(unwrap(Args), NumArgs),
1168 extern "C" void LLVMRustPositionBuilderAtStart(LLVMBuilderRef B,
1169 LLVMBasicBlockRef BB) {
1170 auto Point = unwrap(BB)->getFirstInsertionPt();
1171 unwrap(B)->SetInsertPoint(unwrap(BB), Point);
1174 extern "C" void LLVMRustSetComdat(LLVMModuleRef M, LLVMValueRef V,
1176 Triple TargetTriple(unwrap(M)->getTargetTriple());
1177 GlobalObject *GV = unwrap<GlobalObject>(V);
1178 if (!TargetTriple.isOSBinFormatMachO()) {
1179 GV->setComdat(unwrap(M)->getOrInsertComdat(Name));
1183 extern "C" void LLVMRustUnsetComdat(LLVMValueRef V) {
1184 GlobalObject *GV = unwrap<GlobalObject>(V);
1185 GV->setComdat(nullptr);
1188 enum class LLVMRustLinkage {
1189 ExternalLinkage = 0,
1190 AvailableExternallyLinkage = 1,
1191 LinkOnceAnyLinkage = 2,
1192 LinkOnceODRLinkage = 3,
1195 AppendingLinkage = 6,
1196 InternalLinkage = 7,
1198 ExternalWeakLinkage = 9,
1202 static LLVMRustLinkage toRust(LLVMLinkage Linkage) {
1204 case LLVMExternalLinkage:
1205 return LLVMRustLinkage::ExternalLinkage;
1206 case LLVMAvailableExternallyLinkage:
1207 return LLVMRustLinkage::AvailableExternallyLinkage;
1208 case LLVMLinkOnceAnyLinkage:
1209 return LLVMRustLinkage::LinkOnceAnyLinkage;
1210 case LLVMLinkOnceODRLinkage:
1211 return LLVMRustLinkage::LinkOnceODRLinkage;
1212 case LLVMWeakAnyLinkage:
1213 return LLVMRustLinkage::WeakAnyLinkage;
1214 case LLVMWeakODRLinkage:
1215 return LLVMRustLinkage::WeakODRLinkage;
1216 case LLVMAppendingLinkage:
1217 return LLVMRustLinkage::AppendingLinkage;
1218 case LLVMInternalLinkage:
1219 return LLVMRustLinkage::InternalLinkage;
1220 case LLVMPrivateLinkage:
1221 return LLVMRustLinkage::PrivateLinkage;
1222 case LLVMExternalWeakLinkage:
1223 return LLVMRustLinkage::ExternalWeakLinkage;
1224 case LLVMCommonLinkage:
1225 return LLVMRustLinkage::CommonLinkage;
1227 report_fatal_error("Invalid LLVMRustLinkage value!");
1231 static LLVMLinkage fromRust(LLVMRustLinkage Linkage) {
1233 case LLVMRustLinkage::ExternalLinkage:
1234 return LLVMExternalLinkage;
1235 case LLVMRustLinkage::AvailableExternallyLinkage:
1236 return LLVMAvailableExternallyLinkage;
1237 case LLVMRustLinkage::LinkOnceAnyLinkage:
1238 return LLVMLinkOnceAnyLinkage;
1239 case LLVMRustLinkage::LinkOnceODRLinkage:
1240 return LLVMLinkOnceODRLinkage;
1241 case LLVMRustLinkage::WeakAnyLinkage:
1242 return LLVMWeakAnyLinkage;
1243 case LLVMRustLinkage::WeakODRLinkage:
1244 return LLVMWeakODRLinkage;
1245 case LLVMRustLinkage::AppendingLinkage:
1246 return LLVMAppendingLinkage;
1247 case LLVMRustLinkage::InternalLinkage:
1248 return LLVMInternalLinkage;
1249 case LLVMRustLinkage::PrivateLinkage:
1250 return LLVMPrivateLinkage;
1251 case LLVMRustLinkage::ExternalWeakLinkage:
1252 return LLVMExternalWeakLinkage;
1253 case LLVMRustLinkage::CommonLinkage:
1254 return LLVMCommonLinkage;
1256 report_fatal_error("Invalid LLVMRustLinkage value!");
1259 extern "C" LLVMRustLinkage LLVMRustGetLinkage(LLVMValueRef V) {
1260 return toRust(LLVMGetLinkage(V));
1263 extern "C" void LLVMRustSetLinkage(LLVMValueRef V,
1264 LLVMRustLinkage RustLinkage) {
1265 LLVMSetLinkage(V, fromRust(RustLinkage));
1268 // Returns true if both high and low were successfully set. Fails in case constant wasn’t any of
1269 // the common sizes (1, 8, 16, 32, 64, 128 bits)
1270 extern "C" bool LLVMRustConstInt128Get(LLVMValueRef CV, bool sext, uint64_t *high, uint64_t *low)
1272 auto C = unwrap<llvm::ConstantInt>(CV);
1273 if (C->getBitWidth() > 128) { return false; }
1276 AP = C->getValue().sextOrSelf(128);
1278 AP = C->getValue().zextOrSelf(128);
1280 *low = AP.getLoBits(64).getZExtValue();
1281 *high = AP.getHiBits(64).getZExtValue();
1285 enum class LLVMRustVisibility {
1291 static LLVMRustVisibility toRust(LLVMVisibility Vis) {
1293 case LLVMDefaultVisibility:
1294 return LLVMRustVisibility::Default;
1295 case LLVMHiddenVisibility:
1296 return LLVMRustVisibility::Hidden;
1297 case LLVMProtectedVisibility:
1298 return LLVMRustVisibility::Protected;
1300 report_fatal_error("Invalid LLVMRustVisibility value!");
1303 static LLVMVisibility fromRust(LLVMRustVisibility Vis) {
1305 case LLVMRustVisibility::Default:
1306 return LLVMDefaultVisibility;
1307 case LLVMRustVisibility::Hidden:
1308 return LLVMHiddenVisibility;
1309 case LLVMRustVisibility::Protected:
1310 return LLVMProtectedVisibility;
1312 report_fatal_error("Invalid LLVMRustVisibility value!");
1315 extern "C" LLVMRustVisibility LLVMRustGetVisibility(LLVMValueRef V) {
1316 return toRust(LLVMGetVisibility(V));
1319 // Oh hey, a binding that makes sense for once? (because LLVM’s own do not)
1320 extern "C" LLVMValueRef LLVMRustBuildIntCast(LLVMBuilderRef B, LLVMValueRef Val,
1321 LLVMTypeRef DestTy, bool isSigned) {
1322 return wrap(unwrap(B)->CreateIntCast(unwrap(Val), unwrap(DestTy), isSigned, ""));
1325 extern "C" void LLVMRustSetVisibility(LLVMValueRef V,
1326 LLVMRustVisibility RustVisibility) {
1327 LLVMSetVisibility(V, fromRust(RustVisibility));
1330 struct LLVMRustModuleBuffer {
1334 extern "C" LLVMRustModuleBuffer*
1335 LLVMRustModuleBufferCreate(LLVMModuleRef M) {
1336 auto Ret = llvm::make_unique<LLVMRustModuleBuffer>();
1338 raw_string_ostream OS(Ret->data);
1340 legacy::PassManager PM;
1341 PM.add(createBitcodeWriterPass(OS));
1345 return Ret.release();
1349 LLVMRustModuleBufferFree(LLVMRustModuleBuffer *Buffer) {
1353 extern "C" const void*
1354 LLVMRustModuleBufferPtr(const LLVMRustModuleBuffer *Buffer) {
1355 return Buffer->data.data();
1359 LLVMRustModuleBufferLen(const LLVMRustModuleBuffer *Buffer) {
1360 return Buffer->data.length();
1364 LLVMRustModuleCost(LLVMModuleRef M) {
1365 auto f = unwrap(M)->functions();
1366 return std::distance(std::begin(f), std::end(f));
1369 // Vector reductions:
1370 #if LLVM_VERSION_GE(5, 0)
1371 extern "C" LLVMValueRef
1372 LLVMRustBuildVectorReduceFAdd(LLVMBuilderRef B, LLVMValueRef Acc, LLVMValueRef Src) {
1373 return wrap(unwrap(B)->CreateFAddReduce(unwrap(Acc),unwrap(Src)));
1375 extern "C" LLVMValueRef
1376 LLVMRustBuildVectorReduceFMul(LLVMBuilderRef B, LLVMValueRef Acc, LLVMValueRef Src) {
1377 return wrap(unwrap(B)->CreateFMulReduce(unwrap(Acc),unwrap(Src)));
1379 extern "C" LLVMValueRef
1380 LLVMRustBuildVectorReduceAdd(LLVMBuilderRef B, LLVMValueRef Src) {
1381 return wrap(unwrap(B)->CreateAddReduce(unwrap(Src)));
1383 extern "C" LLVMValueRef
1384 LLVMRustBuildVectorReduceMul(LLVMBuilderRef B, LLVMValueRef Src) {
1385 return wrap(unwrap(B)->CreateMulReduce(unwrap(Src)));
1387 extern "C" LLVMValueRef
1388 LLVMRustBuildVectorReduceAnd(LLVMBuilderRef B, LLVMValueRef Src) {
1389 return wrap(unwrap(B)->CreateAndReduce(unwrap(Src)));
1391 extern "C" LLVMValueRef
1392 LLVMRustBuildVectorReduceOr(LLVMBuilderRef B, LLVMValueRef Src) {
1393 return wrap(unwrap(B)->CreateOrReduce(unwrap(Src)));
1395 extern "C" LLVMValueRef
1396 LLVMRustBuildVectorReduceXor(LLVMBuilderRef B, LLVMValueRef Src) {
1397 return wrap(unwrap(B)->CreateXorReduce(unwrap(Src)));
1399 extern "C" LLVMValueRef
1400 LLVMRustBuildVectorReduceMin(LLVMBuilderRef B, LLVMValueRef Src, bool IsSigned) {
1401 return wrap(unwrap(B)->CreateIntMinReduce(unwrap(Src), IsSigned));
1403 extern "C" LLVMValueRef
1404 LLVMRustBuildVectorReduceMax(LLVMBuilderRef B, LLVMValueRef Src, bool IsSigned) {
1405 return wrap(unwrap(B)->CreateIntMaxReduce(unwrap(Src), IsSigned));
1407 extern "C" LLVMValueRef
1408 LLVMRustBuildVectorReduceFMin(LLVMBuilderRef B, LLVMValueRef Src, bool NoNaN) {
1409 return wrap(unwrap(B)->CreateFPMinReduce(unwrap(Src), NoNaN));
1411 extern "C" LLVMValueRef
1412 LLVMRustBuildVectorReduceFMax(LLVMBuilderRef B, LLVMValueRef Src, bool NoNaN) {
1413 return wrap(unwrap(B)->CreateFPMaxReduce(unwrap(Src), NoNaN));
1418 extern "C" LLVMValueRef
1419 LLVMRustBuildVectorReduceFAdd(LLVMBuilderRef, LLVMValueRef, LLVMValueRef) {
1422 extern "C" LLVMValueRef
1423 LLVMRustBuildVectorReduceFMul(LLVMBuilderRef, LLVMValueRef, LLVMValueRef) {
1426 extern "C" LLVMValueRef
1427 LLVMRustBuildVectorReduceAdd(LLVMBuilderRef, LLVMValueRef) {
1430 extern "C" LLVMValueRef
1431 LLVMRustBuildVectorReduceMul(LLVMBuilderRef, LLVMValueRef) {
1434 extern "C" LLVMValueRef
1435 LLVMRustBuildVectorReduceAnd(LLVMBuilderRef, LLVMValueRef) {
1438 extern "C" LLVMValueRef
1439 LLVMRustBuildVectorReduceOr(LLVMBuilderRef, LLVMValueRef) {
1442 extern "C" LLVMValueRef
1443 LLVMRustBuildVectorReduceXor(LLVMBuilderRef, LLVMValueRef) {
1446 extern "C" LLVMValueRef
1447 LLVMRustBuildVectorReduceMin(LLVMBuilderRef, LLVMValueRef, bool) {
1450 extern "C" LLVMValueRef
1451 LLVMRustBuildVectorReduceMax(LLVMBuilderRef, LLVMValueRef, bool) {
1454 extern "C" LLVMValueRef
1455 LLVMRustBuildVectorReduceFMin(LLVMBuilderRef, LLVMValueRef, bool) {
1458 extern "C" LLVMValueRef
1459 LLVMRustBuildVectorReduceFMax(LLVMBuilderRef, LLVMValueRef, bool) {
1464 #if LLVM_VERSION_LT(4, 0)
1465 extern "C" LLVMValueRef
1466 LLVMBuildExactUDiv(LLVMBuilderRef B, LLVMValueRef LHS,
1467 LLVMValueRef RHS, const char *Name) {
1468 return wrap(unwrap(B)->CreateExactUDiv(unwrap(LHS), unwrap(RHS), Name));
1472 #if LLVM_VERSION_GE(6, 0)
1473 extern "C" LLVMValueRef
1474 LLVMRustBuildMinNum(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS) {
1475 return wrap(unwrap(B)->CreateMinNum(unwrap(LHS),unwrap(RHS)));
1477 extern "C" LLVMValueRef
1478 LLVMRustBuildMaxNum(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS) {
1479 return wrap(unwrap(B)->CreateMaxNum(unwrap(LHS),unwrap(RHS)));
1482 extern "C" LLVMValueRef
1483 LLVMRustBuildMinNum(LLVMBuilderRef, LLVMValueRef, LLVMValueRef) {
1486 extern "C" LLVMValueRef
1487 LLVMRustBuildMaxNum(LLVMBuilderRef, LLVMValueRef, LLVMValueRef) {