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"
19 #include "llvm/IR/CallSite.h"
20 #include "llvm/ADT/Optional.h"
22 //===----------------------------------------------------------------------===
24 // This file defines alternate interfaces to core functions that are more
25 // readily callable by Rust's FFI.
27 //===----------------------------------------------------------------------===
30 using namespace llvm::sys;
31 using namespace llvm::object;
33 // LLVMAtomicOrdering is already an enum - don't create another
35 static AtomicOrdering fromRust(LLVMAtomicOrdering Ordering) {
37 case LLVMAtomicOrderingNotAtomic:
38 return AtomicOrdering::NotAtomic;
39 case LLVMAtomicOrderingUnordered:
40 return AtomicOrdering::Unordered;
41 case LLVMAtomicOrderingMonotonic:
42 return AtomicOrdering::Monotonic;
43 case LLVMAtomicOrderingAcquire:
44 return AtomicOrdering::Acquire;
45 case LLVMAtomicOrderingRelease:
46 return AtomicOrdering::Release;
47 case LLVMAtomicOrderingAcquireRelease:
48 return AtomicOrdering::AcquireRelease;
49 case LLVMAtomicOrderingSequentiallyConsistent:
50 return AtomicOrdering::SequentiallyConsistent;
53 report_fatal_error("Invalid LLVMAtomicOrdering value!");
56 static LLVM_THREAD_LOCAL char *LastError;
58 extern "C" LLVMMemoryBufferRef
59 LLVMRustCreateMemoryBufferWithContentsOfFile(const char *Path) {
60 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOr =
61 MemoryBuffer::getFile(Path, -1, false);
63 LLVMRustSetLastError(BufOr.getError().message().c_str());
66 return wrap(BufOr.get().release());
69 extern "C" char *LLVMRustGetLastError(void) {
70 char *Ret = LastError;
75 extern "C" void LLVMRustSetLastError(const char *Err) {
76 free((void *)LastError);
77 LastError = strdup(Err);
80 extern "C" LLVMContextRef LLVMRustContextCreate(bool shouldDiscardNames) {
81 auto ctx = new LLVMContext();
82 ctx->setDiscardValueNames(shouldDiscardNames);
86 extern "C" void LLVMRustSetNormalizedTarget(LLVMModuleRef M,
88 unwrap(M)->setTargetTriple(Triple::normalize(Triple));
91 extern "C" void LLVMRustPrintPassTimings() {
92 raw_fd_ostream OS(2, false); // stderr.
93 TimerGroup::printAll(OS);
96 extern "C" LLVMValueRef LLVMRustGetNamedValue(LLVMModuleRef M,
98 return wrap(unwrap(M)->getNamedValue(Name));
101 extern "C" LLVMValueRef LLVMRustGetOrInsertFunction(LLVMModuleRef M,
103 LLVMTypeRef FunctionTy) {
105 unwrap(M)->getOrInsertFunction(Name, unwrap<FunctionType>(FunctionTy)));
108 extern "C" LLVMValueRef
109 LLVMRustGetOrInsertGlobal(LLVMModuleRef M, const char *Name, LLVMTypeRef Ty) {
110 return wrap(unwrap(M)->getOrInsertGlobal(Name, unwrap(Ty)));
113 extern "C" LLVMTypeRef LLVMRustMetadataTypeInContext(LLVMContextRef C) {
114 return wrap(Type::getMetadataTy(*unwrap(C)));
117 static Attribute::AttrKind fromRust(LLVMRustAttribute Kind) {
120 return Attribute::AlwaysInline;
122 return Attribute::ByVal;
124 return Attribute::Cold;
126 return Attribute::InlineHint;
128 return Attribute::MinSize;
130 return Attribute::Naked;
132 return Attribute::NoAlias;
134 return Attribute::NoCapture;
136 return Attribute::NoInline;
138 return Attribute::NonNull;
140 return Attribute::NoRedZone;
142 return Attribute::NoReturn;
144 return Attribute::NoUnwind;
145 case OptimizeForSize:
146 return Attribute::OptimizeForSize;
148 return Attribute::ReadOnly;
150 return Attribute::SExt;
152 return Attribute::StructRet;
154 return Attribute::UWTable;
156 return Attribute::ZExt;
158 return Attribute::InReg;
160 return Attribute::SanitizeThread;
161 case SanitizeAddress:
162 return Attribute::SanitizeAddress;
164 return Attribute::SanitizeMemory;
166 report_fatal_error("bad AttributeKind");
169 extern "C" void LLVMRustAddCallSiteAttribute(LLVMValueRef Instr, unsigned Index,
170 LLVMRustAttribute RustAttr) {
171 CallSite Call = CallSite(unwrap<Instruction>(Instr));
172 Attribute Attr = Attribute::get(Call->getContext(), fromRust(RustAttr));
173 Call.addAttribute(Index, Attr);
176 extern "C" void LLVMRustAddAlignmentCallSiteAttr(LLVMValueRef Instr,
179 CallSite Call = CallSite(unwrap<Instruction>(Instr));
181 B.addAlignmentAttr(Bytes);
182 Call.setAttributes(Call.getAttributes().addAttributes(
183 Call->getContext(), Index, B));
186 extern "C" void LLVMRustAddDereferenceableCallSiteAttr(LLVMValueRef Instr,
189 CallSite Call = CallSite(unwrap<Instruction>(Instr));
191 B.addDereferenceableAttr(Bytes);
192 Call.setAttributes(Call.getAttributes().addAttributes(
193 Call->getContext(), Index, B));
196 extern "C" void LLVMRustAddDereferenceableOrNullCallSiteAttr(LLVMValueRef Instr,
199 CallSite Call = CallSite(unwrap<Instruction>(Instr));
201 B.addDereferenceableOrNullAttr(Bytes);
202 Call.setAttributes(Call.getAttributes().addAttributes(
203 Call->getContext(), Index, B));
206 extern "C" void LLVMRustAddFunctionAttribute(LLVMValueRef Fn, unsigned Index,
207 LLVMRustAttribute RustAttr) {
208 Function *A = unwrap<Function>(Fn);
209 Attribute Attr = Attribute::get(A->getContext(), fromRust(RustAttr));
211 A->addAttributes(Index, B);
214 extern "C" void LLVMRustAddAlignmentAttr(LLVMValueRef Fn,
217 Function *A = unwrap<Function>(Fn);
219 B.addAlignmentAttr(Bytes);
220 A->addAttributes(Index, B);
223 extern "C" void LLVMRustAddDereferenceableAttr(LLVMValueRef Fn, unsigned Index,
225 Function *A = unwrap<Function>(Fn);
227 B.addDereferenceableAttr(Bytes);
228 A->addAttributes(Index, B);
231 extern "C" void LLVMRustAddDereferenceableOrNullAttr(LLVMValueRef Fn,
234 Function *A = unwrap<Function>(Fn);
236 B.addDereferenceableOrNullAttr(Bytes);
237 A->addAttributes(Index, B);
240 extern "C" void LLVMRustAddFunctionAttrStringValue(LLVMValueRef Fn,
244 Function *F = unwrap<Function>(Fn);
246 B.addAttribute(Name, Value);
247 F->addAttributes(Index, B);
250 extern "C" void LLVMRustRemoveFunctionAttributes(LLVMValueRef Fn,
252 LLVMRustAttribute RustAttr) {
253 Function *F = unwrap<Function>(Fn);
254 Attribute Attr = Attribute::get(F->getContext(), fromRust(RustAttr));
256 auto PAL = F->getAttributes();
257 auto PALNew = PAL.removeAttributes(F->getContext(), Index, B);
258 F->setAttributes(PALNew);
261 // enable fpmath flag UnsafeAlgebra
262 extern "C" void LLVMRustSetHasUnsafeAlgebra(LLVMValueRef V) {
263 if (auto I = dyn_cast<Instruction>(unwrap<Value>(V))) {
264 #if LLVM_VERSION_GE(6, 0)
267 I->setHasUnsafeAlgebra(true);
272 extern "C" LLVMValueRef
273 LLVMRustBuildAtomicLoad(LLVMBuilderRef B, LLVMValueRef Source, const char *Name,
274 LLVMAtomicOrdering Order) {
275 LoadInst *LI = new LoadInst(unwrap(Source), 0);
276 LI->setAtomic(fromRust(Order));
277 return wrap(unwrap(B)->Insert(LI, Name));
280 extern "C" LLVMValueRef LLVMRustBuildAtomicStore(LLVMBuilderRef B,
283 LLVMAtomicOrdering Order) {
284 StoreInst *SI = new StoreInst(unwrap(V), unwrap(Target));
285 SI->setAtomic(fromRust(Order));
286 return wrap(unwrap(B)->Insert(SI));
289 extern "C" LLVMValueRef
290 LLVMRustBuildAtomicCmpXchg(LLVMBuilderRef B, LLVMValueRef Target,
291 LLVMValueRef Old, LLVMValueRef Source,
292 LLVMAtomicOrdering Order,
293 LLVMAtomicOrdering FailureOrder, LLVMBool Weak) {
294 AtomicCmpXchgInst *ACXI = unwrap(B)->CreateAtomicCmpXchg(
295 unwrap(Target), unwrap(Old), unwrap(Source), fromRust(Order),
296 fromRust(FailureOrder));
301 enum class LLVMRustSynchronizationScope {
307 static SyncScope::ID fromRust(LLVMRustSynchronizationScope Scope) {
309 case LLVMRustSynchronizationScope::SingleThread:
310 return SyncScope::SingleThread;
311 case LLVMRustSynchronizationScope::CrossThread:
312 return SyncScope::System;
314 report_fatal_error("bad SynchronizationScope.");
318 extern "C" LLVMValueRef
319 LLVMRustBuildAtomicFence(LLVMBuilderRef B, LLVMAtomicOrdering Order,
320 LLVMRustSynchronizationScope Scope) {
321 return wrap(unwrap(B)->CreateFence(fromRust(Order), fromRust(Scope)));
324 enum class LLVMRustAsmDialect {
330 static InlineAsm::AsmDialect fromRust(LLVMRustAsmDialect Dialect) {
332 case LLVMRustAsmDialect::Att:
333 return InlineAsm::AD_ATT;
334 case LLVMRustAsmDialect::Intel:
335 return InlineAsm::AD_Intel;
337 report_fatal_error("bad AsmDialect.");
341 extern "C" LLVMValueRef LLVMRustInlineAsm(LLVMTypeRef Ty, char *AsmString,
343 LLVMBool HasSideEffects,
344 LLVMBool IsAlignStack,
345 LLVMRustAsmDialect Dialect) {
346 return wrap(InlineAsm::get(unwrap<FunctionType>(Ty), AsmString, Constraints,
347 HasSideEffects, IsAlignStack, fromRust(Dialect)));
350 extern "C" void LLVMRustAppendModuleInlineAsm(LLVMModuleRef M, const char *Asm) {
351 unwrap(M)->appendModuleInlineAsm(StringRef(Asm));
354 typedef DIBuilder *LLVMRustDIBuilderRef;
356 template <typename DIT> DIT *unwrapDIPtr(LLVMMetadataRef Ref) {
357 return (DIT *)(Ref ? unwrap<MDNode>(Ref) : nullptr);
360 #define DIDescriptor DIScope
361 #define DIArray DINodeArray
362 #define unwrapDI unwrapDIPtr
364 // These values **must** match debuginfo::DIFlags! They also *happen*
365 // to match LLVM, but that isn't required as we do giant sets of
366 // matching below. The value shouldn't be directly passed to LLVM.
367 enum class LLVMRustDIFlags : uint32_t {
372 FlagFwdDecl = (1 << 2),
373 FlagAppleBlock = (1 << 3),
374 FlagBlockByrefStruct = (1 << 4),
375 FlagVirtual = (1 << 5),
376 FlagArtificial = (1 << 6),
377 FlagExplicit = (1 << 7),
378 FlagPrototyped = (1 << 8),
379 FlagObjcClassComplete = (1 << 9),
380 FlagObjectPointer = (1 << 10),
381 FlagVector = (1 << 11),
382 FlagStaticMember = (1 << 12),
383 FlagLValueReference = (1 << 13),
384 FlagRValueReference = (1 << 14),
385 FlagExternalTypeRef = (1 << 15),
386 FlagIntroducedVirtual = (1 << 18),
387 FlagBitField = (1 << 19),
388 FlagNoReturn = (1 << 20),
389 FlagMainSubprogram = (1 << 21),
390 // Do not add values that are not supported by the minimum LLVM
391 // version we support! see llvm/include/llvm/IR/DebugInfoFlags.def
394 inline LLVMRustDIFlags operator&(LLVMRustDIFlags A, LLVMRustDIFlags B) {
395 return static_cast<LLVMRustDIFlags>(static_cast<uint32_t>(A) &
396 static_cast<uint32_t>(B));
399 inline LLVMRustDIFlags operator|(LLVMRustDIFlags A, LLVMRustDIFlags B) {
400 return static_cast<LLVMRustDIFlags>(static_cast<uint32_t>(A) |
401 static_cast<uint32_t>(B));
404 inline LLVMRustDIFlags &operator|=(LLVMRustDIFlags &A, LLVMRustDIFlags B) {
408 inline bool isSet(LLVMRustDIFlags F) { return F != LLVMRustDIFlags::FlagZero; }
410 inline LLVMRustDIFlags visibility(LLVMRustDIFlags F) {
411 return static_cast<LLVMRustDIFlags>(static_cast<uint32_t>(F) & 0x3);
414 static DINode::DIFlags fromRust(LLVMRustDIFlags Flags) {
415 DINode::DIFlags Result = DINode::DIFlags::FlagZero;
417 switch (visibility(Flags)) {
418 case LLVMRustDIFlags::FlagPrivate:
419 Result |= DINode::DIFlags::FlagPrivate;
421 case LLVMRustDIFlags::FlagProtected:
422 Result |= DINode::DIFlags::FlagProtected;
424 case LLVMRustDIFlags::FlagPublic:
425 Result |= DINode::DIFlags::FlagPublic;
428 // The rest are handled below
432 if (isSet(Flags & LLVMRustDIFlags::FlagFwdDecl)) {
433 Result |= DINode::DIFlags::FlagFwdDecl;
435 if (isSet(Flags & LLVMRustDIFlags::FlagAppleBlock)) {
436 Result |= DINode::DIFlags::FlagAppleBlock;
438 if (isSet(Flags & LLVMRustDIFlags::FlagBlockByrefStruct)) {
439 Result |= DINode::DIFlags::FlagBlockByrefStruct;
441 if (isSet(Flags & LLVMRustDIFlags::FlagVirtual)) {
442 Result |= DINode::DIFlags::FlagVirtual;
444 if (isSet(Flags & LLVMRustDIFlags::FlagArtificial)) {
445 Result |= DINode::DIFlags::FlagArtificial;
447 if (isSet(Flags & LLVMRustDIFlags::FlagExplicit)) {
448 Result |= DINode::DIFlags::FlagExplicit;
450 if (isSet(Flags & LLVMRustDIFlags::FlagPrototyped)) {
451 Result |= DINode::DIFlags::FlagPrototyped;
453 if (isSet(Flags & LLVMRustDIFlags::FlagObjcClassComplete)) {
454 Result |= DINode::DIFlags::FlagObjcClassComplete;
456 if (isSet(Flags & LLVMRustDIFlags::FlagObjectPointer)) {
457 Result |= DINode::DIFlags::FlagObjectPointer;
459 if (isSet(Flags & LLVMRustDIFlags::FlagVector)) {
460 Result |= DINode::DIFlags::FlagVector;
462 if (isSet(Flags & LLVMRustDIFlags::FlagStaticMember)) {
463 Result |= DINode::DIFlags::FlagStaticMember;
465 if (isSet(Flags & LLVMRustDIFlags::FlagLValueReference)) {
466 Result |= DINode::DIFlags::FlagLValueReference;
468 if (isSet(Flags & LLVMRustDIFlags::FlagRValueReference)) {
469 Result |= DINode::DIFlags::FlagRValueReference;
471 if (isSet(Flags & LLVMRustDIFlags::FlagIntroducedVirtual)) {
472 Result |= DINode::DIFlags::FlagIntroducedVirtual;
474 if (isSet(Flags & LLVMRustDIFlags::FlagBitField)) {
475 Result |= DINode::DIFlags::FlagBitField;
477 if (isSet(Flags & LLVMRustDIFlags::FlagNoReturn)) {
478 Result |= DINode::DIFlags::FlagNoReturn;
480 if (isSet(Flags & LLVMRustDIFlags::FlagMainSubprogram)) {
481 Result |= DINode::DIFlags::FlagMainSubprogram;
487 extern "C" uint32_t LLVMRustDebugMetadataVersion() {
488 return DEBUG_METADATA_VERSION;
491 extern "C" uint32_t LLVMRustVersionMinor() { return LLVM_VERSION_MINOR; }
493 extern "C" uint32_t LLVMRustVersionMajor() { return LLVM_VERSION_MAJOR; }
495 extern "C" void LLVMRustAddModuleFlag(LLVMModuleRef M, const char *Name,
497 unwrap(M)->addModuleFlag(Module::Warning, Name, Value);
500 extern "C" LLVMValueRef LLVMRustMetadataAsValue(LLVMContextRef C, LLVMMetadataRef MD) {
501 return wrap(MetadataAsValue::get(*unwrap(C), unwrap(MD)));
504 extern "C" LLVMRustDIBuilderRef LLVMRustDIBuilderCreate(LLVMModuleRef M) {
505 return new DIBuilder(*unwrap(M));
508 extern "C" void LLVMRustDIBuilderDispose(LLVMRustDIBuilderRef Builder) {
512 extern "C" void LLVMRustDIBuilderFinalize(LLVMRustDIBuilderRef Builder) {
516 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateCompileUnit(
517 LLVMRustDIBuilderRef Builder, unsigned Lang, LLVMMetadataRef FileRef,
518 const char *Producer, bool isOptimized, const char *Flags,
519 unsigned RuntimeVer, const char *SplitName) {
520 auto *File = unwrapDI<DIFile>(FileRef);
522 return wrap(Builder->createCompileUnit(Lang, File, Producer, isOptimized,
523 Flags, RuntimeVer, SplitName));
526 extern "C" LLVMMetadataRef
527 LLVMRustDIBuilderCreateFile(LLVMRustDIBuilderRef Builder, const char *Filename,
528 const char *Directory) {
529 return wrap(Builder->createFile(Filename, Directory));
532 extern "C" LLVMMetadataRef
533 LLVMRustDIBuilderCreateSubroutineType(LLVMRustDIBuilderRef Builder,
534 LLVMMetadataRef File,
535 LLVMMetadataRef ParameterTypes) {
536 return wrap(Builder->createSubroutineType(
537 DITypeRefArray(unwrap<MDTuple>(ParameterTypes))));
540 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateFunction(
541 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
542 const char *LinkageName, LLVMMetadataRef File, unsigned LineNo,
543 LLVMMetadataRef Ty, bool IsLocalToUnit, bool IsDefinition,
544 unsigned ScopeLine, LLVMRustDIFlags Flags, bool IsOptimized,
545 LLVMValueRef Fn, LLVMMetadataRef TParam, LLVMMetadataRef Decl) {
546 DITemplateParameterArray TParams =
547 DITemplateParameterArray(unwrap<MDTuple>(TParam));
548 DISubprogram *Sub = Builder->createFunction(
549 unwrapDI<DIScope>(Scope), Name, LinkageName, unwrapDI<DIFile>(File),
550 LineNo, unwrapDI<DISubroutineType>(Ty), IsLocalToUnit, IsDefinition,
551 ScopeLine, fromRust(Flags), IsOptimized, TParams,
552 unwrapDIPtr<DISubprogram>(Decl));
553 unwrap<Function>(Fn)->setSubprogram(Sub);
557 extern "C" LLVMMetadataRef
558 LLVMRustDIBuilderCreateBasicType(LLVMRustDIBuilderRef Builder, const char *Name,
559 uint64_t SizeInBits, uint32_t AlignInBits,
561 return wrap(Builder->createBasicType(Name, SizeInBits, Encoding));
564 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreatePointerType(
565 LLVMRustDIBuilderRef Builder, LLVMMetadataRef PointeeTy,
566 uint64_t SizeInBits, uint32_t AlignInBits, const char *Name) {
567 return wrap(Builder->createPointerType(unwrapDI<DIType>(PointeeTy),
568 SizeInBits, AlignInBits,
569 /* DWARFAddressSpace */ None,
573 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateStructType(
574 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
575 LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
576 uint32_t AlignInBits, LLVMRustDIFlags Flags,
577 LLVMMetadataRef DerivedFrom, LLVMMetadataRef Elements,
578 unsigned RunTimeLang, LLVMMetadataRef VTableHolder,
579 const char *UniqueId) {
580 return wrap(Builder->createStructType(
581 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNumber,
582 SizeInBits, AlignInBits, fromRust(Flags), unwrapDI<DIType>(DerivedFrom),
583 DINodeArray(unwrapDI<MDTuple>(Elements)), RunTimeLang,
584 unwrapDI<DIType>(VTableHolder), UniqueId));
587 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateMemberType(
588 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
589 LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits,
590 uint32_t AlignInBits, uint64_t OffsetInBits, LLVMRustDIFlags Flags,
591 LLVMMetadataRef Ty) {
592 return wrap(Builder->createMemberType(unwrapDI<DIDescriptor>(Scope), Name,
593 unwrapDI<DIFile>(File), LineNo,
594 SizeInBits, AlignInBits, OffsetInBits,
595 fromRust(Flags), unwrapDI<DIType>(Ty)));
598 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateLexicalBlock(
599 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope,
600 LLVMMetadataRef File, unsigned Line, unsigned Col) {
601 return wrap(Builder->createLexicalBlock(unwrapDI<DIDescriptor>(Scope),
602 unwrapDI<DIFile>(File), Line, Col));
605 extern "C" LLVMMetadataRef
606 LLVMRustDIBuilderCreateLexicalBlockFile(LLVMRustDIBuilderRef Builder,
607 LLVMMetadataRef Scope,
608 LLVMMetadataRef File) {
609 return wrap(Builder->createLexicalBlockFile(unwrapDI<DIDescriptor>(Scope),
610 unwrapDI<DIFile>(File)));
613 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateStaticVariable(
614 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Context, const char *Name,
615 const char *LinkageName, LLVMMetadataRef File, unsigned LineNo,
616 LLVMMetadataRef Ty, bool IsLocalToUnit, LLVMValueRef V,
617 LLVMMetadataRef Decl = nullptr, uint32_t AlignInBits = 0) {
618 llvm::GlobalVariable *InitVal = cast<llvm::GlobalVariable>(unwrap(V));
620 llvm::DIExpression *InitExpr = nullptr;
621 if (llvm::ConstantInt *IntVal = llvm::dyn_cast<llvm::ConstantInt>(InitVal)) {
622 InitExpr = Builder->createConstantValueExpression(
623 IntVal->getValue().getSExtValue());
624 } else if (llvm::ConstantFP *FPVal =
625 llvm::dyn_cast<llvm::ConstantFP>(InitVal)) {
626 InitExpr = Builder->createConstantValueExpression(
627 FPVal->getValueAPF().bitcastToAPInt().getZExtValue());
630 llvm::DIGlobalVariableExpression *VarExpr = Builder->createGlobalVariableExpression(
631 unwrapDI<DIDescriptor>(Context), Name, LinkageName,
632 unwrapDI<DIFile>(File), LineNo, unwrapDI<DIType>(Ty), IsLocalToUnit,
633 InitExpr, unwrapDIPtr<MDNode>(Decl), AlignInBits);
635 InitVal->setMetadata("dbg", VarExpr);
637 return wrap(VarExpr);
640 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateVariable(
641 LLVMRustDIBuilderRef Builder, unsigned Tag, LLVMMetadataRef Scope,
642 const char *Name, LLVMMetadataRef File, unsigned LineNo,
643 LLVMMetadataRef Ty, bool AlwaysPreserve, LLVMRustDIFlags Flags,
644 unsigned ArgNo, uint32_t AlignInBits) {
645 if (Tag == 0x100) { // DW_TAG_auto_variable
646 return wrap(Builder->createAutoVariable(
647 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNo,
648 unwrapDI<DIType>(Ty), AlwaysPreserve, fromRust(Flags), AlignInBits));
650 return wrap(Builder->createParameterVariable(
651 unwrapDI<DIDescriptor>(Scope), Name, ArgNo, unwrapDI<DIFile>(File),
652 LineNo, unwrapDI<DIType>(Ty), AlwaysPreserve, fromRust(Flags)));
656 extern "C" LLVMMetadataRef
657 LLVMRustDIBuilderCreateArrayType(LLVMRustDIBuilderRef Builder, uint64_t Size,
658 uint32_t AlignInBits, LLVMMetadataRef Ty,
659 LLVMMetadataRef Subscripts) {
661 Builder->createArrayType(Size, AlignInBits, unwrapDI<DIType>(Ty),
662 DINodeArray(unwrapDI<MDTuple>(Subscripts))));
665 extern "C" LLVMMetadataRef
666 LLVMRustDIBuilderCreateVectorType(LLVMRustDIBuilderRef Builder, uint64_t Size,
667 uint32_t AlignInBits, LLVMMetadataRef Ty,
668 LLVMMetadataRef Subscripts) {
670 Builder->createVectorType(Size, AlignInBits, unwrapDI<DIType>(Ty),
671 DINodeArray(unwrapDI<MDTuple>(Subscripts))));
674 extern "C" LLVMMetadataRef
675 LLVMRustDIBuilderGetOrCreateSubrange(LLVMRustDIBuilderRef Builder, int64_t Lo,
677 return wrap(Builder->getOrCreateSubrange(Lo, Count));
680 extern "C" LLVMMetadataRef
681 LLVMRustDIBuilderGetOrCreateArray(LLVMRustDIBuilderRef Builder,
682 LLVMMetadataRef *Ptr, unsigned Count) {
683 Metadata **DataValue = unwrap(Ptr);
685 Builder->getOrCreateArray(ArrayRef<Metadata *>(DataValue, Count)).get());
688 extern "C" LLVMValueRef LLVMRustDIBuilderInsertDeclareAtEnd(
689 LLVMRustDIBuilderRef Builder, LLVMValueRef V, LLVMMetadataRef VarInfo,
690 int64_t *AddrOps, unsigned AddrOpsCount, LLVMValueRef DL,
691 LLVMBasicBlockRef InsertAtEnd) {
692 return wrap(Builder->insertDeclare(
693 unwrap(V), unwrap<DILocalVariable>(VarInfo),
694 Builder->createExpression(llvm::ArrayRef<int64_t>(AddrOps, AddrOpsCount)),
695 DebugLoc(cast<MDNode>(unwrap<MetadataAsValue>(DL)->getMetadata())),
696 unwrap(InsertAtEnd)));
699 extern "C" LLVMMetadataRef
700 LLVMRustDIBuilderCreateEnumerator(LLVMRustDIBuilderRef Builder,
701 const char *Name, uint64_t Val) {
702 return wrap(Builder->createEnumerator(Name, Val));
705 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateEnumerationType(
706 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
707 LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
708 uint32_t AlignInBits, LLVMMetadataRef Elements,
709 LLVMMetadataRef ClassTy) {
710 return wrap(Builder->createEnumerationType(
711 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNumber,
712 SizeInBits, AlignInBits, DINodeArray(unwrapDI<MDTuple>(Elements)),
713 unwrapDI<DIType>(ClassTy)));
716 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateUnionType(
717 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
718 LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits,
719 uint32_t AlignInBits, LLVMRustDIFlags Flags, LLVMMetadataRef Elements,
720 unsigned RunTimeLang, const char *UniqueId) {
721 return wrap(Builder->createUnionType(
722 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIFile>(File), LineNumber,
723 SizeInBits, AlignInBits, fromRust(Flags),
724 DINodeArray(unwrapDI<MDTuple>(Elements)), RunTimeLang, UniqueId));
727 extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateTemplateTypeParameter(
728 LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name,
729 LLVMMetadataRef Ty, LLVMMetadataRef File, unsigned LineNo,
731 return wrap(Builder->createTemplateTypeParameter(
732 unwrapDI<DIDescriptor>(Scope), Name, unwrapDI<DIType>(Ty)));
735 extern "C" LLVMMetadataRef
736 LLVMRustDIBuilderCreateNameSpace(LLVMRustDIBuilderRef Builder,
737 LLVMMetadataRef Scope, const char *Name,
738 LLVMMetadataRef File, unsigned LineNo) {
739 return wrap(Builder->createNameSpace(
740 unwrapDI<DIDescriptor>(Scope), Name,
741 false // ExportSymbols (only relevant for C++ anonymous namespaces)
746 LLVMRustDICompositeTypeSetTypeArray(LLVMRustDIBuilderRef Builder,
747 LLVMMetadataRef CompositeTy,
748 LLVMMetadataRef TyArray) {
749 DICompositeType *Tmp = unwrapDI<DICompositeType>(CompositeTy);
750 Builder->replaceArrays(Tmp, DINodeArray(unwrap<MDTuple>(TyArray)));
753 extern "C" LLVMValueRef
754 LLVMRustDIBuilderCreateDebugLocation(LLVMContextRef ContextRef, unsigned Line,
755 unsigned Column, LLVMMetadataRef Scope,
756 LLVMMetadataRef InlinedAt) {
757 LLVMContext &Context = *unwrap(ContextRef);
759 DebugLoc debug_loc = DebugLoc::get(Line, Column, unwrapDIPtr<MDNode>(Scope),
760 unwrapDIPtr<MDNode>(InlinedAt));
762 return wrap(MetadataAsValue::get(Context, debug_loc.getAsMDNode()));
765 extern "C" int64_t LLVMRustDIBuilderCreateOpDeref() {
766 return dwarf::DW_OP_deref;
769 extern "C" int64_t LLVMRustDIBuilderCreateOpPlusUconst() {
770 return dwarf::DW_OP_plus_uconst;
773 extern "C" void LLVMRustWriteTypeToString(LLVMTypeRef Ty, RustStringRef Str) {
774 RawRustStringOstream OS(Str);
775 unwrap<llvm::Type>(Ty)->print(OS);
778 extern "C" void LLVMRustWriteValueToString(LLVMValueRef V,
780 RawRustStringOstream OS(Str);
785 unwrap<llvm::Value>(V)->getType()->print(OS);
787 unwrap<llvm::Value>(V)->print(OS);
792 // Note that the two following functions look quite similar to the
793 // LLVMGetSectionName function. Sadly, it appears that this function only
794 // returns a char* pointer, which isn't guaranteed to be null-terminated. The
795 // function provided by LLVM doesn't return the length, so we've created our own
796 // function which returns the length as well as the data pointer.
798 // For an example of this not returning a null terminated string, see
799 // lib/Object/COFFObjectFile.cpp in the getSectionName function. One of the
800 // branches explicitly creates a StringRef without a null terminator, and then
803 inline section_iterator *unwrap(LLVMSectionIteratorRef SI) {
804 return reinterpret_cast<section_iterator *>(SI);
807 extern "C" size_t LLVMRustGetSectionName(LLVMSectionIteratorRef SI,
810 if (std::error_code EC = (*unwrap(SI))->getName(Ret))
811 report_fatal_error(EC.message());
816 // LLVMArrayType function does not support 64-bit ElementCount
817 extern "C" LLVMTypeRef LLVMRustArrayType(LLVMTypeRef ElementTy,
818 uint64_t ElementCount) {
819 return wrap(ArrayType::get(unwrap(ElementTy), ElementCount));
822 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(Twine, LLVMTwineRef)
824 extern "C" void LLVMRustWriteTwineToString(LLVMTwineRef T, RustStringRef Str) {
825 RawRustStringOstream OS(Str);
826 unwrap(T)->print(OS);
829 extern "C" void LLVMRustUnpackOptimizationDiagnostic(
830 LLVMDiagnosticInfoRef DI, RustStringRef PassNameOut,
831 LLVMValueRef *FunctionOut, unsigned* Line, unsigned* Column,
832 RustStringRef FilenameOut, RustStringRef MessageOut) {
833 // Undefined to call this not on an optimization diagnostic!
834 llvm::DiagnosticInfoOptimizationBase *Opt =
835 static_cast<llvm::DiagnosticInfoOptimizationBase *>(unwrap(DI));
837 RawRustStringOstream PassNameOS(PassNameOut);
838 PassNameOS << Opt->getPassName();
839 *FunctionOut = wrap(&Opt->getFunction());
841 RawRustStringOstream FilenameOS(FilenameOut);
842 DiagnosticLocation loc = Opt->getLocation();
844 *Line = loc.getLine();
845 *Column = loc.getColumn();
846 FilenameOS << loc.getFilename();
849 RawRustStringOstream MessageOS(MessageOut);
850 MessageOS << Opt->getMsg();
854 LLVMRustUnpackInlineAsmDiagnostic(LLVMDiagnosticInfoRef DI, unsigned *CookieOut,
855 LLVMTwineRef *MessageOut,
856 LLVMValueRef *InstructionOut) {
857 // Undefined to call this not on an inline assembly diagnostic!
858 llvm::DiagnosticInfoInlineAsm *IA =
859 static_cast<llvm::DiagnosticInfoInlineAsm *>(unwrap(DI));
861 *CookieOut = IA->getLocCookie();
862 *MessageOut = wrap(&IA->getMsgStr());
863 *InstructionOut = wrap(IA->getInstruction());
866 extern "C" void LLVMRustWriteDiagnosticInfoToString(LLVMDiagnosticInfoRef DI,
868 RawRustStringOstream OS(Str);
869 DiagnosticPrinterRawOStream DP(OS);
870 unwrap(DI)->print(DP);
873 enum class LLVMRustDiagnosticKind {
877 DebugMetadataVersion,
880 OptimizationRemarkMissed,
881 OptimizationRemarkAnalysis,
882 OptimizationRemarkAnalysisFPCommute,
883 OptimizationRemarkAnalysisAliasing,
884 OptimizationRemarkOther,
889 static LLVMRustDiagnosticKind toRust(DiagnosticKind Kind) {
892 return LLVMRustDiagnosticKind::InlineAsm;
894 return LLVMRustDiagnosticKind::StackSize;
895 case DK_DebugMetadataVersion:
896 return LLVMRustDiagnosticKind::DebugMetadataVersion;
897 case DK_SampleProfile:
898 return LLVMRustDiagnosticKind::SampleProfile;
899 case DK_OptimizationRemark:
900 return LLVMRustDiagnosticKind::OptimizationRemark;
901 case DK_OptimizationRemarkMissed:
902 return LLVMRustDiagnosticKind::OptimizationRemarkMissed;
903 case DK_OptimizationRemarkAnalysis:
904 return LLVMRustDiagnosticKind::OptimizationRemarkAnalysis;
905 case DK_OptimizationRemarkAnalysisFPCommute:
906 return LLVMRustDiagnosticKind::OptimizationRemarkAnalysisFPCommute;
907 case DK_OptimizationRemarkAnalysisAliasing:
908 return LLVMRustDiagnosticKind::OptimizationRemarkAnalysisAliasing;
910 return LLVMRustDiagnosticKind::PGOProfile;
912 return (Kind >= DK_FirstRemark && Kind <= DK_LastRemark)
913 ? LLVMRustDiagnosticKind::OptimizationRemarkOther
914 : LLVMRustDiagnosticKind::Other;
918 extern "C" LLVMRustDiagnosticKind
919 LLVMRustGetDiagInfoKind(LLVMDiagnosticInfoRef DI) {
920 return toRust((DiagnosticKind)unwrap(DI)->getKind());
922 // This is kept distinct from LLVMGetTypeKind, because when
923 // a new type kind is added, the Rust-side enum must be
924 // updated or UB will result.
925 extern "C" LLVMTypeKind LLVMRustGetTypeKind(LLVMTypeRef Ty) {
926 switch (unwrap(Ty)->getTypeID()) {
928 return LLVMVoidTypeKind;
930 return LLVMHalfTypeKind;
931 case Type::FloatTyID:
932 return LLVMFloatTypeKind;
933 case Type::DoubleTyID:
934 return LLVMDoubleTypeKind;
935 case Type::X86_FP80TyID:
936 return LLVMX86_FP80TypeKind;
937 case Type::FP128TyID:
938 return LLVMFP128TypeKind;
939 case Type::PPC_FP128TyID:
940 return LLVMPPC_FP128TypeKind;
941 case Type::LabelTyID:
942 return LLVMLabelTypeKind;
943 case Type::MetadataTyID:
944 return LLVMMetadataTypeKind;
945 case Type::IntegerTyID:
946 return LLVMIntegerTypeKind;
947 case Type::FunctionTyID:
948 return LLVMFunctionTypeKind;
949 case Type::StructTyID:
950 return LLVMStructTypeKind;
951 case Type::ArrayTyID:
952 return LLVMArrayTypeKind;
953 case Type::PointerTyID:
954 return LLVMPointerTypeKind;
955 case Type::VectorTyID:
956 return LLVMVectorTypeKind;
957 case Type::X86_MMXTyID:
958 return LLVMX86_MMXTypeKind;
959 case Type::TokenTyID:
960 return LLVMTokenTypeKind;
962 report_fatal_error("Unhandled TypeID.");
965 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(SMDiagnostic, LLVMSMDiagnosticRef)
967 extern "C" void LLVMRustSetInlineAsmDiagnosticHandler(
968 LLVMContextRef C, LLVMContext::InlineAsmDiagHandlerTy H, void *CX) {
969 unwrap(C)->setInlineAsmDiagnosticHandler(H, CX);
972 extern "C" void LLVMRustWriteSMDiagnosticToString(LLVMSMDiagnosticRef D,
974 RawRustStringOstream OS(Str);
975 unwrap(D)->print("", OS);
978 extern "C" LLVMValueRef LLVMRustBuildCleanupPad(LLVMBuilderRef B,
979 LLVMValueRef ParentPad,
981 LLVMValueRef *LLArgs,
983 Value **Args = unwrap(LLArgs);
984 if (ParentPad == nullptr) {
985 Type *Ty = Type::getTokenTy(unwrap(B)->getContext());
986 ParentPad = wrap(Constant::getNullValue(Ty));
988 return wrap(unwrap(B)->CreateCleanupPad(
989 unwrap(ParentPad), ArrayRef<Value *>(Args, ArgCount), Name));
992 extern "C" LLVMValueRef LLVMRustBuildCleanupRet(LLVMBuilderRef B,
993 LLVMValueRef CleanupPad,
994 LLVMBasicBlockRef UnwindBB) {
995 CleanupPadInst *Inst = cast<CleanupPadInst>(unwrap(CleanupPad));
996 return wrap(unwrap(B)->CreateCleanupRet(Inst, unwrap(UnwindBB)));
999 extern "C" LLVMValueRef
1000 LLVMRustBuildCatchPad(LLVMBuilderRef B, LLVMValueRef ParentPad,
1001 unsigned ArgCount, LLVMValueRef *LLArgs, const char *Name) {
1002 Value **Args = unwrap(LLArgs);
1003 return wrap(unwrap(B)->CreateCatchPad(
1004 unwrap(ParentPad), ArrayRef<Value *>(Args, ArgCount), Name));
1007 extern "C" LLVMValueRef LLVMRustBuildCatchRet(LLVMBuilderRef B,
1009 LLVMBasicBlockRef BB) {
1010 return wrap(unwrap(B)->CreateCatchRet(cast<CatchPadInst>(unwrap(Pad)),
1014 extern "C" LLVMValueRef LLVMRustBuildCatchSwitch(LLVMBuilderRef B,
1015 LLVMValueRef ParentPad,
1016 LLVMBasicBlockRef BB,
1017 unsigned NumHandlers,
1019 if (ParentPad == nullptr) {
1020 Type *Ty = Type::getTokenTy(unwrap(B)->getContext());
1021 ParentPad = wrap(Constant::getNullValue(Ty));
1023 return wrap(unwrap(B)->CreateCatchSwitch(unwrap(ParentPad), unwrap(BB),
1024 NumHandlers, Name));
1027 extern "C" void LLVMRustAddHandler(LLVMValueRef CatchSwitchRef,
1028 LLVMBasicBlockRef Handler) {
1029 Value *CatchSwitch = unwrap(CatchSwitchRef);
1030 cast<CatchSwitchInst>(CatchSwitch)->addHandler(unwrap(Handler));
1033 extern "C" OperandBundleDef *LLVMRustBuildOperandBundleDef(const char *Name,
1034 LLVMValueRef *Inputs,
1035 unsigned NumInputs) {
1036 return new OperandBundleDef(Name, makeArrayRef(unwrap(Inputs), NumInputs));
1039 extern "C" void LLVMRustFreeOperandBundleDef(OperandBundleDef *Bundle) {
1043 extern "C" LLVMValueRef LLVMRustBuildCall(LLVMBuilderRef B, LLVMValueRef Fn,
1044 LLVMValueRef *Args, unsigned NumArgs,
1045 OperandBundleDef *Bundle,
1047 unsigned Len = Bundle ? 1 : 0;
1048 ArrayRef<OperandBundleDef> Bundles = makeArrayRef(Bundle, Len);
1049 return wrap(unwrap(B)->CreateCall(
1050 unwrap(Fn), makeArrayRef(unwrap(Args), NumArgs), Bundles, Name));
1053 extern "C" LLVMValueRef
1054 LLVMRustBuildInvoke(LLVMBuilderRef B, LLVMValueRef Fn, LLVMValueRef *Args,
1055 unsigned NumArgs, LLVMBasicBlockRef Then,
1056 LLVMBasicBlockRef Catch, OperandBundleDef *Bundle,
1058 unsigned Len = Bundle ? 1 : 0;
1059 ArrayRef<OperandBundleDef> Bundles = makeArrayRef(Bundle, Len);
1060 return wrap(unwrap(B)->CreateInvoke(unwrap(Fn), unwrap(Then), unwrap(Catch),
1061 makeArrayRef(unwrap(Args), NumArgs),
1065 extern "C" void LLVMRustPositionBuilderAtStart(LLVMBuilderRef B,
1066 LLVMBasicBlockRef BB) {
1067 auto Point = unwrap(BB)->getFirstInsertionPt();
1068 unwrap(B)->SetInsertPoint(unwrap(BB), Point);
1071 extern "C" void LLVMRustSetComdat(LLVMModuleRef M, LLVMValueRef V,
1073 Triple TargetTriple(unwrap(M)->getTargetTriple());
1074 GlobalObject *GV = unwrap<GlobalObject>(V);
1075 if (!TargetTriple.isOSBinFormatMachO()) {
1076 GV->setComdat(unwrap(M)->getOrInsertComdat(Name));
1080 extern "C" void LLVMRustUnsetComdat(LLVMValueRef V) {
1081 GlobalObject *GV = unwrap<GlobalObject>(V);
1082 GV->setComdat(nullptr);
1085 enum class LLVMRustLinkage {
1086 ExternalLinkage = 0,
1087 AvailableExternallyLinkage = 1,
1088 LinkOnceAnyLinkage = 2,
1089 LinkOnceODRLinkage = 3,
1092 AppendingLinkage = 6,
1093 InternalLinkage = 7,
1095 ExternalWeakLinkage = 9,
1099 static LLVMRustLinkage toRust(LLVMLinkage Linkage) {
1101 case LLVMExternalLinkage:
1102 return LLVMRustLinkage::ExternalLinkage;
1103 case LLVMAvailableExternallyLinkage:
1104 return LLVMRustLinkage::AvailableExternallyLinkage;
1105 case LLVMLinkOnceAnyLinkage:
1106 return LLVMRustLinkage::LinkOnceAnyLinkage;
1107 case LLVMLinkOnceODRLinkage:
1108 return LLVMRustLinkage::LinkOnceODRLinkage;
1109 case LLVMWeakAnyLinkage:
1110 return LLVMRustLinkage::WeakAnyLinkage;
1111 case LLVMWeakODRLinkage:
1112 return LLVMRustLinkage::WeakODRLinkage;
1113 case LLVMAppendingLinkage:
1114 return LLVMRustLinkage::AppendingLinkage;
1115 case LLVMInternalLinkage:
1116 return LLVMRustLinkage::InternalLinkage;
1117 case LLVMPrivateLinkage:
1118 return LLVMRustLinkage::PrivateLinkage;
1119 case LLVMExternalWeakLinkage:
1120 return LLVMRustLinkage::ExternalWeakLinkage;
1121 case LLVMCommonLinkage:
1122 return LLVMRustLinkage::CommonLinkage;
1124 report_fatal_error("Invalid LLVMRustLinkage value!");
1128 static LLVMLinkage fromRust(LLVMRustLinkage Linkage) {
1130 case LLVMRustLinkage::ExternalLinkage:
1131 return LLVMExternalLinkage;
1132 case LLVMRustLinkage::AvailableExternallyLinkage:
1133 return LLVMAvailableExternallyLinkage;
1134 case LLVMRustLinkage::LinkOnceAnyLinkage:
1135 return LLVMLinkOnceAnyLinkage;
1136 case LLVMRustLinkage::LinkOnceODRLinkage:
1137 return LLVMLinkOnceODRLinkage;
1138 case LLVMRustLinkage::WeakAnyLinkage:
1139 return LLVMWeakAnyLinkage;
1140 case LLVMRustLinkage::WeakODRLinkage:
1141 return LLVMWeakODRLinkage;
1142 case LLVMRustLinkage::AppendingLinkage:
1143 return LLVMAppendingLinkage;
1144 case LLVMRustLinkage::InternalLinkage:
1145 return LLVMInternalLinkage;
1146 case LLVMRustLinkage::PrivateLinkage:
1147 return LLVMPrivateLinkage;
1148 case LLVMRustLinkage::ExternalWeakLinkage:
1149 return LLVMExternalWeakLinkage;
1150 case LLVMRustLinkage::CommonLinkage:
1151 return LLVMCommonLinkage;
1153 report_fatal_error("Invalid LLVMRustLinkage value!");
1156 extern "C" LLVMRustLinkage LLVMRustGetLinkage(LLVMValueRef V) {
1157 return toRust(LLVMGetLinkage(V));
1160 extern "C" void LLVMRustSetLinkage(LLVMValueRef V,
1161 LLVMRustLinkage RustLinkage) {
1162 LLVMSetLinkage(V, fromRust(RustLinkage));
1165 // Returns true if both high and low were successfully set. Fails in case constant wasn’t any of
1166 // the common sizes (1, 8, 16, 32, 64, 128 bits)
1167 extern "C" bool LLVMRustConstInt128Get(LLVMValueRef CV, bool sext, uint64_t *high, uint64_t *low)
1169 auto C = unwrap<llvm::ConstantInt>(CV);
1170 if (C->getBitWidth() > 128) { return false; }
1173 AP = C->getValue().sextOrSelf(128);
1175 AP = C->getValue().zextOrSelf(128);
1177 *low = AP.getLoBits(64).getZExtValue();
1178 *high = AP.getHiBits(64).getZExtValue();
1182 enum class LLVMRustVisibility {
1188 static LLVMRustVisibility toRust(LLVMVisibility Vis) {
1190 case LLVMDefaultVisibility:
1191 return LLVMRustVisibility::Default;
1192 case LLVMHiddenVisibility:
1193 return LLVMRustVisibility::Hidden;
1194 case LLVMProtectedVisibility:
1195 return LLVMRustVisibility::Protected;
1197 report_fatal_error("Invalid LLVMRustVisibility value!");
1200 static LLVMVisibility fromRust(LLVMRustVisibility Vis) {
1202 case LLVMRustVisibility::Default:
1203 return LLVMDefaultVisibility;
1204 case LLVMRustVisibility::Hidden:
1205 return LLVMHiddenVisibility;
1206 case LLVMRustVisibility::Protected:
1207 return LLVMProtectedVisibility;
1209 report_fatal_error("Invalid LLVMRustVisibility value!");
1212 extern "C" LLVMRustVisibility LLVMRustGetVisibility(LLVMValueRef V) {
1213 return toRust(LLVMGetVisibility(V));
1216 // Oh hey, a binding that makes sense for once? (because LLVM’s own do not)
1217 extern "C" LLVMValueRef LLVMRustBuildIntCast(LLVMBuilderRef B, LLVMValueRef Val,
1218 LLVMTypeRef DestTy, bool isSigned) {
1219 return wrap(unwrap(B)->CreateIntCast(unwrap(Val), unwrap(DestTy), isSigned, ""));
1222 extern "C" void LLVMRustSetVisibility(LLVMValueRef V,
1223 LLVMRustVisibility RustVisibility) {
1224 LLVMSetVisibility(V, fromRust(RustVisibility));
1227 struct LLVMRustModuleBuffer {
1231 extern "C" LLVMRustModuleBuffer*
1232 LLVMRustModuleBufferCreate(LLVMModuleRef M) {
1233 auto Ret = llvm::make_unique<LLVMRustModuleBuffer>();
1235 raw_string_ostream OS(Ret->data);
1237 legacy::PassManager PM;
1238 PM.add(createBitcodeWriterPass(OS));
1242 return Ret.release();
1246 LLVMRustModuleBufferFree(LLVMRustModuleBuffer *Buffer) {
1250 extern "C" const void*
1251 LLVMRustModuleBufferPtr(const LLVMRustModuleBuffer *Buffer) {
1252 return Buffer->data.data();
1256 LLVMRustModuleBufferLen(const LLVMRustModuleBuffer *Buffer) {
1257 return Buffer->data.length();
1261 LLVMRustModuleCost(LLVMModuleRef M) {
1262 auto f = unwrap(M)->functions();
1263 return std::distance(std::begin(f), std::end(f));
1266 // Vector reductions:
1267 extern "C" LLVMValueRef
1268 LLVMRustBuildVectorReduceFAdd(LLVMBuilderRef B, LLVMValueRef Acc, LLVMValueRef Src) {
1269 return wrap(unwrap(B)->CreateFAddReduce(unwrap(Acc),unwrap(Src)));
1271 extern "C" LLVMValueRef
1272 LLVMRustBuildVectorReduceFMul(LLVMBuilderRef B, LLVMValueRef Acc, LLVMValueRef Src) {
1273 return wrap(unwrap(B)->CreateFMulReduce(unwrap(Acc),unwrap(Src)));
1275 extern "C" LLVMValueRef
1276 LLVMRustBuildVectorReduceAdd(LLVMBuilderRef B, LLVMValueRef Src) {
1277 return wrap(unwrap(B)->CreateAddReduce(unwrap(Src)));
1279 extern "C" LLVMValueRef
1280 LLVMRustBuildVectorReduceMul(LLVMBuilderRef B, LLVMValueRef Src) {
1281 return wrap(unwrap(B)->CreateMulReduce(unwrap(Src)));
1283 extern "C" LLVMValueRef
1284 LLVMRustBuildVectorReduceAnd(LLVMBuilderRef B, LLVMValueRef Src) {
1285 return wrap(unwrap(B)->CreateAndReduce(unwrap(Src)));
1287 extern "C" LLVMValueRef
1288 LLVMRustBuildVectorReduceOr(LLVMBuilderRef B, LLVMValueRef Src) {
1289 return wrap(unwrap(B)->CreateOrReduce(unwrap(Src)));
1291 extern "C" LLVMValueRef
1292 LLVMRustBuildVectorReduceXor(LLVMBuilderRef B, LLVMValueRef Src) {
1293 return wrap(unwrap(B)->CreateXorReduce(unwrap(Src)));
1295 extern "C" LLVMValueRef
1296 LLVMRustBuildVectorReduceMin(LLVMBuilderRef B, LLVMValueRef Src, bool IsSigned) {
1297 return wrap(unwrap(B)->CreateIntMinReduce(unwrap(Src), IsSigned));
1299 extern "C" LLVMValueRef
1300 LLVMRustBuildVectorReduceMax(LLVMBuilderRef B, LLVMValueRef Src, bool IsSigned) {
1301 return wrap(unwrap(B)->CreateIntMaxReduce(unwrap(Src), IsSigned));
1303 extern "C" LLVMValueRef
1304 LLVMRustBuildVectorReduceFMin(LLVMBuilderRef B, LLVMValueRef Src, bool NoNaN) {
1305 return wrap(unwrap(B)->CreateFPMinReduce(unwrap(Src), NoNaN));
1307 extern "C" LLVMValueRef
1308 LLVMRustBuildVectorReduceFMax(LLVMBuilderRef B, LLVMValueRef Src, bool NoNaN) {
1309 return wrap(unwrap(B)->CreateFPMaxReduce(unwrap(Src), NoNaN));
1312 #if LLVM_VERSION_GE(6, 0)
1313 extern "C" LLVMValueRef
1314 LLVMRustBuildMinNum(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS) {
1315 return wrap(unwrap(B)->CreateMinNum(unwrap(LHS),unwrap(RHS)));
1317 extern "C" LLVMValueRef
1318 LLVMRustBuildMaxNum(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS) {
1319 return wrap(unwrap(B)->CreateMaxNum(unwrap(LHS),unwrap(RHS)));
1322 extern "C" LLVMValueRef
1323 LLVMRustBuildMinNum(LLVMBuilderRef, LLVMValueRef, LLVMValueRef) {
1326 extern "C" LLVMValueRef
1327 LLVMRustBuildMaxNum(LLVMBuilderRef, LLVMValueRef, LLVMValueRef) {