1//===- AArch64StackTagging.cpp - Stack tagging in IR --===//
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
10#include "AArch64.h"
11#include "AArch64Subtarget.h"
12#include "llvm/ADT/APInt.h"
13#include "llvm/ADT/MapVector.h"
14#include "llvm/ADT/SmallVector.h"
15#include "llvm/ADT/Statistic.h"
16#include "llvm/Analysis/AliasAnalysis.h"
17#include "llvm/Analysis/CFG.h"
18#include "llvm/Analysis/LoopInfo.h"
19#include "llvm/Analysis/OptimizationRemarkEmitter.h"
20#include "llvm/Analysis/PostDominators.h"
21#include "llvm/Analysis/ScalarEvolution.h"
22#include "llvm/Analysis/ScalarEvolutionExpressions.h"
23#include "llvm/Analysis/StackSafetyAnalysis.h"
24#include "llvm/BinaryFormat/Dwarf.h"
25#include "llvm/CodeGen/MachineBasicBlock.h"
26#include "llvm/CodeGen/MachineFunction.h"
27#include "llvm/CodeGen/MachineInstr.h"
28#include "llvm/CodeGen/MachineOperand.h"
29#include "llvm/IR/DebugLoc.h"
30#include "llvm/IR/Dominators.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/IRBuilder.h"
33#include "llvm/IR/InstIterator.h"
34#include "llvm/IR/Instruction.h"
35#include "llvm/IR/Instructions.h"
36#include "llvm/IR/IntrinsicInst.h"
37#include "llvm/IR/IntrinsicsAArch64.h"
38#include "llvm/IR/Metadata.h"
39#include "llvm/IR/PassManager.h"
40#include "llvm/IR/Value.h"
41#include "llvm/InitializePasses.h"
42#include "llvm/Pass.h"
43#include "llvm/Support/Casting.h"
44#include "llvm/Support/Debug.h"
45#include "llvm/Support/raw_ostream.h"
46#include "llvm/Transforms/Utils/Local.h"
47#include "llvm/Transforms/Utils/MemoryTaggingSupport.h"
48#include <cassert>
49#include <memory>
50
51using namespace llvm;
52
53#define DEBUG_TYPE "aarch64-stack-tagging"
54
55static const Align kTagGranuleSize = Align(16);
56
57namespace {
58
59class InitializerBuilder {
60 uint64_t Size;
61 const DataLayout *DL;
62 Value *BasePtr;
63 Function *SetTagFn;
64 Function *SetTagZeroFn;
65 Function *StgpFn;
66
67 // List of initializers sorted by start offset.
68 struct Range {
69 uint64_t Start, End;
70 Instruction *Inst;
71 };
72 SmallVector<Range, 4> Ranges;
73 // 8-aligned offset => 8-byte initializer
74 // Missing keys are zero initialized.
75 std::map<uint64_t, Value *> Out;
76
77public:
78 InitializerBuilder(uint64_t Size, const DataLayout *DL, Value *BasePtr,
79 Function *SetTagFn, Function *SetTagZeroFn,
80 Function *StgpFn)
81 : Size(Size), DL(DL), BasePtr(BasePtr), SetTagFn(SetTagFn),
82 SetTagZeroFn(SetTagZeroFn), StgpFn(StgpFn) {}
83
84 bool addRange(uint64_t Start, uint64_t End, Instruction *Inst) {
85 auto I =
86 llvm::lower_bound(Range&: Ranges, Value&: Start, C: [](const Range &LHS, uint64_t RHS) {
87 return LHS.End <= RHS;
88 });
89 if (I != Ranges.end() && End > I->Start) {
90 // Overlap - bail.
91 return false;
92 }
93 Ranges.insert(I, Elt: {.Start: Start, .End: End, .Inst: Inst});
94 return true;
95 }
96
97 bool addStore(uint64_t Offset, StoreInst *SI, const DataLayout *DL) {
98 int64_t StoreSize = DL->getTypeStoreSize(Ty: SI->getOperand(i_nocapture: 0)->getType());
99 if (!addRange(Start: Offset, End: Offset + StoreSize, Inst: SI))
100 return false;
101 IRBuilder<> IRB(SI);
102 applyStore(IRB, Start: Offset, End: Offset + StoreSize, StoredValue: SI->getOperand(i_nocapture: 0));
103 return true;
104 }
105
106 bool addMemSet(uint64_t Offset, MemSetInst *MSI) {
107 uint64_t StoreSize = cast<ConstantInt>(Val: MSI->getLength())->getZExtValue();
108 if (!addRange(Start: Offset, End: Offset + StoreSize, Inst: MSI))
109 return false;
110 IRBuilder<> IRB(MSI);
111 applyMemSet(IRB, Start: Offset, End: Offset + StoreSize,
112 V: cast<ConstantInt>(Val: MSI->getValue()));
113 return true;
114 }
115
116 void applyMemSet(IRBuilder<> &IRB, int64_t Start, int64_t End,
117 ConstantInt *V) {
118 // Out[] does not distinguish between zero and undef, and we already know
119 // that this memset does not overlap with any other initializer. Nothing to
120 // do for memset(0).
121 if (V->isZero())
122 return;
123 for (int64_t Offset = Start - Start % 8; Offset < End; Offset += 8) {
124 uint64_t Cst = 0x0101010101010101UL;
125 int LowBits = Offset < Start ? (Start - Offset) * 8 : 0;
126 if (LowBits)
127 Cst = (Cst >> LowBits) << LowBits;
128 int HighBits = End - Offset < 8 ? (8 - (End - Offset)) * 8 : 0;
129 if (HighBits)
130 Cst = (Cst << HighBits) >> HighBits;
131 ConstantInt *C =
132 ConstantInt::get(Ty: IRB.getInt64Ty(), V: Cst * V->getZExtValue());
133
134 Value *&CurrentV = Out[Offset];
135 if (!CurrentV) {
136 CurrentV = C;
137 } else {
138 CurrentV = IRB.CreateOr(LHS: CurrentV, RHS: C);
139 }
140 }
141 }
142
143 // Take a 64-bit slice of the value starting at the given offset (in bytes).
144 // Offset can be negative. Pad with zeroes on both sides when necessary.
145 Value *sliceValue(IRBuilder<> &IRB, Value *V, int64_t Offset) {
146 if (Offset > 0) {
147 V = IRB.CreateLShr(LHS: V, RHS: Offset * 8);
148 V = IRB.CreateZExtOrTrunc(V, DestTy: IRB.getInt64Ty());
149 } else if (Offset < 0) {
150 V = IRB.CreateZExtOrTrunc(V, DestTy: IRB.getInt64Ty());
151 V = IRB.CreateShl(LHS: V, RHS: -Offset * 8);
152 } else {
153 V = IRB.CreateZExtOrTrunc(V, DestTy: IRB.getInt64Ty());
154 }
155 return V;
156 }
157
158 void applyStore(IRBuilder<> &IRB, int64_t Start, int64_t End,
159 Value *StoredValue) {
160 StoredValue = flatten(IRB, V: StoredValue);
161 for (int64_t Offset = Start - Start % 8; Offset < End; Offset += 8) {
162 Value *V = sliceValue(IRB, V: StoredValue, Offset: Offset - Start);
163 Value *&CurrentV = Out[Offset];
164 if (!CurrentV) {
165 CurrentV = V;
166 } else {
167 CurrentV = IRB.CreateOr(LHS: CurrentV, RHS: V);
168 }
169 }
170 }
171
172 void generate(IRBuilder<> &IRB) {
173 LLVM_DEBUG(dbgs() << "Combined initializer\n");
174 // No initializers => the entire allocation is undef.
175 if (Ranges.empty()) {
176 emitUndef(IRB, Offset: 0, Size);
177 return;
178 }
179
180 // Look through 8-byte initializer list 16 bytes at a time;
181 // If one of the two 8-byte halves is non-zero non-undef, emit STGP.
182 // Otherwise, emit zeroes up to next available item.
183 uint64_t LastOffset = 0;
184 for (uint64_t Offset = 0; Offset < Size; Offset += 16) {
185 auto I1 = Out.find(x: Offset);
186 auto I2 = Out.find(x: Offset + 8);
187 if (I1 == Out.end() && I2 == Out.end())
188 continue;
189
190 if (Offset > LastOffset)
191 emitZeroes(IRB, Offset: LastOffset, Size: Offset - LastOffset);
192
193 Value *Store1 = I1 == Out.end() ? Constant::getNullValue(Ty: IRB.getInt64Ty())
194 : I1->second;
195 Value *Store2 = I2 == Out.end() ? Constant::getNullValue(Ty: IRB.getInt64Ty())
196 : I2->second;
197 emitPair(IRB, Offset, A: Store1, B: Store2);
198 LastOffset = Offset + 16;
199 }
200
201 // memset(0) does not update Out[], therefore the tail can be either undef
202 // or zero.
203 if (LastOffset < Size)
204 emitZeroes(IRB, Offset: LastOffset, Size: Size - LastOffset);
205
206 for (const auto &R : Ranges) {
207 R.Inst->eraseFromParent();
208 }
209 }
210
211 void emitZeroes(IRBuilder<> &IRB, uint64_t Offset, uint64_t Size) {
212 LLVM_DEBUG(dbgs() << " [" << Offset << ", " << Offset + Size
213 << ") zero\n");
214 Value *Ptr = BasePtr;
215 if (Offset)
216 Ptr = IRB.CreateConstGEP1_32(Ty: IRB.getInt8Ty(), Ptr, Idx0: Offset);
217 IRB.CreateCall(Callee: SetTagZeroFn,
218 Args: {Ptr, ConstantInt::get(Ty: IRB.getInt64Ty(), V: Size)});
219 }
220
221 void emitUndef(IRBuilder<> &IRB, uint64_t Offset, uint64_t Size) {
222 LLVM_DEBUG(dbgs() << " [" << Offset << ", " << Offset + Size
223 << ") undef\n");
224 Value *Ptr = BasePtr;
225 if (Offset)
226 Ptr = IRB.CreateConstGEP1_32(Ty: IRB.getInt8Ty(), Ptr, Idx0: Offset);
227 IRB.CreateCall(Callee: SetTagFn, Args: {Ptr, ConstantInt::get(Ty: IRB.getInt64Ty(), V: Size)});
228 }
229
230 void emitPair(IRBuilder<> &IRB, uint64_t Offset, Value *A, Value *B) {
231 LLVM_DEBUG(dbgs() << " [" << Offset << ", " << Offset + 16 << "):\n");
232 LLVM_DEBUG(dbgs() << " " << *A << "\n " << *B << "\n");
233 Value *Ptr = BasePtr;
234 if (Offset)
235 Ptr = IRB.CreateConstGEP1_32(Ty: IRB.getInt8Ty(), Ptr, Idx0: Offset);
236 IRB.CreateCall(Callee: StgpFn, Args: {Ptr, A, B});
237 }
238
239 Value *flatten(IRBuilder<> &IRB, Value *V) {
240 if (V->getType()->isIntegerTy())
241 return V;
242 // vector of pointers -> vector of ints
243 if (VectorType *VecTy = dyn_cast<VectorType>(Val: V->getType())) {
244 LLVMContext &Ctx = IRB.getContext();
245 Type *EltTy = VecTy->getElementType();
246 if (EltTy->isPointerTy()) {
247 uint32_t EltSize = DL->getTypeSizeInBits(Ty: EltTy);
248 auto *NewTy = FixedVectorType::get(
249 ElementType: IntegerType::get(C&: Ctx, NumBits: EltSize),
250 NumElts: cast<FixedVectorType>(Val: VecTy)->getNumElements());
251 V = IRB.CreatePointerCast(V, DestTy: NewTy);
252 }
253 }
254 return IRB.CreateBitOrPointerCast(
255 V, DestTy: IRB.getIntNTy(N: DL->getTypeStoreSize(Ty: V->getType()) * 8));
256 }
257};
258
259class AArch64StackTagging : public FunctionPass {
260 const bool MergeInit;
261 const bool UseStackSafety;
262
263public:
264 static char ID; // Pass ID, replacement for typeid
265
266 AArch64StackTagging(bool IsOptNone = false)
267 : FunctionPass(ID),
268 MergeInit(valueOr(X: AArch64Options::Global.stack_tagging_merge_init,
269 Default: !IsOptNone)),
270 UseStackSafety(
271 valueOr(X: AArch64Options::Global.stack_tagging_use_stack_safety,
272 Default: !IsOptNone)) {}
273
274 void tagAlloca(AllocaInst *AI, Instruction *InsertBefore, Value *Ptr,
275 uint64_t Size);
276 void untagAlloca(AllocaInst *AI, Instruction *InsertBefore, uint64_t Size);
277
278 Instruction *collectInitializers(Instruction *StartInst, Value *StartPtr,
279 uint64_t Size, InitializerBuilder &IB);
280
281 Instruction *insertBaseTaggedPointer(
282 const Module &M,
283 const MapVector<AllocaInst *, memtag::AllocaInfo> &Allocas,
284 const DominatorTree *DT);
285 bool runOnFunction(Function &F) override;
286
287 StringRef getPassName() const override { return "AArch64 Stack Tagging"; }
288
289private:
290 Function *F = nullptr;
291 Function *SetTagFunc = nullptr;
292 const DataLayout *DL = nullptr;
293 AAResults *AA = nullptr;
294 const StackSafetyGlobalInfo *SSI = nullptr;
295
296 void getAnalysisUsage(AnalysisUsage &AU) const override {
297 AU.setPreservesCFG();
298 if (UseStackSafety)
299 AU.addRequired<StackSafetyGlobalInfoWrapperPass>();
300 if (MergeInit)
301 AU.addRequired<AAResultsWrapperPass>();
302 AU.addUsedIfAvailable<OptimizationRemarkEmitterWrapperPass>();
303 }
304};
305
306} // end anonymous namespace
307
308char AArch64StackTagging::ID = 0;
309
310INITIALIZE_PASS_BEGIN(AArch64StackTagging, DEBUG_TYPE, "AArch64 Stack Tagging",
311 false, false)
312INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
313INITIALIZE_PASS_DEPENDENCY(StackSafetyGlobalInfoWrapperPass)
314INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
315INITIALIZE_PASS_END(AArch64StackTagging, DEBUG_TYPE, "AArch64 Stack Tagging",
316 false, false)
317
318FunctionPass *llvm::createAArch64StackTaggingPass(bool IsOptNone) {
319 return new AArch64StackTagging(IsOptNone);
320}
321
322Instruction *AArch64StackTagging::collectInitializers(Instruction *StartInst,
323 Value *StartPtr,
324 uint64_t Size,
325 InitializerBuilder &IB) {
326 MemoryLocation AllocaLoc{StartPtr, Size};
327 Instruction *LastInst = StartInst;
328 BasicBlock::iterator BI(StartInst);
329
330 unsigned Count = 0;
331 for (; Count < AArch64Options::Global.stack_tagging_merge_init_scan_limit &&
332 !BI->isTerminator();
333 ++BI) {
334 ++Count;
335
336 if (isNoModRef(MRI: AA->getModRefInfo(I: &*BI, OptLoc: AllocaLoc)))
337 continue;
338
339 if (!isa<StoreInst>(Val: BI) && !isa<MemSetInst>(Val: BI)) {
340 // If the instruction is readnone, ignore it, otherwise bail out. We
341 // don't even allow readonly here because we don't want something like:
342 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
343 if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
344 break;
345 continue;
346 }
347
348 if (StoreInst *NextStore = dyn_cast<StoreInst>(Val&: BI)) {
349 if (!NextStore->isSimple())
350 break;
351
352 // Check to see if this store is to a constant offset from the start ptr.
353 std::optional<int64_t> Offset =
354 NextStore->getPointerOperand()->getPointerOffsetFrom(Other: StartPtr, DL: *DL);
355 if (!Offset)
356 break;
357
358 if (!IB.addStore(Offset: *Offset, SI: NextStore, DL))
359 break;
360 LastInst = NextStore;
361 } else {
362 MemSetInst *MSI = cast<MemSetInst>(Val&: BI);
363
364 if (MSI->isVolatile() || !isa<ConstantInt>(Val: MSI->getLength()))
365 break;
366
367 if (!isa<ConstantInt>(Val: MSI->getValue()))
368 break;
369
370 // Check to see if this store is to a constant offset from the start ptr.
371 std::optional<int64_t> Offset =
372 MSI->getDest()->getPointerOffsetFrom(Other: StartPtr, DL: *DL);
373 if (!Offset)
374 break;
375
376 if (!IB.addMemSet(Offset: *Offset, MSI))
377 break;
378 LastInst = MSI;
379 }
380 }
381 return LastInst;
382}
383
384void AArch64StackTagging::tagAlloca(AllocaInst *AI, Instruction *InsertBefore,
385 Value *Ptr, uint64_t Size) {
386 auto SetTagZeroFunc = Intrinsic::getOrInsertDeclaration(
387 M: F->getParent(), id: Intrinsic::aarch64_settag_zero);
388 auto StgpFunc = Intrinsic::getOrInsertDeclaration(M: F->getParent(),
389 id: Intrinsic::aarch64_stgp);
390
391 InitializerBuilder IB(Size, DL, Ptr, SetTagFunc, SetTagZeroFunc, StgpFunc);
392 bool LittleEndian = AI->getModule()->getTargetTriple().isLittleEndian();
393 // Current implementation of initializer merging assumes little endianness.
394 if (MergeInit && !F->hasOptNone() && LittleEndian &&
395 Size < AArch64Options::Global.stack_tagging_merge_init_size_limit) {
396 LLVM_DEBUG(dbgs() << "collecting initializers for " << *AI
397 << ", size = " << Size << "\n");
398 InsertBefore = collectInitializers(StartInst: InsertBefore, StartPtr: Ptr, Size, IB);
399 }
400
401 IRBuilder<> IRB(InsertBefore);
402 IB.generate(IRB);
403}
404
405void AArch64StackTagging::untagAlloca(AllocaInst *AI, Instruction *InsertBefore,
406 uint64_t Size) {
407 IRBuilder<> IRB(InsertBefore);
408 IRB.CreateCall(Callee: SetTagFunc, Args: {IRB.CreatePointerCast(V: AI, DestTy: IRB.getPtrTy()),
409 ConstantInt::get(Ty: IRB.getInt64Ty(), V: Size)});
410}
411
412static Value *getSlotPtr(IRBuilder<> &IRB, const Triple &TargetTriple,
413 bool HasInstrumentedAllocas) {
414 if (!HasInstrumentedAllocas)
415 return nullptr;
416
417 auto Mode = AArch64Options::Global.stack_tagging_record_stack_history;
418 if (Mode == AArch64::StackTaggingRecordStackHistoryMode::Instr ||
419 (!Mode && TargetTriple.isOSDarwin())) {
420 if (TargetTriple.isAndroid() && TargetTriple.isAArch64() &&
421 !TargetTriple.isAndroidVersionLT(Major: 35))
422 return memtag::getAndroidSlotPtr(IRB, Slot: -3);
423 if (TargetTriple.isOSDarwin() && TargetTriple.isAArch64() &&
424 !TargetTriple.isSimulatorEnvironment())
425 return memtag::getDarwinSlotPtr(IRB, Slot: 231);
426 }
427 return nullptr;
428}
429
430Instruction *AArch64StackTagging::insertBaseTaggedPointer(
431 const Module &M,
432 const MapVector<AllocaInst *, memtag::AllocaInfo> &AllocasToInstrument,
433 const DominatorTree *DT) {
434 BasicBlock *PrologueBB = nullptr;
435 // Try sinking IRG as deep as possible to avoid hurting shrink wrap.
436 for (auto &I : AllocasToInstrument) {
437 const memtag::AllocaInfo &Info = I.second;
438 AllocaInst *AI = Info.AI;
439 if (!PrologueBB) {
440 PrologueBB = AI->getParent();
441 continue;
442 }
443 PrologueBB = DT->findNearestCommonDominator(A: PrologueBB, B: AI->getParent());
444 }
445 assert(PrologueBB);
446
447 IRBuilder<> IRB(&PrologueBB->front());
448 Instruction *Base = IRB.CreateIntrinsicWithoutFolding(
449 ID: Intrinsic::aarch64_irg_sp, OverloadTypes: {},
450 Args: {Constant::getNullValue(Ty: IRB.getInt64Ty())});
451 Base->setName("basetag");
452 const Triple &TargetTriple = M.getTargetTriple();
453 // This ABI will make it into Android API level 35.
454 // The ThreadLong format is the same as with HWASan, but the entries for
455 // stack MTE take two slots (16 bytes).
456 //
457 // Stack history is recorded by default on Darwin.
458 if (Value *SlotPtr =
459 getSlotPtr(IRB, TargetTriple, HasInstrumentedAllocas: !AllocasToInstrument.empty())) {
460 constexpr uint64_t TagMask = 0xFULL << 56;
461 auto *IntptrTy = IRB.getIntPtrTy(DL: M.getDataLayout());
462 auto *ThreadLong = IRB.CreateLoad(Ty: IntptrTy, Ptr: SlotPtr);
463 Value *FP = memtag::getFP(IRB);
464 Value *Tag = IRB.CreateAnd(LHS: IRB.CreatePtrToInt(V: Base, DestTy: IntptrTy), RHS: TagMask);
465 Value *TaggedFP = IRB.CreateOr(LHS: FP, RHS: Tag);
466 Value *PC = memtag::getPC(TargetTriple, IRB);
467 Value *RecordPtr = IRB.CreateIntToPtr(V: ThreadLong, DestTy: IRB.getPtrTy(AddrSpace: 0));
468 IRB.CreateStore(Val: PC, Ptr: RecordPtr);
469 IRB.CreateStore(Val: TaggedFP, Ptr: IRB.CreateConstGEP1_64(Ty: IntptrTy, Ptr: RecordPtr, Idx0: 1));
470
471 IRB.CreateStore(Val: memtag::incrementThreadLong(IRB, ThreadLong, Inc: 16,
472 IsMemtagDarwin: TargetTriple.isOSDarwin()),
473 Ptr: SlotPtr);
474 }
475 return Base;
476}
477
478// FIXME: check for MTE extension
479bool AArch64StackTagging::runOnFunction(Function &Fn) {
480 if (!Fn.hasFnAttribute(Kind: Attribute::SanitizeMemTag))
481 return false;
482
483 if (UseStackSafety)
484 SSI = &getAnalysis<StackSafetyGlobalInfoWrapperPass>().getResult();
485 F = &Fn;
486 DL = &Fn.getDataLayout();
487 if (MergeInit)
488 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
489
490 std::unique_ptr<OptimizationRemarkEmitter> DeleteORE;
491 OptimizationRemarkEmitter *ORE = nullptr;
492 if (auto *P = getAnalysisIfAvailable<OptimizationRemarkEmitterWrapperPass>())
493 ORE = &P->getORE();
494
495 if (ORE == nullptr) {
496 DeleteORE = std::make_unique<OptimizationRemarkEmitter>(args&: F);
497 ORE = DeleteORE.get();
498 }
499
500 memtag::StackInfoBuilder SIB(SSI, DEBUG_TYPE);
501 for (Instruction &I : instructions(F))
502 SIB.visit(ORE&: *ORE, Inst&: I);
503 memtag::StackInfo &SInfo = SIB.get();
504
505 if (SInfo.AllocasToInstrument.empty())
506 return false;
507
508 std::unique_ptr<DominatorTree> DeleteDT;
509 DominatorTree *DT = nullptr;
510 if (auto *P = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
511 DT = &P->getDomTree();
512
513 if (DT == nullptr) {
514 DeleteDT = std::make_unique<DominatorTree>(args&: *F);
515 DT = DeleteDT.get();
516 }
517
518 std::unique_ptr<PostDominatorTree> DeletePDT;
519 PostDominatorTree *PDT = nullptr;
520 if (auto *P = getAnalysisIfAvailable<PostDominatorTreeWrapperPass>())
521 PDT = &P->getPostDomTree();
522
523 if (PDT == nullptr) {
524 DeletePDT = std::make_unique<PostDominatorTree>(args&: *F);
525 PDT = DeletePDT.get();
526 }
527
528 std::unique_ptr<LoopInfo> DeleteLI;
529 LoopInfo *LI = nullptr;
530 if (auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>()) {
531 LI = &LIWP->getLoopInfo();
532 } else {
533 DeleteLI = std::make_unique<LoopInfo>(args&: *DT);
534 LI = DeleteLI.get();
535 }
536
537 SetTagFunc = Intrinsic::getOrInsertDeclaration(M: F->getParent(),
538 id: Intrinsic::aarch64_settag);
539
540 Instruction *Base =
541 insertBaseTaggedPointer(M: *Fn.getParent(), AllocasToInstrument: SInfo.AllocasToInstrument, DT);
542
543 unsigned int NextTag = 0;
544 for (auto &I : SInfo.AllocasToInstrument) {
545 memtag::AllocaInfo &Info = I.second;
546 assert(Info.AI && SIB.getAllocaInterestingness(*Info.AI) ==
547 llvm::memtag::AllocaInterestingness::kInteresting);
548 memtag::alignAndPadAlloca(Info, Align: kTagGranuleSize);
549 AllocaInst *AI = Info.AI;
550 unsigned int Tag = NextTag;
551 NextTag = (NextTag + 1) % 16;
552 // Replace alloca with tagp(alloca).
553 IRBuilder<> IRB(Info.AI->getNextNode());
554 Instruction *TagPCall = IRB.CreateIntrinsicWithoutFolding(
555 ID: Intrinsic::aarch64_tagp, OverloadTypes: {Info.AI->getType()},
556 Args: {Constant::getNullValue(Ty: Info.AI->getType()), Base,
557 ConstantInt::get(Ty: IRB.getInt64Ty(), V: Tag)});
558 if (Info.AI->hasName())
559 TagPCall->setName(Info.AI->getName() + ".tag");
560 // Does not replace metadata, so we don't have to handle DbgVariableRecords.
561 Info.AI->replaceUsesWithIf(New: TagPCall, ShouldReplace: [&](const Use &U) {
562 return !isa<LifetimeIntrinsic>(Val: U.getUser());
563 });
564 TagPCall->setOperand(i: 0, Val: Info.AI);
565
566 // Calls to functions that may return twice (e.g. setjmp) confuse the
567 // postdominator analysis, and will leave us to keep memory tagged after
568 // function return. Work around this by always untagging at every return
569 // statement if return_twice functions are called.
570 bool StandardLifetime =
571 !SInfo.CallsReturnTwice && memtag::isSupportedLifetime(AInfo: Info, DT, LI);
572 if (StandardLifetime) {
573 uint64_t Size = *Info.AI->getAllocationSize(DL: *DL);
574 Size = alignTo(Size, A: kTagGranuleSize);
575 for (IntrinsicInst *Start : Info.LifetimeStart)
576 tagAlloca(AI, InsertBefore: Start->getNextNode(), Ptr: TagPCall, Size);
577
578 auto TagEnd = [&](Instruction *Node) { untagAlloca(AI, InsertBefore: Node, Size); };
579 memtag::forAllReachableExits(DT: *DT, PDT: *PDT, LI: *LI, AInfo: Info, RetVec: SInfo.RetVec, Callback: TagEnd);
580 } else {
581 uint64_t Size = *Info.AI->getAllocationSize(DL: *DL);
582 Value *Ptr = IRB.CreatePointerCast(V: TagPCall, DestTy: IRB.getPtrTy());
583 tagAlloca(AI, InsertBefore: &*IRB.GetInsertPoint(), Ptr, Size);
584 for (auto *RI : SInfo.RetVec) {
585 untagAlloca(AI, InsertBefore: RI, Size);
586 }
587 // We may have inserted tag/untag outside of any lifetime interval.
588 // Remove all lifetime intrinsics for this alloca.
589 for (auto *II : Info.LifetimeStart)
590 II->eraseFromParent();
591 for (auto *II : Info.LifetimeEnd)
592 II->eraseFromParent();
593 }
594
595 memtag::annotateDebugRecords(Info, Tag);
596 }
597
598 return true;
599}
600