1 //===- AArch64StackTagging.cpp - Stack tagging in IR --===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //===----------------------------------------------------------------------===//
10
11 #include "AArch64.h"
12 #include "AArch64InstrInfo.h"
13 #include "AArch64Subtarget.h"
14 #include "AArch64TargetMachine.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/DepthFirstIterator.h"
17 #include "llvm/ADT/MapVector.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/Analysis/CFG.h"
24 #include "llvm/Analysis/LoopInfo.h"
25 #include "llvm/Analysis/PostDominators.h"
26 #include "llvm/Analysis/ScalarEvolution.h"
27 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
28 #include "llvm/Analysis/StackSafetyAnalysis.h"
29 #include "llvm/Analysis/ValueTracking.h"
30 #include "llvm/CodeGen/LiveRegUnits.h"
31 #include "llvm/CodeGen/MachineBasicBlock.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineFunctionPass.h"
34 #include "llvm/CodeGen/MachineInstr.h"
35 #include "llvm/CodeGen/MachineInstrBuilder.h"
36 #include "llvm/CodeGen/MachineLoopInfo.h"
37 #include "llvm/CodeGen/MachineOperand.h"
38 #include "llvm/CodeGen/MachineRegisterInfo.h"
39 #include "llvm/CodeGen/TargetPassConfig.h"
40 #include "llvm/CodeGen/TargetRegisterInfo.h"
41 #include "llvm/IR/DebugLoc.h"
42 #include "llvm/IR/Dominators.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/IR/GetElementPtrTypeIterator.h"
45 #include "llvm/IR/Instruction.h"
46 #include "llvm/IR/Instructions.h"
47 #include "llvm/IR/IntrinsicInst.h"
48 #include "llvm/IR/IntrinsicsAArch64.h"
49 #include "llvm/IR/Metadata.h"
50 #include "llvm/InitializePasses.h"
51 #include "llvm/Pass.h"
52 #include "llvm/Support/Casting.h"
53 #include "llvm/Support/Debug.h"
54 #include "llvm/Support/raw_ostream.h"
55 #include "llvm/Transforms/Utils/Local.h"
56 #include <cassert>
57 #include <iterator>
58 #include <utility>
59
60 using namespace llvm;
61
62 #define DEBUG_TYPE "aarch64-stack-tagging"
63
64 static cl::opt<bool> ClMergeInit(
65 "stack-tagging-merge-init", cl::Hidden, cl::init(true), cl::ZeroOrMore,
66 cl::desc("merge stack variable initializers with tagging when possible"));
67
68 static cl::opt<bool>
69 ClUseStackSafety("stack-tagging-use-stack-safety", cl::Hidden,
70 cl::init(true), cl::ZeroOrMore,
71 cl::desc("Use Stack Safety analysis results"));
72
73 static cl::opt<unsigned> ClScanLimit("stack-tagging-merge-init-scan-limit",
74 cl::init(40), cl::Hidden);
75
76 static cl::opt<unsigned>
77 ClMergeInitSizeLimit("stack-tagging-merge-init-size-limit", cl::init(272),
78 cl::Hidden);
79
80 static const Align kTagGranuleSize = Align(16);
81
82 namespace {
83
84 class InitializerBuilder {
85 uint64_t Size;
86 const DataLayout *DL;
87 Value *BasePtr;
88 Function *SetTagFn;
89 Function *SetTagZeroFn;
90 Function *StgpFn;
91
92 // List of initializers sorted by start offset.
93 struct Range {
94 uint64_t Start, End;
95 Instruction *Inst;
96 };
97 SmallVector<Range, 4> Ranges;
98 // 8-aligned offset => 8-byte initializer
99 // Missing keys are zero initialized.
100 std::map<uint64_t, Value *> Out;
101
102 public:
InitializerBuilder(uint64_t Size,const DataLayout * DL,Value * BasePtr,Function * SetTagFn,Function * SetTagZeroFn,Function * StgpFn)103 InitializerBuilder(uint64_t Size, const DataLayout *DL, Value *BasePtr,
104 Function *SetTagFn, Function *SetTagZeroFn,
105 Function *StgpFn)
106 : Size(Size), DL(DL), BasePtr(BasePtr), SetTagFn(SetTagFn),
107 SetTagZeroFn(SetTagZeroFn), StgpFn(StgpFn) {}
108
addRange(uint64_t Start,uint64_t End,Instruction * Inst)109 bool addRange(uint64_t Start, uint64_t End, Instruction *Inst) {
110 auto I =
111 llvm::lower_bound(Ranges, Start, [](const Range &LHS, uint64_t RHS) {
112 return LHS.End <= RHS;
113 });
114 if (I != Ranges.end() && End > I->Start) {
115 // Overlap - bail.
116 return false;
117 }
118 Ranges.insert(I, {Start, End, Inst});
119 return true;
120 }
121
addStore(uint64_t Offset,StoreInst * SI,const DataLayout * DL)122 bool addStore(uint64_t Offset, StoreInst *SI, const DataLayout *DL) {
123 int64_t StoreSize = DL->getTypeStoreSize(SI->getOperand(0)->getType());
124 if (!addRange(Offset, Offset + StoreSize, SI))
125 return false;
126 IRBuilder<> IRB(SI);
127 applyStore(IRB, Offset, Offset + StoreSize, SI->getOperand(0));
128 return true;
129 }
130
addMemSet(uint64_t Offset,MemSetInst * MSI)131 bool addMemSet(uint64_t Offset, MemSetInst *MSI) {
132 uint64_t StoreSize = cast<ConstantInt>(MSI->getLength())->getZExtValue();
133 if (!addRange(Offset, Offset + StoreSize, MSI))
134 return false;
135 IRBuilder<> IRB(MSI);
136 applyMemSet(IRB, Offset, Offset + StoreSize,
137 cast<ConstantInt>(MSI->getValue()));
138 return true;
139 }
140
applyMemSet(IRBuilder<> & IRB,int64_t Start,int64_t End,ConstantInt * V)141 void applyMemSet(IRBuilder<> &IRB, int64_t Start, int64_t End,
142 ConstantInt *V) {
143 // Out[] does not distinguish between zero and undef, and we already know
144 // that this memset does not overlap with any other initializer. Nothing to
145 // do for memset(0).
146 if (V->isZero())
147 return;
148 for (int64_t Offset = Start - Start % 8; Offset < End; Offset += 8) {
149 uint64_t Cst = 0x0101010101010101UL;
150 int LowBits = Offset < Start ? (Start - Offset) * 8 : 0;
151 if (LowBits)
152 Cst = (Cst >> LowBits) << LowBits;
153 int HighBits = End - Offset < 8 ? (8 - (End - Offset)) * 8 : 0;
154 if (HighBits)
155 Cst = (Cst << HighBits) >> HighBits;
156 ConstantInt *C =
157 ConstantInt::get(IRB.getInt64Ty(), Cst * V->getZExtValue());
158
159 Value *&CurrentV = Out[Offset];
160 if (!CurrentV) {
161 CurrentV = C;
162 } else {
163 CurrentV = IRB.CreateOr(CurrentV, C);
164 }
165 }
166 }
167
168 // Take a 64-bit slice of the value starting at the given offset (in bytes).
169 // Offset can be negative. Pad with zeroes on both sides when necessary.
sliceValue(IRBuilder<> & IRB,Value * V,int64_t Offset)170 Value *sliceValue(IRBuilder<> &IRB, Value *V, int64_t Offset) {
171 if (Offset > 0) {
172 V = IRB.CreateLShr(V, Offset * 8);
173 V = IRB.CreateZExtOrTrunc(V, IRB.getInt64Ty());
174 } else if (Offset < 0) {
175 V = IRB.CreateZExtOrTrunc(V, IRB.getInt64Ty());
176 V = IRB.CreateShl(V, -Offset * 8);
177 } else {
178 V = IRB.CreateZExtOrTrunc(V, IRB.getInt64Ty());
179 }
180 return V;
181 }
182
applyStore(IRBuilder<> & IRB,int64_t Start,int64_t End,Value * StoredValue)183 void applyStore(IRBuilder<> &IRB, int64_t Start, int64_t End,
184 Value *StoredValue) {
185 StoredValue = flatten(IRB, StoredValue);
186 for (int64_t Offset = Start - Start % 8; Offset < End; Offset += 8) {
187 Value *V = sliceValue(IRB, StoredValue, Offset - Start);
188 Value *&CurrentV = Out[Offset];
189 if (!CurrentV) {
190 CurrentV = V;
191 } else {
192 CurrentV = IRB.CreateOr(CurrentV, V);
193 }
194 }
195 }
196
generate(IRBuilder<> & IRB)197 void generate(IRBuilder<> &IRB) {
198 LLVM_DEBUG(dbgs() << "Combined initializer\n");
199 // No initializers => the entire allocation is undef.
200 if (Ranges.empty()) {
201 emitUndef(IRB, 0, Size);
202 return;
203 }
204
205 // Look through 8-byte initializer list 16 bytes at a time;
206 // If one of the two 8-byte halfs is non-zero non-undef, emit STGP.
207 // Otherwise, emit zeroes up to next available item.
208 uint64_t LastOffset = 0;
209 for (uint64_t Offset = 0; Offset < Size; Offset += 16) {
210 auto I1 = Out.find(Offset);
211 auto I2 = Out.find(Offset + 8);
212 if (I1 == Out.end() && I2 == Out.end())
213 continue;
214
215 if (Offset > LastOffset)
216 emitZeroes(IRB, LastOffset, Offset - LastOffset);
217
218 Value *Store1 = I1 == Out.end() ? Constant::getNullValue(IRB.getInt64Ty())
219 : I1->second;
220 Value *Store2 = I2 == Out.end() ? Constant::getNullValue(IRB.getInt64Ty())
221 : I2->second;
222 emitPair(IRB, Offset, Store1, Store2);
223 LastOffset = Offset + 16;
224 }
225
226 // memset(0) does not update Out[], therefore the tail can be either undef
227 // or zero.
228 if (LastOffset < Size)
229 emitZeroes(IRB, LastOffset, Size - LastOffset);
230
231 for (const auto &R : Ranges) {
232 R.Inst->eraseFromParent();
233 }
234 }
235
emitZeroes(IRBuilder<> & IRB,uint64_t Offset,uint64_t Size)236 void emitZeroes(IRBuilder<> &IRB, uint64_t Offset, uint64_t Size) {
237 LLVM_DEBUG(dbgs() << " [" << Offset << ", " << Offset + Size
238 << ") zero\n");
239 Value *Ptr = BasePtr;
240 if (Offset)
241 Ptr = IRB.CreateConstGEP1_32(Ptr, Offset);
242 IRB.CreateCall(SetTagZeroFn,
243 {Ptr, ConstantInt::get(IRB.getInt64Ty(), Size)});
244 }
245
emitUndef(IRBuilder<> & IRB,uint64_t Offset,uint64_t Size)246 void emitUndef(IRBuilder<> &IRB, uint64_t Offset, uint64_t Size) {
247 LLVM_DEBUG(dbgs() << " [" << Offset << ", " << Offset + Size
248 << ") undef\n");
249 Value *Ptr = BasePtr;
250 if (Offset)
251 Ptr = IRB.CreateConstGEP1_32(Ptr, Offset);
252 IRB.CreateCall(SetTagFn, {Ptr, ConstantInt::get(IRB.getInt64Ty(), Size)});
253 }
254
emitPair(IRBuilder<> & IRB,uint64_t Offset,Value * A,Value * B)255 void emitPair(IRBuilder<> &IRB, uint64_t Offset, Value *A, Value *B) {
256 LLVM_DEBUG(dbgs() << " [" << Offset << ", " << Offset + 16 << "):\n");
257 LLVM_DEBUG(dbgs() << " " << *A << "\n " << *B << "\n");
258 Value *Ptr = BasePtr;
259 if (Offset)
260 Ptr = IRB.CreateConstGEP1_32(Ptr, Offset);
261 IRB.CreateCall(StgpFn, {Ptr, A, B});
262 }
263
flatten(IRBuilder<> & IRB,Value * V)264 Value *flatten(IRBuilder<> &IRB, Value *V) {
265 if (V->getType()->isIntegerTy())
266 return V;
267 // vector of pointers -> vector of ints
268 if (VectorType *VecTy = dyn_cast<VectorType>(V->getType())) {
269 LLVMContext &Ctx = IRB.getContext();
270 Type *EltTy = VecTy->getElementType();
271 if (EltTy->isPointerTy()) {
272 uint32_t EltSize = DL->getTypeSizeInBits(EltTy);
273 auto *NewTy = FixedVectorType::get(
274 IntegerType::get(Ctx, EltSize),
275 cast<FixedVectorType>(VecTy)->getNumElements());
276 V = IRB.CreatePointerCast(V, NewTy);
277 }
278 }
279 return IRB.CreateBitOrPointerCast(
280 V, IRB.getIntNTy(DL->getTypeStoreSize(V->getType()) * 8));
281 }
282 };
283
284 class AArch64StackTagging : public FunctionPass {
285 struct AllocaInfo {
286 AllocaInst *AI;
287 SmallVector<IntrinsicInst *, 2> LifetimeStart;
288 SmallVector<IntrinsicInst *, 2> LifetimeEnd;
289 SmallVector<DbgVariableIntrinsic *, 2> DbgVariableIntrinsics;
290 int Tag; // -1 for non-tagged allocations
291 };
292
293 const bool MergeInit;
294 const bool UseStackSafety;
295
296 public:
297 static char ID; // Pass ID, replacement for typeid
298
AArch64StackTagging(bool IsOptNone=false)299 AArch64StackTagging(bool IsOptNone = false)
300 : FunctionPass(ID),
301 MergeInit(ClMergeInit.getNumOccurrences() ? ClMergeInit : !IsOptNone),
302 UseStackSafety(ClUseStackSafety.getNumOccurrences() ? ClUseStackSafety
303 : !IsOptNone) {
304 initializeAArch64StackTaggingPass(*PassRegistry::getPassRegistry());
305 }
306
307 bool isInterestingAlloca(const AllocaInst &AI);
308 void alignAndPadAlloca(AllocaInfo &Info);
309
310 void tagAlloca(AllocaInst *AI, Instruction *InsertBefore, Value *Ptr,
311 uint64_t Size);
312 void untagAlloca(AllocaInst *AI, Instruction *InsertBefore, uint64_t Size);
313
314 Instruction *collectInitializers(Instruction *StartInst, Value *StartPtr,
315 uint64_t Size, InitializerBuilder &IB);
316
317 Instruction *
318 insertBaseTaggedPointer(const MapVector<AllocaInst *, AllocaInfo> &Allocas,
319 const DominatorTree *DT);
320 bool runOnFunction(Function &F) override;
321
getPassName() const322 StringRef getPassName() const override { return "AArch64 Stack Tagging"; }
323
324 private:
325 Function *F = nullptr;
326 Function *SetTagFunc = nullptr;
327 const DataLayout *DL = nullptr;
328 AAResults *AA = nullptr;
329 const StackSafetyGlobalInfo *SSI = nullptr;
330
getAnalysisUsage(AnalysisUsage & AU) const331 void getAnalysisUsage(AnalysisUsage &AU) const override {
332 AU.setPreservesCFG();
333 if (UseStackSafety)
334 AU.addRequired<StackSafetyGlobalInfoWrapperPass>();
335 if (MergeInit)
336 AU.addRequired<AAResultsWrapperPass>();
337 }
338 };
339
340 } // end anonymous namespace
341
342 char AArch64StackTagging::ID = 0;
343
344 INITIALIZE_PASS_BEGIN(AArch64StackTagging, DEBUG_TYPE, "AArch64 Stack Tagging",
345 false, false)
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)346 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
347 INITIALIZE_PASS_DEPENDENCY(StackSafetyGlobalInfoWrapperPass)
348 INITIALIZE_PASS_END(AArch64StackTagging, DEBUG_TYPE, "AArch64 Stack Tagging",
349 false, false)
350
351 FunctionPass *llvm::createAArch64StackTaggingPass(bool IsOptNone) {
352 return new AArch64StackTagging(IsOptNone);
353 }
354
collectInitializers(Instruction * StartInst,Value * StartPtr,uint64_t Size,InitializerBuilder & IB)355 Instruction *AArch64StackTagging::collectInitializers(Instruction *StartInst,
356 Value *StartPtr,
357 uint64_t Size,
358 InitializerBuilder &IB) {
359 MemoryLocation AllocaLoc{StartPtr, Size};
360 Instruction *LastInst = StartInst;
361 BasicBlock::iterator BI(StartInst);
362
363 unsigned Count = 0;
364 for (; Count < ClScanLimit && !BI->isTerminator(); ++BI) {
365 if (!isa<DbgInfoIntrinsic>(*BI))
366 ++Count;
367
368 if (isNoModRef(AA->getModRefInfo(&*BI, AllocaLoc)))
369 continue;
370
371 if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
372 // If the instruction is readnone, ignore it, otherwise bail out. We
373 // don't even allow readonly here because we don't want something like:
374 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
375 if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
376 break;
377 continue;
378 }
379
380 if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
381 if (!NextStore->isSimple())
382 break;
383
384 // Check to see if this store is to a constant offset from the start ptr.
385 Optional<int64_t> Offset =
386 isPointerOffset(StartPtr, NextStore->getPointerOperand(), *DL);
387 if (!Offset)
388 break;
389
390 if (!IB.addStore(*Offset, NextStore, DL))
391 break;
392 LastInst = NextStore;
393 } else {
394 MemSetInst *MSI = cast<MemSetInst>(BI);
395
396 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength()))
397 break;
398
399 if (!isa<ConstantInt>(MSI->getValue()))
400 break;
401
402 // Check to see if this store is to a constant offset from the start ptr.
403 Optional<int64_t> Offset = isPointerOffset(StartPtr, MSI->getDest(), *DL);
404 if (!Offset)
405 break;
406
407 if (!IB.addMemSet(*Offset, MSI))
408 break;
409 LastInst = MSI;
410 }
411 }
412 return LastInst;
413 }
414
isInterestingAlloca(const AllocaInst & AI)415 bool AArch64StackTagging::isInterestingAlloca(const AllocaInst &AI) {
416 // FIXME: support dynamic allocas
417 bool IsInteresting =
418 AI.getAllocatedType()->isSized() && AI.isStaticAlloca() &&
419 // alloca() may be called with 0 size, ignore it.
420 AI.getAllocationSizeInBits(*DL).getValue() > 0 &&
421 // inalloca allocas are not treated as static, and we don't want
422 // dynamic alloca instrumentation for them as well.
423 !AI.isUsedWithInAlloca() &&
424 // swifterror allocas are register promoted by ISel
425 !AI.isSwiftError() &&
426 // safe allocas are not interesting
427 !(SSI && SSI->isSafe(AI));
428 return IsInteresting;
429 }
430
tagAlloca(AllocaInst * AI,Instruction * InsertBefore,Value * Ptr,uint64_t Size)431 void AArch64StackTagging::tagAlloca(AllocaInst *AI, Instruction *InsertBefore,
432 Value *Ptr, uint64_t Size) {
433 auto SetTagZeroFunc =
434 Intrinsic::getDeclaration(F->getParent(), Intrinsic::aarch64_settag_zero);
435 auto StgpFunc =
436 Intrinsic::getDeclaration(F->getParent(), Intrinsic::aarch64_stgp);
437
438 InitializerBuilder IB(Size, DL, Ptr, SetTagFunc, SetTagZeroFunc, StgpFunc);
439 bool LittleEndian =
440 Triple(AI->getModule()->getTargetTriple()).isLittleEndian();
441 // Current implementation of initializer merging assumes little endianness.
442 if (MergeInit && !F->hasOptNone() && LittleEndian &&
443 Size < ClMergeInitSizeLimit) {
444 LLVM_DEBUG(dbgs() << "collecting initializers for " << *AI
445 << ", size = " << Size << "\n");
446 InsertBefore = collectInitializers(InsertBefore, Ptr, Size, IB);
447 }
448
449 IRBuilder<> IRB(InsertBefore);
450 IB.generate(IRB);
451 }
452
untagAlloca(AllocaInst * AI,Instruction * InsertBefore,uint64_t Size)453 void AArch64StackTagging::untagAlloca(AllocaInst *AI, Instruction *InsertBefore,
454 uint64_t Size) {
455 IRBuilder<> IRB(InsertBefore);
456 IRB.CreateCall(SetTagFunc, {IRB.CreatePointerCast(AI, IRB.getInt8PtrTy()),
457 ConstantInt::get(IRB.getInt64Ty(), Size)});
458 }
459
insertBaseTaggedPointer(const MapVector<AllocaInst *,AllocaInfo> & Allocas,const DominatorTree * DT)460 Instruction *AArch64StackTagging::insertBaseTaggedPointer(
461 const MapVector<AllocaInst *, AllocaInfo> &Allocas,
462 const DominatorTree *DT) {
463 BasicBlock *PrologueBB = nullptr;
464 // Try sinking IRG as deep as possible to avoid hurting shrink wrap.
465 for (auto &I : Allocas) {
466 const AllocaInfo &Info = I.second;
467 AllocaInst *AI = Info.AI;
468 if (Info.Tag < 0)
469 continue;
470 if (!PrologueBB) {
471 PrologueBB = AI->getParent();
472 continue;
473 }
474 PrologueBB = DT->findNearestCommonDominator(PrologueBB, AI->getParent());
475 }
476 assert(PrologueBB);
477
478 IRBuilder<> IRB(&PrologueBB->front());
479 Function *IRG_SP =
480 Intrinsic::getDeclaration(F->getParent(), Intrinsic::aarch64_irg_sp);
481 Instruction *Base =
482 IRB.CreateCall(IRG_SP, {Constant::getNullValue(IRB.getInt64Ty())});
483 Base->setName("basetag");
484 return Base;
485 }
486
alignAndPadAlloca(AllocaInfo & Info)487 void AArch64StackTagging::alignAndPadAlloca(AllocaInfo &Info) {
488 const Align NewAlignment =
489 max(MaybeAlign(Info.AI->getAlignment()), kTagGranuleSize);
490 Info.AI->setAlignment(NewAlignment);
491
492 uint64_t Size = Info.AI->getAllocationSizeInBits(*DL).getValue() / 8;
493 uint64_t AlignedSize = alignTo(Size, kTagGranuleSize);
494 if (Size == AlignedSize)
495 return;
496
497 // Add padding to the alloca.
498 Type *AllocatedType =
499 Info.AI->isArrayAllocation()
500 ? ArrayType::get(
501 Info.AI->getAllocatedType(),
502 cast<ConstantInt>(Info.AI->getArraySize())->getZExtValue())
503 : Info.AI->getAllocatedType();
504 Type *PaddingType =
505 ArrayType::get(Type::getInt8Ty(F->getContext()), AlignedSize - Size);
506 Type *TypeWithPadding = StructType::get(AllocatedType, PaddingType);
507 auto *NewAI = new AllocaInst(
508 TypeWithPadding, Info.AI->getType()->getAddressSpace(), nullptr, "", Info.AI);
509 NewAI->takeName(Info.AI);
510 NewAI->setAlignment(Info.AI->getAlign());
511 NewAI->setUsedWithInAlloca(Info.AI->isUsedWithInAlloca());
512 NewAI->setSwiftError(Info.AI->isSwiftError());
513 NewAI->copyMetadata(*Info.AI);
514
515 auto *NewPtr = new BitCastInst(NewAI, Info.AI->getType(), "", Info.AI);
516 Info.AI->replaceAllUsesWith(NewPtr);
517 Info.AI->eraseFromParent();
518 Info.AI = NewAI;
519 }
520
521 // Helper function to check for post-dominance.
postDominates(const PostDominatorTree * PDT,const IntrinsicInst * A,const IntrinsicInst * B)522 static bool postDominates(const PostDominatorTree *PDT, const IntrinsicInst *A,
523 const IntrinsicInst *B) {
524 const BasicBlock *ABB = A->getParent();
525 const BasicBlock *BBB = B->getParent();
526
527 if (ABB != BBB)
528 return PDT->dominates(ABB, BBB);
529
530 for (const Instruction &I : *ABB) {
531 if (&I == B)
532 return true;
533 if (&I == A)
534 return false;
535 }
536 llvm_unreachable("Corrupt instruction list");
537 }
538
539 // FIXME: check for MTE extension
runOnFunction(Function & Fn)540 bool AArch64StackTagging::runOnFunction(Function &Fn) {
541 if (!Fn.hasFnAttribute(Attribute::SanitizeMemTag))
542 return false;
543
544 if (UseStackSafety)
545 SSI = &getAnalysis<StackSafetyGlobalInfoWrapperPass>().getResult();
546 F = &Fn;
547 DL = &Fn.getParent()->getDataLayout();
548 if (MergeInit)
549 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
550
551 MapVector<AllocaInst *, AllocaInfo> Allocas; // need stable iteration order
552 SmallVector<Instruction *, 8> RetVec;
553 SmallVector<Instruction *, 4> UnrecognizedLifetimes;
554
555 for (auto &BB : *F) {
556 for (BasicBlock::iterator IT = BB.begin(); IT != BB.end(); ++IT) {
557 Instruction *I = &*IT;
558 if (auto *AI = dyn_cast<AllocaInst>(I)) {
559 Allocas[AI].AI = AI;
560 continue;
561 }
562
563 if (auto *DVI = dyn_cast<DbgVariableIntrinsic>(I)) {
564 if (auto *AI =
565 dyn_cast_or_null<AllocaInst>(DVI->getVariableLocation())) {
566 Allocas[AI].DbgVariableIntrinsics.push_back(DVI);
567 }
568 continue;
569 }
570
571 auto *II = dyn_cast<IntrinsicInst>(I);
572 if (II && (II->getIntrinsicID() == Intrinsic::lifetime_start ||
573 II->getIntrinsicID() == Intrinsic::lifetime_end)) {
574 AllocaInst *AI = findAllocaForValue(II->getArgOperand(1));
575 if (!AI) {
576 UnrecognizedLifetimes.push_back(I);
577 continue;
578 }
579 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
580 Allocas[AI].LifetimeStart.push_back(II);
581 else
582 Allocas[AI].LifetimeEnd.push_back(II);
583 }
584
585 if (isa<ReturnInst>(I) || isa<ResumeInst>(I) || isa<CleanupReturnInst>(I))
586 RetVec.push_back(I);
587 }
588 }
589
590 if (Allocas.empty())
591 return false;
592
593 int NextTag = 0;
594 int NumInterestingAllocas = 0;
595 for (auto &I : Allocas) {
596 AllocaInfo &Info = I.second;
597 assert(Info.AI);
598
599 if (!isInterestingAlloca(*Info.AI)) {
600 Info.Tag = -1;
601 continue;
602 }
603
604 alignAndPadAlloca(Info);
605 NumInterestingAllocas++;
606 Info.Tag = NextTag;
607 NextTag = (NextTag + 1) % 16;
608 }
609
610 if (NumInterestingAllocas == 0)
611 return true;
612
613 std::unique_ptr<DominatorTree> DeleteDT;
614 DominatorTree *DT = nullptr;
615 if (auto *P = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
616 DT = &P->getDomTree();
617
618 if (DT == nullptr && (NumInterestingAllocas > 1 ||
619 !F->hasFnAttribute(Attribute::OptimizeNone))) {
620 DeleteDT = std::make_unique<DominatorTree>(*F);
621 DT = DeleteDT.get();
622 }
623
624 std::unique_ptr<PostDominatorTree> DeletePDT;
625 PostDominatorTree *PDT = nullptr;
626 if (auto *P = getAnalysisIfAvailable<PostDominatorTreeWrapperPass>())
627 PDT = &P->getPostDomTree();
628
629 if (PDT == nullptr && !F->hasFnAttribute(Attribute::OptimizeNone)) {
630 DeletePDT = std::make_unique<PostDominatorTree>(*F);
631 PDT = DeletePDT.get();
632 }
633
634 SetTagFunc =
635 Intrinsic::getDeclaration(F->getParent(), Intrinsic::aarch64_settag);
636
637 Instruction *Base = insertBaseTaggedPointer(Allocas, DT);
638
639 for (auto &I : Allocas) {
640 const AllocaInfo &Info = I.second;
641 AllocaInst *AI = Info.AI;
642 if (Info.Tag < 0)
643 continue;
644
645 // Replace alloca with tagp(alloca).
646 IRBuilder<> IRB(Info.AI->getNextNode());
647 Function *TagP = Intrinsic::getDeclaration(
648 F->getParent(), Intrinsic::aarch64_tagp, {Info.AI->getType()});
649 Instruction *TagPCall =
650 IRB.CreateCall(TagP, {Constant::getNullValue(Info.AI->getType()), Base,
651 ConstantInt::get(IRB.getInt64Ty(), Info.Tag)});
652 if (Info.AI->hasName())
653 TagPCall->setName(Info.AI->getName() + ".tag");
654 Info.AI->replaceAllUsesWith(TagPCall);
655 TagPCall->setOperand(0, Info.AI);
656
657 if (UnrecognizedLifetimes.empty() && Info.LifetimeStart.size() == 1 &&
658 Info.LifetimeEnd.size() == 1) {
659 IntrinsicInst *Start = Info.LifetimeStart[0];
660 IntrinsicInst *End = Info.LifetimeEnd[0];
661 uint64_t Size =
662 cast<ConstantInt>(Start->getArgOperand(0))->getZExtValue();
663 Size = alignTo(Size, kTagGranuleSize);
664 tagAlloca(AI, Start->getNextNode(), Start->getArgOperand(1), Size);
665 // We need to ensure that if we tag some object, we certainly untag it
666 // before the function exits.
667 if (PDT != nullptr && postDominates(PDT, End, Start)) {
668 untagAlloca(AI, End, Size);
669 } else {
670 SmallVector<Instruction *, 8> ReachableRetVec;
671 unsigned NumCoveredExits = 0;
672 for (auto &RI : RetVec) {
673 if (!isPotentiallyReachable(Start, RI, nullptr, DT))
674 continue;
675 ReachableRetVec.push_back(RI);
676 if (DT != nullptr && DT->dominates(End, RI))
677 ++NumCoveredExits;
678 }
679 // If there's a mix of covered and non-covered exits, just put the untag
680 // on exits, so we avoid the redundancy of untagging twice.
681 if (NumCoveredExits == ReachableRetVec.size()) {
682 untagAlloca(AI, End, Size);
683 } else {
684 for (auto &RI : ReachableRetVec)
685 untagAlloca(AI, RI, Size);
686 // We may have inserted untag outside of the lifetime interval.
687 // Remove the lifetime end call for this alloca.
688 End->eraseFromParent();
689 }
690 }
691 } else {
692 uint64_t Size = Info.AI->getAllocationSizeInBits(*DL).getValue() / 8;
693 Value *Ptr = IRB.CreatePointerCast(TagPCall, IRB.getInt8PtrTy());
694 tagAlloca(AI, &*IRB.GetInsertPoint(), Ptr, Size);
695 for (auto &RI : RetVec) {
696 untagAlloca(AI, RI, Size);
697 }
698 // We may have inserted tag/untag outside of any lifetime interval.
699 // Remove all lifetime intrinsics for this alloca.
700 for (auto &II : Info.LifetimeStart)
701 II->eraseFromParent();
702 for (auto &II : Info.LifetimeEnd)
703 II->eraseFromParent();
704 }
705
706 // Fixup debug intrinsics to point to the new alloca.
707 for (auto DVI : Info.DbgVariableIntrinsics)
708 DVI->setArgOperand(
709 0,
710 MetadataAsValue::get(F->getContext(), LocalAsMetadata::get(Info.AI)));
711 }
712
713 // If we have instrumented at least one alloca, all unrecognized lifetime
714 // instrinsics have to go.
715 for (auto &I : UnrecognizedLifetimes)
716 I->eraseFromParent();
717
718 return true;
719 }
720