LLVM 23.0.0git
AArch64StackTaggingPreRA.cpp
Go to the documentation of this file.
1//===-- AArch64StackTaggingPreRA.cpp --- Stack Tagging for AArch64 -----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "AArch64.h"
10#include "AArch64InstrInfo.h"
12#include "llvm/ADT/SetVector.h"
13#include "llvm/ADT/Statistic.h"
20#include "llvm/CodeGen/Passes.h"
25#include "llvm/Support/Debug.h"
27
28using namespace llvm;
29
30#define DEBUG_TYPE "aarch64-stack-tagging-pre-ra"
31
33
35 "stack-tagging-unchecked-ld-st", cl::Hidden, cl::init(UncheckedSafe),
37 "Unconditionally apply unchecked-ld-st optimization (even for large "
38 "stack frames, or in the presence of variable sized allocas)."),
40 clEnumValN(UncheckedNever, "never", "never apply unchecked-ld-st"),
42 UncheckedSafe, "safe",
43 "apply unchecked-ld-st when the target is definitely within range"),
44 clEnumValN(UncheckedAlways, "always", "always apply unchecked-ld-st")));
45
46static cl::opt<bool>
47 ClFirstSlot("stack-tagging-first-slot-opt", cl::Hidden, cl::init(true),
48 cl::desc("Apply first slot optimization for stack tagging "
49 "(eliminate ADDG Rt, Rn, 0, 0)."));
50
51namespace {
52
53class AArch64StackTaggingPreRAImpl {
59 const AArch64InstrInfo *TII;
60
62
63public:
64 bool run(MachineFunction &Func);
65
66private:
67 bool mayUseUncheckedLoadStore();
68 void uncheckUsesOf(unsigned TaggedReg, int FI);
69 void uncheckLoadsAndStores();
70 std::optional<int> findFirstSlotCandidate();
71};
72
73class AArch64StackTaggingPreRALegacy : public MachineFunctionPass {
74public:
75 static char ID;
76 AArch64StackTaggingPreRALegacy() : MachineFunctionPass(ID) {}
77
78 bool runOnMachineFunction(MachineFunction &MF) override {
79 if (skipFunction(MF.getFunction()))
80 return false;
81 return AArch64StackTaggingPreRAImpl().run(MF);
82 }
83
84 StringRef getPassName() const override {
85 return "AArch64 Stack Tagging PreRA";
86 }
87
88 void getAnalysisUsage(AnalysisUsage &AU) const override {
89 AU.setPreservesCFG();
91 }
92};
93} // end anonymous namespace
94
95char AArch64StackTaggingPreRALegacy::ID = 0;
96
97INITIALIZE_PASS_BEGIN(AArch64StackTaggingPreRALegacy,
98 "aarch64-stack-tagging-pre-ra",
99 "AArch64 Stack Tagging PreRA Pass", false, false)
100INITIALIZE_PASS_END(AArch64StackTaggingPreRALegacy,
101 "aarch64-stack-tagging-pre-ra",
102 "AArch64 Stack Tagging PreRA Pass", false, false)
103
105 return new AArch64StackTaggingPreRALegacy();
106}
107
111 if (AArch64StackTaggingPreRAImpl().run(MF)) {
114 return PA;
115 }
116 return PreservedAnalyses::all();
117}
118
119static bool isUncheckedLoadOrStoreOpcode(unsigned Opcode) {
120 switch (Opcode) {
121 case AArch64::LDRBBui:
122 case AArch64::LDRHHui:
123 case AArch64::LDRWui:
124 case AArch64::LDRXui:
125
126 case AArch64::LDRBui:
127 case AArch64::LDRHui:
128 case AArch64::LDRSui:
129 case AArch64::LDRDui:
130 case AArch64::LDRQui:
131
132 case AArch64::LDRSHWui:
133 case AArch64::LDRSHXui:
134
135 case AArch64::LDRSBWui:
136 case AArch64::LDRSBXui:
137
138 case AArch64::LDRSWui:
139
140 case AArch64::STRBBui:
141 case AArch64::STRHHui:
142 case AArch64::STRWui:
143 case AArch64::STRXui:
144
145 case AArch64::STRBui:
146 case AArch64::STRHui:
147 case AArch64::STRSui:
148 case AArch64::STRDui:
149 case AArch64::STRQui:
150
151 case AArch64::LDPWi:
152 case AArch64::LDPXi:
153 case AArch64::LDPSi:
154 case AArch64::LDPDi:
155 case AArch64::LDPQi:
156
157 case AArch64::LDPSWi:
158
159 case AArch64::STPWi:
160 case AArch64::STPXi:
161 case AArch64::STPSi:
162 case AArch64::STPDi:
163 case AArch64::STPQi:
164 return true;
165 default:
166 return false;
167 }
168}
169
170bool AArch64StackTaggingPreRAImpl::mayUseUncheckedLoadStore() {
172 return false;
174 return true;
175
176 // This estimate can be improved if we had harder guarantees about stack frame
177 // layout. With LocalStackAllocation we can estimate SP offset to any
178 // preallocated slot. AArch64FrameLowering::orderFrameObjects could put tagged
179 // objects ahead of non-tagged ones, but that's not always desirable.
180 //
181 // Underestimating SP offset here may require the use of LDG to materialize
182 // the tagged address of the stack slot, along with a scratch register
183 // allocation (post-regalloc!).
184 //
185 // For now we do the safe thing here and require that the entire stack frame
186 // is within range of the shortest of the unchecked instructions.
187 unsigned FrameSize = 0;
188 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i)
189 FrameSize += MFI->getObjectSize(i);
190 bool EntireFrameReachableFromSP = FrameSize < 0xf00;
191 return !MFI->hasVarSizedObjects() && EntireFrameReachableFromSP;
192}
193
194void AArch64StackTaggingPreRAImpl::uncheckUsesOf(unsigned TaggedReg, int FI) {
195 for (MachineInstr &UseI :
196 llvm::make_early_inc_range(MRI->use_instructions(TaggedReg))) {
197 if (isUncheckedLoadOrStoreOpcode(UseI.getOpcode())) {
198 // FI operand is always the one before the immediate offset.
199 unsigned OpIdx = TII->getLoadStoreImmIdx(UseI.getOpcode()) - 1;
200 if (UseI.getOperand(OpIdx).isReg() &&
201 UseI.getOperand(OpIdx).getReg() == TaggedReg) {
202 UseI.getOperand(OpIdx).ChangeToFrameIndex(FI);
203 UseI.getOperand(OpIdx).setTargetFlags(AArch64II::MO_TAGGED);
204 }
205 } else if (UseI.isCopy() && UseI.getOperand(0).getReg().isVirtual()) {
206 uncheckUsesOf(UseI.getOperand(0).getReg(), FI);
207 }
208 }
209}
210
211void AArch64StackTaggingPreRAImpl::uncheckLoadsAndStores() {
212 for (auto *I : ReTags) {
213 Register TaggedReg = I->getOperand(0).getReg();
214 int FI = I->getOperand(1).getIndex();
215 uncheckUsesOf(TaggedReg, FI);
216 }
217}
218
219namespace {
220struct SlotWithTag {
221 int FI;
222 int Tag;
223 SlotWithTag(int FI, int Tag) : FI(FI), Tag(Tag) {}
224 explicit SlotWithTag(const MachineInstr &MI)
225 : FI(MI.getOperand(1).getIndex()), Tag(MI.getOperand(4).getImm()) {}
226 bool operator==(const SlotWithTag &Other) const {
227 return FI == Other.FI && Tag == Other.Tag;
228 }
229};
230} // namespace
231
232namespace llvm {
233template <> struct DenseMapInfo<SlotWithTag> {
234 static inline SlotWithTag getEmptyKey() { return {-2, -2}; }
235 static inline SlotWithTag getTombstoneKey() { return {-3, -3}; }
236 static unsigned getHashValue(const SlotWithTag &V) {
239 }
240 static bool isEqual(const SlotWithTag &A, const SlotWithTag &B) {
241 return A == B;
242 }
243};
244} // namespace llvm
245
246static bool isSlotPreAllocated(MachineFrameInfo *MFI, int FI) {
247 return MFI->getUseLocalStackAllocationBlock() &&
248 MFI->isObjectPreAllocated(FI);
249}
250
251// Pin one of the tagged slots to offset 0 from the tagged base pointer.
252// This would make its address available in a virtual register (IRG's def), as
253// opposed to requiring an ADDG instruction to materialize. This effectively
254// eliminates a vreg (by replacing it with direct uses of IRG, which is usually
255// live almost everywhere anyway), and therefore needs to happen before
256// regalloc.
257std::optional<int> AArch64StackTaggingPreRAImpl::findFirstSlotCandidate() {
258 // Find the best (FI, Tag) pair to pin to offset 0.
259 // Looking at the possible uses of a tagged address, the advantage of pinning
260 // is:
261 // - COPY to physical register.
262 // Does not matter, this would trade a MOV instruction for an ADDG.
263 // - ST*G matter, but those mostly appear near the function prologue where all
264 // the tagged addresses need to be materialized anyway; also, counting ST*G
265 // uses would overweight large allocas that require more than one ST*G
266 // instruction.
267 // - Load/Store instructions in the address operand do not require a tagged
268 // pointer, so they also do not benefit. These operands have already been
269 // eliminated (see uncheckLoadsAndStores) so all remaining load/store
270 // instructions count.
271 // - Any other instruction may benefit from being pinned to offset 0.
273 dbgs() << "AArch64StackTaggingPreRAImpl::findFirstSlotCandidate\n");
274 if (!ClFirstSlot)
275 return std::nullopt;
276
278 SlotWithTag MaxScoreST{-1, -1};
279 int MaxScore = -1;
280 for (auto *I : ReTags) {
281 SlotWithTag ST{*I};
282 if (isSlotPreAllocated(MFI, ST.FI))
283 continue;
284
285 Register RetagReg = I->getOperand(0).getReg();
286 if (!RetagReg.isVirtual())
287 continue;
288
289 int Score = 0;
291 WorkList.push_back(RetagReg);
292
293 while (!WorkList.empty()) {
294 Register UseReg = WorkList.pop_back_val();
295 for (auto &UseI : MRI->use_instructions(UseReg)) {
296 unsigned Opcode = UseI.getOpcode();
297 if (Opcode == AArch64::STGi || Opcode == AArch64::ST2Gi ||
298 Opcode == AArch64::STZGi || Opcode == AArch64::STZ2Gi ||
299 Opcode == AArch64::STGPi || Opcode == AArch64::STGloop ||
300 Opcode == AArch64::STZGloop || Opcode == AArch64::STGloop_wback ||
301 Opcode == AArch64::STZGloop_wback)
302 continue;
303 if (UseI.isCopy()) {
304 Register DstReg = UseI.getOperand(0).getReg();
305 if (DstReg.isVirtual())
306 WorkList.push_back(DstReg);
307 continue;
308 }
309 LLVM_DEBUG(dbgs() << "[" << ST.FI << ":" << ST.Tag << "] use of "
310 << printReg(UseReg) << " in " << UseI << "\n");
311 Score++;
312 }
313 }
314
315 int TotalScore = RetagScore[ST] += Score;
316 if (TotalScore > MaxScore ||
317 (TotalScore == MaxScore && ST.FI > MaxScoreST.FI)) {
318 MaxScore = TotalScore;
319 MaxScoreST = ST;
320 }
321 }
322
323 if (MaxScoreST.FI < 0)
324 return std::nullopt;
325
326 // If FI's tag is already 0, we are done.
327 if (MaxScoreST.Tag == 0)
328 return MaxScoreST.FI;
329
330 // Otherwise, find a random victim pair (FI, Tag) where Tag == 0.
331 SlotWithTag SwapST{-1, -1};
332 for (auto *I : ReTags) {
333 SlotWithTag ST{*I};
334 if (ST.Tag == 0) {
335 SwapST = ST;
336 break;
337 }
338 }
339
340 // Swap tags between the victim and the highest scoring pair.
341 // If SwapWith is still (-1, -1), that's fine, too - we'll simply take tag for
342 // the highest score slot without changing anything else.
343 for (auto *&I : ReTags) {
344 SlotWithTag ST{*I};
345 MachineOperand &TagOp = I->getOperand(4);
346 if (ST == MaxScoreST) {
347 TagOp.setImm(0);
348 } else if (ST == SwapST) {
349 TagOp.setImm(MaxScoreST.Tag);
350 }
351 }
352 return MaxScoreST.FI;
353}
354
355bool AArch64StackTaggingPreRAImpl::run(MachineFunction &Func) {
356 MF = &Func;
357 MRI = &MF->getRegInfo();
358 AFI = MF->getInfo<AArch64FunctionInfo>();
359 TII = static_cast<const AArch64InstrInfo *>(MF->getSubtarget().getInstrInfo());
360 TRI = static_cast<const AArch64RegisterInfo *>(
361 MF->getSubtarget().getRegisterInfo());
362 MFI = &MF->getFrameInfo();
363 ReTags.clear();
364
365 assert(MRI->isSSA());
366
367 LLVM_DEBUG(dbgs() << "********** AArch64 Stack Tagging PreRA **********\n"
368 << "********** Function: " << MF->getName() << '\n');
369
370 SmallSetVector<int, 8> TaggedSlots;
371 for (auto &BB : *MF) {
372 for (auto &I : BB) {
373 if (I.getOpcode() == AArch64::TAGPstack) {
374 ReTags.push_back(&I);
375 int FI = I.getOperand(1).getIndex();
376 TaggedSlots.insert(FI);
377 // There should be no offsets in TAGP yet.
378 assert(I.getOperand(2).getImm() == 0);
379 }
380 }
381 }
382
383 // Take over from SSP. It does nothing for tagged slots, and should not really
384 // have been enabled in the first place.
385 for (int FI : TaggedSlots)
386 MFI->setObjectSSPLayout(FI, MachineFrameInfo::SSPLK_None);
387
388 if (ReTags.empty())
389 return false;
390
391 if (mayUseUncheckedLoadStore())
392 uncheckLoadsAndStores();
393
394 // Find a slot that is used with zero tag offset, like ADDG #fi, 0.
395 // If the base tagged pointer is set up to the address of this slot,
396 // the ADDG instruction can be eliminated.
397 std::optional<int> BaseSlot = findFirstSlotCandidate();
398 if (BaseSlot)
399 AFI->setTaggedBasePointerIndex(*BaseSlot);
400
401 for (auto *I : ReTags) {
402 int FI = I->getOperand(1).getIndex();
403 int Tag = I->getOperand(4).getImm();
404 Register Base = I->getOperand(3).getReg();
405 if (Tag == 0 && FI == BaseSlot) {
406 BuildMI(*I->getParent(), I, {}, TII->get(AArch64::COPY),
407 I->getOperand(0).getReg())
408 .addReg(Base);
410 }
411 }
412
413 return true;
414}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool isSlotPreAllocated(MachineFrameInfo *MFI, int FI)
static cl::opt< UncheckedLdStMode > ClUncheckedLdSt("stack-tagging-unchecked-ld-st", cl::Hidden, cl::init(UncheckedSafe), cl::desc("Unconditionally apply unchecked-ld-st optimization (even for large " "stack frames, or in the presence of variable sized allocas)."), cl::values(clEnumValN(UncheckedNever, "never", "never apply unchecked-ld-st"), clEnumValN(UncheckedSafe, "safe", "apply unchecked-ld-st when the target is definitely within range"), clEnumValN(UncheckedAlways, "always", "always apply unchecked-ld-st")))
static cl::opt< bool > ClFirstSlot("stack-tagging-first-slot-opt", cl::Hidden, cl::init(true), cl::desc("Apply first slot optimization for stack tagging " "(eliminate ADDG Rt, Rn, 0, 0)."))
static bool isUncheckedLoadOrStoreOpcode(unsigned Opcode)
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
static Register UseReg(const MachineOperand &MO)
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
Register const TargetRegisterInfo * TRI
MachineInstr unsigned OpIdx
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file implements a set that has insertion order iteration characteristics.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define LLVM_DEBUG(...)
Definition Debug.h:114
AArch64FunctionInfo - This class is derived from MachineFunctionInfo and contains private AArch64-spe...
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:270
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
bool isObjectPreAllocated(int ObjectIdx) const
Return true if the object was pre-allocated into the local block.
@ SSPLK_None
Did not trigger a stack protector.
bool getUseLocalStackAllocationBlock() const
Get whether the local allocation blob should be allocated together or let PEI allocate the locals in ...
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
MachineOperand class - Representation of each machine instruction operand.
void setImm(int64_t immVal)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:151
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:339
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
@ MO_TAGGED
MO_TAGGED - With MO_PAGE, indicates that the page includes a memory tag in bits 56-63.
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:634
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
FunctionPass * createAArch64StackTaggingPreRALegacyPass()
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
@ Other
Any other memory.
Definition ModRef.h:68
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition Hashing.h:592
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
static bool isEqual(const SlotWithTag &A, const SlotWithTag &B)
static unsigned getHashValue(const SlotWithTag &V)
An information struct used to provide DenseMap with the various necessary components for a given valu...