Skip to content

Commit ad6a8b3

Browse files
committed
[CodeGen][ARM64EC] Add support for hybrid_patchable attribute.
1 parent e64ed1d commit ad6a8b3

File tree

10 files changed

+482
-11
lines changed

10 files changed

+482
-11
lines changed

llvm/include/llvm/Bitcode/LLVMBitCodes.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -755,6 +755,7 @@ enum AttributeKindCodes {
755755
ATTR_KIND_DEAD_ON_UNWIND = 91,
756756
ATTR_KIND_RANGE = 92,
757757
ATTR_KIND_SANITIZE_NUMERICAL_STABILITY = 93,
758+
ATTR_KIND_HYBRID_PATCHABLE = 94,
758759
};
759760

760761
enum ComdatSelectionKindCodes {

llvm/include/llvm/CodeGen/AsmPrinter.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -905,14 +905,14 @@ class AsmPrinter : public MachineFunctionPass {
905905
virtual void emitModuleCommandLines(Module &M);
906906

907907
GCMetadataPrinter *getOrCreateGCPrinter(GCStrategy &S);
908-
virtual void emitGlobalAlias(const Module &M, const GlobalAlias &GA);
909908
void emitGlobalIFunc(Module &M, const GlobalIFunc &GI);
910909

911910
private:
912911
/// This method decides whether the specified basic block requires a label.
913912
bool shouldEmitLabelForBasicBlock(const MachineBasicBlock &MBB) const;
914913

915914
protected:
915+
virtual void emitGlobalAlias(const Module &M, const GlobalAlias &GA);
916916
virtual bool shouldEmitWeakSwiftAsyncExtendedFramePointerFlags() const {
917917
return false;
918918
}

llvm/include/llvm/IR/Attributes.td

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,9 @@ def ElementType : TypeAttr<"elementtype", [ParamAttr]>;
109109
/// symbol.
110110
def FnRetThunkExtern : EnumAttr<"fn_ret_thunk_extern", [FnAttr]>;
111111

112+
/// Function has a hybrid patchable thunk.
113+
def HybridPatchable : EnumAttr<"hybrid_patchable", [FnAttr]>;
114+
112115
/// Pass structure in an alloca.
113116
def InAlloca : TypeAttr<"inalloca", [ParamAttr]>;
114117

llvm/lib/Bitcode/Writer/BitcodeWriter.cpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -716,6 +716,8 @@ static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
716716
return bitc::ATTR_KIND_HOT;
717717
case Attribute::ElementType:
718718
return bitc::ATTR_KIND_ELEMENTTYPE;
719+
case Attribute::HybridPatchable:
720+
return bitc::ATTR_KIND_HYBRID_PATCHABLE;
719721
case Attribute::InlineHint:
720722
return bitc::ATTR_KIND_INLINE_HINT;
721723
case Attribute::InReg:

llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2903,8 +2903,8 @@ bool AsmPrinter::emitSpecialLLVMGlobal(const GlobalVariable *GV) {
29032903
auto *Arr = cast<ConstantArray>(GV->getInitializer());
29042904
for (auto &U : Arr->operands()) {
29052905
auto *C = cast<Constant>(U);
2906-
auto *Src = cast<Function>(C->getOperand(0)->stripPointerCasts());
2907-
auto *Dst = cast<Function>(C->getOperand(1)->stripPointerCasts());
2906+
auto *Src = cast<GlobalValue>(C->getOperand(0)->stripPointerCasts());
2907+
auto *Dst = cast<GlobalValue>(C->getOperand(1)->stripPointerCasts());
29082908
int Kind = cast<ConstantInt>(C->getOperand(2))->getZExtValue();
29092909

29102910
if (Src->hasDLLImportStorageClass()) {

llvm/lib/Target/AArch64/AArch64Arm64ECCallLowering.cpp

Lines changed: 129 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
#include "llvm/ADT/SmallVector.h"
2222
#include "llvm/ADT/Statistic.h"
2323
#include "llvm/IR/CallingConv.h"
24+
#include "llvm/IR/GlobalAlias.h"
2425
#include "llvm/IR/IRBuilder.h"
2526
#include "llvm/IR/Instruction.h"
2627
#include "llvm/IR/Mangler.h"
@@ -57,15 +58,21 @@ class AArch64Arm64ECCallLowering : public ModulePass {
5758
Function *buildEntryThunk(Function *F);
5859
void lowerCall(CallBase *CB);
5960
Function *buildGuestExitThunk(Function *F);
60-
bool processFunction(Function &F, SetVector<Function *> &DirectCalledFns);
61+
Function *buildPatchableThunk(GlobalAlias *UnmangledAlias,
62+
GlobalAlias *MangledAlias);
63+
bool processFunction(Function &F, SetVector<GlobalValue *> &DirectCalledFns,
64+
DenseMap<GlobalAlias *, GlobalAlias *> &FnsMap);
6165
bool runOnModule(Module &M) override;
6266

6367
private:
6468
int cfguard_module_flag = 0;
6569
FunctionType *GuardFnType = nullptr;
6670
PointerType *GuardFnPtrType = nullptr;
71+
FunctionType *DispatchFnType = nullptr;
72+
PointerType *DispatchFnPtrType = nullptr;
6773
Constant *GuardFnCFGlobal = nullptr;
6874
Constant *GuardFnGlobal = nullptr;
75+
Constant *DispatchFnGlobal = nullptr;
6976
Module *M = nullptr;
7077

7178
Type *PtrTy;
@@ -615,6 +622,64 @@ Function *AArch64Arm64ECCallLowering::buildGuestExitThunk(Function *F) {
615622
return GuestExit;
616623
}
617624

625+
Function *
626+
AArch64Arm64ECCallLowering::buildPatchableThunk(GlobalAlias *UnmangledAlias,
627+
GlobalAlias *MangledAlias) {
628+
llvm::raw_null_ostream NullThunkName;
629+
FunctionType *Arm64Ty, *X64Ty;
630+
Function *F = cast<Function>(MangledAlias->getAliasee());
631+
getThunkType(F->getFunctionType(), F->getAttributes(),
632+
Arm64ECThunkType::GuestExit, NullThunkName, Arm64Ty, X64Ty);
633+
std::string ThunkName(MangledAlias->getName());
634+
if (ThunkName[0] == '?' && ThunkName.find("@") != std::string::npos) {
635+
ThunkName.insert(ThunkName.find("@"), "$hybpatch_thunk");
636+
} else {
637+
ThunkName.append("$hybpatch_thunk");
638+
}
639+
640+
Function *GuestExit =
641+
Function::Create(Arm64Ty, GlobalValue::WeakODRLinkage, 0, ThunkName, M);
642+
GuestExit->setComdat(M->getOrInsertComdat(ThunkName));
643+
GuestExit->setSection(".wowthk$aa");
644+
BasicBlock *BB = BasicBlock::Create(M->getContext(), "", GuestExit);
645+
IRBuilder<> B(BB);
646+
647+
// Load the global symbol as a pointer to the check function.
648+
LoadInst *DispatchLoad = B.CreateLoad(DispatchFnPtrType, DispatchFnGlobal);
649+
650+
// Create new dispatch call instruction.
651+
Function *ExitThunk =
652+
buildExitThunk(F->getFunctionType(), F->getAttributes());
653+
CallInst *Dispatch =
654+
B.CreateCall(DispatchFnType, DispatchLoad,
655+
{UnmangledAlias, ExitThunk, UnmangledAlias->getAliasee()});
656+
657+
// Ensure that the first arguments are passed in the correct registers.
658+
Dispatch->setCallingConv(CallingConv::CFGuard_Check);
659+
660+
Value *DispatchRetVal = B.CreateBitCast(Dispatch, PtrTy);
661+
SmallVector<Value *> Args;
662+
for (Argument &Arg : GuestExit->args())
663+
Args.push_back(&Arg);
664+
CallInst *Call = B.CreateCall(Arm64Ty, DispatchRetVal, Args);
665+
Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
666+
667+
if (Call->getType()->isVoidTy())
668+
B.CreateRetVoid();
669+
else
670+
B.CreateRet(Call);
671+
672+
auto SRetAttr = F->getAttributes().getParamAttr(0, Attribute::StructRet);
673+
auto InRegAttr = F->getAttributes().getParamAttr(0, Attribute::InReg);
674+
if (SRetAttr.isValid() && !InRegAttr.isValid()) {
675+
GuestExit->addParamAttr(0, SRetAttr);
676+
Call->addParamAttr(0, SRetAttr);
677+
}
678+
679+
MangledAlias->setAliasee(GuestExit);
680+
return GuestExit;
681+
}
682+
618683
// Lower an indirect call with inline code.
619684
void AArch64Arm64ECCallLowering::lowerCall(CallBase *CB) {
620685
assert(Triple(CB->getModule()->getTargetTriple()).isOSWindows() &&
@@ -670,17 +735,57 @@ bool AArch64Arm64ECCallLowering::runOnModule(Module &Mod) {
670735

671736
GuardFnType = FunctionType::get(PtrTy, {PtrTy, PtrTy}, false);
672737
GuardFnPtrType = PointerType::get(GuardFnType, 0);
738+
DispatchFnType = FunctionType::get(PtrTy, {PtrTy, PtrTy, PtrTy}, false);
739+
DispatchFnPtrType = PointerType::get(DispatchFnType, 0);
673740
GuardFnCFGlobal =
674741
M->getOrInsertGlobal("__os_arm64x_check_icall_cfg", GuardFnPtrType);
675742
GuardFnGlobal =
676743
M->getOrInsertGlobal("__os_arm64x_check_icall", GuardFnPtrType);
744+
DispatchFnGlobal =
745+
M->getOrInsertGlobal("__os_arm64x_dispatch_call", DispatchFnPtrType);
746+
747+
DenseMap<GlobalAlias *, GlobalAlias *> FnsMap;
748+
SetVector<GlobalAlias *> PatchableFns;
677749

678-
SetVector<Function *> DirectCalledFns;
750+
for (Function &F : Mod) {
751+
if (!F.hasFnAttribute(Attribute::HybridPatchable) || F.isDeclaration() ||
752+
F.hasLocalLinkage() || F.getName().ends_with("$hp_target"))
753+
continue;
754+
755+
// Rename hybrid patchable functions and change callers to use a global
756+
// alias instead.
757+
if (std::optional<std::string> MangledName =
758+
getArm64ECMangledFunctionName(F.getName().str())) {
759+
std::string OrigName(F.getName());
760+
F.setName(MangledName.value() + "$hp_target");
761+
762+
// The unmangled symbol is a weak alias to an undefined symbol with the
763+
// "EXP+" prefix. This undefined symbol is resolved by the linker by
764+
// creating an x86 thunk that jumps back to the actual EC target. Since we
765+
// can't represent that in IR, we create an alias to the target instead.
766+
// The "EXP+" symbol is set as metadata, which is then used by
767+
// emitGlobalAlias to emit the right alias.
768+
auto *A =
769+
GlobalAlias::create(GlobalValue::LinkOnceODRLinkage, OrigName, &F);
770+
F.replaceAllUsesWith(A);
771+
F.setMetadata("arm64ec_exp_name",
772+
MDNode::get(M->getContext(),
773+
MDString::get(M->getContext(),
774+
"EXP+" + MangledName.value())));
775+
A->setAliasee(&F);
776+
777+
FnsMap[A] = GlobalAlias::create(GlobalValue::LinkOnceODRLinkage,
778+
MangledName.value(), &F);
779+
PatchableFns.insert(A);
780+
}
781+
}
782+
783+
SetVector<GlobalValue *> DirectCalledFns;
679784
for (Function &F : Mod)
680785
if (!F.isDeclaration() &&
681786
F.getCallingConv() != CallingConv::ARM64EC_Thunk_Native &&
682787
F.getCallingConv() != CallingConv::ARM64EC_Thunk_X64)
683-
processFunction(F, DirectCalledFns);
788+
processFunction(F, DirectCalledFns, FnsMap);
684789

685790
struct ThunkInfo {
686791
Constant *Src;
@@ -698,14 +803,20 @@ bool AArch64Arm64ECCallLowering::runOnModule(Module &Mod) {
698803
{&F, buildEntryThunk(&F), Arm64ECThunkType::Entry});
699804
}
700805
}
701-
for (Function *F : DirectCalledFns) {
806+
for (GlobalValue *O : DirectCalledFns) {
807+
auto GA = dyn_cast<GlobalAlias>(O);
808+
auto F = dyn_cast<Function>(GA ? GA->getAliasee() : O);
702809
ThunkMapping.push_back(
703-
{F, buildExitThunk(F->getFunctionType(), F->getAttributes()),
810+
{O, buildExitThunk(F->getFunctionType(), F->getAttributes()),
704811
Arm64ECThunkType::Exit});
705-
if (!F->hasDLLImportStorageClass())
812+
if (!GA && !F->hasDLLImportStorageClass())
706813
ThunkMapping.push_back(
707814
{buildGuestExitThunk(F), F, Arm64ECThunkType::GuestExit});
708815
}
816+
for (GlobalAlias *A : PatchableFns) {
817+
Function *Thunk = buildPatchableThunk(A, FnsMap[A]);
818+
ThunkMapping.push_back({Thunk, A, Arm64ECThunkType::GuestExit});
819+
}
709820

710821
if (!ThunkMapping.empty()) {
711822
SmallVector<Constant *> ThunkMappingArrayElems;
@@ -728,7 +839,8 @@ bool AArch64Arm64ECCallLowering::runOnModule(Module &Mod) {
728839
}
729840

730841
bool AArch64Arm64ECCallLowering::processFunction(
731-
Function &F, SetVector<Function *> &DirectCalledFns) {
842+
Function &F, SetVector<GlobalValue *> &DirectCalledFns,
843+
DenseMap<GlobalAlias *, GlobalAlias *> &FnsMap) {
732844
SmallVector<CallBase *, 8> IndirectCalls;
733845

734846
// For ARM64EC targets, a function definition's name is mangled differently
@@ -780,6 +892,16 @@ bool AArch64Arm64ECCallLowering::processFunction(
780892
continue;
781893
}
782894

895+
// Use mangled global alias for direct calls to patchable functions.
896+
if (GlobalAlias *A = dyn_cast<GlobalAlias>(CB->getCalledOperand())) {
897+
auto I = FnsMap.find(A);
898+
if (I != FnsMap.end()) {
899+
CB->setCalledOperand(I->second);
900+
DirectCalledFns.insert(I->first);
901+
continue;
902+
}
903+
}
904+
783905
IndirectCalls.push_back(CB);
784906
++Arm64ECCallsLowered;
785907
}

llvm/lib/Target/AArch64/AArch64AsmPrinter.cpp

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,7 @@ class AArch64AsmPrinter : public AsmPrinter {
193193
void PrintDebugValueComment(const MachineInstr *MI, raw_ostream &OS);
194194

195195
void emitFunctionBodyEnd() override;
196+
void emitGlobalAlias(const Module &M, const GlobalAlias &GA) override;
196197

197198
MCSymbol *GetCPISymbol(unsigned CPID) const override;
198199
void emitEndOfAsmFile(Module &M) override;
@@ -1210,6 +1211,32 @@ void AArch64AsmPrinter::emitFunctionEntryLabel() {
12101211
}
12111212
}
12121213

1214+
void AArch64AsmPrinter::emitGlobalAlias(const Module &M,
1215+
const GlobalAlias &GA) {
1216+
if (auto F = dyn_cast_or_null<Function>(GA.getAliasee())) {
1217+
// Global aliases must point to a definition, but unmangled patchable
1218+
// symbols are special and need to point to an undefined symbol with "EXP+"
1219+
// prefix. Such undefined symbol is resolved by the linker by creating
1220+
// x86 thunk that jumps back to the actual EC target.
1221+
if (MDNode *Node = F->getMetadata("arm64ec_exp_name")) {
1222+
StringRef ExpStr = cast<MDString>(Node->getOperand(0))->getString();
1223+
MCSymbol *ExpSym = MMI->getContext().getOrCreateSymbol(ExpStr);
1224+
MCSymbol *Sym = MMI->getContext().getOrCreateSymbol(GA.getName());
1225+
OutStreamer->beginCOFFSymbolDef(Sym);
1226+
OutStreamer->emitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_EXTERNAL);
1227+
OutStreamer->emitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
1228+
<< COFF::SCT_COMPLEX_TYPE_SHIFT);
1229+
OutStreamer->endCOFFSymbolDef();
1230+
OutStreamer->emitSymbolAttribute(Sym, MCSA_Weak);
1231+
OutStreamer->emitAssignment(
1232+
Sym, MCSymbolRefExpr::create(ExpSym, MCSymbolRefExpr::VK_None,
1233+
MMI->getContext()));
1234+
return;
1235+
}
1236+
}
1237+
AsmPrinter::emitGlobalAlias(M, GA);
1238+
}
1239+
12131240
/// Small jump tables contain an unsigned byte or half, representing the offset
12141241
/// from the lowest-addressed possible destination to the desired basic
12151242
/// block. Since all instructions are 4-byte aligned, this is further compressed

llvm/lib/Target/AArch64/AArch64CallingConvention.td

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -333,7 +333,7 @@ def CC_AArch64_Win64_CFGuard_Check : CallingConv<[
333333

334334
let Entry = 1 in
335335
def CC_AArch64_Arm64EC_CFGuard_Check : CallingConv<[
336-
CCIfType<[i64], CCAssignToReg<[X11, X10]>>
336+
CCIfType<[i64], CCAssignToReg<[X11, X10, X9]>>
337337
]>;
338338

339339
let Entry = 1 in

llvm/lib/Transforms/Utils/CodeExtractor.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -932,6 +932,7 @@ Function *CodeExtractor::constructFunction(const ValueSet &inputs,
932932
case Attribute::DisableSanitizerInstrumentation:
933933
case Attribute::FnRetThunkExtern:
934934
case Attribute::Hot:
935+
case Attribute::HybridPatchable:
935936
case Attribute::NoRecurse:
936937
case Attribute::InlineHint:
937938
case Attribute::MinSize:

0 commit comments

Comments
 (0)