1//=- AArch64MachineFunctionInfo.cpp - AArch64 Machine Function Info ---------=//
2
3//
4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// This file implements AArch64-specific per-machine-function
12/// information.
13///
14//===----------------------------------------------------------------------===//
15
16#include "AArch64MachineFunctionInfo.h"
17#include "AArch64InstrInfo.h"
18#include "AArch64Subtarget.h"
19#include "llvm/ADT/StringSwitch.h"
20#include "llvm/IR/Constants.h"
21#include "llvm/IR/DiagnosticInfo.h"
22#include "llvm/IR/Metadata.h"
23#include "llvm/IR/Module.h"
24#include "llvm/MC/MCAsmInfo.h"
25
26using namespace llvm;
27
28static std::optional<uint64_t>
29getSVEStackSize(const AArch64FunctionInfo &MFI,
30 uint64_t (AArch64FunctionInfo::*GetStackSize)() const) {
31 if (!MFI.hasCalculatedStackSizeSVE())
32 return std::nullopt;
33 return (MFI.*GetStackSize)();
34}
35
36yaml::AArch64FunctionInfo::AArch64FunctionInfo(
37 const llvm::AArch64FunctionInfo &MFI)
38 : HasRedZone(MFI.hasRedZone()),
39 StackSizeZPR(
40 getSVEStackSize(MFI, GetStackSize: &llvm::AArch64FunctionInfo::getStackSizeZPR)),
41 StackSizePPR(
42 getSVEStackSize(MFI, GetStackSize: &llvm::AArch64FunctionInfo::getStackSizePPR)),
43 HasStackFrame(MFI.hasStackFrame()
44 ? std::optional<bool>(MFI.hasStackFrame())
45 : std::nullopt),
46 HasStreamingModeChanges(
47 MFI.hasStreamingModeChanges()
48 ? std::optional<bool>(MFI.hasStreamingModeChanges())
49 : std::nullopt) {}
50
51void yaml::AArch64FunctionInfo::mappingImpl(yaml::IO &YamlIO) {
52 MappingTraits<AArch64FunctionInfo>::mapping(YamlIO, MFI&: *this);
53}
54
55void AArch64FunctionInfo::initializeBaseYamlFields(
56 const yaml::AArch64FunctionInfo &YamlMFI) {
57 if (YamlMFI.HasRedZone)
58 HasRedZone = YamlMFI.HasRedZone;
59 if (YamlMFI.StackSizeZPR || YamlMFI.StackSizePPR)
60 setStackSizeSVE(ZPR: YamlMFI.StackSizeZPR.value_or(u: 0),
61 PPR: YamlMFI.StackSizePPR.value_or(u: 0));
62 if (YamlMFI.HasStackFrame)
63 setHasStackFrame(*YamlMFI.HasStackFrame);
64 if (YamlMFI.HasStreamingModeChanges)
65 setHasStreamingModeChanges(*YamlMFI.HasStreamingModeChanges);
66}
67
68static SignReturnAddress GetSignReturnAddress(const Function &F) {
69 if (F.hasFnAttribute(Kind: "ptrauth-returns"))
70 return SignReturnAddress::NonLeaf;
71
72 // The function should be signed in the following situations:
73 // - sign-return-address=all
74 // - sign-return-address=non-leaf and the functions spills the LR
75 if (!F.hasFnAttribute(Kind: "sign-return-address"))
76 return SignReturnAddress::None;
77
78 StringRef Scope = F.getFnAttribute(Kind: "sign-return-address").getValueAsString();
79 return StringSwitch<SignReturnAddress>(Scope)
80 .Case(S: "none", Value: SignReturnAddress::None)
81 .Case(S: "non-leaf", Value: SignReturnAddress::NonLeaf)
82 .Case(S: "all", Value: SignReturnAddress::All);
83}
84
85static bool ShouldSignWithBKey(const Function &F, const AArch64Subtarget &STI) {
86 if (F.hasFnAttribute(Kind: "ptrauth-returns"))
87 return true;
88 if (!F.hasFnAttribute(Kind: "sign-return-address-key")) {
89 if (STI.getTargetTriple().isOSWindows())
90 return true;
91 return false;
92 }
93
94 const StringRef Key =
95 F.getFnAttribute(Kind: "sign-return-address-key").getValueAsString();
96 assert(Key == "a_key" || Key == "b_key");
97 if (STI.getTargetTriple().isOSWindows() && Key == "a_key" &&
98 GetSignReturnAddress(F) != SignReturnAddress::None) {
99 F.getContext().diagnose(DI: DiagnosticInfoUnsupported{
100 F, "A-key return address signing is unsupported on AArch64 Windows"});
101 return true;
102 }
103 return Key == "b_key";
104}
105
106static bool hasELFSignedGOTHelper(const Function &F,
107 const AArch64Subtarget *STI) {
108 if (!STI->getTargetTriple().isOSBinFormatELF())
109 return false;
110 const Module *M = F.getParent();
111 const auto *Flag = mdconst::extract_or_null<ConstantInt>(
112 MD: M->getModuleFlag(Key: "ptrauth-elf-got"));
113 if (Flag && Flag->getZExtValue() == 1)
114 return true;
115 return false;
116}
117
118AArch64FunctionInfo::AArch64FunctionInfo(const Function &F,
119 const AArch64Subtarget *STI) {
120 // If we already know that the function doesn't have a redzone, set
121 // HasRedZone here.
122 if (F.hasFnAttribute(Kind: Attribute::NoRedZone))
123 HasRedZone = false;
124 SignCondition = GetSignReturnAddress(F);
125 SignWithBKey = ShouldSignWithBKey(F, STI: *STI);
126 HasELFSignedGOT = hasELFSignedGOTHelper(F, STI);
127 // TODO: skip functions that have no instrumented allocas for optimization
128 IsMTETagged = F.hasFnAttribute(Kind: Attribute::SanitizeMemTag);
129
130 // BTI/PAuthLR are set on the function attribute.
131 BranchTargetEnforcement = F.hasFnAttribute(Kind: "branch-target-enforcement");
132 BranchProtectionPAuthLR = F.hasFnAttribute(Kind: "branch-protection-pauth-lr");
133
134 // Parse the SME function attributes.
135 SMEFnAttrs = SMEAttrs(F);
136
137 // The default stack probe size is 4096 if the function has no
138 // stack-probe-size attribute. This is a safe default because it is the
139 // smallest possible guard page size.
140 uint64_t ProbeSize = 4096;
141 if (F.hasFnAttribute(Kind: "stack-probe-size"))
142 ProbeSize = F.getFnAttributeAsParsedInteger(Kind: "stack-probe-size");
143 else if (const auto *PS = mdconst::extract_or_null<ConstantInt>(
144 MD: F.getParent()->getModuleFlag(Key: "stack-probe-size")))
145 ProbeSize = PS->getZExtValue();
146 assert(int64_t(ProbeSize) > 0 && "Invalid stack probe size");
147
148 if (STI->isTargetWindows()) {
149 if (!F.hasFnAttribute(Kind: "no-stack-arg-probe"))
150 StackProbeSize = ProbeSize;
151 } else {
152 // Round down to the stack alignment.
153 uint64_t StackAlign =
154 STI->getFrameLowering()->getTransientStackAlign().value();
155 ProbeSize = std::max(a: StackAlign, b: ProbeSize & ~(StackAlign - 1U));
156 StringRef ProbeKind;
157 if (F.hasFnAttribute(Kind: "probe-stack"))
158 ProbeKind = F.getFnAttribute(Kind: "probe-stack").getValueAsString();
159 else if (const auto *PS = dyn_cast_or_null<MDString>(
160 Val: F.getParent()->getModuleFlag(Key: "probe-stack")))
161 ProbeKind = PS->getString();
162 if (ProbeKind.size()) {
163 if (ProbeKind != "inline-asm")
164 report_fatal_error(reason: "Unsupported stack probing method");
165 StackProbeSize = ProbeSize;
166 }
167 }
168}
169
170MachineFunctionInfo *AArch64FunctionInfo::clone(
171 BumpPtrAllocator &Allocator, MachineFunction &DestMF,
172 const DenseMap<MachineBasicBlock *, MachineBasicBlock *> &Src2DstMBB)
173 const {
174 return DestMF.cloneInfo<AArch64FunctionInfo>(Old: *this);
175}
176
177static bool isLRSpilled(const MachineFunction &MF) {
178 return llvm::any_of(
179 Range: MF.getFrameInfo().getCalleeSavedInfo(),
180 P: [](const auto &Info) { return Info.getReg() == AArch64::LR; });
181}
182
183bool AArch64FunctionInfo::shouldSignReturnAddress(SignReturnAddress Condition,
184 bool IsLRSpilled) {
185 switch (Condition) {
186 case SignReturnAddress::None:
187 return false;
188 case SignReturnAddress::NonLeaf:
189 return IsLRSpilled;
190 case SignReturnAddress::All:
191 return true;
192 }
193 llvm_unreachable("Unknown SignReturnAddress enum");
194}
195
196bool AArch64FunctionInfo::shouldSignReturnAddress(
197 const MachineFunction &MF) const {
198 return shouldSignReturnAddress(Condition: SignCondition, IsLRSpilled: isLRSpilled(MF));
199}
200
201bool AArch64FunctionInfo::needsShadowCallStackPrologueEpilogue(
202 MachineFunction &MF) const {
203 if (!(isLRSpilled(MF) &&
204 MF.getFunction().hasFnAttribute(Kind: Attribute::ShadowCallStack)))
205 return false;
206
207 if (!MF.getSubtarget<AArch64Subtarget>().isXRegisterReserved(i: 18))
208 report_fatal_error(reason: "Must reserve x18 to use shadow call stack");
209
210 return true;
211}
212
213bool AArch64FunctionInfo::needsDwarfUnwindInfo(
214 const MachineFunction &MF) const {
215 if (!NeedsDwarfUnwindInfo)
216 NeedsDwarfUnwindInfo =
217 MF.needsFrameMoves() && !MF.getTarget().getMCAsmInfo().usesWindowsCFI();
218
219 return *NeedsDwarfUnwindInfo;
220}
221
222bool AArch64FunctionInfo::needsAsyncDwarfUnwindInfo(
223 const MachineFunction &MF) const {
224 if (!NeedsAsyncDwarfUnwindInfo) {
225 const Function &F = MF.getFunction();
226 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
227 // The check got "minsize" is because epilogue unwind info is not emitted
228 // (yet) for homogeneous epilogues, outlined functions, and functions
229 // outlined from.
230 NeedsAsyncDwarfUnwindInfo =
231 needsDwarfUnwindInfo(MF) &&
232 ((F.getUWTableKind() == UWTableKind::Async && !F.hasMinSize()) ||
233 AFI->hasStreamingModeChanges());
234 }
235 return *NeedsAsyncDwarfUnwindInfo;
236}
237