Skip to content

Commit 6465118

Browse files
authored
Preserve deallocation function via linkage (rust-lang#948)
1 parent 9f04b23 commit 6465118

File tree

2 files changed

+21
-13
lines changed

2 files changed

+21
-13
lines changed

enzyme/Enzyme/PreserveNVVM.cpp

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,24 @@ using namespace llvm;
5252
#if LLVM_VERSION_MAJOR >= 14
5353
#define addAttribute addAttributeAtIndex
5454
#endif
55+
56+
//! Returns whether changed.
57+
bool preserveLinkage(bool Begin, Function &F) {
58+
if (Begin && !F.hasFnAttribute("prev_fixup")) {
59+
F.addFnAttr("prev_fixup");
60+
if (F.hasFnAttribute(Attribute::AlwaysInline))
61+
F.addFnAttr("prev_always_inline");
62+
if (F.hasFnAttribute(Attribute::NoInline))
63+
F.addFnAttr("prev_no_inline");
64+
F.addFnAttr("prev_linkage", std::to_string(F.getLinkage()));
65+
F.setLinkage(Function::LinkageTypes::ExternalLinkage);
66+
F.addFnAttr(Attribute::NoInline);
67+
F.removeFnAttr(Attribute::AlwaysInline);
68+
return true;
69+
}
70+
return false;
71+
}
72+
5573
bool preserveNVVM(bool Begin, Function &F) {
5674
bool changed = false;
5775
std::map<std::string, std::pair<std::string, std::string>> Implements;
@@ -129,18 +147,7 @@ bool preserveNVVM(bool Begin, Function &F) {
129147
break;
130148
}
131149
if (V == &F) {
132-
changed = true;
133-
if (Begin && !F.hasFnAttribute("prev_fixup")) {
134-
F.addFnAttr("prev_fixup");
135-
if (F.hasFnAttribute(Attribute::AlwaysInline))
136-
F.addFnAttr("prev_always_inline");
137-
if (F.hasFnAttribute(Attribute::NoInline))
138-
F.addFnAttr("prev_no_inline");
139-
F.addFnAttr("prev_linkage", std::to_string(F.getLinkage()));
140-
F.setLinkage(Function::LinkageTypes::ExternalLinkage);
141-
F.addFnAttr(Attribute::NoInline);
142-
F.removeFnAttr(Attribute::AlwaysInline);
143-
}
150+
changed |= preserveLinkage(Begin, F);
144151
break;
145152
}
146153
}
@@ -334,6 +341,7 @@ bool preserveNVVM(bool Begin, Function &F) {
334341
"enzyme_deallocator_fn",
335342
llvm::MDTuple::get(F->getContext(),
336343
{llvm::ValueAsMetadata::get(F)}));
344+
changed |= preserveLinkage(Begin, *F);
337345
} else {
338346
llvm::errs() << "Free fn of __enzyme_allocation_like must be a "
339347
"function"

enzyme/test/Integration/ReverseMode/customalloc.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ void* myallocator(void* buffer, int size, int* off) {
2727
return &cur[prev];
2828
}
2929

30-
void* myfree(int* off, void* tofree) {
30+
static void* myfree(int* off, void* tofree) {
3131
printf("freeing %p and %d\n", tofree, *off);
3232
}
3333

0 commit comments

Comments
 (0)