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"
19 #include "llvm/IR/CallSite.h"
21 //===----------------------------------------------------------------------===
23 // This file defines alternate interfaces to core functions that are more
24 // readily callable by Rust's FFI.
26 //===----------------------------------------------------------------------===
29 using namespace llvm::sys;
30 using namespace llvm::object;
32 // LLVMAtomicOrdering is already an enum - don't create another
34 static AtomicOrdering fromRust(LLVMAtomicOrdering Ordering) {
36 case LLVMAtomicOrderingNotAtomic:
37 return AtomicOrdering::NotAtomic;
38 case LLVMAtomicOrderingUnordered:
39 return AtomicOrdering::Unordered;
40 case LLVMAtomicOrderingMonotonic:
41 return AtomicOrdering::Monotonic;
42 case LLVMAtomicOrderingAcquire:
43 return AtomicOrdering::Acquire;
44 case LLVMAtomicOrderingRelease:
45 return AtomicOrdering::Release;
46 case LLVMAtomicOrderingAcquireRelease:
47 return AtomicOrdering::AcquireRelease;
48 case LLVMAtomicOrderingSequentiallyConsistent:
49 return AtomicOrdering::SequentiallyConsistent;
52 llvm_unreachable("Invalid LLVMAtomicOrdering value!");
55 static char *LastError;
57 extern "C" LLVMMemoryBufferRef
58 LLVMRustCreateMemoryBufferWithContentsOfFile(const char *Path) {
59 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOr =
60 MemoryBuffer::getFile(Path, -1, false);
62 LLVMRustSetLastError(BufOr.getError().message().c_str());
65 return wrap(BufOr.get().release());
68 extern "C" char *LLVMRustGetLastError(void) {
69 char *Ret = LastError;
74 void LLVMRustSetLastError(const char *Err) {
75 free((void *)LastError);
76 LastError = strdup(Err);
79 extern "C" void LLVMRustSetNormalizedTarget(LLVMModuleRef M,
81 unwrap(M)->setTargetTriple(Triple::normalize(Triple));
84 extern "C" void LLVMRustPrintPassTimings() {
85 raw_fd_ostream OS(2, false); // stderr.
86 TimerGroup::printAll(OS);
89 extern "C" LLVMValueRef LLVMRustGetNamedValue(LLVMModuleRef M,
91 return wrap(unwrap(M)->getNamedValue(Name));
94 extern "C" LLVMValueRef LLVMRustGetOrInsertFunction(LLVMModuleRef M,
96 LLVMTypeRef FunctionTy) {
98 unwrap(M)->getOrInsertFunction(Name, unwrap<FunctionType>(FunctionTy)));
101 extern "C" LLVMValueRef
102 LLVMRustGetOrInsertGlobal(LLVMModuleRef M, const char *Name, LLVMTypeRef Ty) {
103 return wrap(unwrap(M)->getOrInsertGlobal(Name, unwrap(Ty)));
106 extern "C" LLVMTypeRef LLVMRustMetadataTypeInContext(LLVMContextRef C) {
107 return wrap(Type::getMetadataTy(*unwrap(C)));
110 static Attribute::AttrKind fromRust(LLVMRustAttribute Kind) {
113 return Attribute::AlwaysInline;
115 return Attribute::ByVal;
117 return Attribute::Cold;
119 return Attribute::InlineHint;
121 return Attribute::MinSize;
123 return Attribute::Naked;
125 return Attribute::NoAlias;
127 return Attribute::NoCapture;
129 return Attribute::NoInline;
131 return Attribute::NonNull;
133 return Attribute::NoRedZone;
135 return Attribute::NoReturn;
137 return Attribute::NoUnwind;
138 case OptimizeForSize:
139 return Attribute::OptimizeForSize;
141 return Attribute::ReadOnly;
143 return Attribute::SExt;
145 return Attribute::StructRet;
147 return Attribute::UWTable;
149 return Attribute::ZExt;
151 return Attribute::InReg;
153 return Attribute::SanitizeThread;
154 case SanitizeAddress:
155 return Attribute::SanitizeAddress;
157 return Attribute::SanitizeMemory;
159 llvm_unreachable("bad AttributeKind");
162 extern "C" void LLVMRustAddCallSiteAttribute(LLVMValueRef Instr, unsigned Index,
163 LLVMRustAttribute RustAttr) {
164 CallSite Call = CallSite(unwrap<Instruction>(Instr));
165 Attribute Attr = Attribute::get(Call->getContext(), fromRust(RustAttr));
167 Call.setAttributes(Call.getAttributes().addAttributes(
168 Call->getContext(), Index,
169 AttributeSet::get(Call->getContext(), Index, B)));
172 extern "C" void LLVMRustAddDereferenceableCallSiteAttr(LLVMValueRef Instr,
175 CallSite Call = CallSite(unwrap<Instruction>(Instr));
177 B.addDereferenceableAttr(Bytes);
178 Call.setAttributes(Call.getAttributes().addAttributes(
179 Call->getContext(), Index,
180 AttributeSet::get(Call->getContext(), Index, B)));
183 extern "C" void LLVMRustAddFunctionAttribute(LLVMValueRef Fn, unsigned Index,
184 LLVMRustAttribute RustAttr) {
185 Function *A = unwrap<Function>(Fn);
186 Attribute Attr = Attribute::get(A->getContext(), fromRust(RustAttr));
188 A->addAttributes(Index, AttributeSet::get(A->getContext(), Index, B));
191 extern "C" void LLVMRustAddDereferenceableAttr(LLVMValueRef Fn, unsigned Index,
193 Function *A = unwrap<Function>(Fn);
195 B.addDereferenceableAttr(Bytes);
196 A->addAttributes(Index, AttributeSet::get(A->getContext(), Index, B));
199 extern "C" void LLVMRustAddFunctionAttrStringValue(LLVMValueRef Fn,
203 Function *F = unwrap<Function>(Fn);
205 B.addAttribute(Name, Value);
206 F->addAttributes(Index, AttributeSet::get(F->getContext(), Index, B));
209 extern "C" void LLVMRustRemoveFunctionAttributes(LLVMValueRef Fn,
211 LLVMRustAttribute RustAttr) {
212 Function *F = unwrap<Function>(Fn);
213 const AttributeSet PAL = F->getAttributes();
214 Attribute Attr = Attribute::get(F->getContext(), fromRust(RustAttr));
216 const AttributeSet PALNew = PAL.removeAttributes(
217 F->getContext(), Index, AttributeSet::get(F->getContext(), Index, B));
218 F->setAttributes(PALNew);
221 // enable fpmath flag UnsafeAlgebra
222 extern "C" void LLVMRustSetHasUnsafeAlgebra(LLVMValueRef V) {
223 if (auto I = dyn_cast<Instruction>(unwrap<Value>(V))) {
224 I->setHasUnsafeAlgebra(true);
228 extern "C" LLVMValueRef
229 LLVMRustBuildAtomicLoad(LLVMBuilderRef B, LLVMValueRef Source, const char *Name,
230 LLVMAtomicOrdering Order, unsigned Alignment) {
231 LoadInst *LI = new LoadInst(unwrap(Source), 0);
232 LI->setAtomic(fromRust(Order));
233 LI->setAlignment(Alignment);
234 return wrap(unwrap(B)->Insert(LI, Name));
237 extern "C" LLVMValueRef LLVMRustBuildAtomicStore(LLVMBuilderRef B,
240 LLVMAtomicOrdering Order,
241 unsigned Alignment) {
242 StoreInst *SI = new StoreInst(unwrap(V), unwrap(Target));
243 SI->setAtomic(fromRust(Order));
244 SI->setAlignment(Alignment);
245 return wrap(unwrap(B)->Insert(SI));
248 extern "C" LLVMValueRef
249 LLVMRustBuildAtomicCmpXchg(LLVMBuilderRef B, LLVMValueRef Target,
250 LLVMValueRef Old, LLVMValueRef Source,
251 LLVMAtomicOrdering Order,
252 LLVMAtomicOrdering FailureOrder, LLVMBool Weak) {
253 AtomicCmpXchgInst *ACXI = unwrap(B)->CreateAtomicCmpXchg(
254 unwrap(Target), unwrap(Old), unwrap(Source), fromRust(Order),
255 fromRust(FailureOrder));
260 enum class LLVMRustSynchronizationScope {
266 static SynchronizationScope fromRust(LLVMRustSynchronizationScope Scope) {
268 case LLVMRustSynchronizationScope::SingleThread:
270 case LLVMRustSynchronizationScope::CrossThread:
273 llvm_unreachable("bad SynchronizationScope.");
277 extern "C" LLVMValueRef
278 LLVMRustBuildAtomicFence(LLVMBuilderRef B, LLVMAtomicOrdering Order,
279 LLVMRustSynchronizationScope Scope) {
280 return wrap(unwrap(B)->CreateFence(fromRust(Order), fromRust(Scope)));
283 extern "C" void LLVMRustSetDebug(int Enabled) {
289 enum class LLVMRustAsmDialect {
295 static InlineAsm::AsmDialect fromRust(LLVMRustAsmDialect Dialect) {
297 case LLVMRustAsmDialect::Att:
298 return InlineAsm::AD_ATT;
299 case LLVMRustAsmDialect::Intel:
300 return InlineAsm::AD_Intel;
302 llvm_unreachable("bad AsmDialect.");
306 extern "C" LLVMValueRef LLVMRustInlineAsm(LLVMTypeRef Ty, char *AsmString,
308 LLVMBool HasSideEffects,
309 LLVMBool IsAlignStack,
310 LLVMRustAsmDialect Dialect) {
311 return wrap(InlineAsm::get(unwrap<FunctionType>(Ty), AsmString, Constraints,
312 HasSideEffects, IsAlignStack, fromRust(Dialect)));
315 extern "C" void LLVMRustAppendModuleInlineAsm(LLVMModuleRef M, const char *Asm) {
316 unwrap(M)->appendModuleInlineAsm(StringRef(Asm));
319 typedef DIBuilder *LLVMRustDIBuilderRef;
321 typedef struct LLVMOpaqueMetadata *LLVMRustMetadataRef;
324 DEFINE_ISA_CONVERSION_FUNCTIONS(Metadata, LLVMRustMetadataRef)
326 inline Metadata **unwrap(LLVMRustMetadataRef *Vals) {
327 return reinterpret_cast<Metadata **>(Vals);
331 template <typename DIT> DIT *unwrapDIPtr(LLVMRustMetadataRef Ref) {
332 return (DIT *)(Ref ? unwrap<MDNode>(Ref) : nullptr);
335 #define DIDescriptor DIScope
336 #define DIArray DINodeArray
337 #define unwrapDI unwrapDIPtr
339 // These values **must** match debuginfo::DIFlags! They also *happen*
340 // to match LLVM, but that isn't required as we do giant sets of
341 // matching below. The value shouldn't be directly passed to LLVM.
342 enum class LLVMRustDIFlags : uint32_t {
347 FlagFwdDecl = (1 << 2),
348 FlagAppleBlock = (1 << 3),
349 FlagBlockByrefStruct = (1 << 4),
350 FlagVirtual = (1 << 5),
351 FlagArtificial = (1 << 6),
352 FlagExplicit = (1 << 7),
353 FlagPrototyped = (1 << 8),
354 FlagObjcClassComplete = (1 << 9),
355 FlagObjectPointer = (1 << 10),
356 FlagVector = (1 << 11),
357 FlagStaticMember = (1 << 12),
358 FlagLValueReference = (1 << 13),
359 FlagRValueReference = (1 << 14),
360 FlagMainSubprogram = (1 << 21),
361 // Do not add values that are not supported by the minimum LLVM
362 // version we support!
365 inline LLVMRustDIFlags operator&(LLVMRustDIFlags A, LLVMRustDIFlags B) {
366 return static_cast<LLVMRustDIFlags>(static_cast<uint32_t>(A) &
367 static_cast<uint32_t>(B));
370 inline LLVMRustDIFlags operator|(LLVMRustDIFlags A, LLVMRustDIFlags B) {
371 return static_cast<LLVMRustDIFlags>(static_cast<uint32_t>(A) |
372 static_cast<uint32_t>(B));
375 inline LLVMRustDIFlags &operator|=(LLVMRustDIFlags &A, LLVMRustDIFlags B) {
379 inline bool isSet(LLVMRustDIFlags F) { return F != LLVMRustDIFlags::FlagZero; }
381 inline LLVMRustDIFlags visibility(LLVMRustDIFlags F) {
382 return static_cast<LLVMRustDIFlags>(static_cast<uint32_t>(F) & 0x3);
385 #if LLVM_VERSION_GE(4, 0)
386 static DINode::DIFlags fromRust(LLVMRustDIFlags Flags) {
387 DINode::DIFlags Result = DINode::DIFlags::FlagZero;
389 static unsigned fromRust(LLVMRustDIFlags Flags) {
393 switch (visibility(Flags)) {
394 case LLVMRustDIFlags::FlagPrivate:
395 Result |= DINode::DIFlags::FlagPrivate;
397 case LLVMRustDIFlags::FlagProtected:
398 Result |= DINode::DIFlags::FlagProtected;
400 case LLVMRustDIFlags::FlagPublic:
401 Result |= DINode::DIFlags::FlagPublic;
404 // The rest are handled below
408 if (isSet(Flags & LLVMRustDIFlags::FlagFwdDecl)) {
409 Result |= DINode::DIFlags::FlagFwdDecl;
411 if (isSet(Flags & LLVMRustDIFlags::FlagAppleBlock)) {
412 Result |= DINode::DIFlags::FlagAppleBlock;
414 if (isSet(Flags & LLVMRustDIFlags::FlagBlockByrefStruct)) {
415 Result |= DINode::DIFlags::FlagBlockByrefStruct;
417 if (isSet(Flags & LLVMRustDIFlags::FlagVirtual)) {
418 Result |= DINode::DIFlags::FlagVirtual;
420 if (isSet(Flags & LLVMRustDIFlags::FlagArtificial)) {
421 Result |= DINode::DIFlags::FlagArtificial;
423 if (isSet(Flags & LLVMRustDIFlags::FlagExplicit)) {
424 Result |= DINode::DIFlags::FlagExplicit;
426 if (isSet(Flags & LLVMRustDIFlags::FlagPrototyped)) {
427 Result |= DINode::DIFlags::FlagPrototyped;
429 if (isSet(Flags & LLVMRustDIFlags::FlagObjcClassComplete)) {
430 Result |= DINode::DIFlags::FlagObjcClassComplete;
432 if (isSet(Flags & LLVMRustDIFlags::FlagObjectPointer)) {
433 Result |= DINode::DIFlags::FlagObjectPointer;
435 if (isSet(Flags & LLVMRustDIFlags::FlagVector)) {
436 Result |= DINode::DIFlags::FlagVector;
438 if (isSet(Flags & LLVMRustDIFlags::FlagStaticMember)) {
439 Result |= DINode::DIFlags::FlagStaticMember;
441 if (isSet(Flags & LLVMRustDIFlags::FlagLValueReference)) {
442 Result |= DINode::DIFlags::FlagLValueReference;
444 if (isSet(Flags & LLVMRustDIFlags::FlagRValueReference)) {
445 Result |= DINode::DIFlags::FlagRValueReference;
447 #if LLVM_RUSTLLVM || LLVM_VERSION_GE(4, 0)
448 if (isSet(Flags & LLVMRustDIFlags::FlagMainSubprogram)) {
449 Result |= DINode::DIFlags::FlagMainSubprogram;
456 extern "C" uint32_t LLVMRustDebugMetadataVersion() {
457 return DEBUG_METADATA_VERSION;
460 extern "C" uint32_t LLVMRustVersionMinor() { return LLVM_VERSION_MINOR; }
462 extern "C" uint32_t LLVMRustVersionMajor() { return LLVM_VERSION_MAJOR; }
464 extern "C" void LLVMRustAddModuleFlag(LLVMModuleRef M, const char *Name,
466 unwrap(M)->addModuleFlag(Module::Warning, Name, Value);
469 extern "C" LLVMRustDIBuilderRef LLVMRustDIBuilderCreate(LLVMModuleRef M) {
470 return new DIBuilder(*unwrap(M));
473 extern "C" void LLVMRustDIBuilderDispose(LLVMRustDIBuilderRef Builder) {
477 extern "C" void LLVMRustDIBuilderFinalize(LLVMRustDIBuilderRef Builder) {
481 extern "C" LLVMRustMetadataRef LLVMRustDIBuilderCreateCompileUnit(
482 LLVMRustDIBuilderRef Builder, unsigned Lang, LLVMRustMetadataRef FileRef,
483 const char *Producer, bool isOptimized, const char *Flags,
484 unsigned RuntimeVer, const char *SplitName) {
485 auto *File = unwrapDI<DIFile>(FileRef);
487 #if LLVM_VERSION_GE(4, 0)
488 return wrap(Builder->createCompileUnit(Lang, File, Producer, isOptimized,
489 Flags, RuntimeVer, SplitName));
491 return wrap(Builder->createCompileUnit(Lang, File->getFilename(),
492 File->getDirectory(), Producer, isOptimized,
493 Flags, RuntimeVer, SplitName));
497 extern "C" LLVMRustMetadataRef
498 LLVMRustDIBuilderCreateFile(LLVMRustDIBuilderRef Builder, const char *Filename,
499 const char *Directory) {
500 return wrap(Builder->createFile(Filename, Directory));
503 extern "C" LLVMRustMetadataRef
504 LLVMRustDIBuilderCreateSubroutineType(LLVMRustDIBuilderRef Builder,
505 LLVMRustMetadataRef File,
506 LLVMRustMetadataRef ParameterTypes) {
507 return wrap(Builder->createSubroutineType(
508 #if LLVM_VERSION_EQ(3, 7)
509 unwrapDI<DIFile>(File),
511 DITypeRefArray(unwrap<MDTuple>(ParameterTypes))));
514 extern "C" LLVMRustMetadataRef LLVMRustDIBuilderCreateFunction(
515 LLVMRustDIBuilderRef Builder, LLVMRustMetadataRef Scope, const char *Name,
516 const char *LinkageName, LLVMRustMetadataRef File, unsigned LineNo,
517 LLVMRustMetadataRef Ty, bool IsLocalToUnit, bool IsDefinition,
518 unsigned ScopeLine, LLVMRustDIFlags Flags, bool IsOptimized,
519 LLVMValueRef Fn, LLVMRustMetadataRef TParam, LLVMRustMetadataRef Decl) {
520 #if LLVM_VERSION_GE(3, 8)
521 DITemplateParameterArray TParams =
522 DITemplateParameterArray(unwrap<MDTuple>(TParam));
523 DISubprogram *Sub = Builder->createFunction(
524 unwrapDI<DIScope>(Scope), Name, LinkageName, unwrapDI<DIFile>(File),
525 LineNo, unwrapDI<DISubroutineType>(Ty), IsLocalToUnit, IsDefinition,
526 ScopeLine, fromRust(Flags), IsOptimized, TParams,
527 unwrapDIPtr<DISubprogram>(Decl));
528 unwrap<Function>(Fn)->setSubprogram(Sub);
531 return wrap(Builder->createFunction(
532 unwrapDI<DIScope>(Scope), Name, LinkageName, unwrapDI<DIFile>(File),
533 LineNo, unwrapDI<DISubroutineType>(Ty), IsLocalToUnit, IsDefinition,
534 ScopeLine, fromRust(Flags), IsOptimized, unwrap<Function>(Fn),
535 unwrapDIPtr<MDNode>(TParam), unwrapDIPtr<MDNode>(Decl)));
539 extern "C" LLVMRustMetadataRef
540 LLVMRustDIBuilderCreateBasicType(LLVMRustDIBuilderRef Builder, const char *Name,
541 uint64_t SizeInBits, uint32_t AlignInBits,
543 return wrap(Builder->createBasicType(Name, SizeInBits,
544 #if LLVM_VERSION_LE(3, 9)
550 extern "C" LLVMRustMetadataRef LLVMRustDIBuilderCreatePointerType(
551 LLVMRustDIBuilderRef Builder, LLVMRustMetadataRef PointeeTy,
552 uint64_t SizeInBits, uint32_t AlignInBits, const char *Name) {
553 return wrap(Builder->createPointerType(unwrapDI<DIType>(PointeeTy),
554 SizeInBits, AlignInBits, Name));
557 extern "C" LLVMRustMetadataRef LLVMRustDIBuilderCreateStructType(
558 LLVMRustDIBuilderRef Builder, LLVMRustMetadataRef Scope, const char *Name,
559 LLVMRustMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
560 uint32_t AlignInBits, LLVMRustDIFlags Flags,
561 LLVMRustMetadataRef DerivedFrom, LLVMRustMetadataRef Elements,
562 unsigned RunTimeLang, LLVMRustMetadataRef VTableHolder,
563 const char *UniqueId) {
564 return wrap(Builder->createStructType(
565 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNumber,
566 SizeInBits, AlignInBits, fromRust(Flags), unwrapDI<DIType>(DerivedFrom),
567 DINodeArray(unwrapDI<MDTuple>(Elements)), RunTimeLang,
568 unwrapDI<DIType>(VTableHolder), UniqueId));
571 extern "C" LLVMRustMetadataRef LLVMRustDIBuilderCreateMemberType(
572 LLVMRustDIBuilderRef Builder, LLVMRustMetadataRef Scope, const char *Name,
573 LLVMRustMetadataRef File, unsigned LineNo, uint64_t SizeInBits,
574 uint32_t AlignInBits, uint64_t OffsetInBits, LLVMRustDIFlags Flags,
575 LLVMRustMetadataRef Ty) {
576 return wrap(Builder->createMemberType(unwrapDI<DIDescriptor>(Scope), Name,
577 unwrapDI<DIFile>(File), LineNo,
578 SizeInBits, AlignInBits, OffsetInBits,
579 fromRust(Flags), unwrapDI<DIType>(Ty)));
582 extern "C" LLVMRustMetadataRef LLVMRustDIBuilderCreateLexicalBlock(
583 LLVMRustDIBuilderRef Builder, LLVMRustMetadataRef Scope,
584 LLVMRustMetadataRef File, unsigned Line, unsigned Col) {
585 return wrap(Builder->createLexicalBlock(unwrapDI<DIDescriptor>(Scope),
586 unwrapDI<DIFile>(File), Line, Col));
589 extern "C" LLVMRustMetadataRef
590 LLVMRustDIBuilderCreateLexicalBlockFile(LLVMRustDIBuilderRef Builder,
591 LLVMRustMetadataRef Scope,
592 LLVMRustMetadataRef File) {
593 return wrap(Builder->createLexicalBlockFile(unwrapDI<DIDescriptor>(Scope),
594 unwrapDI<DIFile>(File)));
597 extern "C" LLVMRustMetadataRef LLVMRustDIBuilderCreateStaticVariable(
598 LLVMRustDIBuilderRef Builder, LLVMRustMetadataRef Context, const char *Name,
599 const char *LinkageName, LLVMRustMetadataRef File, unsigned LineNo,
600 LLVMRustMetadataRef Ty, bool IsLocalToUnit, LLVMValueRef V,
601 LLVMRustMetadataRef Decl = nullptr, uint32_t AlignInBits = 0) {
602 llvm::GlobalVariable *InitVal = cast<llvm::GlobalVariable>(unwrap(V));
604 #if LLVM_VERSION_GE(4, 0)
605 llvm::DIExpression *InitExpr = nullptr;
606 if (llvm::ConstantInt *IntVal = llvm::dyn_cast<llvm::ConstantInt>(InitVal)) {
607 InitExpr = Builder->createConstantValueExpression(
608 IntVal->getValue().getSExtValue());
609 } else if (llvm::ConstantFP *FPVal =
610 llvm::dyn_cast<llvm::ConstantFP>(InitVal)) {
611 InitExpr = Builder->createConstantValueExpression(
612 FPVal->getValueAPF().bitcastToAPInt().getZExtValue());
615 llvm::DIGlobalVariableExpression *VarExpr = Builder->createGlobalVariableExpression(
616 unwrapDI<DIDescriptor>(Context), Name, LinkageName,
617 unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), IsLocalToUnit,
618 InitExpr, unwrapDIPtr<MDNode>(Decl), AlignInBits);
620 InitVal->setMetadata("dbg", VarExpr);
622 return wrap(VarExpr);
624 return wrap(Builder->createGlobalVariable(
625 unwrapDI<DIDescriptor>(Context), Name, LinkageName,
626 unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), IsLocalToUnit,
627 InitVal, unwrapDIPtr<MDNode>(Decl)));
631 extern "C" LLVMRustMetadataRef LLVMRustDIBuilderCreateVariable(
632 LLVMRustDIBuilderRef Builder, unsigned Tag, LLVMRustMetadataRef Scope,
633 const char *Name, LLVMRustMetadataRef File, unsigned LineNo,
634 LLVMRustMetadataRef Ty, bool AlwaysPreserve, LLVMRustDIFlags Flags,
635 unsigned ArgNo, uint32_t AlignInBits) {
636 #if LLVM_VERSION_GE(3, 8)
637 if (Tag == 0x100) { // DW_TAG_auto_variable
638 return wrap(Builder->createAutoVariable(
639 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNo,
640 unwrapDI<DIType>(Ty), AlwaysPreserve, fromRust(Flags)
641 #if LLVM_VERSION_GE(4, 0)
647 return wrap(Builder->createParameterVariable(
648 unwrapDI<DIDescriptor>(Scope), Name, ArgNo, unwrapDI<DIFile>(File),
649 LineNo, unwrapDI<DIType>(Ty), AlwaysPreserve, fromRust(Flags)));
652 return wrap(Builder->createLocalVariable(
653 Tag, unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNo,
654 unwrapDI<DIType>(Ty), AlwaysPreserve, fromRust(Flags), ArgNo));
658 extern "C" LLVMRustMetadataRef
659 LLVMRustDIBuilderCreateArrayType(LLVMRustDIBuilderRef Builder, uint64_t Size,
660 uint32_t AlignInBits, LLVMRustMetadataRef Ty,
661 LLVMRustMetadataRef Subscripts) {
663 Builder->createArrayType(Size, AlignInBits, unwrapDI<DIType>(Ty),
664 DINodeArray(unwrapDI<MDTuple>(Subscripts))));
667 extern "C" LLVMRustMetadataRef
668 LLVMRustDIBuilderCreateVectorType(LLVMRustDIBuilderRef Builder, uint64_t Size,
669 uint32_t AlignInBits, LLVMRustMetadataRef Ty,
670 LLVMRustMetadataRef Subscripts) {
672 Builder->createVectorType(Size, AlignInBits, unwrapDI<DIType>(Ty),
673 DINodeArray(unwrapDI<MDTuple>(Subscripts))));
676 extern "C" LLVMRustMetadataRef
677 LLVMRustDIBuilderGetOrCreateSubrange(LLVMRustDIBuilderRef Builder, int64_t Lo,
679 return wrap(Builder->getOrCreateSubrange(Lo, Count));
682 extern "C" LLVMRustMetadataRef
683 LLVMRustDIBuilderGetOrCreateArray(LLVMRustDIBuilderRef Builder,
684 LLVMRustMetadataRef *Ptr, unsigned Count) {
685 Metadata **DataValue = unwrap(Ptr);
687 Builder->getOrCreateArray(ArrayRef<Metadata *>(DataValue, Count)).get());
690 extern "C" LLVMValueRef LLVMRustDIBuilderInsertDeclareAtEnd(
691 LLVMRustDIBuilderRef Builder, LLVMValueRef V, LLVMRustMetadataRef VarInfo,
692 int64_t *AddrOps, unsigned AddrOpsCount, LLVMValueRef DL,
693 LLVMBasicBlockRef InsertAtEnd) {
694 return wrap(Builder->insertDeclare(
695 unwrap(V), unwrap<DILocalVariable>(VarInfo),
696 Builder->createExpression(llvm::ArrayRef<int64_t>(AddrOps, AddrOpsCount)),
697 DebugLoc(cast<MDNode>(unwrap<MetadataAsValue>(DL)->getMetadata())),
698 unwrap(InsertAtEnd)));
701 extern "C" LLVMRustMetadataRef
702 LLVMRustDIBuilderCreateEnumerator(LLVMRustDIBuilderRef Builder,
703 const char *Name, uint64_t Val) {
704 return wrap(Builder->createEnumerator(Name, Val));
707 extern "C" LLVMRustMetadataRef LLVMRustDIBuilderCreateEnumerationType(
708 LLVMRustDIBuilderRef Builder, LLVMRustMetadataRef Scope, const char *Name,
709 LLVMRustMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
710 uint32_t AlignInBits, LLVMRustMetadataRef Elements,
711 LLVMRustMetadataRef ClassTy) {
712 return wrap(Builder->createEnumerationType(
713 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNumber,
714 SizeInBits, AlignInBits, DINodeArray(unwrapDI<MDTuple>(Elements)),
715 unwrapDI<DIType>(ClassTy)));
718 extern "C" LLVMRustMetadataRef LLVMRustDIBuilderCreateUnionType(
719 LLVMRustDIBuilderRef Builder, LLVMRustMetadataRef Scope, const char *Name,
720 LLVMRustMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
721 uint32_t AlignInBits, LLVMRustDIFlags Flags, LLVMRustMetadataRef Elements,
722 unsigned RunTimeLang, const char *UniqueId) {
723 return wrap(Builder->createUnionType(
724 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNumber,
725 SizeInBits, AlignInBits, fromRust(Flags),
726 DINodeArray(unwrapDI<MDTuple>(Elements)), RunTimeLang, UniqueId));
729 extern "C" LLVMRustMetadataRef LLVMRustDIBuilderCreateTemplateTypeParameter(
730 LLVMRustDIBuilderRef Builder, LLVMRustMetadataRef Scope, const char *Name,
731 LLVMRustMetadataRef Ty, LLVMRustMetadataRef File, unsigned LineNo,
733 return wrap(Builder->createTemplateTypeParameter(
734 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIType>(Ty)));
737 extern "C" LLVMRustMetadataRef
738 LLVMRustDIBuilderCreateNameSpace(LLVMRustDIBuilderRef Builder,
739 LLVMRustMetadataRef Scope, const char *Name,
740 LLVMRustMetadataRef File, unsigned LineNo) {
741 return wrap(Builder->createNameSpace(
742 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNo
743 #if LLVM_VERSION_GE(4, 0)
745 false // ExportSymbols (only relevant for C++ anonymous namespaces)
751 LLVMRustDICompositeTypeSetTypeArray(LLVMRustDIBuilderRef Builder,
752 LLVMRustMetadataRef CompositeTy,
753 LLVMRustMetadataRef TyArray) {
754 DICompositeType *Tmp = unwrapDI<DICompositeType>(CompositeTy);
755 Builder->replaceArrays(Tmp, DINodeArray(unwrap<MDTuple>(TyArray)));
758 extern "C" LLVMValueRef
759 LLVMRustDIBuilderCreateDebugLocation(LLVMContextRef ContextRef, unsigned Line,
760 unsigned Column, LLVMRustMetadataRef Scope,
761 LLVMRustMetadataRef InlinedAt) {
762 LLVMContext &Context = *unwrap(ContextRef);
764 DebugLoc debug_loc = DebugLoc::get(Line, Column, unwrapDIPtr<MDNode>(Scope),
765 unwrapDIPtr<MDNode>(InlinedAt));
767 return wrap(MetadataAsValue::get(Context, debug_loc.getAsMDNode()));
770 extern "C" int64_t LLVMRustDIBuilderCreateOpDeref() {
771 return dwarf::DW_OP_deref;
774 extern "C" int64_t LLVMRustDIBuilderCreateOpPlus() { return dwarf::DW_OP_plus; }
776 extern "C" void LLVMRustWriteTypeToString(LLVMTypeRef Ty, RustStringRef Str) {
777 RawRustStringOstream OS(Str);
778 unwrap<llvm::Type>(Ty)->print(OS);
781 extern "C" void LLVMRustWriteValueToString(LLVMValueRef V,
783 RawRustStringOstream OS(Str);
785 unwrap<llvm::Value>(V)->getType()->print(OS);
787 unwrap<llvm::Value>(V)->print(OS);
791 extern "C" bool LLVMRustLinkInExternalBitcode(LLVMModuleRef DstRef, char *BC,
793 Module *Dst = unwrap(DstRef);
795 std::unique_ptr<MemoryBuffer> Buf =
796 MemoryBuffer::getMemBufferCopy(StringRef(BC, Len));
798 #if LLVM_VERSION_GE(4, 0)
799 Expected<std::unique_ptr<Module>> SrcOrError =
800 llvm::getLazyBitcodeModule(Buf->getMemBufferRef(), Dst->getContext());
802 LLVMRustSetLastError(toString(SrcOrError.takeError()).c_str());
806 auto Src = std::move(*SrcOrError);
808 ErrorOr<std::unique_ptr<Module>> Src =
809 llvm::getLazyBitcodeModule(std::move(Buf), Dst->getContext());
811 LLVMRustSetLastError(Src.getError().message().c_str());
818 raw_string_ostream Stream(Err);
819 DiagnosticPrinterRawOStream DP(Stream);
820 #if LLVM_VERSION_GE(4, 0)
821 if (Linker::linkModules(*Dst, std::move(Src))) {
822 #elif LLVM_VERSION_GE(3, 8)
823 if (Linker::linkModules(*Dst, std::move(Src.get()))) {
825 if (Linker::LinkModules(Dst, Src->get(),
826 [&](const DiagnosticInfo &DI) { DI.print(DP); })) {
828 LLVMRustSetLastError(Err.c_str());
834 // Note that the two following functions look quite similar to the
835 // LLVMGetSectionName function. Sadly, it appears that this function only
836 // returns a char* pointer, which isn't guaranteed to be null-terminated. The
837 // function provided by LLVM doesn't return the length, so we've created our own
838 // function which returns the length as well as the data pointer.
840 // For an example of this not returning a null terminated string, see
841 // lib/Object/COFFObjectFile.cpp in the getSectionName function. One of the
842 // branches explicitly creates a StringRef without a null terminator, and then
845 inline section_iterator *unwrap(LLVMSectionIteratorRef SI) {
846 return reinterpret_cast<section_iterator *>(SI);
849 extern "C" size_t LLVMRustGetSectionName(LLVMSectionIteratorRef SI,
852 if (std::error_code EC = (*unwrap(SI))->getName(Ret))
853 report_fatal_error(EC.message());
858 // LLVMArrayType function does not support 64-bit ElementCount
859 extern "C" LLVMTypeRef LLVMRustArrayType(LLVMTypeRef ElementTy,
860 uint64_t ElementCount) {
861 return wrap(ArrayType::get(unwrap(ElementTy), ElementCount));
864 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Twine, LLVMTwineRef)
865 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(DebugLoc, LLVMDebugLocRef)
867 extern "C" void LLVMRustWriteTwineToString(LLVMTwineRef T, RustStringRef Str) {
868 RawRustStringOstream OS(Str);
869 unwrap(T)->print(OS);
872 extern "C" void LLVMRustUnpackOptimizationDiagnostic(
873 LLVMDiagnosticInfoRef DI, RustStringRef PassNameOut,
874 LLVMValueRef *FunctionOut, LLVMDebugLocRef *DebugLocOut,
875 RustStringRef MessageOut) {
876 // Undefined to call this not on an optimization diagnostic!
877 llvm::DiagnosticInfoOptimizationBase *Opt =
878 static_cast<llvm::DiagnosticInfoOptimizationBase *>(unwrap(DI));
880 RawRustStringOstream PassNameOS(PassNameOut);
881 PassNameOS << Opt->getPassName();
882 *FunctionOut = wrap(&Opt->getFunction());
883 *DebugLocOut = wrap(&Opt->getDebugLoc());
884 RawRustStringOstream MessageOS(MessageOut);
885 MessageOS << Opt->getMsg();
889 LLVMRustUnpackInlineAsmDiagnostic(LLVMDiagnosticInfoRef DI, unsigned *CookieOut,
890 LLVMTwineRef *MessageOut,
891 LLVMValueRef *InstructionOut) {
892 // Undefined to call this not on an inline assembly diagnostic!
893 llvm::DiagnosticInfoInlineAsm *IA =
894 static_cast<llvm::DiagnosticInfoInlineAsm *>(unwrap(DI));
896 *CookieOut = IA->getLocCookie();
897 *MessageOut = wrap(&IA->getMsgStr());
898 *InstructionOut = wrap(IA->getInstruction());
901 extern "C" void LLVMRustWriteDiagnosticInfoToString(LLVMDiagnosticInfoRef DI,
903 RawRustStringOstream OS(Str);
904 DiagnosticPrinterRawOStream DP(OS);
905 unwrap(DI)->print(DP);
908 enum class LLVMRustDiagnosticKind {
912 DebugMetadataVersion,
915 OptimizationRemarkMissed,
916 OptimizationRemarkAnalysis,
917 OptimizationRemarkAnalysisFPCommute,
918 OptimizationRemarkAnalysisAliasing,
919 OptimizationRemarkOther,
923 static LLVMRustDiagnosticKind toRust(DiagnosticKind Kind) {
926 return LLVMRustDiagnosticKind::InlineAsm;
928 return LLVMRustDiagnosticKind::StackSize;
929 case DK_DebugMetadataVersion:
930 return LLVMRustDiagnosticKind::DebugMetadataVersion;
931 case DK_SampleProfile:
932 return LLVMRustDiagnosticKind::SampleProfile;
933 case DK_OptimizationRemark:
934 return LLVMRustDiagnosticKind::OptimizationRemark;
935 case DK_OptimizationRemarkMissed:
936 return LLVMRustDiagnosticKind::OptimizationRemarkMissed;
937 case DK_OptimizationRemarkAnalysis:
938 return LLVMRustDiagnosticKind::OptimizationRemarkAnalysis;
939 #if LLVM_VERSION_GE(3, 8)
940 case DK_OptimizationRemarkAnalysisFPCommute:
941 return LLVMRustDiagnosticKind::OptimizationRemarkAnalysisFPCommute;
942 case DK_OptimizationRemarkAnalysisAliasing:
943 return LLVMRustDiagnosticKind::OptimizationRemarkAnalysisAliasing;
946 #if LLVM_VERSION_GE(3, 9)
947 return (Kind >= DK_FirstRemark && Kind <= DK_LastRemark)
948 ? LLVMRustDiagnosticKind::OptimizationRemarkOther
949 : LLVMRustDiagnosticKind::Other;
951 return LLVMRustDiagnosticKind::Other;
956 extern "C" LLVMRustDiagnosticKind
957 LLVMRustGetDiagInfoKind(LLVMDiagnosticInfoRef DI) {
958 return toRust((DiagnosticKind)unwrap(DI)->getKind());
960 // This is kept distinct from LLVMGetTypeKind, because when
961 // a new type kind is added, the Rust-side enum must be
962 // updated or UB will result.
963 extern "C" LLVMTypeKind LLVMRustGetTypeKind(LLVMTypeRef Ty) {
964 switch (unwrap(Ty)->getTypeID()) {
966 return LLVMVoidTypeKind;
968 return LLVMHalfTypeKind;
969 case Type::FloatTyID:
970 return LLVMFloatTypeKind;
971 case Type::DoubleTyID:
972 return LLVMDoubleTypeKind;
973 case Type::X86_FP80TyID:
974 return LLVMX86_FP80TypeKind;
975 case Type::FP128TyID:
976 return LLVMFP128TypeKind;
977 case Type::PPC_FP128TyID:
978 return LLVMPPC_FP128TypeKind;
979 case Type::LabelTyID:
980 return LLVMLabelTypeKind;
981 case Type::MetadataTyID:
982 return LLVMMetadataTypeKind;
983 case Type::IntegerTyID:
984 return LLVMIntegerTypeKind;
985 case Type::FunctionTyID:
986 return LLVMFunctionTypeKind;
987 case Type::StructTyID:
988 return LLVMStructTypeKind;
989 case Type::ArrayTyID:
990 return LLVMArrayTypeKind;
991 case Type::PointerTyID:
992 return LLVMPointerTypeKind;
993 case Type::VectorTyID:
994 return LLVMVectorTypeKind;
995 case Type::X86_MMXTyID:
996 return LLVMX86_MMXTypeKind;
997 #if LLVM_VERSION_GE(3, 8)
998 case Type::TokenTyID:
999 return LLVMTokenTypeKind;
1002 llvm_unreachable("Unhandled TypeID.");
1005 extern "C" void LLVMRustWriteDebugLocToString(LLVMContextRef C,
1007 RustStringRef Str) {
1008 RawRustStringOstream OS(Str);
1009 unwrap(DL)->print(OS);
1012 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(SMDiagnostic, LLVMSMDiagnosticRef)
1014 extern "C" void LLVMRustSetInlineAsmDiagnosticHandler(
1015 LLVMContextRef C, LLVMContext::InlineAsmDiagHandlerTy H, void *CX) {
1016 unwrap(C)->setInlineAsmDiagnosticHandler(H, CX);
1019 extern "C" void LLVMRustWriteSMDiagnosticToString(LLVMSMDiagnosticRef D,
1020 RustStringRef Str) {
1021 RawRustStringOstream OS(Str);
1022 unwrap(D)->print("", OS);
1025 extern "C" LLVMValueRef
1026 LLVMRustBuildLandingPad(LLVMBuilderRef B, LLVMTypeRef Ty,
1027 LLVMValueRef PersFn, unsigned NumClauses,
1028 const char *Name, LLVMValueRef F) {
1029 return LLVMBuildLandingPad(B, Ty, PersFn, NumClauses, Name);
1032 extern "C" LLVMValueRef LLVMRustBuildCleanupPad(LLVMBuilderRef B,
1033 LLVMValueRef ParentPad,
1035 LLVMValueRef *LLArgs,
1037 #if LLVM_VERSION_GE(3, 8)
1038 Value **Args = unwrap(LLArgs);
1039 if (ParentPad == nullptr) {
1040 Type *Ty = Type::getTokenTy(unwrap(B)->getContext());
1041 ParentPad = wrap(Constant::getNullValue(Ty));
1043 return wrap(unwrap(B)->CreateCleanupPad(
1044 unwrap(ParentPad), ArrayRef<Value *>(Args, ArgCount), Name));
1050 extern "C" LLVMValueRef LLVMRustBuildCleanupRet(LLVMBuilderRef B,
1051 LLVMValueRef CleanupPad,
1052 LLVMBasicBlockRef UnwindBB) {
1053 #if LLVM_VERSION_GE(3, 8)
1054 CleanupPadInst *Inst = cast<CleanupPadInst>(unwrap(CleanupPad));
1055 return wrap(unwrap(B)->CreateCleanupRet(Inst, unwrap(UnwindBB)));
1061 extern "C" LLVMValueRef
1062 LLVMRustBuildCatchPad(LLVMBuilderRef B, LLVMValueRef ParentPad,
1063 unsigned ArgCount, LLVMValueRef *LLArgs, const char *Name) {
1064 #if LLVM_VERSION_GE(3, 8)
1065 Value **Args = unwrap(LLArgs);
1066 return wrap(unwrap(B)->CreateCatchPad(
1067 unwrap(ParentPad), ArrayRef<Value *>(Args, ArgCount), Name));
1073 extern "C" LLVMValueRef LLVMRustBuildCatchRet(LLVMBuilderRef B,
1075 LLVMBasicBlockRef BB) {
1076 #if LLVM_VERSION_GE(3, 8)
1077 return wrap(unwrap(B)->CreateCatchRet(cast<CatchPadInst>(unwrap(Pad)),
1084 extern "C" LLVMValueRef LLVMRustBuildCatchSwitch(LLVMBuilderRef B,
1085 LLVMValueRef ParentPad,
1086 LLVMBasicBlockRef BB,
1087 unsigned NumHandlers,
1089 #if LLVM_VERSION_GE(3, 8)
1090 if (ParentPad == nullptr) {
1091 Type *Ty = Type::getTokenTy(unwrap(B)->getContext());
1092 ParentPad = wrap(Constant::getNullValue(Ty));
1094 return wrap(unwrap(B)->CreateCatchSwitch(unwrap(ParentPad), unwrap(BB),
1095 NumHandlers, Name));
1101 extern "C" void LLVMRustAddHandler(LLVMValueRef CatchSwitchRef,
1102 LLVMBasicBlockRef Handler) {
1103 #if LLVM_VERSION_GE(3, 8)
1104 Value *CatchSwitch = unwrap(CatchSwitchRef);
1105 cast<CatchSwitchInst>(CatchSwitch)->addHandler(unwrap(Handler));
1109 #if LLVM_VERSION_GE(3, 8)
1110 extern "C" OperandBundleDef *LLVMRustBuildOperandBundleDef(const char *Name,
1111 LLVMValueRef *Inputs,
1112 unsigned NumInputs) {
1113 return new OperandBundleDef(Name, makeArrayRef(unwrap(Inputs), NumInputs));
1116 extern "C" void LLVMRustFreeOperandBundleDef(OperandBundleDef *Bundle) {
1120 extern "C" LLVMValueRef LLVMRustBuildCall(LLVMBuilderRef B, LLVMValueRef Fn,
1121 LLVMValueRef *Args, unsigned NumArgs,
1122 OperandBundleDef *Bundle,
1124 unsigned Len = Bundle ? 1 : 0;
1125 ArrayRef<OperandBundleDef> Bundles = makeArrayRef(Bundle, Len);
1126 return wrap(unwrap(B)->CreateCall(
1127 unwrap(Fn), makeArrayRef(unwrap(Args), NumArgs), Bundles, Name));
1130 extern "C" LLVMValueRef
1131 LLVMRustBuildInvoke(LLVMBuilderRef B, LLVMValueRef Fn, LLVMValueRef *Args,
1132 unsigned NumArgs, LLVMBasicBlockRef Then,
1133 LLVMBasicBlockRef Catch, OperandBundleDef *Bundle,
1135 unsigned Len = Bundle ? 1 : 0;
1136 ArrayRef<OperandBundleDef> Bundles = makeArrayRef(Bundle, Len);
1137 return wrap(unwrap(B)->CreateInvoke(unwrap(Fn), unwrap(Then), unwrap(Catch),
1138 makeArrayRef(unwrap(Args), NumArgs),
1142 extern "C" void *LLVMRustBuildOperandBundleDef(const char *Name,
1143 LLVMValueRef *Inputs,
1144 unsigned NumInputs) {
1148 extern "C" void LLVMRustFreeOperandBundleDef(void *Bundle) {}
1150 extern "C" LLVMValueRef LLVMRustBuildCall(LLVMBuilderRef B, LLVMValueRef Fn,
1151 LLVMValueRef *Args, unsigned NumArgs,
1152 void *Bundle, const char *Name) {
1153 return LLVMBuildCall(B, Fn, Args, NumArgs, Name);
1156 extern "C" LLVMValueRef
1157 LLVMRustBuildInvoke(LLVMBuilderRef B, LLVMValueRef Fn, LLVMValueRef *Args,
1158 unsigned NumArgs, LLVMBasicBlockRef Then,
1159 LLVMBasicBlockRef Catch, void *Bundle, const char *Name) {
1160 return LLVMBuildInvoke(B, Fn, Args, NumArgs, Then, Catch, Name);
1164 extern "C" void LLVMRustPositionBuilderAtStart(LLVMBuilderRef B,
1165 LLVMBasicBlockRef BB) {
1166 auto Point = unwrap(BB)->getFirstInsertionPt();
1167 unwrap(B)->SetInsertPoint(unwrap(BB), Point);
1170 extern "C" void LLVMRustSetComdat(LLVMModuleRef M, LLVMValueRef V,
1172 Triple TargetTriple(unwrap(M)->getTargetTriple());
1173 GlobalObject *GV = unwrap<GlobalObject>(V);
1174 if (!TargetTriple.isOSBinFormatMachO()) {
1175 GV->setComdat(unwrap(M)->getOrInsertComdat(Name));
1179 extern "C" void LLVMRustUnsetComdat(LLVMValueRef V) {
1180 GlobalObject *GV = unwrap<GlobalObject>(V);
1181 GV->setComdat(nullptr);
1184 enum class LLVMRustLinkage {
1185 ExternalLinkage = 0,
1186 AvailableExternallyLinkage = 1,
1187 LinkOnceAnyLinkage = 2,
1188 LinkOnceODRLinkage = 3,
1191 AppendingLinkage = 6,
1192 InternalLinkage = 7,
1194 ExternalWeakLinkage = 9,
1198 static LLVMRustLinkage toRust(LLVMLinkage Linkage) {
1200 case LLVMExternalLinkage:
1201 return LLVMRustLinkage::ExternalLinkage;
1202 case LLVMAvailableExternallyLinkage:
1203 return LLVMRustLinkage::AvailableExternallyLinkage;
1204 case LLVMLinkOnceAnyLinkage:
1205 return LLVMRustLinkage::LinkOnceAnyLinkage;
1206 case LLVMLinkOnceODRLinkage:
1207 return LLVMRustLinkage::LinkOnceODRLinkage;
1208 case LLVMWeakAnyLinkage:
1209 return LLVMRustLinkage::WeakAnyLinkage;
1210 case LLVMWeakODRLinkage:
1211 return LLVMRustLinkage::WeakODRLinkage;
1212 case LLVMAppendingLinkage:
1213 return LLVMRustLinkage::AppendingLinkage;
1214 case LLVMInternalLinkage:
1215 return LLVMRustLinkage::InternalLinkage;
1216 case LLVMPrivateLinkage:
1217 return LLVMRustLinkage::PrivateLinkage;
1218 case LLVMExternalWeakLinkage:
1219 return LLVMRustLinkage::ExternalWeakLinkage;
1220 case LLVMCommonLinkage:
1221 return LLVMRustLinkage::CommonLinkage;
1223 llvm_unreachable("Invalid LLVMRustLinkage value!");
1227 static LLVMLinkage fromRust(LLVMRustLinkage Linkage) {
1229 case LLVMRustLinkage::ExternalLinkage:
1230 return LLVMExternalLinkage;
1231 case LLVMRustLinkage::AvailableExternallyLinkage:
1232 return LLVMAvailableExternallyLinkage;
1233 case LLVMRustLinkage::LinkOnceAnyLinkage:
1234 return LLVMLinkOnceAnyLinkage;
1235 case LLVMRustLinkage::LinkOnceODRLinkage:
1236 return LLVMLinkOnceODRLinkage;
1237 case LLVMRustLinkage::WeakAnyLinkage:
1238 return LLVMWeakAnyLinkage;
1239 case LLVMRustLinkage::WeakODRLinkage:
1240 return LLVMWeakODRLinkage;
1241 case LLVMRustLinkage::AppendingLinkage:
1242 return LLVMAppendingLinkage;
1243 case LLVMRustLinkage::InternalLinkage:
1244 return LLVMInternalLinkage;
1245 case LLVMRustLinkage::PrivateLinkage:
1246 return LLVMPrivateLinkage;
1247 case LLVMRustLinkage::ExternalWeakLinkage:
1248 return LLVMExternalWeakLinkage;
1249 case LLVMRustLinkage::CommonLinkage:
1250 return LLVMCommonLinkage;
1252 llvm_unreachable("Invalid LLVMRustLinkage value!");
1255 extern "C" LLVMRustLinkage LLVMRustGetLinkage(LLVMValueRef V) {
1256 return toRust(LLVMGetLinkage(V));
1259 extern "C" void LLVMRustSetLinkage(LLVMValueRef V,
1260 LLVMRustLinkage RustLinkage) {
1261 LLVMSetLinkage(V, fromRust(RustLinkage));
1264 // Returns true if both high and low were successfully set. Fails in case constant wasn’t any of
1265 // the common sizes (1, 8, 16, 32, 64, 128 bits)
1266 extern "C" bool LLVMRustConstInt128Get(LLVMValueRef CV, bool sext, uint64_t *high, uint64_t *low)
1268 auto C = unwrap<llvm::ConstantInt>(CV);
1269 if (C->getBitWidth() > 128) { return false; }
1272 AP = C->getValue().sextOrSelf(128);
1274 AP = C->getValue().zextOrSelf(128);
1276 *low = AP.getLoBits(64).getZExtValue();
1277 *high = AP.getHiBits(64).getZExtValue();
1281 extern "C" LLVMContextRef LLVMRustGetValueContext(LLVMValueRef V) {
1282 return wrap(&unwrap(V)->getContext());
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 llvm_unreachable("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 llvm_unreachable("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));