LLVM 24.0.0git
TypeSanitizer.cpp
Go to the documentation of this file.
1//===----- TypeSanitizer.cpp - type-based-aliasing-violation detector -----===//
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// This file is a part of TypeSanitizer, a type-based-aliasing-violation
10// detector.
11//
12//===----------------------------------------------------------------------===//
13
16#include "llvm/ADT/SetVector.h"
18#include "llvm/ADT/Statistic.h"
22#include "llvm/IR/DataLayout.h"
23#include "llvm/IR/Function.h"
24#include "llvm/IR/IRBuilder.h"
28#include "llvm/IR/Intrinsics.h"
29#include "llvm/IR/LLVMContext.h"
30#include "llvm/IR/MDBuilder.h"
31#include "llvm/IR/Metadata.h"
32#include "llvm/IR/Module.h"
33#include "llvm/IR/Type.h"
35#include "llvm/Support/MD5.h"
36#include "llvm/Support/Regex.h"
40
41#include <cctype>
42
43using namespace llvm;
44
45#define DEBUG_TYPE "tysan"
46
47static const char *const kTysanModuleCtorName = "tysan.module_ctor";
48static const char *const kTysanInitName = "__tysan_init";
49static const char *const kTysanCheckName = "__tysan_check";
50static const char *const kTysanGVNamePrefix = "__tysan_v1_";
51
52static const char *const kTysanShadowMemoryAddress =
53 "__tysan_shadow_memory_address";
54static const char *const kTysanAppMemMask = "__tysan_app_memory_mask";
55
56STATISTIC(NumInstrumentedAccesses, "Number of instrumented accesses");
57
58namespace {
59
60/// TypeSanitizer: instrument the code in module to find type-based aliasing
61/// violations.
62struct TypeSanitizer {
63 TypeSanitizer(const InstrumentationOptions &Opts, Module &M);
64 bool sanitizeFunction(Function &F, const TargetLibraryInfo &TLI);
65 void instrumentGlobals(Module &M);
66
67 const InstrumentationOptions &Opts;
68 bool OutlineInstrumentation;
69
70private:
72 TypeDescriptorsMapTy;
74
75 void initializeCallbacks(Module &M);
76
77 Instruction *getShadowBase(Function &F);
78 Instruction *getAppMemMask(Function &F);
79
80 bool instrumentWithShadowUpdate(IRBuilder<> &IRB, const MDNode *TBAAMD,
81 Value *Ptr, uint64_t AccessSize, bool IsRead,
82 bool IsWrite, Value *ShadowBase,
83 Value *AppMemMask, bool ForceSetType,
84 bool SanitizeFunction,
85 TypeDescriptorsMapTy &TypeDescriptors,
86 const DataLayout &DL);
87
88 /// Memory-related intrinsics/instructions reset the type of the destination
89 /// memory (including allocas and byval arguments).
90 bool instrumentMemInst(Value *I, Instruction *ShadowBase,
91 Instruction *AppMemMask, const DataLayout &DL);
92
93 std::string getAnonymousStructIdentifier(const MDNode *MD,
94 TypeNameMapTy &TypeNames);
95 bool generateTypeDescriptor(const MDNode *MD,
96 TypeDescriptorsMapTy &TypeDescriptors,
97 TypeNameMapTy &TypeNames, Module &M);
98 bool generateBaseTypeDescriptor(const MDNode *MD,
99 TypeDescriptorsMapTy &TypeDescriptors,
100 TypeNameMapTy &TypeNames, Module &M);
101
102 const Triple TargetTriple;
103 Regex AnonNameRegex;
104 Type *IntptrTy;
105 uint64_t PtrShift;
106 IntegerType *OrdTy, *U64Ty;
107
108 /// Callbacks to run-time library are computed in initializeCallbacks.
109 FunctionCallee TysanCheck;
110 FunctionCallee TysanCtorFunction;
111
112 FunctionCallee TysanIntrumentMemInst;
113 FunctionCallee TysanInstrumentWithShadowUpdate;
114 FunctionCallee TysanSetShadowType;
115
116 /// Callback to set types for gloabls.
117 Function *TysanGlobalsSetTypeFunction;
118};
119} // namespace
120
121TypeSanitizer::TypeSanitizer(const InstrumentationOptions &Opts, Module &M)
122 : Opts(Opts), OutlineInstrumentation(Opts.tysan_outline_instrumentation),
123 TargetTriple(M.getTargetTriple()),
124 AnonNameRegex("^_ZTS.*N[1-9][0-9]*_GLOBAL__N") {
125 const DataLayout &DL = M.getDataLayout();
126 IntptrTy = DL.getIntPtrType(M.getContext());
127 PtrShift = countr_zero(IntptrTy->getPrimitiveSizeInBits() / 8);
128
129 TysanGlobalsSetTypeFunction = M.getFunction("__tysan_set_globals_types");
130 initializeCallbacks(M);
131}
132
133void TypeSanitizer::initializeCallbacks(Module &M) {
134 LLVMContext &C = M.getContext();
135 IRBuilder<> IRB(M);
136 OrdTy = IRB.getInt32Ty();
137 U64Ty = IRB.getInt64Ty();
138 Type *BoolType = IRB.getInt1Ty();
139
140 AttributeList Attr;
141 Attr = Attr.addFnAttribute(C, Attribute::NoUnwind);
142 Attribute::AttrKind SExtAttr =
143 TargetLibraryInfo::getExtAttrForI32Param(TargetTriple, /*Signed=*/true);
144 Attribute::AttrKind BoolExtAttr =
146
147 // Initialize the callbacks. TODO: use TLI/emitLibFunc() for these functions.
148 TysanCheck =
149 M.getOrInsertFunction(kTysanCheckName,
150 Attr.maybeAddParamAttribute(C, 1, SExtAttr)
151 .maybeAddParamAttribute(C, 3, SExtAttr),
152 IRB.getVoidTy(),
153 IRB.getPtrTy(), // Pointer to data to be read.
154 OrdTy, // Size of the data in bytes.
155 IRB.getPtrTy(), // Pointer to type descriptor.
156 OrdTy // Flags.
157 );
158
159 TysanCtorFunction =
160 M.getOrInsertFunction(kTysanModuleCtorName, Attr, IRB.getVoidTy());
161
162 TysanIntrumentMemInst = M.getOrInsertFunction(
163 "__tysan_instrument_mem_inst",
164 Attr.maybeAddParamAttribute(C, 3, BoolExtAttr), IRB.getVoidTy(),
165 IRB.getPtrTy(), // Pointer of data to be written to
166 IRB.getPtrTy(), // Pointer of data to write
167 U64Ty, // Size of the data in bytes
168 BoolType // Do we need to call memmove
169 );
170
171 TysanInstrumentWithShadowUpdate =
172 M.getOrInsertFunction("__tysan_instrument_with_shadow_update",
173 Attr.maybeAddParamAttribute(C, 2, BoolExtAttr)
174 .maybeAddParamAttribute(C, 4, SExtAttr),
175 IRB.getVoidTy(),
176 IRB.getPtrTy(), // Pointer to data to be read
177 IRB.getPtrTy(), // Pointer to type descriptor
178 BoolType, // Do we need to type check this
179 U64Ty, // Size of data we access in bytes
180 OrdTy // Flags
181 );
182
183 TysanSetShadowType = M.getOrInsertFunction(
184 "__tysan_set_shadow_type", Attr, IRB.getVoidTy(),
185 IRB.getPtrTy(), // Pointer of data to be written to
186 IRB.getPtrTy(), // Pointer to the new type descriptor
187 U64Ty // Size of data we access in bytes
188 );
189}
190
191void TypeSanitizer::instrumentGlobals(Module &M) {
192 TysanGlobalsSetTypeFunction = nullptr;
193
194 NamedMDNode *Globals = M.getNamedMetadata("llvm.tysan.globals");
195 if (!Globals)
196 return;
197
198 TysanGlobalsSetTypeFunction = Function::Create(
199 FunctionType::get(Type::getVoidTy(M.getContext()), false),
200 GlobalValue::InternalLinkage, "__tysan_set_globals_types", &M);
201 BasicBlock *BB =
202 BasicBlock::Create(M.getContext(), "", TysanGlobalsSetTypeFunction);
203 ReturnInst::Create(M.getContext(), BB);
204
205 const DataLayout &DL = M.getDataLayout();
206 Value *ShadowBase = getShadowBase(*TysanGlobalsSetTypeFunction);
207 Value *AppMemMask = getAppMemMask(*TysanGlobalsSetTypeFunction);
208 TypeDescriptorsMapTy TypeDescriptors;
209 TypeNameMapTy TypeNames;
210
211 for (const auto &GMD : Globals->operands()) {
212 auto *GV = mdconst::dyn_extract_or_null<GlobalVariable>(GMD->getOperand(0));
213 if (!GV)
214 continue;
215 const MDNode *TBAAMD = cast<MDNode>(GMD->getOperand(1));
216 if (!generateBaseTypeDescriptor(TBAAMD, TypeDescriptors, TypeNames, M))
217 continue;
218
219 IRBuilder<> IRB(
220 TysanGlobalsSetTypeFunction->getEntryBlock().getTerminator());
221 Type *AccessTy = GV->getValueType();
222 assert(AccessTy->isSized());
223 uint64_t AccessSize = DL.getTypeStoreSize(AccessTy);
224 instrumentWithShadowUpdate(IRB, TBAAMD, GV, AccessSize, false, false,
225 ShadowBase, AppMemMask, true, false,
226 TypeDescriptors, DL);
227 }
228
229 if (TysanGlobalsSetTypeFunction) {
230 IRBuilder<> IRB(cast<Function>(TysanCtorFunction.getCallee())
231 ->getEntryBlock()
232 .getTerminator());
233 IRB.CreateCall(TysanGlobalsSetTypeFunction, {});
234 }
235}
236
237static const char LUT[] = "0123456789abcdef";
238
239static std::string encodeName(StringRef Name) {
240 size_t Length = Name.size();
241 std::string Output = kTysanGVNamePrefix;
242 Output.reserve(Output.size() + 3 * Length);
243 for (size_t i = 0; i < Length; ++i) {
244 const unsigned char c = Name[i];
245 if (isalnum(c)) {
246 Output.push_back(c);
247 continue;
248 }
249
250 if (c == '_') {
251 Output.append("__");
252 continue;
253 }
254
255 Output.push_back('_');
256 Output.push_back(LUT[c >> 4]);
257 Output.push_back(LUT[c & 15]);
258 }
259
260 return Output;
261}
262
263std::string
264TypeSanitizer::getAnonymousStructIdentifier(const MDNode *MD,
265 TypeNameMapTy &TypeNames) {
266 MD5 Hash;
267
268 for (int i = 1, e = MD->getNumOperands(); i < e; i += 2) {
269 const MDNode *MemberNode = dyn_cast<MDNode>(MD->getOperand(i));
270 if (!MemberNode)
271 return "";
272
273 auto TNI = TypeNames.find(MemberNode);
274 std::string MemberName;
275 if (TNI != TypeNames.end()) {
276 MemberName = TNI->second;
277 } else {
278 if (MemberNode->getNumOperands() < 1)
279 return "";
280 MDString *MemberNameNode = dyn_cast<MDString>(MemberNode->getOperand(0));
281 if (!MemberNameNode)
282 return "";
283 MemberName = MemberNameNode->getString().str();
284 if (MemberName.empty())
285 MemberName = getAnonymousStructIdentifier(MemberNode, TypeNames);
286 if (MemberName.empty())
287 return "";
288 TypeNames[MemberNode] = MemberName;
289 }
290
291 Hash.update(MemberName);
292 Hash.update("\0");
293
295 mdconst::extract<ConstantInt>(MD->getOperand(i + 1))->getZExtValue();
296 Hash.update(utostr(Offset));
297 Hash.update("\0");
298 }
299
300 MD5::MD5Result HashResult;
301 Hash.final(HashResult);
302 return "__anonymous_" + std::string(HashResult.digest().str());
303}
304
305bool TypeSanitizer::generateBaseTypeDescriptor(
306 const MDNode *MD, TypeDescriptorsMapTy &TypeDescriptors,
307 TypeNameMapTy &TypeNames, Module &M) {
308 if (MD->getNumOperands() < 1)
309 return false;
310
311 MDString *NameNode = dyn_cast<MDString>(MD->getOperand(0));
312 if (!NameNode)
313 return false;
314
315 std::string Name = NameNode->getString().str();
316 if (Name.empty())
317 Name = getAnonymousStructIdentifier(MD, TypeNames);
318 if (Name.empty())
319 return false;
320 TypeNames[MD] = Name;
321 std::string EncodedName = encodeName(Name);
322
323 GlobalVariable *GV =
324 dyn_cast_or_null<GlobalVariable>(M.getNamedValue(EncodedName));
325 if (GV) {
326 TypeDescriptors[MD] = GV;
327 return true;
328 }
329
331 for (int i = 1, e = MD->getNumOperands(); i < e; i += 2) {
332 const MDNode *MemberNode = dyn_cast<MDNode>(MD->getOperand(i));
333 if (!MemberNode)
334 return false;
335
337 auto TDI = TypeDescriptors.find(MemberNode);
338 if (TDI != TypeDescriptors.end()) {
339 Member = TDI->second;
340 } else {
341 if (!generateBaseTypeDescriptor(MemberNode, TypeDescriptors, TypeNames,
342 M))
343 return false;
344
345 Member = TypeDescriptors[MemberNode];
346 }
347
349 if ((unsigned)i + 1 < MD->getNumOperands()) {
350 Offset =
351 mdconst::extract<ConstantInt>(MD->getOperand(i + 1))->getZExtValue();
352 } else {
353 assert(i == 1 && MD->getNumOperands() == 2 && "Malformed TBAA MD.");
354 // The third operand for a scalar tag is actually optional, its absence
355 // indicating an offset of zero.
356 Offset = 0;
357 }
358
359 Members.push_back(std::make_pair(Member, Offset));
360 }
361
362 // The descriptor for a scalar is:
363 // [2, member count, [type pointer, offset]..., name]
364
365 LLVMContext &C = MD->getContext();
366 Constant *NameData = ConstantDataArray::getString(C, NameNode->getString());
367 SmallVector<Type *> TDSubTys;
368 SmallVector<Constant *> TDSubData;
369
370 auto PushTDSub = [&](Constant *C) {
371 TDSubTys.push_back(C->getType());
372 TDSubData.push_back(C);
373 };
374
375 PushTDSub(ConstantInt::get(IntptrTy, 2));
376 PushTDSub(ConstantInt::get(IntptrTy, Members.size()));
377
378 // Types that are in an anonymous namespace are local to this module.
379 // FIXME: This should really be marked by the frontend in the metadata
380 // instead of having us guess this from the mangled name. Moreover, the regex
381 // here can pick up (unlikely) names in the non-reserved namespace (because
382 // it needs to search into the type to pick up cases where the type in the
383 // anonymous namespace is a template parameter, etc.).
384 bool ShouldBeComdat = !AnonNameRegex.match(NameNode->getString());
385 for (auto &Member : Members) {
386 PushTDSub(Member.first);
387 PushTDSub(ConstantInt::get(IntptrTy, Member.second));
388 }
389
390 PushTDSub(NameData);
391
392 StructType *TDTy = StructType::get(C, TDSubTys);
393 Constant *TD = ConstantStruct::get(TDTy, TDSubData);
394
395 GlobalVariable *TDGV =
396 new GlobalVariable(TDTy, true,
397 !ShouldBeComdat ? GlobalValue::InternalLinkage
399 TD, EncodedName);
400 M.insertGlobalVariable(TDGV);
401
402 if (ShouldBeComdat) {
403 if (TargetTriple.isOSBinFormatELF()) {
404 Comdat *TDComdat = M.getOrInsertComdat(EncodedName);
405 TDGV->setComdat(TDComdat);
406 }
407 appendToUsed(M, TDGV);
408 }
409
410 TypeDescriptors[MD] = TDGV;
411 return true;
412}
413
414bool TypeSanitizer::generateTypeDescriptor(
415 const MDNode *MD, TypeDescriptorsMapTy &TypeDescriptors,
416 TypeNameMapTy &TypeNames, Module &M) {
417 // Here we need to generate a type descriptor corresponding to this TBAA
418 // metadata node. Under the current scheme there are three kinds of TBAA
419 // metadata nodes: scalar nodes, struct nodes, and struct tag nodes.
420
421 if (MD->getNumOperands() < 3)
422 return false;
423
424 const MDNode *BaseNode = dyn_cast<MDNode>(MD->getOperand(0));
425 if (!BaseNode)
426 return false;
427
428 // This is a struct tag (element-access) node.
429
430 const MDNode *AccessNode = dyn_cast<MDNode>(MD->getOperand(1));
431 if (!AccessNode)
432 return false;
433
434 Constant *Base;
435 auto TDI = TypeDescriptors.find(BaseNode);
436 if (TDI != TypeDescriptors.end()) {
437 Base = TDI->second;
438 } else {
439 if (!generateBaseTypeDescriptor(BaseNode, TypeDescriptors, TypeNames, M))
440 return false;
441
442 Base = TypeDescriptors[BaseNode];
443 }
444
446 TDI = TypeDescriptors.find(AccessNode);
447 if (TDI != TypeDescriptors.end()) {
448 Access = TDI->second;
449 } else {
450 if (!generateBaseTypeDescriptor(AccessNode, TypeDescriptors, TypeNames, M))
451 return false;
452
453 Access = TypeDescriptors[AccessNode];
454 }
455
457 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
458 std::string EncodedName =
459 std::string(Base->getName()) + "_o_" + utostr(Offset);
460
461 GlobalVariable *GV =
462 dyn_cast_or_null<GlobalVariable>(M.getNamedValue(EncodedName));
463 if (GV) {
464 TypeDescriptors[MD] = GV;
465 return true;
466 }
467
468 // The descriptor for a scalar is:
469 // [1, base-type pointer, access-type pointer, offset]
470
471 StructType *TDTy =
472 StructType::get(IntptrTy, Base->getType(), Access->getType(), IntptrTy);
473 Constant *TD =
474 ConstantStruct::get(TDTy, ConstantInt::get(IntptrTy, 1), Base, Access,
475 ConstantInt::get(IntptrTy, Offset));
476
477 bool ShouldBeComdat = cast<GlobalVariable>(Base)->getLinkage() ==
479
480 GlobalVariable *TDGV =
481 new GlobalVariable(TDTy, true,
482 !ShouldBeComdat ? GlobalValue::InternalLinkage
484 TD, EncodedName);
485 M.insertGlobalVariable(TDGV);
486
487 if (ShouldBeComdat) {
488 if (TargetTriple.isOSBinFormatELF()) {
489 Comdat *TDComdat = M.getOrInsertComdat(EncodedName);
490 TDGV->setComdat(TDComdat);
491 }
492 appendToUsed(M, TDGV);
493 }
494
495 TypeDescriptors[MD] = TDGV;
496 return true;
497}
498
499Instruction *TypeSanitizer::getShadowBase(Function &F) {
500 IRBuilder<> IRB(&F.front().front());
501 Constant *GlobalShadowAddress =
502 F.getParent()->getOrInsertGlobal(kTysanShadowMemoryAddress, IntptrTy);
503 return IRB.CreateLoad(IntptrTy, GlobalShadowAddress, "shadow.base");
504}
505
506Instruction *TypeSanitizer::getAppMemMask(Function &F) {
507 IRBuilder<> IRB(&F.front().front());
508 Value *GlobalAppMemMask =
509 F.getParent()->getOrInsertGlobal(kTysanAppMemMask, IntptrTy);
510 return IRB.CreateLoad(IntptrTy, GlobalAppMemMask, "app.mem.mask");
511}
512
513/// Collect all loads and stores, and for what TBAA nodes we need to generate
514/// type descriptors.
516 Function &F, const TargetLibraryInfo &TLI,
517 SmallVectorImpl<std::pair<Instruction *, MemoryLocation>> &MemoryAccesses,
519 SmallVectorImpl<Value *> &MemTypeResetInsts) {
520 // Traverse all instructions, collect loads/stores/returns, check for calls.
521 for (Instruction &Inst : instructions(F)) {
522 // Skip memory accesses inserted by another instrumentation.
523 if (Inst.getMetadata(LLVMContext::MD_nosanitize))
524 continue;
525
526 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst) ||
529
530 // Swift errors are special (we can't introduce extra uses on them).
531 if (MLoc.Ptr->isSwiftError())
532 continue;
533
534 // Skip non-address-space-0 pointers; we don't know how to handle them.
535 Type *PtrTy = cast<PointerType>(MLoc.Ptr->getType());
536 if (PtrTy->getPointerAddressSpace() != 0)
537 continue;
538
539 if (MLoc.AATags.TBAA)
540 TBAAMetadata.insert(MLoc.AATags.TBAA);
541 MemoryAccesses.push_back(std::make_pair(&Inst, MLoc));
542 } else if (isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) {
543 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
545
547 MemTypeResetInsts.push_back(&Inst);
548 } else if (isa<AllocaInst>(Inst)) {
549 MemTypeResetInsts.push_back(&Inst);
550 }
551 }
552}
553
554bool TypeSanitizer::sanitizeFunction(Function &F,
555 const TargetLibraryInfo &TLI) {
556 if (F.isDeclaration())
557 return false;
558 if (F.hasFnAttribute(Attribute::DisableSanitizerInstrumentation))
559 return false;
560 // This is required to prevent instrumenting call to __tysan_init from within
561 // the module constructor.
562 if (&F == TysanCtorFunction.getCallee() || &F == TysanGlobalsSetTypeFunction)
563 return false;
564 initializeCallbacks(*F.getParent());
565
566 // We need to collect all loads and stores, and know for what TBAA nodes we
567 // need to generate type descriptors.
569 SmallSetVector<const MDNode *, 8> TBAAMetadata;
570 SmallVector<Value *> MemTypeResetInsts;
571 collectMemAccessInfo(F, TLI, MemoryAccesses, TBAAMetadata, MemTypeResetInsts);
572
573 // byval arguments also need their types reset (they're new stack memory,
574 // just like allocas).
575 for (auto &A : F.args())
576 if (A.hasByValAttr())
577 MemTypeResetInsts.push_back(&A);
578
579 Module &M = *F.getParent();
580 TypeDescriptorsMapTy TypeDescriptors;
581 TypeNameMapTy TypeNames;
582 bool Res = false;
583 for (const MDNode *MD : TBAAMetadata) {
584 if (TypeDescriptors.count(MD))
585 continue;
586
587 if (!generateTypeDescriptor(MD, TypeDescriptors, TypeNames, M))
588 return Res; // Giving up.
589
590 Res = true;
591 }
592
593 const DataLayout &DL = F.getDataLayout();
594 bool SanitizeFunction = F.hasFnAttribute(Attribute::SanitizeType);
595 bool NeedsInstrumentation =
596 MemTypeResetInsts.empty() && MemoryAccesses.empty();
597 Instruction *ShadowBase = NeedsInstrumentation ? nullptr : getShadowBase(F);
598 Instruction *AppMemMask = NeedsInstrumentation ? nullptr : getAppMemMask(F);
599 for (const auto &[I, MLoc] : MemoryAccesses) {
600 IRBuilder<> IRB(I);
601 assert(MLoc.Size.isPrecise());
602 if (instrumentWithShadowUpdate(
603 IRB, MLoc.AATags.TBAA, const_cast<Value *>(MLoc.Ptr),
604 MLoc.Size.getValue(), I->mayReadFromMemory(), I->mayWriteToMemory(),
605 ShadowBase, AppMemMask, false, SanitizeFunction, TypeDescriptors,
606 DL)) {
607 ++NumInstrumentedAccesses;
608 Res = true;
609 }
610 }
611
612 for (auto Inst : MemTypeResetInsts)
613 Res |= instrumentMemInst(Inst, ShadowBase, AppMemMask, DL);
614
615 return Res;
616}
617
619 Type *IntptrTy, uint64_t PtrShift,
620 Value *ShadowBase, Value *AppMemMask) {
621 return IRB.CreateAdd(
622 IRB.CreateShl(
623 IRB.CreateAnd(IRB.CreatePtrToInt(Ptr, IntptrTy, "app.ptr.int"),
624 AppMemMask, "app.ptr.masked"),
625 PtrShift, "app.ptr.shifted"),
626 ShadowBase, "shadow.ptr.int");
627}
628
629bool TypeSanitizer::instrumentWithShadowUpdate(
630 IRBuilder<> &IRB, const MDNode *TBAAMD, Value *Ptr, uint64_t AccessSize,
631 bool IsRead, bool IsWrite, Value *ShadowBase, Value *AppMemMask,
632 bool ForceSetType, bool SanitizeFunction,
633 TypeDescriptorsMapTy &TypeDescriptors, const DataLayout &DL) {
634 Constant *TDGV;
635 if (TBAAMD)
636 TDGV = TypeDescriptors[TBAAMD];
637 else
638 TDGV = Constant::getNullValue(IRB.getPtrTy());
639
640 Value *TD = IRB.CreateBitCast(TDGV, IRB.getPtrTy());
641
642 if (OutlineInstrumentation) {
643 if (!ForceSetType && (!Opts.tysan_writes_always_set_type || IsRead)) {
644 // We need to check the type here. If the type is unknown, then the read
645 // sets the type. If the type is known, then it is checked. If the type
646 // doesn't match, then we call the runtime type check (which may yet
647 // determine that the mismatch is okay).
648
649 Constant *Flags =
650 ConstantInt::get(OrdTy, (int)IsRead | (((int)IsWrite) << 1));
651
652 IRB.CreateCall(TysanInstrumentWithShadowUpdate,
653 {Ptr, TD,
654 SanitizeFunction ? IRB.getTrue() : IRB.getFalse(),
655 IRB.getInt64(AccessSize), Flags});
656 } else if (ForceSetType || IsWrite) {
657 // In the mode where writes always set the type, for a write (which does
658 // not also read), we just set the type.
659 IRB.CreateCall(TysanSetShadowType, {Ptr, TD, IRB.getInt64(AccessSize)});
660 }
661
662 return true;
663 }
664
665 Value *ShadowDataInt = convertToShadowDataInt(IRB, Ptr, IntptrTy, PtrShift,
666 ShadowBase, AppMemMask);
667 Type *Int8PtrPtrTy = PointerType::get(IRB.getContext(), 0);
668 Value *ShadowData =
669 IRB.CreateIntToPtr(ShadowDataInt, Int8PtrPtrTy, "shadow.ptr");
670
671 auto SetType = [&]() {
672 IRB.CreateStore(TD, ShadowData);
673
674 // Now fill the remainder of the shadow memory corresponding to the
675 // remainder of the the bytes of the type with a bad type descriptor.
676 for (uint64_t i = 1; i < AccessSize; ++i) {
677 Value *BadShadowData = IRB.CreateIntToPtr(
678 IRB.CreateAdd(ShadowDataInt,
679 ConstantInt::get(IntptrTy, i << PtrShift),
680 "shadow.byte." + Twine(i) + ".offset"),
681 Int8PtrPtrTy, "shadow.byte." + Twine(i) + ".ptr");
682
683 // This is the TD value, -i, which is used to indicate that the byte is
684 // i bytes after the first byte of the type.
685 Value *BadTD =
686 IRB.CreateIntToPtr(ConstantInt::getSigned(IntptrTy, -i),
687 IRB.getPtrTy(), "bad.descriptor" + Twine(i));
688 IRB.CreateStore(BadTD, BadShadowData);
689 }
690 };
691
692 if (ForceSetType || (Opts.tysan_writes_always_set_type && IsWrite)) {
693 // In the mode where writes always set the type, for a write (which does
694 // not also read), we just set the type.
695 SetType();
696 return true;
697 }
698
699 assert((!Opts.tysan_writes_always_set_type || IsRead) &&
700 "should have handled case above");
701 LLVMContext &C = IRB.getContext();
702 MDNode *UnlikelyBW = MDBuilder(C).createBranchWeights(1, 100000);
703
704 if (!SanitizeFunction) {
705 // If we're not sanitizing this function, then we only care whether we
706 // need to *set* the type.
707 Value *LoadedTD = IRB.CreateLoad(IRB.getPtrTy(), ShadowData, "shadow.desc");
708 Value *NullTDCmp = IRB.CreateIsNull(LoadedTD, "desc.set");
710 NullTDCmp, &*IRB.GetInsertPoint(), false, UnlikelyBW);
711 IRB.SetInsertPoint(NullTDTerm);
712 NullTDTerm->getParent()->setName("set.type");
713 SetType();
714 return true;
715 }
716 // We need to check the type here. If the type is unknown, then the read
717 // sets the type. If the type is known, then it is checked. If the type
718 // doesn't match, then we call the runtime (which may yet determine that
719 // the mismatch is okay).
720 //
721 // The checks generated below have the following structure.
722 //
723 // ; First we load the descriptor for the load from shadow memory and
724 // ; compare it against the type descriptor for the current access type.
725 // %shadow.desc = load ptr %shadow.data
726 // %bad.desc = icmp ne %shadow.desc, %td
727 // br %bad.desc, %bad.bb, %good.bb
728 //
729 // bad.bb:
730 // %shadow.desc.null = icmp eq %shadow.desc, null
731 // br %shadow.desc.null, %null.td.bb, %good.td.bb
732 //
733 // null.td.bb:
734 // ; The typ is unknown, set it if all bytes in the value are also unknown.
735 // ; To check, we load the shadow data for all bytes of the access. For the
736 // ; pseudo code below, assume an access of size 1.
737 // %shadow.data.int = add %shadow.data.int, 0
738 // %l = load (inttoptr %shadow.data.int)
739 // %is.not.null = icmp ne %l, null
740 // %not.all.unknown = %is.not.null
741 // br %no.all.unknown, before.set.type.bb
742 //
743 // before.set.type.bb:
744 // ; Call runtime to check mismatch.
745 // call void @__tysan_check()
746 // br %set.type.bb
747 //
748 // set.type.bb:
749 // ; Now fill the remainder of the shadow memory corresponding to the
750 // ; remainder of the the bytes of the type with a bad type descriptor.
751 // store %TD, %shadow.data
752 // br %continue.bb
753 //
754 // good.td.bb::
755 // ; We have a non-trivial mismatch. Call the runtime.
756 // call void @__tysan_check()
757 // br %continue.bb
758 //
759 // good.bb:
760 // ; We appear to have the right type. Make sure that all other bytes in
761 // ; the type are still marked as interior bytes. If not, call the runtime.
762 // %shadow.data.int = add %shadow.data.int, 0
763 // %l = load (inttoptr %shadow.data.int)
764 // %not.all.interior = icmp sge %l, 0
765 // br %not.all.interior, label %check.rt.bb, label %continue.bb
766 //
767 // check.rt.bb:
768 // call void @__tysan_check()
769 // br %continue.bb
770
771 Constant *Flags = ConstantInt::get(OrdTy, int(IsRead) | (int(IsWrite) << 1));
772
773 Value *LoadedTD = IRB.CreateLoad(IRB.getPtrTy(), ShadowData, "shadow.desc");
774 Value *BadTDCmp = IRB.CreateICmpNE(LoadedTD, TD, "bad.desc");
775 Instruction *BadTDTerm, *GoodTDTerm;
776 SplitBlockAndInsertIfThenElse(BadTDCmp, &*IRB.GetInsertPoint(), &BadTDTerm,
777 &GoodTDTerm, UnlikelyBW);
778 IRB.SetInsertPoint(BadTDTerm);
779
780 // We now know that the types did not match (we're on the slow path). If
781 // the type is unknown, then set it.
782 Value *NullTDCmp = IRB.CreateIsNull(LoadedTD);
783 Instruction *NullTDTerm, *MismatchTerm;
784 SplitBlockAndInsertIfThenElse(NullTDCmp, &*IRB.GetInsertPoint(), &NullTDTerm,
785 &MismatchTerm);
786
787 // If the type is unknown, then set the type.
788 IRB.SetInsertPoint(NullTDTerm);
789
790 // We're about to set the type. Make sure that all bytes in the value are
791 // also of unknown type.
792 Value *Size = ConstantInt::get(OrdTy, AccessSize);
793 Value *NotAllUnkTD = IRB.getFalse();
794 for (uint64_t i = 1; i < AccessSize; ++i) {
795 Value *UnkShadowData = IRB.CreateIntToPtr(
796 IRB.CreateAdd(ShadowDataInt, ConstantInt::get(IntptrTy, i << PtrShift)),
797 Int8PtrPtrTy);
798 Value *ILdTD = IRB.CreateLoad(IRB.getPtrTy(), UnkShadowData);
799 NotAllUnkTD = IRB.CreateOr(NotAllUnkTD, IRB.CreateIsNotNull(ILdTD));
800 }
801
802 Instruction *BeforeSetType = &*IRB.GetInsertPoint();
803 Instruction *BadUTDTerm =
804 SplitBlockAndInsertIfThen(NotAllUnkTD, BeforeSetType, false, UnlikelyBW);
805 IRB.SetInsertPoint(BadUTDTerm);
806 IRB.CreateCall(TysanCheck, {IRB.CreateBitCast(Ptr, IRB.getPtrTy()), Size,
807 (Value *)TD, (Value *)Flags});
808
809 IRB.SetInsertPoint(BeforeSetType);
810 SetType();
811
812 // We have a non-trivial mismatch. Call the runtime.
813 IRB.SetInsertPoint(MismatchTerm);
814 IRB.CreateCall(TysanCheck, {IRB.CreateBitCast(Ptr, IRB.getPtrTy()), Size,
815 (Value *)TD, (Value *)Flags});
816
817 // We appear to have the right type. Make sure that all other bytes in
818 // the type are still marked as interior bytes. If not, call the runtime.
819 IRB.SetInsertPoint(GoodTDTerm);
820 Value *NotAllBadTD = IRB.getFalse();
821 for (uint64_t i = 1; i < AccessSize; ++i) {
822 Value *BadShadowData = IRB.CreateIntToPtr(
823 IRB.CreateAdd(ShadowDataInt, ConstantInt::get(IntptrTy, i << PtrShift)),
824 Int8PtrPtrTy);
825 Value *ILdTD = IRB.CreatePtrToInt(
826 IRB.CreateLoad(IRB.getPtrTy(), BadShadowData), IntptrTy);
827 NotAllBadTD = IRB.CreateOr(
828 NotAllBadTD, IRB.CreateICmpSGE(ILdTD, ConstantInt::get(IntptrTy, 0)));
829 }
830
832 NotAllBadTD, &*IRB.GetInsertPoint(), false, UnlikelyBW);
833 IRB.SetInsertPoint(BadITDTerm);
834 IRB.CreateCall(TysanCheck, {IRB.CreateBitCast(Ptr, IRB.getPtrTy()), Size,
835 (Value *)TD, (Value *)Flags});
836 return true;
837}
838
839bool TypeSanitizer::instrumentMemInst(Value *V, Instruction *ShadowBase,
840 Instruction *AppMemMask,
841 const DataLayout &DL) {
843 BasicBlock *BB;
844 Function *F;
845
846 if (auto *I = dyn_cast<Instruction>(V)) {
848 BB = I->getParent();
849 F = BB->getParent();
850 } else {
851 auto *A = cast<Argument>(V);
852 F = A->getParent();
853 BB = &F->getEntryBlock();
854 IP = BB->getFirstInsertionPt();
855
856 // Find the next insert point after both ShadowBase and AppMemMask.
857 if (IP->comesBefore(ShadowBase))
858 IP = ShadowBase->getNextNode()->getIterator();
859 if (IP->comesBefore(AppMemMask))
860 IP = AppMemMask->getNextNode()->getIterator();
861 }
862
863 Value *Dest, *Size, *Src = nullptr;
864 bool NeedsMemMove = false;
865 IRBuilder<> IRB(IP);
866
867 if (auto *A = dyn_cast<Argument>(V)) {
868 assert(A->hasByValAttr() && "Type reset for non-byval argument?");
869
870 Dest = A;
871 Size =
872 ConstantInt::get(IntptrTy, DL.getTypeAllocSize(A->getParamByValType()));
873 } else {
874 auto *I = cast<Instruction>(V);
875 if (auto *MI = dyn_cast<MemIntrinsic>(I)) {
876 if (MI->getDestAddressSpace() != 0)
877 return false;
878
879 Dest = MI->getDest();
880 Size = MI->getLength();
881
882 if (auto *MTI = dyn_cast<MemTransferInst>(MI)) {
883 if (MTI->getSourceAddressSpace() == 0) {
884 Src = MTI->getSource();
885 NeedsMemMove = isa<MemMoveInst>(MTI);
886 }
887 }
888 } else if (auto *II = dyn_cast<LifetimeIntrinsic>(I)) {
889 auto *AI = dyn_cast<AllocaInst>(II->getArgOperand(0));
890 if (!AI)
891 return false;
892
893 Size = IRB.CreateAllocationSize(IntptrTy, AI);
894 Dest = II->getArgOperand(0);
895 } else if (auto *AI = dyn_cast<AllocaInst>(I)) {
896 // We need to clear the types for new stack allocations (or else we might
897 // read stale type information from a previous function execution).
898
899 IRB.SetInsertPoint(&*std::next(BasicBlock::iterator(I)));
901
902 Size = IRB.CreateAllocationSize(IntptrTy, AI);
903 Dest = I;
904 } else {
905 return false;
906 }
907 }
908
909 if (OutlineInstrumentation) {
910 if (!Src)
912
913 // The runtime function expects a uint64_t size parameter. On 32-bit
914 // targets, Size may be IntptrTy (i32), so extend it to match.
915 Value *Size64 = IRB.CreateZExtOrTrunc(Size, U64Ty);
916 IRB.CreateCall(
917 TysanIntrumentMemInst,
918 {Dest, Src, Size64, NeedsMemMove ? IRB.getTrue() : IRB.getFalse()});
919 return true;
920 } else {
921 if (!ShadowBase)
922 ShadowBase = getShadowBase(*F);
923 if (!AppMemMask)
924 AppMemMask = getAppMemMask(*F);
925
926 Value *ShadowDataInt = IRB.CreateAdd(
927 IRB.CreateShl(
928 IRB.CreateAnd(IRB.CreatePtrToInt(Dest, IntptrTy), AppMemMask),
929 PtrShift),
930 ShadowBase);
931 Value *ShadowData = IRB.CreateIntToPtr(ShadowDataInt, IRB.getPtrTy());
932
933 if (!Src) {
934 IRB.CreateMemSet(ShadowData, IRB.getInt8(0),
935 IRB.CreateShl(Size, PtrShift),
936 Align::fromLog2(PtrShift));
937 return true;
938 }
939
940 Value *SrcShadowDataInt = IRB.CreateAdd(
941 IRB.CreateShl(
942 IRB.CreateAnd(IRB.CreatePtrToInt(Src, IntptrTy), AppMemMask),
943 PtrShift),
944 ShadowBase);
945 Value *SrcShadowData = IRB.CreateIntToPtr(SrcShadowDataInt, IRB.getPtrTy());
946
947 if (NeedsMemMove) {
948 IRB.CreateMemMove(ShadowData, Align::fromLog2(PtrShift), SrcShadowData,
949 Align::fromLog2(PtrShift),
950 IRB.CreateShl(Size, PtrShift));
951 } else {
952 IRB.CreateMemCpy(ShadowData, Align::fromLog2(PtrShift), SrcShadowData,
953 Align::fromLog2(PtrShift),
954 IRB.CreateShl(Size, PtrShift));
955 }
956 }
957
958 return true;
959}
960
963 Function *TysanCtorFunction;
964 std::tie(TysanCtorFunction, std::ignore) =
966 kTysanInitName, /*InitArgTypes=*/{},
967 /*InitArgs=*/{});
968
969 const InstrumentationOptions &Opts =
970 M.getContext().getLibraryOptions().get<InstrumentationOptions>();
971 TypeSanitizer TySan(Opts, M);
972 TySan.instrumentGlobals(M);
973 appendToGlobalCtors(M, TysanCtorFunction, 0);
974
975 auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
976 for (Function &F : M) {
977 const TargetLibraryInfo &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
978 TySan.sanitizeFunction(F, TLI);
979 if (Opts.tysan_verify_outlined_instrumentation &&
980 Opts.tysan_outline_instrumentation) {
981 // Outlined instrumentation is a new option, and so this exists to
982 // verify there is no difference in behaviour between the options.
983 // If the outlined instrumentation triggers a verification failure
984 // when the original inlined instrumentation does not, or vice versa,
985 // then there is a discrepency which should be investigated.
986 TySan.OutlineInstrumentation = false;
987 TySan.sanitizeFunction(F, TLI);
988 TySan.OutlineInstrumentation = true;
989 }
990 }
991
993}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
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")
DXIL Resource Access
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
This file provides utility analysis objects describing memory locations.
This file contains the declarations for metadata subclasses.
uint64_t IntrinsicInst * II
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
This file implements a set that has insertion order iteration characteristics.
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 STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
This file contains some functions that are useful when dealing with strings.
static const char *const kTysanInitName
static Value * convertToShadowDataInt(IRBuilder<> &IRB, Value *Ptr, Type *IntptrTy, uint64_t PtrShift, Value *ShadowBase, Value *AppMemMask)
static const char *const kTysanShadowMemoryAddress
static const char LUT[]
static const char *const kTysanGVNamePrefix
static const char *const kTysanModuleCtorName
static const char *const kTysanAppMemMask
void collectMemAccessInfo(Function &F, const TargetLibraryInfo &TLI, SmallVectorImpl< std::pair< Instruction *, MemoryLocation > > &MemoryAccesses, SmallSetVector< const MDNode *, 8 > &TBAAMetadata, SmallVectorImpl< Value * > &MemTypeResetInsts)
Collect all loads and stores, and for what TBAA nodes we need to generate type descriptors.
static const char *const kTysanCheckName
static std::string encodeName(StringRef Name)
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
This class represents a function call, abstracting a target machine's calling convention.
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true, bool ByteString=false)
This method constructs a CDS and initializes it with a text string.
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
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
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:169
const BasicBlock & getEntryBlock() const
Definition Function.h:794
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:287
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:56
LLVM_ABI Value * CreateAllocationSize(Type *DestTy, AllocaInst *AI)
Get allocation size of an alloca as a runtime Value* (handles both static and dynamic allocas and vsc...
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
CallInst * CreateMemCpy(Value *Dst, MaybeAlign DstAlign, Value *Src, MaybeAlign SrcAlign, uint64_t Size, bool isVolatile=false, const AAMDNodes &AAInfo=AAMDNodes())
Create and insert a memcpy between the specified pointers.
Definition IRBuilder.h:651
ConstantInt * getTrue()
Get the constant value for i1 true.
Definition IRBuilder.h:445
Value * CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2410
BasicBlock::iterator GetInsertPoint() const
Definition IRBuilder.h:176
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2238
ConstantInt * getInt8(uint8_t C)
Get a constant 8-bit value.
Definition IRBuilder.h:455
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2386
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
Definition IRBuilder.h:470
CallInst * CreateMemMove(Value *Dst, MaybeAlign DstAlign, Value *Src, MaybeAlign SrcAlign, uint64_t Size, bool isVolatile=false, const AAMDNodes &AAInfo=AAMDNodes())
Definition IRBuilder.h:693
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2243
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
CallInst * CreateMemSet(Value *Ptr, Value *Val, uint64_t Size, MaybeAlign Align, bool isVolatile=false, const AAMDNodes &AAInfo=AAMDNodes())
Create and insert a memset to the specified pointer and the specified value.
Definition IRBuilder.h:596
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 * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1418
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2233
ConstantInt * getFalse()
Get the constant value for i1 false.
Definition IRBuilder.h:450
Value * CreateIsNotNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg != 0.
Definition IRBuilder.h:2763
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 * CreateIsNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg == 0.
Definition IRBuilder.h:2758
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:196
LLVM_ABI void SetInstDebugLocation(Instruction *I) const
If this builder has a current debug location, set it on the specified instruction.
Definition IRBuilder.cpp:67
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1588
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2909
Class to represent integer types.
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Updates the hash for the byte stream provided.
Definition MD5.cpp:188
LLVM_ABI void final(MD5Result &Result)
Finishes off the hash and puts the result in result.
Definition MD5.cpp:233
Metadata node.
Definition Metadata.h:1081
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1443
LLVMContext & getContext() const
Definition Metadata.h:1245
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:615
Representation for a specific memory location.
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
AAMDNodes AATags
The metadata nodes which describes the aliasing of the location (each member is null if that kind of ...
const Value * Ptr
The address of the start of the location.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
iterator_range< op_iterator > operands()
Definition Metadata.h:1893
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
LLVM_ABI bool match(StringRef String, SmallVectorImpl< StringRef > *Matches=nullptr, std::string *Error=nullptr) const
matches - Match the regex against a given String.
Definition Regex.cpp:84
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
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:345
StringRef str() const
Explicit conversion to StringRef.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:467
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
static Attribute::AttrKind getExtAttrForBoolParam(const Triple &T)
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
bool isOSBinFormatELF() const
Tests whether the OS uses the ELF binary format.
Definition Triple.h:867
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:300
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSized() const
Return true if it makes sense to take the size of this type.
Definition Type.h:321
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI bool isSwiftError() const
Return true if this value is a swifterror value.
Definition Value.cpp:1162
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract_or_null(Y &&MD)
Extract a Value from Metadata, if any, allowing null.
Definition Metadata.h:720
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:679
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
@ Length
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
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
std::string utostr(uint64_t X, bool isNeg=false)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI std::pair< Function *, FunctionCallee > createSanitizerCtorAndInitFunctions(Module &M, StringRef CtorName, StringRef InitName, ArrayRef< Type * > InitArgTypes, ArrayRef< Value * > InitArgs, StringRef VersionCheckName=StringRef(), bool Weak=false)
Creates sanitizer constructor function, and calls sanitizer's init function from it.
LLVM_ABI void SplitBlockAndInsertIfThenElse(Value *Cond, BasicBlock::iterator SplitBefore, Instruction **ThenTerm, Instruction **ElseTerm, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr)
SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen, but also creates the ElseBlock...
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
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
LLVM_ABI void appendToGlobalCtors(Module &M, Function *F, int Priority, Constant *Data=nullptr)
Append F to the list of global ctors of module M with the given Priority.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
LLVM_ABI void maybeMarkSanitizerLibraryCallNoBuiltin(CallInst *CI, const TargetLibraryInfo *TLI)
Given a CallInst, check if it calls a string function known to CodeGen, and mark it with NoBuiltin if...
Definition Local.cpp:3900
LLVM_ABI void appendToUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.used list.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
MDNode * TBAA
The tag for type-based alias analysis.
Definition Metadata.h:791
static constexpr Align fromLog2(unsigned Log2Value)
Returns an alignment of 1 << Log2Value bytes.
Definition Alignment.h:73
LLVM_ABI SmallString< 32 > digest() const
Definition MD5.cpp:280
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)