LLVM 24.0.0git
AArch64StackTagging.cpp
Go to the documentation of this file.
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"
15#include "llvm/ADT/Statistic.h"
17#include "llvm/Analysis/CFG.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"
34#include "llvm/IR/Instruction.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"
42#include "llvm/Pass.h"
44#include "llvm/Support/Debug.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 {
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 };
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(Ranges, Start, [](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, {Start, End, Inst});
94 return true;
95 }
96
97 bool addStore(uint64_t Offset, StoreInst *SI, const DataLayout *DL) {
98 int64_t StoreSize = DL->getTypeStoreSize(SI->getOperand(0)->getType());
99 if (!addRange(Offset, Offset + StoreSize, SI))
100 return false;
101 IRBuilder<> IRB(SI);
102 applyStore(IRB, Offset, Offset + StoreSize, SI->getOperand(0));
103 return true;
104 }
105
106 bool addMemSet(uint64_t Offset, MemSetInst *MSI) {
107 uint64_t StoreSize = cast<ConstantInt>(MSI->getLength())->getZExtValue();
108 if (!addRange(Offset, Offset + StoreSize, MSI))
109 return false;
110 IRBuilder<> IRB(MSI);
111 applyMemSet(IRB, Offset, Offset + StoreSize,
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(IRB.getInt64Ty(), Cst * V->getZExtValue());
133
134 Value *&CurrentV = Out[Offset];
135 if (!CurrentV) {
136 CurrentV = C;
137 } else {
138 CurrentV = IRB.CreateOr(CurrentV, 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(V, Offset * 8);
148 V = IRB.CreateZExtOrTrunc(V, IRB.getInt64Ty());
149 } else if (Offset < 0) {
150 V = IRB.CreateZExtOrTrunc(V, IRB.getInt64Ty());
151 V = IRB.CreateShl(V, -Offset * 8);
152 } else {
153 V = IRB.CreateZExtOrTrunc(V, 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, StoredValue);
161 for (int64_t Offset = Start - Start % 8; Offset < End; Offset += 8) {
162 Value *V = sliceValue(IRB, StoredValue, Offset - Start);
163 Value *&CurrentV = Out[Offset];
164 if (!CurrentV) {
165 CurrentV = V;
166 } else {
167 CurrentV = IRB.CreateOr(CurrentV, 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, 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(Offset);
186 auto I2 = Out.find(Offset + 8);
187 if (I1 == Out.end() && I2 == Out.end())
188 continue;
189
190 if (Offset > LastOffset)
191 emitZeroes(IRB, LastOffset, Offset - LastOffset);
192
193 Value *Store1 = I1 == Out.end() ? Constant::getNullValue(IRB.getInt64Ty())
194 : I1->second;
195 Value *Store2 = I2 == Out.end() ? Constant::getNullValue(IRB.getInt64Ty())
196 : I2->second;
197 emitPair(IRB, Offset, Store1, 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, LastOffset, 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(IRB.getInt8Ty(), Ptr, Offset);
217 IRB.CreateCall(SetTagZeroFn,
218 {Ptr, ConstantInt::get(IRB.getInt64Ty(), 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(IRB.getInt8Ty(), Ptr, Offset);
227 IRB.CreateCall(SetTagFn, {Ptr, ConstantInt::get(IRB.getInt64Ty(), 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(IRB.getInt8Ty(), Ptr, Offset);
236 IRB.CreateCall(StgpFn, {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>(V->getType())) {
244 LLVMContext &Ctx = IRB.getContext();
245 Type *EltTy = VecTy->getElementType();
246 if (EltTy->isPointerTy()) {
247 uint32_t EltSize = DL->getTypeSizeInBits(EltTy);
248 auto *NewTy = FixedVectorType::get(
249 IntegerType::get(Ctx, EltSize),
251 V = IRB.CreatePointerCast(V, NewTy);
252 }
253 }
254 return IRB.CreateBitOrPointerCast(
255 V, IRB.getIntNTy(DL->getTypeStoreSize(V->getType()) * 8));
256 }
257};
258
259class AArch64StackTagging : public FunctionPass {
260 // Without the TargetMachine's options (opt -aarch64-stack-tagging), require
261 // both analyses; runOnFunction may disable them per the context's options.
262 const bool MergeInit;
263 const bool UseStackSafety;
264
265public:
266 static char ID; // Pass ID, replacement for typeid
267
268 AArch64StackTagging(const AArch64Options *Opts = nullptr,
269 bool IsOptNone = false)
270 : FunctionPass(ID),
271 MergeInit(!Opts || valueOr(Opts->stack_tagging_merge_init, !IsOptNone)),
272 UseStackSafety(!Opts || valueOr(Opts->stack_tagging_use_stack_safety,
273 !IsOptNone)) {}
274
275 void tagAlloca(AllocaInst *AI, Instruction *InsertBefore, Value *Ptr,
276 uint64_t Size);
277 void untagAlloca(AllocaInst *AI, Instruction *InsertBefore, uint64_t Size);
278
279 Instruction *collectInitializers(Instruction *StartInst, Value *StartPtr,
280 uint64_t Size, InitializerBuilder &IB);
281
282 Instruction *insertBaseTaggedPointer(
283 const Module &M,
284 const MapVector<AllocaInst *, memtag::AllocaInfo> &Allocas,
285 const DominatorTree *DT);
286 bool runOnFunction(Function &F) override;
287
288 StringRef getPassName() const override { return "AArch64 Stack Tagging"; }
289
290private:
291 const AArch64Options *CLOpts = nullptr;
292 Function *F = nullptr;
293 Function *SetTagFunc = nullptr;
294 const DataLayout *DL = nullptr;
295 AAResults *AA = nullptr;
296 const StackSafetyGlobalInfo *SSI = nullptr;
297
298 void getAnalysisUsage(AnalysisUsage &AU) const override {
299 AU.setPreservesCFG();
300 if (UseStackSafety)
301 AU.addRequired<StackSafetyGlobalInfoWrapperPass>();
302 if (MergeInit)
303 AU.addRequired<AAResultsWrapperPass>();
304 AU.addUsedIfAvailable<OptimizationRemarkEmitterWrapperPass>();
305 }
306};
307
308} // end anonymous namespace
309
310char AArch64StackTagging::ID = 0;
311
312INITIALIZE_PASS_BEGIN(AArch64StackTagging, DEBUG_TYPE, "AArch64 Stack Tagging",
313 false, false)
317INITIALIZE_PASS_END(AArch64StackTagging, DEBUG_TYPE, "AArch64 Stack Tagging",
319
321 bool IsOptNone) {
322 return new AArch64StackTagging(&CLOpts, IsOptNone);
323}
324
325Instruction *AArch64StackTagging::collectInitializers(Instruction *StartInst,
326 Value *StartPtr,
328 InitializerBuilder &IB) {
329 MemoryLocation AllocaLoc{StartPtr, Size};
330 Instruction *LastInst = StartInst;
331 BasicBlock::iterator BI(StartInst);
332
333 unsigned Count = 0;
334 for (; Count < CLOpts->stack_tagging_merge_init_scan_limit &&
335 !BI->isTerminator();
336 ++BI) {
337 ++Count;
338
339 if (isNoModRef(AA->getModRefInfo(&*BI, AllocaLoc)))
340 continue;
341
342 if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
343 // If the instruction is readnone, ignore it, otherwise bail out. We
344 // don't even allow readonly here because we don't want something like:
345 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
346 if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
347 break;
348 continue;
349 }
350
351 if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
352 if (!NextStore->isSimple())
353 break;
354
355 // Check to see if this store is to a constant offset from the start ptr.
356 std::optional<int64_t> Offset =
357 NextStore->getPointerOperand()->getPointerOffsetFrom(StartPtr, *DL);
358 if (!Offset)
359 break;
360
361 if (!IB.addStore(*Offset, NextStore, DL))
362 break;
363 LastInst = NextStore;
364 } else {
365 MemSetInst *MSI = cast<MemSetInst>(BI);
366
367 if (MSI->isVolatile() || !isa<ConstantInt>(MSI->getLength()))
368 break;
369
370 if (!isa<ConstantInt>(MSI->getValue()))
371 break;
372
373 // Check to see if this store is to a constant offset from the start ptr.
374 std::optional<int64_t> Offset =
375 MSI->getDest()->getPointerOffsetFrom(StartPtr, *DL);
376 if (!Offset)
377 break;
378
379 if (!IB.addMemSet(*Offset, MSI))
380 break;
381 LastInst = MSI;
382 }
383 }
384 return LastInst;
385}
386
387void AArch64StackTagging::tagAlloca(AllocaInst *AI, Instruction *InsertBefore,
388 Value *Ptr, uint64_t Size) {
389 auto SetTagZeroFunc = Intrinsic::getOrInsertDeclaration(
390 F->getParent(), Intrinsic::aarch64_settag_zero);
391 auto StgpFunc = Intrinsic::getOrInsertDeclaration(F->getParent(),
392 Intrinsic::aarch64_stgp);
393
394 InitializerBuilder IB(Size, DL, Ptr, SetTagFunc, SetTagZeroFunc, StgpFunc);
395 bool LittleEndian = AI->getModule()->getTargetTriple().isLittleEndian();
396 // Current implementation of initializer merging assumes little endianness.
397 if (AA && !F->hasOptNone() && LittleEndian &&
398 Size < CLOpts->stack_tagging_merge_init_size_limit) {
399 LLVM_DEBUG(dbgs() << "collecting initializers for " << *AI
400 << ", size = " << Size << "\n");
401 InsertBefore = collectInitializers(InsertBefore, Ptr, Size, IB);
402 }
403
404 IRBuilder<> IRB(InsertBefore);
405 IB.generate(IRB);
406}
407
408void AArch64StackTagging::untagAlloca(AllocaInst *AI, Instruction *InsertBefore,
409 uint64_t Size) {
410 IRBuilder<> IRB(InsertBefore);
411 IRB.CreateCall(SetTagFunc, {IRB.CreatePointerCast(AI, IRB.getPtrTy()),
412 ConstantInt::get(IRB.getInt64Ty(), Size)});
413}
414
415static Value *getSlotPtr(const AArch64Options &CLOpts, IRBuilder<> &IRB,
416 const Triple &TargetTriple,
417 bool HasInstrumentedAllocas) {
418 if (!HasInstrumentedAllocas)
419 return nullptr;
420
421 auto Mode = CLOpts.stack_tagging_record_stack_history;
423 (!Mode && TargetTriple.isOSDarwin())) {
424 if (TargetTriple.isAndroid() && TargetTriple.isAArch64() &&
425 !TargetTriple.isAndroidVersionLT(35))
426 return memtag::getAndroidSlotPtr(IRB, -3);
427 if (TargetTriple.isOSDarwin() && TargetTriple.isAArch64() &&
428 !TargetTriple.isSimulatorEnvironment())
429 return memtag::getDarwinSlotPtr(IRB, 231);
430 }
431 return nullptr;
432}
433
434Instruction *AArch64StackTagging::insertBaseTaggedPointer(
435 const Module &M,
436 const MapVector<AllocaInst *, memtag::AllocaInfo> &AllocasToInstrument,
437 const DominatorTree *DT) {
438 BasicBlock *PrologueBB = nullptr;
439 // Try sinking IRG as deep as possible to avoid hurting shrink wrap.
440 for (auto &I : AllocasToInstrument) {
441 const memtag::AllocaInfo &Info = I.second;
442 AllocaInst *AI = Info.AI;
443 if (!PrologueBB) {
444 PrologueBB = AI->getParent();
445 continue;
446 }
447 PrologueBB = DT->findNearestCommonDominator(PrologueBB, AI->getParent());
448 }
449 assert(PrologueBB);
450
451 IRBuilder<> IRB(&PrologueBB->front());
453 Intrinsic::aarch64_irg_sp, {},
455 Base->setName("basetag");
456 const Triple &TargetTriple = M.getTargetTriple();
457 // This ABI will make it into Android API level 35.
458 // The ThreadLong format is the same as with HWASan, but the entries for
459 // stack MTE take two slots (16 bytes).
460 //
461 // Stack history is recorded by default on Darwin.
462 if (Value *SlotPtr = getSlotPtr(*CLOpts, IRB, TargetTriple,
463 !AllocasToInstrument.empty())) {
464 constexpr uint64_t TagMask = 0xFULL << 56;
465 auto *IntptrTy = IRB.getIntPtrTy(M.getDataLayout());
466 auto *ThreadLong = IRB.CreateLoad(IntptrTy, SlotPtr);
467 Value *FP = memtag::getFP(IRB);
468 Value *Tag = IRB.CreateAnd(IRB.CreatePtrToInt(Base, IntptrTy), TagMask);
469 Value *TaggedFP = IRB.CreateOr(FP, Tag);
470 Value *PC = memtag::getPC(TargetTriple, IRB);
471 Value *RecordPtr = IRB.CreateIntToPtr(ThreadLong, IRB.getPtrTy(0));
472 IRB.CreateStore(PC, RecordPtr);
473 IRB.CreateStore(TaggedFP, IRB.CreateConstGEP1_64(IntptrTy, RecordPtr, 1));
474
475 IRB.CreateStore(memtag::incrementThreadLong(IRB, ThreadLong, 16,
476 TargetTriple.isOSDarwin()),
477 SlotPtr);
478 }
479 return Base;
480}
481
482// FIXME: check for MTE extension
483bool AArch64StackTagging::runOnFunction(Function &Fn) {
484 if (!Fn.hasFnAttribute(Attribute::SanitizeMemTag))
485 return false;
486
487 CLOpts = &Fn.getContext().getLibraryOptions().get<AArch64Options>();
488 SSI = UseStackSafety && valueOr(CLOpts->stack_tagging_use_stack_safety, true)
489 ? &getAnalysis<StackSafetyGlobalInfoWrapperPass>().getResult()
490 : nullptr;
491 F = &Fn;
492 DL = &Fn.getDataLayout();
493 AA = MergeInit && valueOr(CLOpts->stack_tagging_merge_init, true)
494 ? &getAnalysis<AAResultsWrapperPass>().getAAResults()
495 : nullptr;
496
497 std::unique_ptr<OptimizationRemarkEmitter> DeleteORE;
498 OptimizationRemarkEmitter *ORE = nullptr;
499 if (auto *P = getAnalysisIfAvailable<OptimizationRemarkEmitterWrapperPass>())
500 ORE = &P->getORE();
501
502 if (ORE == nullptr) {
503 DeleteORE = std::make_unique<OptimizationRemarkEmitter>(F);
504 ORE = DeleteORE.get();
505 }
506
507 memtag::StackInfoBuilder SIB(SSI, DEBUG_TYPE);
508 for (Instruction &I : instructions(F))
509 SIB.visit(*ORE, I);
510 memtag::StackInfo &SInfo = SIB.get();
511
512 if (SInfo.AllocasToInstrument.empty())
513 return false;
514
515 std::unique_ptr<DominatorTree> DeleteDT;
516 DominatorTree *DT = nullptr;
517 if (auto *P = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
518 DT = &P->getDomTree();
519
520 if (DT == nullptr) {
521 DeleteDT = std::make_unique<DominatorTree>(*F);
522 DT = DeleteDT.get();
523 }
524
525 std::unique_ptr<PostDominatorTree> DeletePDT;
526 PostDominatorTree *PDT = nullptr;
527 if (auto *P = getAnalysisIfAvailable<PostDominatorTreeWrapperPass>())
528 PDT = &P->getPostDomTree();
529
530 if (PDT == nullptr) {
531 DeletePDT = std::make_unique<PostDominatorTree>(*F);
532 PDT = DeletePDT.get();
533 }
534
535 std::unique_ptr<LoopInfo> DeleteLI;
536 LoopInfo *LI = nullptr;
537 if (auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>()) {
538 LI = &LIWP->getLoopInfo();
539 } else {
540 DeleteLI = std::make_unique<LoopInfo>(*DT);
541 LI = DeleteLI.get();
542 }
543
544 SetTagFunc = Intrinsic::getOrInsertDeclaration(F->getParent(),
545 Intrinsic::aarch64_settag);
546
548 insertBaseTaggedPointer(*Fn.getParent(), SInfo.AllocasToInstrument, DT);
549
550 unsigned int NextTag = 0;
551 for (auto &I : SInfo.AllocasToInstrument) {
552 memtag::AllocaInfo &Info = I.second;
553 assert(Info.AI && SIB.getAllocaInterestingness(*Info.AI) ==
556 AllocaInst *AI = Info.AI;
557 unsigned int Tag = NextTag;
558 NextTag = (NextTag + 1) % 16;
559 // Replace alloca with tagp(alloca).
560 IRBuilder<> IRB(Info.AI->getNextNode());
562 Intrinsic::aarch64_tagp, {Info.AI->getType()},
563 {Constant::getNullValue(Info.AI->getType()), Base,
564 ConstantInt::get(IRB.getInt64Ty(), Tag)});
565 if (Info.AI->hasName())
566 TagPCall->setName(Info.AI->getName() + ".tag");
567 // Does not replace metadata, so we don't have to handle DbgVariableRecords.
568 Info.AI->replaceUsesWithIf(TagPCall, [&](const Use &U) {
569 return !isa<LifetimeIntrinsic>(U.getUser());
570 });
571 TagPCall->setOperand(0, Info.AI);
572
573 // Calls to functions that may return twice (e.g. setjmp) confuse the
574 // postdominator analysis, and will leave us to keep memory tagged after
575 // function return. Work around this by always untagging at every return
576 // statement if return_twice functions are called.
577 bool StandardLifetime =
578 !SInfo.CallsReturnTwice && memtag::isSupportedLifetime(Info, DT, LI);
579 if (StandardLifetime) {
580 uint64_t Size = *Info.AI->getAllocationSize(*DL);
582 for (IntrinsicInst *Start : Info.LifetimeStart)
583 tagAlloca(AI, Start->getNextNode(), TagPCall, Size);
584
585 auto TagEnd = [&](Instruction *Node) { untagAlloca(AI, Node, Size); };
586 memtag::forAllReachableExits(*DT, *PDT, *LI, Info, SInfo.RetVec, TagEnd);
587 } else {
588 uint64_t Size = *Info.AI->getAllocationSize(*DL);
589 Value *Ptr = IRB.CreatePointerCast(TagPCall, IRB.getPtrTy());
590 tagAlloca(AI, &*IRB.GetInsertPoint(), Ptr, Size);
591 for (auto *RI : SInfo.RetVec) {
592 untagAlloca(AI, RI, Size);
593 }
594 // We may have inserted tag/untag outside of any lifetime interval.
595 // Remove all lifetime intrinsics for this alloca.
596 for (auto *II : Info.LifetimeStart)
597 II->eraseFromParent();
598 for (auto *II : Info.LifetimeEnd)
599 II->eraseFromParent();
600 }
601
603 }
604
605 return true;
606}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
static Value * getSlotPtr(const AArch64Options &CLOpts, IRBuilder<> &IRB, const Triple &TargetTriple, bool HasInstrumentedAllocas)
static const Align kTagGranuleSize
uint64_t uint64_t
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains constants used for implementing Dwarf debug support.
static bool runOnFunction(Function &F, bool PostInlining)
#define DEBUG_TYPE
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
static void addRange(SmallVectorImpl< ConstantInt * > &EndPoints, ConstantInt *Low, ConstantInt *High)
This file contains the declarations for metadata subclasses.
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#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
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 defines the SmallVector class.
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
Value * RHS
Value * LHS
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
ModRefInfo getModRefInfo(const Instruction *I, const std::optional< MemoryLocation > &OptLoc)
Check whether or not an instruction may read or write the optionally specified memory location.
AnalysisUsage & addUsedIfAvailable()
Add the specified Pass class to the set of analyses used by this pass.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
const Instruction & front() const
Definition BasicBlock.h:463
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
LLVM_ABI Instruction * findNearestCommonDominator(Instruction *I1, Instruction *I2) const
Find the nearest instruction I that dominates both I1 and I2, in the sense that a result produced bef...
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:843
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
const DataLayout & getDataLayout() const
Get the data layout of the module this function belongs to.
Definition Function.cpp:356
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:731
Module * getParent()
Get the module that this global value is contained inside of...
LLVM_ABI CallInst * CreateIntrinsicWithoutFolding(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={})
Create a call to intrinsic ID with Args, mangled using OverloadTypes.
Value * CreateConstGEP1_64(Type *Ty, Value *Ptr, uint64_t Idx0, const Twine &Name="")
Definition IRBuilder.h:2055
Value * CreateConstGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0, const Twine &Name="")
Definition IRBuilder.h:2024
IntegerType * getIntNTy(unsigned N)
Fetch the type representing an N-bit integer.
Definition IRBuilder.h:535
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
Definition IRBuilder.h:2139
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2297
BasicBlock::iterator GetInsertPoint() const
Definition IRBuilder.h:176
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2238
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition IRBuilder.h:1528
IntegerType * getIntPtrTy(const DataLayout &DL, unsigned AddrSpace=0)
Fetch the type of an integer with size at least as big as that of a pointer in the given address spac...
Definition IRBuilder.h:577
IntegerType * getInt64Ty()
Fetch the type representing a 64-bit integer.
Definition IRBuilder.h:527
Value * CreateBitOrPointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2332
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition IRBuilder.h:1907
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1507
LLVMContext & getContext() const
Definition IRBuilder.h:177
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1566
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition IRBuilder.h:1925
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2233
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2561
PointerType * getPtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer.
Definition IRBuilder.h:565
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1588
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
Definition IRBuilder.h:512
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2909
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:338
LLVM_ABI cl::LibraryOptionsContext & getLibraryOptions() const
The library options this context reads in place of their process-wide values.
Value * getLength() const
Value * getDest() const
This is just like getRawDest, but it strips off any cast instructions (including addrspacecast) that ...
bool isVolatile() const
Value * getValue() const
Representation for a specific memory location.
const Triple & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition Module.h:328
OptimizationRemarkEmitter legacy analysis pass.
This pass performs the global (interprocedural) stack safety analysis (legacy pass manager).
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
bool isAndroidVersionLT(unsigned Major) const
Definition Triple.h:913
bool isAndroid() const
Tests whether the target is Android.
Definition Triple.h:911
LLVM_ABI bool isLittleEndian() const
Tests whether the target triple is little endian.
Definition Triple.cpp:2213
bool isSimulatorEnvironment() const
Definition Triple.h:731
bool isOSDarwin() const
Is this a "Darwin" OS (macOS, iOS, tvOS, watchOS, DriverKit, XROS, or bridgeOS).
Definition Triple.h:724
bool isAArch64() const
Tests whether the target is AArch64 (little and big endian).
Definition Triple.h:1099
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
void setOperand(unsigned i, Value *Val)
Definition User.h:212
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:390
LLVM_ABI std::optional< int64_t > getPointerOffsetFrom(const Value *Other, const DataLayout &DL) const
If this ptr is provably equal to Other plus a constant offset, return that offset in bytes.
Definition Value.cpp:1096
const ParentTy * getParent() const
Definition ilist_node.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI Value * getFP(IRBuilder<> &IRB)
LLVM_ABI void forAllReachableExits(const DominatorTree &DT, const PostDominatorTree &PDT, const LoopInfo &LI, const AllocaInfo &AInfo, const SmallVectorImpl< Instruction * > &RetVec, llvm::function_ref< void(Instruction *)> Callback)
LLVM_ABI bool isSupportedLifetime(const AllocaInfo &AInfo, const DominatorTree *DT, const LoopInfo *LI)
LLVM_ABI Value * getDarwinSlotPtr(IRBuilder<> &IRB, int Slot)
LLVM_ABI Value * getAndroidSlotPtr(IRBuilder<> &IRB, int Slot)
LLVM_ABI void annotateDebugRecords(AllocaInfo &Info, unsigned int Tag)
LLVM_ABI void alignAndPadAlloca(memtag::AllocaInfo &Info, llvm::Align Align)
LLVM_ABI Value * getPC(const Triple &TargetTriple, IRBuilder<> &IRB)
LLVM_ABI Value * incrementThreadLong(IRBuilder<> &IRB, Value *ThreadLong, unsigned int Inc, bool IsMemtagDarwin=false)
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
unsigned getNumElements(Type *Ty)
Definition SLPUtils.cpp:110
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
FunctionPass * createAArch64StackTaggingPass(const AArch64Options &CLOpts, bool IsOptNone)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2068
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
constexpr bool valueOr(BoolOrDefault X, bool Default)
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:267
bool isNoModRef(const ModRefInfo MRI)
Definition ModRef.h:40
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
MapVector< AllocaInst *, AllocaInfo > AllocasToInstrument
SmallVector< Instruction *, 8 > RetVec