LLVM 24.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"
24#include "llvm/Support/Debug.h"
26
27using namespace llvm;
28
29#define DEBUG_TYPE "aarch64-stack-tagging-pre-ra"
30
31namespace {
32
33class AArch64StackTaggingPreRAImpl {
38 const AArch64InstrInfo *TII;
39
41
42public:
43 bool run(MachineFunction &Func);
44
45private:
46 bool mayUseUncheckedLoadStore();
47 void uncheckUsesOf(unsigned TaggedReg, int FI);
48 void uncheckLoadsAndStores();
49 std::optional<int> findFirstSlotCandidate();
50};
51
52class AArch64StackTaggingPreRALegacy : public MachineFunctionPass {
53public:
54 static char ID;
55 AArch64StackTaggingPreRALegacy() : MachineFunctionPass(ID) {}
56
57 bool runOnMachineFunction(MachineFunction &MF) override {
58 if (skipFunction(MF.getFunction()))
59 return false;
60 return AArch64StackTaggingPreRAImpl().run(MF);
61 }
62
63 StringRef getPassName() const override {
64 return "AArch64 Stack Tagging PreRA";
65 }
66
67 void getAnalysisUsage(AnalysisUsage &AU) const override {
68 AU.setPreservesCFG();
70 }
71};
72} // end anonymous namespace
73
74char AArch64StackTaggingPreRALegacy::ID = 0;
75
76INITIALIZE_PASS_BEGIN(AArch64StackTaggingPreRALegacy,
77 "aarch64-stack-tagging-pre-ra",
78 "AArch64 Stack Tagging PreRA Pass", false, false)
79INITIALIZE_PASS_END(AArch64StackTaggingPreRALegacy,
80 "aarch64-stack-tagging-pre-ra",
81 "AArch64 Stack Tagging PreRA Pass", false, false)
82
84 return new AArch64StackTaggingPreRALegacy();
85}
86
90 if (AArch64StackTaggingPreRAImpl().run(MF)) {
93 return PA;
94 }
96}
97
98static bool isUncheckedLoadOrStoreOpcode(unsigned Opcode) {
99 switch (Opcode) {
100 case AArch64::LDRBBui:
101 case AArch64::LDRHHui:
102 case AArch64::LDRWui:
103 case AArch64::LDRXui:
104
105 case AArch64::LDRBui:
106 case AArch64::LDRHui:
107 case AArch64::LDRSui:
108 case AArch64::LDRDui:
109 case AArch64::LDRQui:
110
111 case AArch64::LDRSHWui:
112 case AArch64::LDRSHXui:
113
114 case AArch64::LDRSBWui:
115 case AArch64::LDRSBXui:
116
117 case AArch64::LDRSWui:
118
119 case AArch64::STRBBui:
120 case AArch64::STRHHui:
121 case AArch64::STRWui:
122 case AArch64::STRXui:
123
124 case AArch64::STRBui:
125 case AArch64::STRHui:
126 case AArch64::STRSui:
127 case AArch64::STRDui:
128 case AArch64::STRQui:
129
130 case AArch64::LDPWi:
131 case AArch64::LDPXi:
132 case AArch64::LDPSi:
133 case AArch64::LDPDi:
134 case AArch64::LDPQi:
135
136 case AArch64::LDPSWi:
137
138 case AArch64::STPWi:
139 case AArch64::STPXi:
140 case AArch64::STPSi:
141 case AArch64::STPDi:
142 case AArch64::STPQi:
143 return true;
144 default:
145 return false;
146 }
147}
148
149bool AArch64StackTaggingPreRAImpl::mayUseUncheckedLoadStore() {
151 .getCLOpts()
152 .stack_tagging_unchecked_ld_st;
154 return false;
156 return true;
157
158 // This estimate can be improved if we had harder guarantees about stack frame
159 // layout. With LocalStackAllocation we can estimate SP offset to any
160 // preallocated slot. AArch64FrameLowering::orderFrameObjects could put tagged
161 // objects ahead of non-tagged ones, but that's not always desirable.
162 //
163 // Underestimating SP offset here may require the use of LDG to materialize
164 // the tagged address of the stack slot, along with a scratch register
165 // allocation (post-regalloc!).
166 //
167 // For now we do the safe thing here and require that the entire stack frame
168 // is within range of the shortest of the unchecked instructions.
169 unsigned FrameSize = 0;
170 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i)
171 FrameSize += MFI->getObjectSize(i);
172 bool EntireFrameReachableFromSP = FrameSize < 0xf00;
173 return !MFI->hasVarSizedObjects() && EntireFrameReachableFromSP;
174}
175
176void AArch64StackTaggingPreRAImpl::uncheckUsesOf(unsigned TaggedReg, int FI) {
177 for (MachineInstr &UseI :
179 if (isUncheckedLoadOrStoreOpcode(UseI.getOpcode())) {
180 // FI operand is always the one before the immediate offset.
181 unsigned OpIdx = TII->getLoadStoreImmIdx(UseI.getOpcode()) - 1;
182 if (UseI.getOperand(OpIdx).isReg() &&
183 UseI.getOperand(OpIdx).getReg() == TaggedReg) {
184 UseI.getOperand(OpIdx).ChangeToFrameIndex(FI);
185 UseI.getOperand(OpIdx).setTargetFlags(AArch64II::MO_TAGGED);
186 }
187 } else if (UseI.isCopy() && UseI.getOperand(0).getReg().isVirtual()) {
188 uncheckUsesOf(UseI.getOperand(0).getReg(), FI);
189 }
190 }
191}
192
193void AArch64StackTaggingPreRAImpl::uncheckLoadsAndStores() {
194 for (auto *I : ReTags) {
195 Register TaggedReg = I->getOperand(0).getReg();
196 int FI = I->getOperand(1).getIndex();
197 uncheckUsesOf(TaggedReg, FI);
198 }
199}
200
201namespace {
202struct SlotWithTag {
203 int FI;
204 int Tag;
205 SlotWithTag(int FI, int Tag) : FI(FI), Tag(Tag) {}
206 explicit SlotWithTag(const MachineInstr &MI)
207 : FI(MI.getOperand(1).getIndex()), Tag(MI.getOperand(4).getImm()) {}
208 bool operator==(const SlotWithTag &Other) const {
209 return FI == Other.FI && Tag == Other.Tag;
210 }
211};
212} // namespace
213
214namespace llvm {
215template <> struct DenseMapInfo<SlotWithTag> {
216 static unsigned getHashValue(const SlotWithTag &V) {
219 }
220 static bool isEqual(const SlotWithTag &A, const SlotWithTag &B) {
221 return A == B;
222 }
223};
224} // namespace llvm
225
226static bool isSlotPreAllocated(MachineFrameInfo *MFI, int FI) {
227 return MFI->getUseLocalStackAllocationBlock() &&
228 MFI->isObjectPreAllocated(FI);
229}
230
231// Pin one of the tagged slots to offset 0 from the tagged base pointer.
232// This would make its address available in a virtual register (IRG's def), as
233// opposed to requiring an ADDG instruction to materialize. This effectively
234// eliminates a vreg (by replacing it with direct uses of IRG, which is usually
235// live almost everywhere anyway), and therefore needs to happen before
236// regalloc.
237std::optional<int> AArch64StackTaggingPreRAImpl::findFirstSlotCandidate() {
238 // Find the best (FI, Tag) pair to pin to offset 0.
239 // Looking at the possible uses of a tagged address, the advantage of pinning
240 // is:
241 // - COPY to physical register.
242 // Does not matter, this would trade a MOV instruction for an ADDG.
243 // - ST*G matter, but those mostly appear near the function prologue where all
244 // the tagged addresses need to be materialized anyway; also, counting ST*G
245 // uses would overweight large allocas that require more than one ST*G
246 // instruction.
247 // - Load/Store instructions in the address operand do not require a tagged
248 // pointer, so they also do not benefit. These operands have already been
249 // eliminated (see uncheckLoadsAndStores) so all remaining load/store
250 // instructions count.
251 // - Any other instruction may benefit from being pinned to offset 0.
253 dbgs() << "AArch64StackTaggingPreRAImpl::findFirstSlotCandidate\n");
254 if (!MF->getSubtarget<AArch64Subtarget>()
255 .getCLOpts()
256 .stack_tagging_first_slot_opt)
257 return std::nullopt;
258
260 SlotWithTag MaxScoreST{-1, -1};
261 int MaxScore = -1;
262 for (auto *I : ReTags) {
263 SlotWithTag ST{*I};
264 if (isSlotPreAllocated(MFI, ST.FI))
265 continue;
266
267 Register RetagReg = I->getOperand(0).getReg();
268 if (!RetagReg.isVirtual())
269 continue;
270
271 int Score = 0;
273 WorkList.push_back(RetagReg);
274
275 while (!WorkList.empty()) {
276 Register UseReg = WorkList.pop_back_val();
277 for (auto &UseI : MRI->use_nodbg_instructions(UseReg)) {
278 unsigned Opcode = UseI.getOpcode();
279 if (Opcode == AArch64::STGi || Opcode == AArch64::ST2Gi ||
280 Opcode == AArch64::STZGi || Opcode == AArch64::STZ2Gi ||
281 Opcode == AArch64::STGPi || Opcode == AArch64::STGloop ||
282 Opcode == AArch64::STZGloop || Opcode == AArch64::STGloop_wback ||
283 Opcode == AArch64::STZGloop_wback)
284 continue;
285 if (UseI.isCopy()) {
286 Register DstReg = UseI.getOperand(0).getReg();
287 if (DstReg.isVirtual())
288 WorkList.push_back(DstReg);
289 continue;
290 }
291 LLVM_DEBUG(dbgs() << "[" << ST.FI << ":" << ST.Tag << "] use of "
292 << printReg(UseReg) << " in " << UseI << "\n");
293 Score++;
294 }
295 }
296
297 int TotalScore = RetagScore[ST] += Score;
298 if (TotalScore > MaxScore ||
299 (TotalScore == MaxScore && ST.FI > MaxScoreST.FI)) {
300 MaxScore = TotalScore;
301 MaxScoreST = ST;
302 }
303 }
304
305 if (MaxScoreST.FI < 0)
306 return std::nullopt;
307
308 // If FI's tag is already 0, we are done.
309 if (MaxScoreST.Tag == 0)
310 return MaxScoreST.FI;
311
312 // Otherwise, find a random victim pair (FI, Tag) where Tag == 0.
313 SlotWithTag SwapST{-1, -1};
314 for (auto *I : ReTags) {
315 SlotWithTag ST{*I};
316 if (ST.Tag == 0) {
317 SwapST = ST;
318 break;
319 }
320 }
321
322 // Swap tags between the victim and the highest scoring pair.
323 // If SwapWith is still (-1, -1), that's fine, too - we'll simply take tag for
324 // the highest score slot without changing anything else.
325 for (auto *&I : ReTags) {
326 SlotWithTag ST{*I};
327 MachineOperand &TagOp = I->getOperand(4);
328 if (ST == MaxScoreST) {
329 TagOp.setImm(0);
330 } else if (ST == SwapST) {
331 TagOp.setImm(MaxScoreST.Tag);
332 }
333 }
334 return MaxScoreST.FI;
335}
336
337bool AArch64StackTaggingPreRAImpl::run(MachineFunction &Func) {
338 MF = &Func;
339 MRI = &MF->getRegInfo();
340 AFI = MF->getInfo<AArch64FunctionInfo>();
341 TII =
342 static_cast<const AArch64InstrInfo *>(MF->getSubtarget().getInstrInfo());
343 MFI = &MF->getFrameInfo();
344 ReTags.clear();
345
346 assert(MRI->isSSA());
347
348 LLVM_DEBUG(dbgs() << "********** AArch64 Stack Tagging PreRA **********\n"
349 << "********** Function: " << MF->getName() << '\n');
350
351 SmallSetVector<int, 8> TaggedSlots;
352 for (auto &BB : *MF) {
353 for (auto &I : BB) {
354 if (I.getOpcode() == AArch64::TAGPstack) {
355 ReTags.push_back(&I);
356 int FI = I.getOperand(1).getIndex();
357 TaggedSlots.insert(FI);
358 // There should be no offsets in TAGP yet.
359 assert(I.getOperand(2).getImm() == 0);
360 }
361 }
362 }
363
364 // Take over from SSP. It does nothing for tagged slots, and should not really
365 // have been enabled in the first place.
366 for (int FI : TaggedSlots)
367 MFI->setObjectSSPLayout(FI, MachineFrameInfo::SSPLK_None);
368
369 if (ReTags.empty())
370 return false;
371
372 if (mayUseUncheckedLoadStore())
373 uncheckLoadsAndStores();
374
375 // Find a slot that is used with zero tag offset, like ADDG #fi, 0.
376 // If the base tagged pointer is set up to the address of this slot,
377 // the ADDG instruction can be eliminated.
378 std::optional<int> BaseSlot = findFirstSlotCandidate();
379 if (BaseSlot)
380 AFI->setTaggedBasePointerIndex(*BaseSlot);
381
382 for (auto *I : ReTags) {
383 int FI = I->getOperand(1).getIndex();
384 int Tag = I->getOperand(4).getImm();
385 Register Base = I->getOperand(3).getReg();
386 if (Tag == 0 && FI == BaseSlot) {
387 BuildMI(*I->getParent(), I, {}, TII->get(AArch64::COPY),
388 I->getOperand(0).getReg())
389 .addReg(Base);
391 }
392 }
393
394 return true;
395}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool isSlotPreAllocated(MachineFrameInfo *MFI, int FI)
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")
static Register UseReg(const MachineOperand &MO)
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
#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
MachineRegisterInfo & MRI
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
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:119
AArch64FunctionInfo - This class is derived from MachineFunctionInfo and contains private AArch64-spe...
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
const AArch64Options & getCLOpts() const
Represent the analysis usage information of a pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
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:312
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.
Function & getFunction()
Return the LLVM function that this machine code represents.
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,...
iterator_range< use_instr_nodbg_iterator > use_nodbg_instructions(Register Reg) const
iterator_range< use_instr_iterator > use_instructions(Register Reg) const
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:152
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:157
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:346
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
@ MO_TAGGED
MO_TAGGED - With MO_PAGE, indicates that the page includes a memory tag in bits 56-63.
const AArch64MCOptions & getCLOpts(const MCTargetOptions &Options)
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:649
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:209
@ 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:307
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...