LLVM 24.0.0git
NumericalStabilitySanitizer.cpp
Go to the documentation of this file.
1//===-- NumericalStabilitySanitizer.cpp -----------------------------------===//
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 contains the instrumentation pass for the numerical sanitizer.
10// Conceptually the pass injects shadow computations using higher precision
11// types and inserts consistency checks. For details see the paper
12// https://arxiv.org/abs/2102.12782.
13//
14//===----------------------------------------------------------------------===//
15
18
19#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/Statistic.h"
25#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/Function.h"
27#include "llvm/IR/IRBuilder.h"
29#include "llvm/IR/Intrinsics.h"
30#include "llvm/IR/LLVMContext.h"
31#include "llvm/IR/MDBuilder.h"
32#include "llvm/IR/Metadata.h"
33#include "llvm/IR/Module.h"
34#include "llvm/IR/Type.h"
35#include "llvm/Support/Debug.h"
36#include "llvm/Support/Regex.h"
42
43#include <cstdint>
44
45using namespace llvm;
46
47#define DEBUG_TYPE "nsan"
48
49STATISTIC(NumInstrumentedFTLoads,
50 "Number of instrumented floating-point loads");
51
52STATISTIC(NumInstrumentedFTCalls,
53 "Number of instrumented floating-point calls");
54STATISTIC(NumInstrumentedFTRets,
55 "Number of instrumented floating-point returns");
56STATISTIC(NumInstrumentedFTStores,
57 "Number of instrumented floating-point stores");
58STATISTIC(NumInstrumentedNonFTStores,
59 "Number of instrumented non floating-point stores");
61 NumInstrumentedNonFTMemcpyStores,
62 "Number of instrumented non floating-point stores with memcpy semantics");
63STATISTIC(NumInstrumentedFCmp, "Number of instrumented fcmps");
64
65constexpr StringLiteral kNsanModuleCtorName("nsan.module_ctor");
66constexpr StringLiteral kNsanInitName("__nsan_init");
67
68// The following values must be kept in sync with the runtime.
69constexpr int kShadowScale = 2;
70constexpr int kMaxVectorWidth = 8;
71constexpr int kMaxNumArgs = 128;
72constexpr int kMaxShadowTypeSizeBytes = 16; // fp128
73
74namespace {
75
76// Defines the characteristics (type id, type, and floating-point semantics)
77// attached for all possible shadow types.
78class ShadowTypeConfig {
79public:
80 static std::unique_ptr<ShadowTypeConfig> fromNsanTypeId(char TypeId);
81
82 // The LLVM Type corresponding to the shadow type.
83 virtual Type *getType(LLVMContext &Context) const = 0;
84
85 // The nsan type id of the shadow type (`d`, `l`, `q`, ...).
86 virtual char getNsanTypeId() const = 0;
87
88 virtual ~ShadowTypeConfig() = default;
89};
90
91template <char NsanTypeId>
92class ShadowTypeConfigImpl : public ShadowTypeConfig {
93public:
94 char getNsanTypeId() const override { return NsanTypeId; }
95 static constexpr char kNsanTypeId = NsanTypeId;
96};
97
98// `double` (`d`) shadow type.
99class F64ShadowConfig : public ShadowTypeConfigImpl<'d'> {
100 Type *getType(LLVMContext &Context) const override {
101 return Type::getDoubleTy(Context);
102 }
103};
104
105// `x86_fp80` (`l`) shadow type: X86 long double.
106class F80ShadowConfig : public ShadowTypeConfigImpl<'l'> {
107 Type *getType(LLVMContext &Context) const override {
108 return Type::getX86_FP80Ty(Context);
109 }
110};
111
112// `fp128` (`q`) shadow type.
113class F128ShadowConfig : public ShadowTypeConfigImpl<'q'> {
114 Type *getType(LLVMContext &Context) const override {
115 return Type::getFP128Ty(Context);
116 }
117};
118
119// `ppc_fp128` (`e`) shadow type: IBM extended double with 106 bits of mantissa.
120class PPC128ShadowConfig : public ShadowTypeConfigImpl<'e'> {
121 Type *getType(LLVMContext &Context) const override {
122 return Type::getPPC_FP128Ty(Context);
123 }
124};
125
126// Creates a ShadowTypeConfig given its type id.
127std::unique_ptr<ShadowTypeConfig>
128ShadowTypeConfig::fromNsanTypeId(const char TypeId) {
129 switch (TypeId) {
130 case F64ShadowConfig::kNsanTypeId:
131 return std::make_unique<F64ShadowConfig>();
132 case F80ShadowConfig::kNsanTypeId:
133 return std::make_unique<F80ShadowConfig>();
134 case F128ShadowConfig::kNsanTypeId:
135 return std::make_unique<F128ShadowConfig>();
136 case PPC128ShadowConfig::kNsanTypeId:
137 return std::make_unique<PPC128ShadowConfig>();
138 }
139 report_fatal_error("nsan: invalid shadow type id '" + Twine(TypeId) + "'");
140}
141
142// An enum corresponding to shadow value types. Used as indices in arrays, so
143// not an `enum class`.
144enum FTValueType { kFloat, kDouble, kLongDouble, kNumValueTypes };
145
146// If `FT` corresponds to a primitive FTValueType, return it.
147static std::optional<FTValueType> ftValueTypeFromType(Type *FT) {
148 if (FT->isFloatTy())
149 return kFloat;
150 if (FT->isDoubleTy())
151 return kDouble;
152 if (FT->isX86_FP80Ty())
153 return kLongDouble;
154 return {};
155}
156
157// Returns the LLVM type for an FTValueType.
158static Type *typeFromFTValueType(FTValueType VT, LLVMContext &Context) {
159 switch (VT) {
160 case kFloat:
161 return Type::getFloatTy(Context);
162 case kDouble:
163 return Type::getDoubleTy(Context);
164 case kLongDouble:
165 return Type::getX86_FP80Ty(Context);
166 case kNumValueTypes:
167 return nullptr;
168 }
169 llvm_unreachable("Unhandled FTValueType enum");
170}
171
172// Returns the type name for an FTValueType.
173static const char *typeNameFromFTValueType(FTValueType VT) {
174 switch (VT) {
175 case kFloat:
176 return "float";
177 case kDouble:
178 return "double";
179 case kLongDouble:
180 return "longdouble";
181 case kNumValueTypes:
182 return nullptr;
183 }
184 llvm_unreachable("Unhandled FTValueType enum");
185}
186
187// A specific mapping configuration of application type to shadow type for nsan
188// (see -nsan-shadow-mapping flag).
189class MappingConfig {
190public:
191 MappingConfig(const InstrumentationOptions &Opts, LLVMContext &C)
192 : Context(C) {
193 if (Opts.nsan_shadow_type_mapping.size() != 3)
194 report_fatal_error("Invalid nsan mapping: " +
195 Twine(Opts.nsan_shadow_type_mapping));
196 unsigned ShadowTypeSizeBits[kNumValueTypes];
197 for (int VT = 0; VT < kNumValueTypes; ++VT) {
198 auto Config =
199 ShadowTypeConfig::fromNsanTypeId(Opts.nsan_shadow_type_mapping[VT]);
200 if (!Config)
201 report_fatal_error("Failed to get ShadowTypeConfig for " +
202 Twine(Opts.nsan_shadow_type_mapping[VT]));
203 const unsigned AppTypeSize =
204 typeFromFTValueType(static_cast<FTValueType>(VT), Context)
205 ->getScalarSizeInBits();
206 const unsigned ShadowTypeSize =
207 Config->getType(Context)->getScalarSizeInBits();
208 // Check that the shadow type size is at most kShadowScale times the
209 // application type size, so that shadow memory compoutations are valid.
210 if (ShadowTypeSize > kShadowScale * AppTypeSize)
211 report_fatal_error("Invalid nsan mapping f" + Twine(AppTypeSize) +
212 "->f" + Twine(ShadowTypeSize) +
213 ": The shadow type size should be at most " +
215 " times the application type size");
216 ShadowTypeSizeBits[VT] = ShadowTypeSize;
217 Configs[VT] = std::move(Config);
218 }
219
220 // Check that the mapping is monotonous. This is required because if one
221 // does an fpextend of `float->long double` in application code, nsan is
222 // going to do an fpextend of `shadow(float) -> shadow(long double)` in
223 // shadow code. This will fail in `qql` mode, since nsan would be
224 // fpextending `f128->long`, which is invalid.
225 // TODO: Relax this.
226 if (ShadowTypeSizeBits[kFloat] > ShadowTypeSizeBits[kDouble] ||
227 ShadowTypeSizeBits[kDouble] > ShadowTypeSizeBits[kLongDouble])
228 report_fatal_error("Invalid nsan mapping: { float->f" +
229 Twine(ShadowTypeSizeBits[kFloat]) + "; double->f" +
230 Twine(ShadowTypeSizeBits[kDouble]) +
231 "; long double->f" +
232 Twine(ShadowTypeSizeBits[kLongDouble]) + " }");
233 }
234
235 const ShadowTypeConfig &byValueType(FTValueType VT) const {
236 assert(VT < FTValueType::kNumValueTypes && "invalid value type");
237 return *Configs[VT];
238 }
239
240 // Returns the extended shadow type for a given application type.
241 Type *getExtendedFPType(Type *FT) const {
242 if (const auto VT = ftValueTypeFromType(FT))
243 return Configs[*VT]->getType(Context);
244 if (FT->isVectorTy()) {
245 auto *VecTy = cast<VectorType>(FT);
246 // TODO: add support for scalable vector types.
247 if (VecTy->isScalableTy())
248 return nullptr;
249 Type *ExtendedScalar = getExtendedFPType(VecTy->getElementType());
250 return ExtendedScalar
251 ? VectorType::get(ExtendedScalar, VecTy->getElementCount())
252 : nullptr;
253 }
254 return nullptr;
255 }
256
257private:
258 LLVMContext &Context;
259 std::unique_ptr<ShadowTypeConfig> Configs[FTValueType::kNumValueTypes];
260};
261
262// The memory extents of a type specifies how many elements of a given
263// FTValueType needs to be stored when storing this type.
264struct MemoryExtents {
265 FTValueType ValueType;
266 uint64_t NumElts;
267};
268
269static MemoryExtents getMemoryExtentsOrDie(Type *FT) {
270 if (const auto VT = ftValueTypeFromType(FT))
271 return {*VT, 1};
272 if (auto *VecTy = dyn_cast<VectorType>(FT)) {
273 const auto ScalarExtents = getMemoryExtentsOrDie(VecTy->getElementType());
274 return {ScalarExtents.ValueType,
275 ScalarExtents.NumElts * VecTy->getElementCount().getFixedValue()};
276 }
277 llvm_unreachable("invalid value type");
278}
279
280// The location of a check. Passed as parameters to runtime checking functions.
281class CheckLoc {
282public:
283 // Creates a location that references an application memory location.
284 static CheckLoc makeStore(Value *Address) {
285 CheckLoc Result(kStore);
286 Result.Address = Address;
287 return Result;
288 }
289 static CheckLoc makeLoad(Value *Address) {
290 CheckLoc Result(kLoad);
291 Result.Address = Address;
292 return Result;
293 }
294
295 // Creates a location that references an argument, given by id.
296 static CheckLoc makeArg(int ArgId) {
297 CheckLoc Result(kArg);
298 Result.ArgId = ArgId;
299 return Result;
300 }
301
302 // Creates a location that references the return value of a function.
303 static CheckLoc makeRet() { return CheckLoc(kRet); }
304
305 // Creates a location that references a vector insert.
306 static CheckLoc makeInsert() { return CheckLoc(kInsert); }
307
308 // Returns the CheckType of location this refers to, as an integer-typed LLVM
309 // IR value.
310 Value *getType(LLVMContext &C) const {
311 return ConstantInt::get(Type::getInt32Ty(C), static_cast<int>(CheckTy));
312 }
313
314 // Returns a CheckType-specific value representing details of the location
315 // (e.g. application address for loads or stores), as an `IntptrTy`-typed LLVM
316 // IR value.
317 Value *getValue(Type *IntptrTy, IRBuilder<> &Builder) const {
318 switch (CheckTy) {
319 case kUnknown:
320 llvm_unreachable("unknown type");
321 case kRet:
322 case kInsert:
323 return ConstantInt::get(IntptrTy, 0);
324 case kArg:
325 return ConstantInt::get(IntptrTy, ArgId);
326 case kLoad:
327 case kStore:
328 return Builder.CreatePtrToInt(Address, IntptrTy);
329 }
330 llvm_unreachable("Unhandled CheckType enum");
331 }
332
333private:
334 // Must be kept in sync with the runtime,
335 // see compiler-rt/lib/nsan/nsan_stats.h
336 enum CheckType {
337 kUnknown = 0,
338 kRet,
339 kArg,
340 kLoad,
341 kStore,
342 kInsert,
343 };
344 explicit CheckLoc(CheckType CheckTy) : CheckTy(CheckTy) {}
345
346 Value *Address = nullptr;
347 const CheckType CheckTy;
348 int ArgId = -1;
349};
350
351// A map of LLVM IR values to shadow LLVM IR values.
352class ValueToShadowMap {
353public:
354 explicit ValueToShadowMap(const MappingConfig &Config) : Config(Config) {}
355
356 ValueToShadowMap(const ValueToShadowMap &) = delete;
357 ValueToShadowMap &operator=(const ValueToShadowMap &) = delete;
358
359 // Sets the shadow value for a value. Asserts that the value does not already
360 // have a value.
361 void setShadow(Value &V, Value &Shadow) {
362 [[maybe_unused]] const bool Inserted = Map.try_emplace(&V, &Shadow).second;
363 LLVM_DEBUG({
364 if (!Inserted) {
365 if (auto *I = dyn_cast<Instruction>(&V))
366 errs() << I->getFunction()->getName() << ": ";
367 errs() << "duplicate shadow (" << &V << "): ";
368 V.dump();
369 }
370 });
371 assert(Inserted && "duplicate shadow");
372 }
373
374 // Returns true if the value already has a shadow (including if the value is a
375 // constant). If true, calling getShadow() is valid.
376 bool hasShadow(Value *V) const { return isa<Constant>(V) || Map.contains(V); }
377
378 // Returns the shadow value for a given value. Asserts that the value has
379 // a shadow value. Lazily creates shadows for constant values.
380 Value *getShadow(Value *V) const {
381 if (Constant *C = dyn_cast<Constant>(V))
382 return getShadowConstant(C);
383 return Map.find(V)->second;
384 }
385
386 bool empty() const { return Map.empty(); }
387
388private:
389 // Extends a constant application value to its shadow counterpart.
390 APFloat extendConstantFP(APFloat CV, const fltSemantics &To) const {
391 bool LosesInfo = false;
392 CV.convert(To, APFloatBase::rmTowardZero, &LosesInfo);
393 return CV;
394 }
395
396 // Returns the shadow constant for the given application constant.
397 Constant *getShadowConstant(Constant *C) const {
399 return UndefValue::get(Config.getExtendedFPType(U->getType()));
400 }
401 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
402 // Floating-point constants.
403 Type *Ty = Config.getExtendedFPType(CFP->getType());
404 return ConstantFP::get(
405 Ty, extendConstantFP(CFP->getValueAPF(),
406 Ty->getScalarType()->getFltSemantics()));
407 }
408 // Vector, array, or aggregate constants.
409 if (C->getType()->isVectorTy()) {
411 for (int I = 0, E = cast<VectorType>(C->getType())
412 ->getElementCount()
413 .getFixedValue();
414 I < E; ++I)
415 Elements.push_back(getShadowConstant(C->getAggregateElement(I)));
416 return ConstantVector::get(Elements);
417 }
418 llvm_unreachable("unimplemented");
419 }
420
421 const MappingConfig &Config;
423};
424
425class NsanMemOpFn {
426public:
427 NsanMemOpFn(Module &M, ArrayRef<StringRef> Sized, StringRef Fallback,
428 size_t NumArgs);
429 FunctionCallee getFunctionFor(uint64_t MemOpSize) const;
430 FunctionCallee getFallback() const;
431
432private:
434 size_t NumSizedFuncs;
435};
436
437NsanMemOpFn::NsanMemOpFn(Module &M, ArrayRef<StringRef> Sized,
438 StringRef Fallback, size_t NumArgs) {
439 LLVMContext &Ctx = M.getContext();
440 AttributeList Attr;
441 Attr = Attr.addFnAttribute(Ctx, Attribute::NoUnwind);
442 Type *PtrTy = PointerType::getUnqual(Ctx);
443 Type *VoidTy = Type::getVoidTy(Ctx);
444 IntegerType *IntptrTy = M.getDataLayout().getIntPtrType(Ctx);
445 FunctionType *SizedFnTy = nullptr;
446
447 NumSizedFuncs = Sized.size();
448
449 // First entry is fallback function
450 if (NumArgs == 3) {
451 Funcs.push_back(
452 M.getOrInsertFunction(Fallback, Attr, VoidTy, PtrTy, PtrTy, IntptrTy));
453 SizedFnTy = FunctionType::get(VoidTy, {PtrTy, PtrTy}, false);
454 } else if (NumArgs == 2) {
455 Funcs.push_back(
456 M.getOrInsertFunction(Fallback, Attr, VoidTy, PtrTy, IntptrTy));
457 SizedFnTy = FunctionType::get(VoidTy, {PtrTy}, false);
458 } else {
459 llvm_unreachable("Unexpected value of sized functions arguments");
460 }
461
462 for (size_t i = 0; i < NumSizedFuncs; ++i)
463 Funcs.push_back(M.getOrInsertFunction(Sized[i], SizedFnTy, Attr));
464}
465
466FunctionCallee NsanMemOpFn::getFunctionFor(uint64_t MemOpSize) const {
467 // Now `getFunctionFor` operates on `Funcs` of size 4 (at least) and the
468 // following code assumes that the number of functions in `Func` is sufficient
469 assert(NumSizedFuncs >= 3 && "Unexpected number of sized functions");
470
471 size_t Idx =
472 MemOpSize == 4 ? 1 : (MemOpSize == 8 ? 2 : (MemOpSize == 16 ? 3 : 0));
473
474 return Funcs[Idx];
475}
476
477FunctionCallee NsanMemOpFn::getFallback() const { return Funcs[0]; }
478
479/// Instantiating NumericalStabilitySanitizer inserts the nsan runtime library
480/// API function declarations into the module if they don't exist already.
481/// Instantiating ensures the __nsan_init function is in the list of global
482/// constructors for the module.
483class NumericalStabilitySanitizer {
484public:
485 NumericalStabilitySanitizer(const InstrumentationOptions &Opts, Module &M);
486 bool sanitizeFunction(Function &F, const TargetLibraryInfo &TLI);
487
488private:
489 bool instrumentMemIntrinsic(MemIntrinsic *MI);
490 void maybeAddSuffixForNsanInterface(CallBase *CI);
491 bool addrPointsToConstantData(Value *Addr);
492 void maybeCreateShadowValue(Instruction &Root, const TargetLibraryInfo &TLI,
493 ValueToShadowMap &Map);
494 Value *createShadowValueWithOperandsAvailable(Instruction &Inst,
495 const TargetLibraryInfo &TLI,
496 const ValueToShadowMap &Map);
497 PHINode *maybeCreateShadowPhi(PHINode &Phi, const TargetLibraryInfo &TLI);
498 void createShadowArguments(Function &F, const TargetLibraryInfo &TLI,
499 ValueToShadowMap &Map);
500
501 void populateShadowStack(CallBase &CI, const TargetLibraryInfo &TLI,
502 const ValueToShadowMap &Map);
503
504 void propagateShadowValues(Instruction &Inst, const TargetLibraryInfo &TLI,
505 const ValueToShadowMap &Map);
506 Value *emitCheck(Value *V, Value *ShadowV, IRBuilder<> &Builder,
507 CheckLoc Loc);
508 Value *emitCheckInternal(Value *V, Value *ShadowV, IRBuilder<> &Builder,
509 CheckLoc Loc);
510 void emitFCmpCheck(FCmpInst &FCmp, const ValueToShadowMap &Map);
511
512 // Value creation handlers.
513 Value *handleLoad(LoadInst &Load, Type *VT, Type *ExtendedVT);
514 Value *handleCallBase(CallBase &Call, Type *VT, Type *ExtendedVT,
515 const TargetLibraryInfo &TLI,
516 const ValueToShadowMap &Map, IRBuilder<> &Builder);
517 Value *maybeHandleKnownCallBase(CallBase &Call, Type *VT, Type *ExtendedVT,
518 const TargetLibraryInfo &TLI,
519 const ValueToShadowMap &Map,
520 IRBuilder<> &Builder);
521 Value *handleTrunc(const FPTruncInst &Trunc, Type *VT, Type *ExtendedVT,
522 const ValueToShadowMap &Map, IRBuilder<> &Builder);
523 Value *handleExt(const FPExtInst &Ext, Type *VT, Type *ExtendedVT,
524 const ValueToShadowMap &Map, IRBuilder<> &Builder);
525
526 // Value propagation handlers.
527 void propagateFTStore(StoreInst &Store, Type *VT, Type *ExtendedVT,
528 const ValueToShadowMap &Map);
529 void propagateNonFTStore(StoreInst &Store, Type *VT,
530 const ValueToShadowMap &Map);
531
532 const InstrumentationOptions &Opts;
533 const DataLayout &DL;
534 LLVMContext &Context;
535 MappingConfig Config;
536 IntegerType *IntptrTy = nullptr;
537
538 // TODO: Use std::array instead?
539 FunctionCallee NsanGetShadowPtrForStore[FTValueType::kNumValueTypes] = {};
540 FunctionCallee NsanGetShadowPtrForLoad[FTValueType::kNumValueTypes] = {};
541 FunctionCallee NsanCheckValue[FTValueType::kNumValueTypes] = {};
542 FunctionCallee NsanFCmpFail[FTValueType::kNumValueTypes] = {};
543
544 NsanMemOpFn NsanCopyFns;
545 NsanMemOpFn NsanSetUnknownFns;
546
547 FunctionCallee NsanGetRawShadowTypePtr;
548 FunctionCallee NsanGetRawShadowPtr;
549 GlobalValue *NsanShadowRetTag = nullptr;
550
551 Type *NsanShadowRetType = nullptr;
552 GlobalValue *NsanShadowRetPtr = nullptr;
553
554 GlobalValue *NsanShadowArgsTag = nullptr;
555
556 Type *NsanShadowArgsType = nullptr;
557 GlobalValue *NsanShadowArgsPtr = nullptr;
558
559 std::optional<Regex> CheckFunctionsFilter;
560};
561} // end anonymous namespace
562
563PreservedAnalyses
566 M, kNsanModuleCtorName, kNsanInitName, /*InitArgTypes=*/{},
567 /*InitArgs=*/{},
568 // This callback is invoked when the functions are created the first
569 // time. Hook them into the global ctors list in that case:
570 [&](Function *Ctor, FunctionCallee) { appendToGlobalCtors(M, Ctor, 0); });
571
572 NumericalStabilitySanitizer Nsan(InstrumentationOptions::Global, M);
573 auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
574 for (Function &F : M)
575 Nsan.sanitizeFunction(F, FAM.getResult<TargetLibraryAnalysis>(F));
576
578}
579
580static GlobalValue *createThreadLocalGV(const char *Name, Module &M, Type *Ty) {
581 return M.getOrInsertGlobal(Name, Ty, [&M, Ty, Name] {
582 return new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage,
583 nullptr, Name, nullptr,
585 });
586}
587
588NumericalStabilitySanitizer::NumericalStabilitySanitizer(
589 const InstrumentationOptions &Opts, Module &M)
590 : Opts(Opts), DL(M.getDataLayout()), Context(M.getContext()),
591 Config(Opts, Context),
592 NsanCopyFns(M, {"__nsan_copy_4", "__nsan_copy_8", "__nsan_copy_16"},
593 "__nsan_copy_values", /*NumArgs=*/3),
594 NsanSetUnknownFns(M,
595 {"__nsan_set_value_unknown_4",
596 "__nsan_set_value_unknown_8",
597 "__nsan_set_value_unknown_16"},
598 "__nsan_set_value_unknown", /*NumArgs=*/2) {
599 IntptrTy = DL.getIntPtrType(Context);
600 Type *PtrTy = PointerType::getUnqual(Context);
601 Type *Int32Ty = Type::getInt32Ty(Context);
602 Type *Int1Ty = Type::getInt1Ty(Context);
603 Type *VoidTy = Type::getVoidTy(Context);
604
605 AttributeList Attr;
606 Attr = Attr.addFnAttribute(Context, Attribute::NoUnwind);
607 // Initialize the runtime values (functions and global variables).
608 for (int I = 0; I < kNumValueTypes; ++I) {
609 const FTValueType VT = static_cast<FTValueType>(I);
610 const char *VTName = typeNameFromFTValueType(VT);
611 Type *VTTy = typeFromFTValueType(VT, Context);
612
613 // Load/store.
614 const std::string GetterPrefix =
615 std::string("__nsan_get_shadow_ptr_for_") + VTName;
616 NsanGetShadowPtrForStore[VT] = M.getOrInsertFunction(
617 GetterPrefix + "_store", Attr, PtrTy, PtrTy, IntptrTy);
618 NsanGetShadowPtrForLoad[VT] = M.getOrInsertFunction(
619 GetterPrefix + "_load", Attr, PtrTy, PtrTy, IntptrTy);
620
621 // Check.
622 const auto &ShadowConfig = Config.byValueType(VT);
623 Type *ShadowTy = ShadowConfig.getType(Context);
624 NsanCheckValue[VT] =
625 M.getOrInsertFunction(std::string("__nsan_internal_check_") + VTName +
626 "_" + ShadowConfig.getNsanTypeId(),
627 Attr, Int32Ty, VTTy, ShadowTy, Int32Ty, IntptrTy);
628 NsanFCmpFail[VT] = M.getOrInsertFunction(
629 std::string("__nsan_fcmp_fail_") + VTName + "_" +
630 ShadowConfig.getNsanTypeId(),
631 Attr, VoidTy, VTTy, VTTy, ShadowTy, ShadowTy, Int32Ty, Int1Ty, Int1Ty);
632 }
633
634 // TODO: Add attributes nofree, nosync, readnone, readonly,
635 NsanGetRawShadowTypePtr = M.getOrInsertFunction(
636 "__nsan_internal_get_raw_shadow_type_ptr", Attr, PtrTy, PtrTy);
637 NsanGetRawShadowPtr = M.getOrInsertFunction(
638 "__nsan_internal_get_raw_shadow_ptr", Attr, PtrTy, PtrTy);
639
640 NsanShadowRetTag = createThreadLocalGV("__nsan_shadow_ret_tag", M, IntptrTy);
641
642 NsanShadowRetType = ArrayType::get(Type::getInt8Ty(Context),
644 NsanShadowRetPtr =
645 createThreadLocalGV("__nsan_shadow_ret_ptr", M, NsanShadowRetType);
646
647 NsanShadowArgsTag =
648 createThreadLocalGV("__nsan_shadow_args_tag", M, IntptrTy);
649
650 NsanShadowArgsType =
653
654 NsanShadowArgsPtr =
655 createThreadLocalGV("__nsan_shadow_args_ptr", M, NsanShadowArgsType);
656
657 if (!Opts.check_functions_filter.empty()) {
658 Regex R = Regex(Opts.check_functions_filter);
659 std::string RegexError;
660 assert(R.isValid(RegexError));
661 CheckFunctionsFilter = std::move(R);
662 }
663}
664
665// Returns true if the given LLVM Value points to constant data (typically, a
666// global variable reference).
667bool NumericalStabilitySanitizer::addrPointsToConstantData(Value *Addr) {
668 // If this is a GEP, just analyze its pointer operand.
669 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr))
670 Addr = GEP->getPointerOperand();
671
672 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr))
673 return GV->isConstant();
674 return false;
675}
676
677// This instruments the function entry to create shadow arguments.
678// Pseudocode:
679// if (this_fn_ptr == __nsan_shadow_args_tag) {
680// s(arg0) = LOAD<sizeof(arg0)>(__nsan_shadow_args);
681// s(arg1) = LOAD<sizeof(arg1)>(__nsan_shadow_args + sizeof(arg0));
682// ...
683// __nsan_shadow_args_tag = 0;
684// } else {
685// s(arg0) = fext(arg0);
686// s(arg1) = fext(arg1);
687// ...
688// }
689void NumericalStabilitySanitizer::createShadowArguments(
690 Function &F, const TargetLibraryInfo &TLI, ValueToShadowMap &Map) {
691 assert(!F.getIntrinsicID() && "found a definition of an intrinsic");
692
693 // Do not bother if there are no FP args.
694 if (all_of(F.args(), [this](const Argument &Arg) {
695 return Config.getExtendedFPType(Arg.getType()) == nullptr;
696 }))
697 return;
698
699 IRBuilder<> Builder(F.getEntryBlock().getFirstNonPHIIt());
700 // The function has shadow args if the shadow args tag matches the function
701 // address.
702 Value *HasShadowArgs = Builder.CreateICmpEQ(
703 Builder.CreateLoad(IntptrTy, NsanShadowArgsTag, /*isVolatile=*/false),
704 Builder.CreatePtrToInt(&F, IntptrTy));
705
706 unsigned ShadowArgsOffsetBytes = 0;
707 for (Argument &Arg : F.args()) {
708 Type *VT = Arg.getType();
709 Type *ExtendedVT = Config.getExtendedFPType(VT);
710 if (ExtendedVT == nullptr)
711 continue; // Not an FT value.
712 Value *L = Builder.CreateAlignedLoad(
713 ExtendedVT,
714 Builder.CreateConstGEP2_64(NsanShadowArgsType, NsanShadowArgsPtr, 0,
715 ShadowArgsOffsetBytes),
716 Align(1), /*isVolatile=*/false);
717 Value *Shadow = Builder.CreateSelect(HasShadowArgs, L,
718 Builder.CreateFPExt(&Arg, ExtendedVT));
719 Map.setShadow(Arg, *Shadow);
720 TypeSize SlotSize = DL.getTypeStoreSize(ExtendedVT);
721 assert(!SlotSize.isScalable() && "unsupported");
722 ShadowArgsOffsetBytes += SlotSize;
723 }
724 Builder.CreateStore(ConstantInt::get(IntptrTy, 0), NsanShadowArgsTag);
725}
726
727// Returns true if the instrumentation should emit code to check arguments
728// before a function call.
729static bool shouldCheckArgs(CallBase &CI, const TargetLibraryInfo &TLI,
730 const std::optional<Regex> &CheckFunctionsFilter) {
731
732 Function *Fn = CI.getCalledFunction();
733
734 if (CheckFunctionsFilter) {
735 // Skip checking args of indirect calls.
736 if (Fn == nullptr)
737 return false;
738 if (CheckFunctionsFilter->match(Fn->getName()))
739 return true;
740 return false;
741 }
742
743 if (Fn == nullptr)
744 return true; // Always check args of indirect calls.
745
746 // Never check nsan functions, the user called them for a reason.
747 if (Fn->getName().starts_with("__nsan_"))
748 return false;
749
750 const auto ID = Fn->getIntrinsicID();
751 LibFunc LFunc = TLI.getLibFunc(*Fn);
752 // Always check args of unknown functions.
753 if (ID == Intrinsic::ID() && LFunc == NotLibFunc)
754 return true;
755
756 // Do not check args of an `fabs` call that is used for a comparison.
757 // This is typically used for `fabs(a-b) < tolerance`, where what matters is
758 // the result of the comparison, which is already caught be the fcmp checks.
759 if (ID == Intrinsic::fabs || LFunc == LibFunc_fabsf ||
760 LFunc == LibFunc_fabs || LFunc == LibFunc_fabsl)
761 for (const auto &U : CI.users())
762 if (isa<CmpInst>(U))
763 return false;
764
765 return true; // Default is check.
766}
767
768// Populates the shadow call stack (which contains shadow values for every
769// floating-point parameter to the function).
770void NumericalStabilitySanitizer::populateShadowStack(
771 CallBase &CI, const TargetLibraryInfo &TLI, const ValueToShadowMap &Map) {
772 // Do not create a shadow stack for inline asm.
773 if (CI.isInlineAsm())
774 return;
775
776 // Do not bother if there are no FP args.
777 if (all_of(CI.operands(), [this](const Value *Arg) {
778 return Config.getExtendedFPType(Arg->getType()) == nullptr;
779 }))
780 return;
781
782 IRBuilder<> Builder(&CI);
783 SmallVector<Value *, 8> ArgShadows;
784 const bool ShouldCheckArgs = shouldCheckArgs(CI, TLI, CheckFunctionsFilter);
785 for (auto [ArgIdx, Arg] : enumerate(CI.operands())) {
786 if (Config.getExtendedFPType(Arg->getType()) == nullptr)
787 continue; // Not an FT value.
788 Value *ArgShadow = Map.getShadow(Arg);
789 ArgShadows.push_back(ShouldCheckArgs ? emitCheck(Arg, ArgShadow, Builder,
790 CheckLoc::makeArg(ArgIdx))
791 : ArgShadow);
792 }
793
794 // Do not create shadow stacks for intrinsics/known lib funcs.
795 if (Function *Fn = CI.getCalledFunction()) {
796 if (Fn->isIntrinsic() || TLI.getLibFunc(*Fn) != NotLibFunc)
797 return;
798 }
799
800 // Set the shadow stack tag.
801 Builder.CreateStore(CI.getCalledOperand(), NsanShadowArgsTag);
802 TypeSize ShadowArgsOffsetBytes = TypeSize::getFixed(0);
803
804 unsigned ShadowArgId = 0;
805 for (const Value *Arg : CI.operands()) {
806 Type *VT = Arg->getType();
807 Type *ExtendedVT = Config.getExtendedFPType(VT);
808 if (ExtendedVT == nullptr)
809 continue; // Not an FT value.
810 Builder.CreateAlignedStore(
811 ArgShadows[ShadowArgId++],
812 Builder.CreateConstGEP2_64(NsanShadowArgsType, NsanShadowArgsPtr, 0,
813 ShadowArgsOffsetBytes),
814 Align(1), /*isVolatile=*/false);
815 TypeSize SlotSize = DL.getTypeStoreSize(ExtendedVT);
816 assert(!SlotSize.isScalable() && "unsupported");
817 ShadowArgsOffsetBytes += SlotSize;
818 }
819}
820
821// Internal part of emitCheck(). Returns a value that indicates whether
822// computation should continue with the shadow or resume by re-fextending the
823// value.
824enum class ContinuationType { // Keep in sync with runtime.
827};
828
829Value *NumericalStabilitySanitizer::emitCheckInternal(Value *V, Value *ShadowV,
830 IRBuilder<> &Builder,
831 CheckLoc Loc) {
832 // Do not emit checks for constant values, this is redundant.
833 if (isa<Constant>(V))
834 return ConstantInt::get(
835 Builder.getInt32Ty(),
836 static_cast<int>(ContinuationType::ContinueWithShadow));
837
838 Type *Ty = V->getType();
839 if (const auto VT = ftValueTypeFromType(Ty))
840 return Builder.CreateCall(
841 NsanCheckValue[*VT],
842 {V, ShadowV, Loc.getType(Context), Loc.getValue(IntptrTy, Builder)});
843
844 if (Ty->isVectorTy()) {
845 auto *VecTy = cast<VectorType>(Ty);
846 // We currently skip scalable vector types in MappingConfig,
847 // thus we should not encounter any such types here.
848 assert(!VecTy->isScalableTy() &&
849 "Scalable vector types are not supported yet");
850 Value *CheckResult = nullptr;
851 for (int I = 0, E = VecTy->getElementCount().getFixedValue(); I < E; ++I) {
852 // We resume if any element resumes. Another option would be to create a
853 // vector shuffle with the array of ContinueWithShadow, but that is too
854 // complex.
855 Value *ExtractV = Builder.CreateExtractElement(V, I);
856 Value *ExtractShadowV = Builder.CreateExtractElement(ShadowV, I);
857 Value *ComponentCheckResult =
858 emitCheckInternal(ExtractV, ExtractShadowV, Builder, Loc);
859 CheckResult = CheckResult
860 ? Builder.CreateOr(CheckResult, ComponentCheckResult)
861 : ComponentCheckResult;
862 }
863 return CheckResult;
864 }
865 if (Ty->isArrayTy()) {
866 Value *CheckResult = nullptr;
867 for (auto I : seq(Ty->getArrayNumElements())) {
868 Value *ExtractV = Builder.CreateExtractElement(V, I);
869 Value *ExtractShadowV = Builder.CreateExtractElement(ShadowV, I);
870 Value *ComponentCheckResult =
871 emitCheckInternal(ExtractV, ExtractShadowV, Builder, Loc);
872 CheckResult = CheckResult
873 ? Builder.CreateOr(CheckResult, ComponentCheckResult)
874 : ComponentCheckResult;
875 }
876 return CheckResult;
877 }
878 if (Ty->isStructTy()) {
879 Value *CheckResult = nullptr;
880 for (auto I : seq(Ty->getStructNumElements())) {
881 if (Config.getExtendedFPType(Ty->getStructElementType(I)) == nullptr)
882 continue; // Only check FT values.
883 Value *ExtractV = Builder.CreateExtractValue(V, I);
884 Value *ExtractShadowV = Builder.CreateExtractElement(ShadowV, I);
885 Value *ComponentCheckResult =
886 emitCheckInternal(ExtractV, ExtractShadowV, Builder, Loc);
887 CheckResult = CheckResult
888 ? Builder.CreateOr(CheckResult, ComponentCheckResult)
889 : ComponentCheckResult;
890 }
891 if (!CheckResult)
892 return ConstantInt::get(
893 Builder.getInt32Ty(),
894 static_cast<int>(ContinuationType::ContinueWithShadow));
895 return CheckResult;
896 }
897
898 llvm_unreachable("not implemented");
899}
900
901// Inserts a runtime check of V against its shadow value ShadowV.
902// We check values whenever they escape: on return, call, stores, and
903// insertvalue.
904// Returns the shadow value that should be used to continue the computations,
905// depending on the answer from the runtime.
906// TODO: Should we check on select ? phi ?
907Value *NumericalStabilitySanitizer::emitCheck(Value *V, Value *ShadowV,
908 IRBuilder<> &Builder,
909 CheckLoc Loc) {
910 // Do not emit checks for constant values, this is redundant.
911 if (isa<Constant>(V))
912 return ShadowV;
913
914 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
915 Function *F = Inst->getFunction();
916 if (CheckFunctionsFilter && !CheckFunctionsFilter->match(F->getName())) {
917 return ShadowV;
918 }
919 }
920
921 Value *CheckResult = emitCheckInternal(V, ShadowV, Builder, Loc);
922 Value *ICmpEQ = Builder.CreateICmpEQ(
923 CheckResult,
924 ConstantInt::get(Builder.getInt32Ty(),
925 static_cast<int>(ContinuationType::ResumeFromValue)));
926 return Builder.CreateSelect(
927 ICmpEQ, Builder.CreateFPExt(V, Config.getExtendedFPType(V->getType())),
928 ShadowV);
929}
930
931// Inserts a check that fcmp on shadow values are consistent with that on base
932// values.
933void NumericalStabilitySanitizer::emitFCmpCheck(FCmpInst &FCmp,
934 const ValueToShadowMap &Map) {
935 if (!Opts.nsan_instrument_fcmp)
936 return;
937
938 Function *F = FCmp.getFunction();
939 if (CheckFunctionsFilter && !CheckFunctionsFilter->match(F->getName()))
940 return;
941
942 Value *LHS = FCmp.getOperand(0);
943 if (Config.getExtendedFPType(LHS->getType()) == nullptr)
944 return;
945 Value *RHS = FCmp.getOperand(1);
946
947 // Split the basic block. On mismatch, we'll jump to the new basic block with
948 // a call to the runtime for error reporting.
949 BasicBlock *FCmpBB = FCmp.getParent();
950 BasicBlock *NextBB = FCmpBB->splitBasicBlock(FCmp.getNextNode());
951 // Remove the newly created terminator unconditional branch.
952 FCmpBB->back().eraseFromParent();
953 BasicBlock *FailBB =
954 BasicBlock::Create(Context, "", FCmpBB->getParent(), NextBB);
955
956 // Create the shadow fcmp and comparison between the fcmps.
957 IRBuilder<> FCmpBuilder(FCmpBB);
958 FCmpBuilder.SetCurrentDebugLocation(FCmp.getDebugLoc());
959 Value *ShadowLHS = Map.getShadow(LHS);
960 Value *ShadowRHS = Map.getShadow(RHS);
961 // See the help text of -nsan-truncate-fcmp-eq.
962 if (FCmp.isEquality() && Opts.nsan_truncate_fcmp_eq) {
963 Type *Ty = ShadowLHS->getType();
964 ShadowLHS = FCmpBuilder.CreateFPExt(
965 FCmpBuilder.CreateFPTrunc(ShadowLHS, LHS->getType()), Ty);
966 ShadowRHS = FCmpBuilder.CreateFPExt(
967 FCmpBuilder.CreateFPTrunc(ShadowRHS, RHS->getType()), Ty);
968 }
969 Value *ShadowFCmp =
970 FCmpBuilder.CreateFCmp(FCmp.getPredicate(), ShadowLHS, ShadowRHS);
971 Value *OriginalAndShadowFcmpMatch =
972 FCmpBuilder.CreateICmpEQ(&FCmp, ShadowFCmp);
973
974 if (OriginalAndShadowFcmpMatch->getType()->isVectorTy()) {
975 // If we have a vector type, `OriginalAndShadowFcmpMatch` is a vector of i1,
976 // where an element is true if the corresponding elements in original and
977 // shadow are the same. We want all elements to be 1.
978 OriginalAndShadowFcmpMatch =
979 FCmpBuilder.CreateAndReduce(OriginalAndShadowFcmpMatch);
980 }
981
982 // Use MDBuilder(*C).createLikelyBranchWeights() because "match" is the common
983 // case.
984 FCmpBuilder.CreateCondBr(OriginalAndShadowFcmpMatch, NextBB, FailBB,
985 MDBuilder(Context).createLikelyBranchWeights());
986
987 // Fill in FailBB.
988 IRBuilder<> FailBuilder(FailBB);
989 FailBuilder.SetCurrentDebugLocation(FCmp.getDebugLoc());
990
991 const auto EmitFailCall = [this, &FCmp, &FCmpBuilder,
992 &FailBuilder](Value *L, Value *R, Value *ShadowL,
993 Value *ShadowR, Value *Result,
994 Value *ShadowResult) {
995 Type *FT = L->getType();
996 FunctionCallee *Callee = nullptr;
997 if (FT->isFloatTy()) {
998 Callee = &(NsanFCmpFail[kFloat]);
999 } else if (FT->isDoubleTy()) {
1000 Callee = &(NsanFCmpFail[kDouble]);
1001 } else if (FT->isX86_FP80Ty()) {
1002 // TODO: make NsanFCmpFailLongDouble work.
1003 Callee = &(NsanFCmpFail[kDouble]);
1004 L = FailBuilder.CreateFPTrunc(L, Type::getDoubleTy(Context));
1005 R = FailBuilder.CreateFPTrunc(L, Type::getDoubleTy(Context));
1006 } else {
1007 llvm_unreachable("not implemented");
1008 }
1009 FailBuilder.CreateCall(*Callee, {L, R, ShadowL, ShadowR,
1010 ConstantInt::get(FCmpBuilder.getInt32Ty(),
1011 FCmp.getPredicate()),
1012 Result, ShadowResult});
1013 };
1014 if (LHS->getType()->isVectorTy()) {
1015 for (int I = 0, E = cast<VectorType>(LHS->getType())
1016 ->getElementCount()
1017 .getFixedValue();
1018 I < E; ++I) {
1019 Value *ExtractLHS = FailBuilder.CreateExtractElement(LHS, I);
1020 Value *ExtractRHS = FailBuilder.CreateExtractElement(RHS, I);
1021 Value *ExtractShaodwLHS = FailBuilder.CreateExtractElement(ShadowLHS, I);
1022 Value *ExtractShaodwRHS = FailBuilder.CreateExtractElement(ShadowRHS, I);
1023 Value *ExtractFCmp = FailBuilder.CreateExtractElement(&FCmp, I);
1024 Value *ExtractShadowFCmp =
1025 FailBuilder.CreateExtractElement(ShadowFCmp, I);
1026 EmitFailCall(ExtractLHS, ExtractRHS, ExtractShaodwLHS, ExtractShaodwRHS,
1027 ExtractFCmp, ExtractShadowFCmp);
1028 }
1029 } else {
1030 EmitFailCall(LHS, RHS, ShadowLHS, ShadowRHS, &FCmp, ShadowFCmp);
1031 }
1032 FailBuilder.CreateBr(NextBB);
1033
1034 ++NumInstrumentedFCmp;
1035}
1036
1037// Creates a shadow phi value for any phi that defines a value of FT type.
1038PHINode *NumericalStabilitySanitizer::maybeCreateShadowPhi(
1039 PHINode &Phi, const TargetLibraryInfo &TLI) {
1040 Type *VT = Phi.getType();
1041 Type *ExtendedVT = Config.getExtendedFPType(VT);
1042 if (ExtendedVT == nullptr)
1043 return nullptr; // Not an FT value.
1044 // The phi operands are shadow values and are not available when the phi is
1045 // created. They will be populated in a final phase, once all shadow values
1046 // have been created.
1047 PHINode *Shadow = PHINode::Create(ExtendedVT, Phi.getNumIncomingValues());
1048 Shadow->insertAfter(Phi.getIterator());
1049 return Shadow;
1050}
1051
1052Value *NumericalStabilitySanitizer::handleLoad(LoadInst &Load, Type *VT,
1053 Type *ExtendedVT) {
1054 IRBuilder<> Builder(Load.getNextNode());
1055 Builder.SetCurrentDebugLocation(Load.getDebugLoc());
1056 if (addrPointsToConstantData(Load.getPointerOperand())) {
1057 // No need to look into the shadow memory, the value is a constant. Just
1058 // convert from FT to 2FT.
1059 return Builder.CreateFPExt(&Load, ExtendedVT);
1060 }
1061
1062 // if (%shadowptr == &)
1063 // %shadow = fpext %v
1064 // else
1065 // %shadow = load (ptrcast %shadow_ptr))
1066 // Considered options here:
1067 // - Have `NsanGetShadowPtrForLoad` return a fixed address
1068 // &__nsan_unknown_value_shadow_address that is valid to load from, and
1069 // use a select. This has the advantage that the generated IR is simpler.
1070 // - Have `NsanGetShadowPtrForLoad` return nullptr. Because `select` does
1071 // not short-circuit, dereferencing the returned pointer is no longer an
1072 // option, have to split and create a separate basic block. This has the
1073 // advantage of being easier to debug because it crashes if we ever mess
1074 // up.
1075
1076 const auto Extents = getMemoryExtentsOrDie(VT);
1077 Value *ShadowPtr = Builder.CreateCall(
1078 NsanGetShadowPtrForLoad[Extents.ValueType],
1079 {Load.getPointerOperand(), ConstantInt::get(IntptrTy, Extents.NumElts)});
1080 ++NumInstrumentedFTLoads;
1081
1082 // Split the basic block.
1083 BasicBlock *LoadBB = Load.getParent();
1084 BasicBlock *NextBB = LoadBB->splitBasicBlock(Builder.GetInsertPoint());
1085 // Create the two options for creating the shadow value.
1086 BasicBlock *ShadowLoadBB =
1087 BasicBlock::Create(Context, "", LoadBB->getParent(), NextBB);
1088 BasicBlock *FExtBB =
1089 BasicBlock::Create(Context, "", LoadBB->getParent(), NextBB);
1090
1091 // Replace the newly created terminator unconditional branch by a conditional
1092 // branch to one of the options.
1093 {
1094 LoadBB->back().eraseFromParent();
1095 IRBuilder<> LoadBBBuilder(LoadBB); // The old builder has been invalidated.
1096 LoadBBBuilder.SetCurrentDebugLocation(Load.getDebugLoc());
1097 LoadBBBuilder.CreateCondBr(LoadBBBuilder.CreateIsNull(ShadowPtr), FExtBB,
1098 ShadowLoadBB);
1099 }
1100
1101 // Fill in ShadowLoadBB.
1102 IRBuilder<> ShadowLoadBBBuilder(ShadowLoadBB);
1103 ShadowLoadBBBuilder.SetCurrentDebugLocation(Load.getDebugLoc());
1104 Value *ShadowLoad = ShadowLoadBBBuilder.CreateAlignedLoad(
1105 ExtendedVT, ShadowPtr, Align(1), Load.isVolatile());
1106 if (Opts.nsan_check_loads) {
1107 ShadowLoad = emitCheck(&Load, ShadowLoad, ShadowLoadBBBuilder,
1108 CheckLoc::makeLoad(Load.getPointerOperand()));
1109 }
1110 ShadowLoadBBBuilder.CreateBr(NextBB);
1111
1112 // Fill in FExtBB.
1113 IRBuilder<> FExtBBBuilder(FExtBB);
1114 FExtBBBuilder.SetCurrentDebugLocation(Load.getDebugLoc());
1115 Value *FExt = FExtBBBuilder.CreateFPExt(&Load, ExtendedVT);
1116 FExtBBBuilder.CreateBr(NextBB);
1117
1118 // The shadow value come from any of the options.
1119 IRBuilder<> NextBBBuilder(&*NextBB->begin());
1120 NextBBBuilder.SetCurrentDebugLocation(Load.getDebugLoc());
1121 PHINode *ShadowPhi = NextBBBuilder.CreatePHI(ExtendedVT, 2);
1122 ShadowPhi->addIncoming(ShadowLoad, ShadowLoadBB);
1123 ShadowPhi->addIncoming(FExt, FExtBB);
1124 return ShadowPhi;
1125}
1126
1127Value *NumericalStabilitySanitizer::handleTrunc(const FPTruncInst &Trunc,
1128 Type *VT, Type *ExtendedVT,
1129 const ValueToShadowMap &Map,
1130 IRBuilder<> &Builder) {
1131 Value *OrigSource = Trunc.getOperand(0);
1132 Type *OrigSourceTy = OrigSource->getType();
1133 Type *ExtendedSourceTy = Config.getExtendedFPType(OrigSourceTy);
1134
1135 // When truncating:
1136 // - (A) If the source has a shadow, we truncate from the shadow, else we
1137 // truncate from the original source.
1138 // - (B) If the shadow of the source is larger than the shadow of the dest,
1139 // we still need a truncate. Else, the shadow of the source is the same
1140 // type as the shadow of the dest (because mappings are non-decreasing), so
1141 // we don't need to emit a truncate.
1142 // Examples,
1143 // with a mapping of {f32->f64;f64->f80;f80->f128}
1144 // fptrunc double %1 to float -> fptrunc x86_fp80 s(%1) to double
1145 // fptrunc x86_fp80 %1 to float -> fptrunc fp128 s(%1) to double
1146 // fptrunc fp128 %1 to float -> fptrunc fp128 %1 to double
1147 // fptrunc x86_fp80 %1 to double -> x86_fp80 s(%1)
1148 // fptrunc fp128 %1 to double -> fptrunc fp128 %1 to x86_fp80
1149 // fptrunc fp128 %1 to x86_fp80 -> fp128 %1
1150 // with a mapping of {f32->f64;f64->f128;f80->f128}
1151 // fptrunc double %1 to float -> fptrunc fp128 s(%1) to double
1152 // fptrunc x86_fp80 %1 to float -> fptrunc fp128 s(%1) to double
1153 // fptrunc fp128 %1 to float -> fptrunc fp128 %1 to double
1154 // fptrunc x86_fp80 %1 to double -> fp128 %1
1155 // fptrunc fp128 %1 to double -> fp128 %1
1156 // fptrunc fp128 %1 to x86_fp80 -> fp128 %1
1157 // with a mapping of {f32->f32;f64->f32;f80->f64}
1158 // fptrunc double %1 to float -> float s(%1)
1159 // fptrunc x86_fp80 %1 to float -> fptrunc double s(%1) to float
1160 // fptrunc fp128 %1 to float -> fptrunc fp128 %1 to float
1161 // fptrunc x86_fp80 %1 to double -> fptrunc double s(%1) to float
1162 // fptrunc fp128 %1 to double -> fptrunc fp128 %1 to float
1163 // fptrunc fp128 %1 to x86_fp80 -> fptrunc fp128 %1 to double
1164
1165 // See (A) above.
1166 Value *Source = ExtendedSourceTy ? Map.getShadow(OrigSource) : OrigSource;
1167 Type *SourceTy = ExtendedSourceTy ? ExtendedSourceTy : OrigSourceTy;
1168 // See (B) above.
1169 if (SourceTy == ExtendedVT)
1170 return Source;
1171
1172 return Builder.CreateFPTrunc(Source, ExtendedVT);
1173}
1174
1175Value *NumericalStabilitySanitizer::handleExt(const FPExtInst &Ext, Type *VT,
1176 Type *ExtendedVT,
1177 const ValueToShadowMap &Map,
1178 IRBuilder<> &Builder) {
1179 Value *OrigSource = Ext.getOperand(0);
1180 Type *OrigSourceTy = OrigSource->getType();
1181 Type *ExtendedSourceTy = Config.getExtendedFPType(OrigSourceTy);
1182 // When extending:
1183 // - (A) If the source has a shadow, we extend from the shadow, else we
1184 // extend from the original source.
1185 // - (B) If the shadow of the dest is larger than the shadow of the source,
1186 // we still need an extend. Else, the shadow of the source is the same
1187 // type as the shadow of the dest (because mappings are non-decreasing), so
1188 // we don't need to emit an extend.
1189 // Examples,
1190 // with a mapping of {f32->f64;f64->f80;f80->f128}
1191 // fpext half %1 to float -> fpext half %1 to double
1192 // fpext half %1 to double -> fpext half %1 to x86_fp80
1193 // fpext half %1 to x86_fp80 -> fpext half %1 to fp128
1194 // fpext float %1 to double -> double s(%1)
1195 // fpext float %1 to x86_fp80 -> fpext double s(%1) to fp128
1196 // fpext double %1 to x86_fp80 -> fpext x86_fp80 s(%1) to fp128
1197 // with a mapping of {f32->f64;f64->f128;f80->f128}
1198 // fpext half %1 to float -> fpext half %1 to double
1199 // fpext half %1 to double -> fpext half %1 to fp128
1200 // fpext half %1 to x86_fp80 -> fpext half %1 to fp128
1201 // fpext float %1 to double -> fpext double s(%1) to fp128
1202 // fpext float %1 to x86_fp80 -> fpext double s(%1) to fp128
1203 // fpext double %1 to x86_fp80 -> fp128 s(%1)
1204 // with a mapping of {f32->f32;f64->f32;f80->f64}
1205 // fpext half %1 to float -> fpext half %1 to float
1206 // fpext half %1 to double -> fpext half %1 to float
1207 // fpext half %1 to x86_fp80 -> fpext half %1 to double
1208 // fpext float %1 to double -> s(%1)
1209 // fpext float %1 to x86_fp80 -> fpext float s(%1) to double
1210 // fpext double %1 to x86_fp80 -> fpext float s(%1) to double
1211
1212 // See (A) above.
1213 Value *Source = ExtendedSourceTy ? Map.getShadow(OrigSource) : OrigSource;
1214 Type *SourceTy = ExtendedSourceTy ? ExtendedSourceTy : OrigSourceTy;
1215 // See (B) above.
1216 if (SourceTy == ExtendedVT)
1217 return Source;
1218
1219 return Builder.CreateFPExt(Source, ExtendedVT);
1220}
1221
1222namespace {
1223// TODO: This should be tablegen-ed.
1224struct KnownIntrinsic {
1225 struct WidenedIntrinsic {
1226 const char *NarrowName;
1227 Intrinsic::ID ID; // wide id.
1228 using FnTypeFactory = FunctionType *(*)(LLVMContext &);
1229 FnTypeFactory MakeFnTy;
1230 };
1231
1232 static const char *get(LibFunc LFunc);
1233
1234 // Given an intrinsic with an `FT` argument, try to find a wider intrinsic
1235 // that applies the same operation on the shadow argument.
1236 // Options are:
1237 // - pass in the ID and full function type,
1238 // - pass in the name, which includes the function type through mangling.
1239 static const WidenedIntrinsic *widen(StringRef Name);
1240
1241private:
1242 struct LFEntry {
1243 LibFunc LFunc;
1244 const char *IntrinsicName;
1245 };
1246 static const LFEntry kLibfuncIntrinsics[];
1247
1248 static const WidenedIntrinsic kWidenedIntrinsics[];
1249};
1250} // namespace
1251
1255
1260
1265
1271
1276
1282
1289
1296
1297const KnownIntrinsic::WidenedIntrinsic KnownIntrinsic::kWidenedIntrinsics[] = {
1298 // TODO: Right now we ignore vector intrinsics.
1299 // This is hard because we have to model the semantics of the intrinsics,
1300 // e.g. llvm.x86.sse2.min.sd means extract first element, min, insert back.
1301 // Intrinsics that take any non-vector FT types:
1302 // NOTE: Right now because of
1303 // https://github.com/llvm/llvm-project/issues/44744
1304 // for f128 we need to use makeX86FP80X86FP80 (go to a lower precision and
1305 // come back).
1306 {"llvm.sqrt.f32", Intrinsic::sqrt, makeDoubleDouble},
1307 {"llvm.sqrt.f64", Intrinsic::sqrt, makeX86FP80X86FP80},
1308 {"llvm.sqrt.f80", Intrinsic::sqrt, makeX86FP80X86FP80},
1309 {"llvm.powi.f32", Intrinsic::powi, makeDoubleDoubleI32},
1310 {"llvm.powi.f64", Intrinsic::powi, makeX86FP80X86FP80I32},
1311 {"llvm.powi.f80", Intrinsic::powi, makeX86FP80X86FP80I32},
1312 {"llvm.sin.f32", Intrinsic::sin, makeDoubleDouble},
1313 {"llvm.sin.f64", Intrinsic::sin, makeX86FP80X86FP80},
1314 {"llvm.sin.f80", Intrinsic::sin, makeX86FP80X86FP80},
1315 {"llvm.cos.f32", Intrinsic::cos, makeDoubleDouble},
1316 {"llvm.cos.f64", Intrinsic::cos, makeX86FP80X86FP80},
1317 {"llvm.cos.f80", Intrinsic::cos, makeX86FP80X86FP80},
1318 {"llvm.pow.f32", Intrinsic::pow, makeDoubleDoubleDouble},
1319 {"llvm.pow.f64", Intrinsic::pow, makeX86FP80X86FP80X86FP80},
1320 {"llvm.pow.f80", Intrinsic::pow, makeX86FP80X86FP80X86FP80},
1321 {"llvm.exp.f32", Intrinsic::exp, makeDoubleDouble},
1322 {"llvm.exp.f64", Intrinsic::exp, makeX86FP80X86FP80},
1323 {"llvm.exp.f80", Intrinsic::exp, makeX86FP80X86FP80},
1324 {"llvm.exp2.f32", Intrinsic::exp2, makeDoubleDouble},
1325 {"llvm.exp2.f64", Intrinsic::exp2, makeX86FP80X86FP80},
1326 {"llvm.exp2.f80", Intrinsic::exp2, makeX86FP80X86FP80},
1327 {"llvm.log.f32", Intrinsic::log, makeDoubleDouble},
1328 {"llvm.log.f64", Intrinsic::log, makeX86FP80X86FP80},
1329 {"llvm.log.f80", Intrinsic::log, makeX86FP80X86FP80},
1330 {"llvm.log10.f32", Intrinsic::log10, makeDoubleDouble},
1331 {"llvm.log10.f64", Intrinsic::log10, makeX86FP80X86FP80},
1332 {"llvm.log10.f80", Intrinsic::log10, makeX86FP80X86FP80},
1333 {"llvm.log2.f32", Intrinsic::log2, makeDoubleDouble},
1334 {"llvm.log2.f64", Intrinsic::log2, makeX86FP80X86FP80},
1335 {"llvm.log2.f80", Intrinsic::log2, makeX86FP80X86FP80},
1336 {"llvm.fma.f32", Intrinsic::fma, makeDoubleDoubleDoubleDouble},
1337 {"llvm.fma.f64", Intrinsic::fma, makeX86FP80X86FP80X86FP80X86FP80},
1338 {"llvm.fma.f80", Intrinsic::fma, makeX86FP80X86FP80X86FP80X86FP80},
1339 {"llvm.fmuladd.f32", Intrinsic::fmuladd, makeDoubleDoubleDoubleDouble},
1340 {"llvm.fmuladd.f64", Intrinsic::fmuladd, makeX86FP80X86FP80X86FP80X86FP80},
1341 {"llvm.fmuladd.f80", Intrinsic::fmuladd, makeX86FP80X86FP80X86FP80X86FP80},
1342 {"llvm.fabs.f32", Intrinsic::fabs, makeDoubleDouble},
1343 {"llvm.fabs.f64", Intrinsic::fabs, makeX86FP80X86FP80},
1344 {"llvm.fabs.f80", Intrinsic::fabs, makeX86FP80X86FP80},
1345 {"llvm.minnum.f32", Intrinsic::minnum, makeDoubleDoubleDouble},
1346 {"llvm.minnum.f64", Intrinsic::minnum, makeX86FP80X86FP80X86FP80},
1347 {"llvm.minnum.f80", Intrinsic::minnum, makeX86FP80X86FP80X86FP80},
1348 {"llvm.maxnum.f32", Intrinsic::maxnum, makeDoubleDoubleDouble},
1349 {"llvm.maxnum.f64", Intrinsic::maxnum, makeX86FP80X86FP80X86FP80},
1350 {"llvm.maxnum.f80", Intrinsic::maxnum, makeX86FP80X86FP80X86FP80},
1351 {"llvm.minimum.f32", Intrinsic::minimum, makeDoubleDoubleDouble},
1352 {"llvm.minimum.f64", Intrinsic::minimum, makeX86FP80X86FP80X86FP80},
1353 {"llvm.minimum.f80", Intrinsic::minimum, makeX86FP80X86FP80X86FP80},
1354 {"llvm.maximum.f32", Intrinsic::maximum, makeDoubleDoubleDouble},
1355 {"llvm.maximum.f64", Intrinsic::maximum, makeX86FP80X86FP80X86FP80},
1356 {"llvm.maximum.f80", Intrinsic::maximum, makeX86FP80X86FP80X86FP80},
1357 {"llvm.minimumnum.f32", Intrinsic::minimumnum, makeDoubleDoubleDouble},
1358 {"llvm.minimumnum.f64", Intrinsic::minimumnum, makeX86FP80X86FP80X86FP80},
1359 {"llvm.minimumnum.f80", Intrinsic::minimumnum, makeX86FP80X86FP80X86FP80},
1360 {"llvm.maximumnum.f32", Intrinsic::maximumnum, makeDoubleDoubleDouble},
1361 {"llvm.maximumnum.f64", Intrinsic::maximumnum, makeX86FP80X86FP80X86FP80},
1362 {"llvm.maximumnum.f80", Intrinsic::maximumnum, makeX86FP80X86FP80X86FP80},
1363 {"llvm.copysign.f32", Intrinsic::copysign, makeDoubleDoubleDouble},
1364 {"llvm.copysign.f64", Intrinsic::copysign, makeX86FP80X86FP80X86FP80},
1365 {"llvm.copysign.f80", Intrinsic::copysign, makeX86FP80X86FP80X86FP80},
1366 {"llvm.floor.f32", Intrinsic::floor, makeDoubleDouble},
1367 {"llvm.floor.f64", Intrinsic::floor, makeX86FP80X86FP80},
1368 {"llvm.floor.f80", Intrinsic::floor, makeX86FP80X86FP80},
1369 {"llvm.ceil.f32", Intrinsic::ceil, makeDoubleDouble},
1370 {"llvm.ceil.f64", Intrinsic::ceil, makeX86FP80X86FP80},
1371 {"llvm.ceil.f80", Intrinsic::ceil, makeX86FP80X86FP80},
1372 {"llvm.trunc.f32", Intrinsic::trunc, makeDoubleDouble},
1373 {"llvm.trunc.f64", Intrinsic::trunc, makeX86FP80X86FP80},
1374 {"llvm.trunc.f80", Intrinsic::trunc, makeX86FP80X86FP80},
1375 {"llvm.rint.f32", Intrinsic::rint, makeDoubleDouble},
1376 {"llvm.rint.f64", Intrinsic::rint, makeX86FP80X86FP80},
1377 {"llvm.rint.f80", Intrinsic::rint, makeX86FP80X86FP80},
1378 {"llvm.nearbyint.f32", Intrinsic::nearbyint, makeDoubleDouble},
1379 {"llvm.nearbyint.f64", Intrinsic::nearbyint, makeX86FP80X86FP80},
1380 {"llvm.nearbyint.f80", Intrinsic::nearbyint, makeX86FP80X86FP80},
1381 {"llvm.round.f32", Intrinsic::round, makeDoubleDouble},
1382 {"llvm.round.f64", Intrinsic::round, makeX86FP80X86FP80},
1383 {"llvm.round.f80", Intrinsic::round, makeX86FP80X86FP80},
1384};
1385
1386const KnownIntrinsic::LFEntry KnownIntrinsic::kLibfuncIntrinsics[] = {
1387 {LibFunc_sqrtf, "llvm.sqrt.f32"},
1388 {LibFunc_sqrt, "llvm.sqrt.f64"},
1389 {LibFunc_sqrtl, "llvm.sqrt.f80"},
1390 {LibFunc_sinf, "llvm.sin.f32"},
1391 {LibFunc_sin, "llvm.sin.f64"},
1392 {LibFunc_sinl, "llvm.sin.f80"},
1393 {LibFunc_cosf, "llvm.cos.f32"},
1394 {LibFunc_cos, "llvm.cos.f64"},
1395 {LibFunc_cosl, "llvm.cos.f80"},
1396 {LibFunc_powf, "llvm.pow.f32"},
1397 {LibFunc_pow, "llvm.pow.f64"},
1398 {LibFunc_powl, "llvm.pow.f80"},
1399 {LibFunc_expf, "llvm.exp.f32"},
1400 {LibFunc_exp, "llvm.exp.f64"},
1401 {LibFunc_expl, "llvm.exp.f80"},
1402 {LibFunc_exp2f, "llvm.exp2.f32"},
1403 {LibFunc_exp2, "llvm.exp2.f64"},
1404 {LibFunc_exp2l, "llvm.exp2.f80"},
1405 {LibFunc_logf, "llvm.log.f32"},
1406 {LibFunc_log, "llvm.log.f64"},
1407 {LibFunc_logl, "llvm.log.f80"},
1408 {LibFunc_log10f, "llvm.log10.f32"},
1409 {LibFunc_log10, "llvm.log10.f64"},
1410 {LibFunc_log10l, "llvm.log10.f80"},
1411 {LibFunc_log2f, "llvm.log2.f32"},
1412 {LibFunc_log2, "llvm.log2.f64"},
1413 {LibFunc_log2l, "llvm.log2.f80"},
1414 {LibFunc_fabsf, "llvm.fabs.f32"},
1415 {LibFunc_fabs, "llvm.fabs.f64"},
1416 {LibFunc_fabsl, "llvm.fabs.f80"},
1417 {LibFunc_copysignf, "llvm.copysign.f32"},
1418 {LibFunc_copysign, "llvm.copysign.f64"},
1419 {LibFunc_copysignl, "llvm.copysign.f80"},
1420 {LibFunc_floorf, "llvm.floor.f32"},
1421 {LibFunc_floor, "llvm.floor.f64"},
1422 {LibFunc_floorl, "llvm.floor.f80"},
1423 {LibFunc_fmaxf, "llvm.maxnum.f32"},
1424 {LibFunc_fmax, "llvm.maxnum.f64"},
1425 {LibFunc_fmaxl, "llvm.maxnum.f80"},
1426 {LibFunc_fminf, "llvm.minnum.f32"},
1427 {LibFunc_fmin, "llvm.minnum.f64"},
1428 {LibFunc_fminl, "llvm.minnum.f80"},
1429 {LibFunc_fmaximum_numf, "llvm.maximumnum.f32"},
1430 {LibFunc_fmaximum_num, "llvm.maximumnum.f64"},
1431 {LibFunc_fmaximum_numl, "llvm.maximumnum.f80"},
1432 {LibFunc_fminimum_numf, "llvm.minimumnum.f32"},
1433 {LibFunc_fminimum_num, "llvm.minimumnum.f64"},
1434 {LibFunc_fminimum_numl, "llvm.minimumnum.f80"},
1435 {LibFunc_ceilf, "llvm.ceil.f32"},
1436 {LibFunc_ceil, "llvm.ceil.f64"},
1437 {LibFunc_ceill, "llvm.ceil.f80"},
1438 {LibFunc_truncf, "llvm.trunc.f32"},
1439 {LibFunc_trunc, "llvm.trunc.f64"},
1440 {LibFunc_truncl, "llvm.trunc.f80"},
1441 {LibFunc_rintf, "llvm.rint.f32"},
1442 {LibFunc_rint, "llvm.rint.f64"},
1443 {LibFunc_rintl, "llvm.rint.f80"},
1444 {LibFunc_nearbyintf, "llvm.nearbyint.f32"},
1445 {LibFunc_nearbyint, "llvm.nearbyint.f64"},
1446 {LibFunc_nearbyintl, "llvm.nearbyint.f80"},
1447 {LibFunc_roundf, "llvm.round.f32"},
1448 {LibFunc_round, "llvm.round.f64"},
1449 {LibFunc_roundl, "llvm.round.f80"},
1450};
1451
1452const char *KnownIntrinsic::get(LibFunc LFunc) {
1453 for (const auto &E : kLibfuncIntrinsics) {
1454 if (E.LFunc == LFunc)
1455 return E.IntrinsicName;
1456 }
1457 return nullptr;
1458}
1459
1460const KnownIntrinsic::WidenedIntrinsic *KnownIntrinsic::widen(StringRef Name) {
1461 for (const auto &E : kWidenedIntrinsics) {
1462 if (E.NarrowName == Name)
1463 return &E;
1464 }
1465 return nullptr;
1466}
1467
1468// Returns the name of the LLVM intrinsic corresponding to the given function.
1469static const char *getIntrinsicFromLibfunc(Function &Fn, Type *VT,
1470 const TargetLibraryInfo &TLI) {
1471 LibFunc LFunc = TLI.getLibFunc(Fn);
1472 if (LFunc == NotLibFunc)
1473 return nullptr;
1474
1475 if (const char *Name = KnownIntrinsic::get(LFunc))
1476 return Name;
1477
1478 LLVM_DEBUG(errs() << "TODO: LibFunc: " << TLI.getName(LFunc) << "\n");
1479 return nullptr;
1480}
1481
1482// Try to handle a known function call.
1483Value *NumericalStabilitySanitizer::maybeHandleKnownCallBase(
1484 CallBase &Call, Type *VT, Type *ExtendedVT, const TargetLibraryInfo &TLI,
1485 const ValueToShadowMap &Map, IRBuilder<> &Builder) {
1487 if (Fn == nullptr)
1488 return nullptr;
1489
1490 Intrinsic::ID WidenedId = Intrinsic::ID();
1491 FunctionType *WidenedFnTy = nullptr;
1492 if (const auto ID = Fn->getIntrinsicID()) {
1493 const auto *Widened = KnownIntrinsic::widen(Fn->getName());
1494 if (Widened) {
1495 WidenedId = Widened->ID;
1496 WidenedFnTy = Widened->MakeFnTy(Context);
1497 } else {
1498 // If we don't know how to widen the intrinsic, we have no choice but to
1499 // call the non-wide version on a truncated shadow and extend again
1500 // afterwards.
1501 WidenedId = ID;
1502 WidenedFnTy = Fn->getFunctionType();
1503 }
1504 } else if (const char *Name = getIntrinsicFromLibfunc(*Fn, VT, TLI)) {
1505 // We might have a call to a library function that we can replace with a
1506 // wider Intrinsic.
1507 const auto *Widened = KnownIntrinsic::widen(Name);
1508 assert(Widened && "make sure KnownIntrinsic entries are consistent");
1509 WidenedId = Widened->ID;
1510 WidenedFnTy = Widened->MakeFnTy(Context);
1511 } else {
1512 // This is not a known library function or intrinsic.
1513 return nullptr;
1514 }
1515
1516 // Check that the widened intrinsic is valid.
1517 SmallVector<Type *, 4> OverloadTys;
1518 [[maybe_unused]] bool IsValid =
1519 Intrinsic::isSignatureValid(WidenedId, WidenedFnTy, OverloadTys);
1520 assert(IsValid && "invalid widened intrinsic");
1521 // For known intrinsic functions, we create a second call to the same
1522 // intrinsic with a different type.
1523 SmallVector<Value *, 4> Args;
1524 // The last operand is the intrinsic itself, skip it.
1525 for (unsigned I = 0, E = Call.getNumOperands() - 1; I < E; ++I) {
1526 Value *Arg = Call.getOperand(I);
1527 Type *OrigArgTy = Arg->getType();
1528 Type *IntrinsicArgTy = WidenedFnTy->getParamType(I);
1529 if (OrigArgTy == IntrinsicArgTy) {
1530 Args.push_back(Arg); // The arg is passed as is.
1531 continue;
1532 }
1533 Type *ShadowArgTy = Config.getExtendedFPType(Arg->getType());
1534 assert(ShadowArgTy &&
1535 "don't know how to get the shadow value for a non-FT");
1536 Value *Shadow = Map.getShadow(Arg);
1537 if (ShadowArgTy == IntrinsicArgTy) {
1538 // The shadow is the right type for the intrinsic.
1539 assert(Shadow->getType() == ShadowArgTy);
1540 Args.push_back(Shadow);
1541 continue;
1542 }
1543 // There is no intrinsic with his level of precision, truncate the shadow.
1544 Args.push_back(Builder.CreateFPTrunc(Shadow, IntrinsicArgTy));
1545 }
1546 Value *IntrinsicCall = Builder.CreateIntrinsic(WidenedId, OverloadTys, Args);
1547 return WidenedFnTy->getReturnType() == ExtendedVT
1548 ? IntrinsicCall
1549 : Builder.CreateFPExt(IntrinsicCall, ExtendedVT);
1550}
1551
1552// Handle a CallBase, i.e. a function call, an inline asm sequence, or an
1553// invoke.
1554Value *NumericalStabilitySanitizer::handleCallBase(CallBase &Call, Type *VT,
1555 Type *ExtendedVT,
1556 const TargetLibraryInfo &TLI,
1557 const ValueToShadowMap &Map,
1558 IRBuilder<> &Builder) {
1559 // We cannot look inside inline asm, just expand the result again.
1560 if (Call.isInlineAsm())
1561 return Builder.CreateFPExt(&Call, ExtendedVT);
1562
1563 // Intrinsics and library functions (e.g. sin, exp) are handled
1564 // specifically, because we know their semantics and can do better than
1565 // blindly calling them (e.g. compute the sinus in the actual shadow domain).
1566 if (Value *V =
1567 maybeHandleKnownCallBase(Call, VT, ExtendedVT, TLI, Map, Builder))
1568 return V;
1569
1570 // If the return tag matches that of the called function, read the extended
1571 // return value from the shadow ret ptr. Else, just extend the return value.
1572 Value *L =
1573 Builder.CreateLoad(IntptrTy, NsanShadowRetTag, /*isVolatile=*/false);
1574 Value *HasShadowRet = Builder.CreateICmpEQ(
1575 L, Builder.CreatePtrToInt(Call.getCalledOperand(), IntptrTy));
1576
1577 Value *ShadowRetVal = Builder.CreateLoad(
1578 ExtendedVT,
1579 Builder.CreateConstGEP2_64(NsanShadowRetType, NsanShadowRetPtr, 0, 0),
1580 /*isVolatile=*/false);
1581 Value *Shadow = Builder.CreateSelect(HasShadowRet, ShadowRetVal,
1582 Builder.CreateFPExt(&Call, ExtendedVT));
1583 ++NumInstrumentedFTCalls;
1584 return Shadow;
1585}
1586
1587// Creates a shadow value for the given FT value. At that point all operands are
1588// guaranteed to be available.
1589Value *NumericalStabilitySanitizer::createShadowValueWithOperandsAvailable(
1590 Instruction &Inst, const TargetLibraryInfo &TLI,
1591 const ValueToShadowMap &Map) {
1592 Type *VT = Inst.getType();
1593 Type *ExtendedVT = Config.getExtendedFPType(VT);
1594 assert(ExtendedVT != nullptr && "trying to create a shadow for a non-FT");
1595
1596 if (auto *Load = dyn_cast<LoadInst>(&Inst))
1597 return handleLoad(*Load, VT, ExtendedVT);
1598
1599 if (auto *Call = dyn_cast<CallInst>(&Inst)) {
1600 // Insert after the call.
1601 BasicBlock::iterator It(Inst);
1602 IRBuilder<> Builder(++It);
1604 return handleCallBase(*Call, VT, ExtendedVT, TLI, Map, Builder);
1605 }
1606
1607 if (auto *Invoke = dyn_cast<InvokeInst>(&Inst)) {
1608 // The Invoke terminates the basic block, create a new basic block in
1609 // between the successful invoke and the next block.
1610 BasicBlock *InvokeBB = Invoke->getParent();
1611 BasicBlock *NextBB = Invoke->getNormalDest();
1612 BasicBlock *NewBB =
1613 BasicBlock::Create(Context, "", NextBB->getParent(), NextBB);
1614 Inst.replaceSuccessorWith(NextBB, NewBB);
1615
1616 IRBuilder<> Builder(NewBB);
1617 Builder.SetCurrentDebugLocation(Invoke->getDebugLoc());
1618 Value *Shadow = handleCallBase(*Invoke, VT, ExtendedVT, TLI, Map, Builder);
1619 Builder.CreateBr(NextBB);
1620 NewBB->replaceSuccessorsPhiUsesWith(InvokeBB, NewBB);
1621 return Shadow;
1622 }
1623
1624 IRBuilder<> Builder(Inst.getNextNode());
1625 Builder.SetCurrentDebugLocation(Inst.getDebugLoc());
1626
1627 if (auto *Trunc = dyn_cast<FPTruncInst>(&Inst))
1628 return handleTrunc(*Trunc, VT, ExtendedVT, Map, Builder);
1629 if (auto *Ext = dyn_cast<FPExtInst>(&Inst))
1630 return handleExt(*Ext, VT, ExtendedVT, Map, Builder);
1631
1632 if (auto *UnaryOp = dyn_cast<UnaryOperator>(&Inst))
1633 return Builder.CreateUnOp(UnaryOp->getOpcode(),
1634 Map.getShadow(UnaryOp->getOperand(0)));
1635
1636 if (auto *BinOp = dyn_cast<BinaryOperator>(&Inst))
1637 return Builder.CreateBinOp(BinOp->getOpcode(),
1638 Map.getShadow(BinOp->getOperand(0)),
1639 Map.getShadow(BinOp->getOperand(1)));
1640
1641 if (isa<UIToFPInst>(&Inst) || isa<SIToFPInst>(&Inst)) {
1642 auto *Cast = cast<CastInst>(&Inst);
1643 return Builder.CreateCast(Cast->getOpcode(), Cast->getOperand(0),
1644 ExtendedVT);
1645 }
1646
1647 if (auto *S = dyn_cast<SelectInst>(&Inst))
1648 return Builder.CreateSelect(S->getCondition(),
1649 Map.getShadow(S->getTrueValue()),
1650 Map.getShadow(S->getFalseValue()));
1651
1652 if (auto *Freeze = dyn_cast<FreezeInst>(&Inst))
1653 return Builder.CreateFreeze(Map.getShadow(Freeze->getOperand(0)));
1654
1655 if (auto *Extract = dyn_cast<ExtractElementInst>(&Inst))
1656 return Builder.CreateExtractElement(
1657 Map.getShadow(Extract->getVectorOperand()), Extract->getIndexOperand());
1658
1659 if (auto *Insert = dyn_cast<InsertElementInst>(&Inst))
1660 return Builder.CreateInsertElement(Map.getShadow(Insert->getOperand(0)),
1661 Map.getShadow(Insert->getOperand(1)),
1662 Insert->getOperand(2));
1663
1664 if (auto *Shuffle = dyn_cast<ShuffleVectorInst>(&Inst))
1665 return Builder.CreateShuffleVector(Map.getShadow(Shuffle->getOperand(0)),
1666 Map.getShadow(Shuffle->getOperand(1)),
1667 Shuffle->getShuffleMask());
1668 // TODO: We could make aggregate object first class citizens. For now we
1669 // just extend the extracted value.
1670 if (auto *Extract = dyn_cast<ExtractValueInst>(&Inst))
1671 return Builder.CreateFPExt(Extract, ExtendedVT);
1672
1673 if (auto *BC = dyn_cast<BitCastInst>(&Inst))
1674 return Builder.CreateFPExt(BC, ExtendedVT);
1675
1676 report_fatal_error("Unimplemented support for " +
1677 Twine(Inst.getOpcodeName()));
1678}
1679
1680// Creates a shadow value for an instruction that defines a value of FT type.
1681// FT operands that do not already have shadow values are created recursively.
1682// The DFS is guaranteed to not loop as phis and arguments already have
1683// shadows.
1684void NumericalStabilitySanitizer::maybeCreateShadowValue(
1685 Instruction &Root, const TargetLibraryInfo &TLI, ValueToShadowMap &Map) {
1686 Type *VT = Root.getType();
1687 Type *ExtendedVT = Config.getExtendedFPType(VT);
1688 if (ExtendedVT == nullptr)
1689 return; // Not an FT value.
1690
1691 if (Map.hasShadow(&Root))
1692 return; // Shadow already exists.
1693
1694 assert(!isa<PHINode>(Root) && "phi nodes should already have shadows");
1695
1696 std::vector<Instruction *> DfsStack(1, &Root);
1697 while (!DfsStack.empty()) {
1698 // Ensure that all operands to the instruction have shadows before
1699 // proceeding.
1700 Instruction *I = DfsStack.back();
1701 // The shadow for the instruction might have been created deeper in the DFS,
1702 // see `forward_use_with_two_uses` test.
1703 if (Map.hasShadow(I)) {
1704 DfsStack.pop_back();
1705 continue;
1706 }
1707
1708 bool MissingShadow = false;
1709 for (Value *Op : I->operands()) {
1710 Type *VT = Op->getType();
1711 if (!Config.getExtendedFPType(VT))
1712 continue; // Not an FT value.
1713 if (Map.hasShadow(Op))
1714 continue; // Shadow is already available.
1715 MissingShadow = true;
1716 DfsStack.push_back(cast<Instruction>(Op));
1717 }
1718 if (MissingShadow)
1719 continue; // Process operands and come back to this instruction later.
1720
1721 // All operands have shadows. Create a shadow for the current value.
1722 Value *Shadow = createShadowValueWithOperandsAvailable(*I, TLI, Map);
1723 Map.setShadow(*I, *Shadow);
1724 DfsStack.pop_back();
1725 }
1726}
1727
1728// A floating-point store needs its value and type written to shadow memory.
1729void NumericalStabilitySanitizer::propagateFTStore(
1730 StoreInst &Store, Type *VT, Type *ExtendedVT, const ValueToShadowMap &Map) {
1731 Value *StoredValue = Store.getValueOperand();
1732 IRBuilder<> Builder(&Store);
1733 Builder.SetCurrentDebugLocation(Store.getDebugLoc());
1734 const auto Extents = getMemoryExtentsOrDie(VT);
1735 Value *ShadowPtr = Builder.CreateCall(
1736 NsanGetShadowPtrForStore[Extents.ValueType],
1737 {Store.getPointerOperand(), ConstantInt::get(IntptrTy, Extents.NumElts)});
1738
1739 Value *StoredShadow = Map.getShadow(StoredValue);
1740 if (!Store.getParent()->getParent()->hasOptNone()) {
1741 // Only check stores when optimizing, because non-optimized code generates
1742 // too many stores to the stack, creating false positives.
1743 if (Opts.nsan_check_stores) {
1744 StoredShadow = emitCheck(StoredValue, StoredShadow, Builder,
1745 CheckLoc::makeStore(Store.getPointerOperand()));
1746 ++NumInstrumentedFTStores;
1747 }
1748 }
1749
1750 Builder.CreateAlignedStore(StoredShadow, ShadowPtr, Align(1),
1751 Store.isVolatile());
1752}
1753
1754// A non-ft store needs to invalidate shadow memory. Exceptions are:
1755// - memory transfers of floating-point data through other pointer types (llvm
1756// optimization passes transform `*(float*)a = *(float*)b` into
1757// `*(i32*)a = *(i32*)b` ). These have the same semantics as memcpy.
1758// - Writes of FT-sized constants. LLVM likes to do float stores as bitcasted
1759// ints. Note that this is not really necessary because if the value is
1760// unknown the framework will re-extend it on load anyway. It just felt
1761// easier to debug tests with vectors of FTs.
1762void NumericalStabilitySanitizer::propagateNonFTStore(
1763 StoreInst &Store, Type *VT, const ValueToShadowMap &Map) {
1764 Value *PtrOp = Store.getPointerOperand();
1765 IRBuilder<> Builder(Store.getNextNode());
1766 Builder.SetCurrentDebugLocation(Store.getDebugLoc());
1767 Value *Dst = PtrOp;
1768 TypeSize SlotSize = DL.getTypeStoreSize(VT);
1769 assert(!SlotSize.isScalable() && "unsupported");
1770 const auto LoadSizeBytes = SlotSize.getFixedValue();
1771 Value *ValueSize = Constant::getIntegerValue(
1772 IntptrTy, APInt(IntptrTy->getPrimitiveSizeInBits(), LoadSizeBytes));
1773
1774 ++NumInstrumentedNonFTStores;
1775 Value *StoredValue = Store.getValueOperand();
1776 if (LoadInst *Load = dyn_cast<LoadInst>(StoredValue)) {
1777 // TODO: Handle the case when the value is from a phi.
1778 // This is a memory transfer with memcpy semantics. Copy the type and
1779 // value from the source. Note that we cannot use __nsan_copy_values()
1780 // here, because that will not work when there is a write to memory in
1781 // between the load and the store, e.g. in the case of a swap.
1782 Type *ShadowTypeIntTy = Type::getIntNTy(Context, 8 * LoadSizeBytes);
1783 Type *ShadowValueIntTy =
1784 Type::getIntNTy(Context, 8 * kShadowScale * LoadSizeBytes);
1785 IRBuilder<> LoadBuilder(Load->getNextNode());
1786 Builder.SetCurrentDebugLocation(Store.getDebugLoc());
1787 Value *LoadSrc = Load->getPointerOperand();
1788 // Read the shadow type and value at load time. The type has the same size
1789 // as the FT value, the value has twice its size.
1790 // TODO: cache them to avoid re-creating them when a load is used by
1791 // several stores. Maybe create them like the FT shadows when a load is
1792 // encountered.
1793 Value *RawShadowType = LoadBuilder.CreateAlignedLoad(
1794 ShadowTypeIntTy,
1795 LoadBuilder.CreateCall(NsanGetRawShadowTypePtr, {LoadSrc}), Align(1),
1796 /*isVolatile=*/false);
1797 Value *RawShadowValue = LoadBuilder.CreateAlignedLoad(
1798 ShadowValueIntTy,
1799 LoadBuilder.CreateCall(NsanGetRawShadowPtr, {LoadSrc}), Align(1),
1800 /*isVolatile=*/false);
1801
1802 // Write back the shadow type and value at store time.
1803 Builder.CreateAlignedStore(
1804 RawShadowType, Builder.CreateCall(NsanGetRawShadowTypePtr, {Dst}),
1805 Align(1),
1806 /*isVolatile=*/false);
1807 Builder.CreateAlignedStore(RawShadowValue,
1808 Builder.CreateCall(NsanGetRawShadowPtr, {Dst}),
1809 Align(1),
1810 /*isVolatile=*/false);
1811
1812 ++NumInstrumentedNonFTMemcpyStores;
1813 return;
1814 }
1815 if (Constant *C; Opts.nsan_propagate_non_ft_const_stores_as_ft &&
1816 (C = dyn_cast<Constant>(StoredValue))) {
1817 // This might be a fp constant stored as an int. Bitcast and store if it has
1818 // appropriate size.
1819 Type *BitcastTy = nullptr; // The FT type to bitcast to.
1821 switch (C->getType()->getScalarSizeInBits()) {
1822 case 32:
1823 BitcastTy = Type::getFloatTy(Context);
1824 break;
1825 case 64:
1826 BitcastTy = Type::getDoubleTy(Context);
1827 break;
1828 case 80:
1829 BitcastTy = Type::getX86_FP80Ty(Context);
1830 break;
1831 default:
1832 break;
1833 }
1834
1835 if (BitcastTy)
1836 if (auto *VectorTy = dyn_cast<VectorType>(C->getType()))
1837 BitcastTy = VectorType::get(BitcastTy, VectorTy->getElementCount());
1838 }
1839 if (BitcastTy) {
1840 const MemoryExtents Extents = getMemoryExtentsOrDie(BitcastTy);
1841 Value *ShadowPtr = Builder.CreateCall(
1842 NsanGetShadowPtrForStore[Extents.ValueType],
1843 {PtrOp, ConstantInt::get(IntptrTy, Extents.NumElts)});
1844 // Bitcast the integer value to the appropriate FT type and extend to 2FT.
1845 Type *ExtVT = Config.getExtendedFPType(BitcastTy);
1846 Value *Shadow =
1847 Builder.CreateFPExt(Builder.CreateBitCast(C, BitcastTy), ExtVT);
1848 Builder.CreateAlignedStore(Shadow, ShadowPtr, Align(1),
1849 Store.isVolatile());
1850 return;
1851 }
1852 }
1853 // All other stores just reset the shadow value to unknown.
1854 Builder.CreateCall(NsanSetUnknownFns.getFallback(), {Dst, ValueSize});
1855}
1856
1857void NumericalStabilitySanitizer::propagateShadowValues(
1858 Instruction &Inst, const TargetLibraryInfo &TLI,
1859 const ValueToShadowMap &Map) {
1860 if (auto *Store = dyn_cast<StoreInst>(&Inst)) {
1861 Value *StoredValue = Store->getValueOperand();
1862 Type *VT = StoredValue->getType();
1863 Type *ExtendedVT = Config.getExtendedFPType(VT);
1864 if (ExtendedVT == nullptr)
1865 return propagateNonFTStore(*Store, VT, Map);
1866 return propagateFTStore(*Store, VT, ExtendedVT, Map);
1867 }
1868
1869 if (auto *FCmp = dyn_cast<FCmpInst>(&Inst)) {
1870 emitFCmpCheck(*FCmp, Map);
1871 return;
1872 }
1873
1874 if (auto *CB = dyn_cast<CallBase>(&Inst)) {
1875 maybeAddSuffixForNsanInterface(CB);
1876 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
1878 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&Inst)) {
1879 instrumentMemIntrinsic(MI);
1880 return;
1881 }
1882 populateShadowStack(*CB, TLI, Map);
1883 return;
1884 }
1885
1886 if (auto *RetInst = dyn_cast<ReturnInst>(&Inst)) {
1887 if (!Opts.nsan_check_ret)
1888 return;
1889
1890 Value *RV = RetInst->getReturnValue();
1891 if (RV == nullptr)
1892 return; // This is a `ret void`.
1893 Type *VT = RV->getType();
1894 Type *ExtendedVT = Config.getExtendedFPType(VT);
1895 if (ExtendedVT == nullptr)
1896 return; // Not an FT ret.
1897 Value *RVShadow = Map.getShadow(RV);
1898 IRBuilder<> Builder(RetInst);
1899
1900 RVShadow = emitCheck(RV, RVShadow, Builder, CheckLoc::makeRet());
1901 ++NumInstrumentedFTRets;
1902 // Store tag.
1903 Value *FnAddr =
1904 Builder.CreatePtrToInt(Inst.getParent()->getParent(), IntptrTy);
1905 Builder.CreateStore(FnAddr, NsanShadowRetTag);
1906 // Store value.
1907 Value *ShadowRetValPtr =
1908 Builder.CreateConstGEP2_64(NsanShadowRetType, NsanShadowRetPtr, 0, 0);
1909 Builder.CreateStore(RVShadow, ShadowRetValPtr);
1910 return;
1911 }
1912
1913 if (InsertValueInst *Insert = dyn_cast<InsertValueInst>(&Inst)) {
1914 Value *V = Insert->getOperand(1);
1915 Type *VT = V->getType();
1916 Type *ExtendedVT = Config.getExtendedFPType(VT);
1917 if (ExtendedVT == nullptr)
1918 return;
1919 IRBuilder<> Builder(Insert);
1920 emitCheck(V, Map.getShadow(V), Builder, CheckLoc::makeInsert());
1921 return;
1922 }
1923}
1924
1925// Moves fast math flags from the function to individual instructions, and
1926// removes the attribute from the function.
1927// TODO: Make this controllable with a flag.
1929 std::vector<Instruction *> &Instructions) {
1930 FastMathFlags FMF;
1931#define MOVE_FLAG(attr, setter) \
1932 if (F.getFnAttribute(attr).getValueAsString() == "true") { \
1933 F.removeFnAttr(attr); \
1934 FMF.set##setter(); \
1935 }
1936 MOVE_FLAG("no-signed-zeros-fp-math", NoSignedZeros)
1937#undef MOVE_FLAG
1938
1939 for (Instruction *I : Instructions)
1941 I->setFastMathFlags(FMF);
1942}
1943
1944bool NumericalStabilitySanitizer::sanitizeFunction(
1945 Function &F, const TargetLibraryInfo &TLI) {
1946 if (!F.hasFnAttribute(Attribute::SanitizeNumericalStability) ||
1947 F.isDeclaration())
1948 return false;
1949
1950 // This is required to prevent instrumenting call to __nsan_init from within
1951 // the module constructor.
1952 if (F.getName() == kNsanModuleCtorName)
1953 return false;
1954
1955 // The instrumentation maintains:
1956 // - for each IR value `v` of floating-point (or vector floating-point) type
1957 // FT, a shadow IR value `s(v)` with twice the precision 2FT (e.g.
1958 // double for float and f128 for double).
1959 // - A shadow memory, which stores `s(v)` for any `v` that has been stored,
1960 // along with a shadow memory tag, which stores whether the value in the
1961 // corresponding shadow memory is valid. Note that this might be
1962 // incorrect if a non-instrumented function stores to memory, or if
1963 // memory is stored to through a char pointer.
1964 // - A shadow stack, which holds `s(v)` for any floating-point argument `v`
1965 // of a call to an instrumented function. This allows
1966 // instrumented functions to retrieve the shadow values for their
1967 // arguments.
1968 // Because instrumented functions can be called from non-instrumented
1969 // functions, the stack needs to include a tag so that the instrumented
1970 // function knows whether shadow values are available for their
1971 // parameters (i.e. whether is was called by an instrumented function).
1972 // When shadow arguments are not available, they have to be recreated by
1973 // extending the precision of the non-shadow arguments to the non-shadow
1974 // value. Non-instrumented functions do not modify (or even know about) the
1975 // shadow stack. The shadow stack pointer is __nsan_shadow_args. The shadow
1976 // stack tag is __nsan_shadow_args_tag. The tag is any unique identifier
1977 // for the function (we use the address of the function). Both variables
1978 // are thread local.
1979 // Example:
1980 // calls shadow stack tag shadow stack
1981 // =======================================================================
1982 // non_instrumented_1() 0 0
1983 // |
1984 // v
1985 // instrumented_2(float a) 0 0
1986 // |
1987 // v
1988 // instrumented_3(float b, double c) &instrumented_3 s(b),s(c)
1989 // |
1990 // v
1991 // instrumented_4(float d) &instrumented_4 s(d)
1992 // |
1993 // v
1994 // non_instrumented_5(float e) &non_instrumented_5 s(e)
1995 // |
1996 // v
1997 // instrumented_6(float f) &non_instrumented_5 s(e)
1998 //
1999 // On entry, instrumented_2 checks whether the tag corresponds to its
2000 // function ptr.
2001 // Note that functions reset the tag to 0 after reading shadow parameters.
2002 // This ensures that the function does not erroneously read invalid data if
2003 // called twice in the same stack, once from an instrumented function and
2004 // once from an uninstrumented one. For example, in the following example,
2005 // resetting the tag in (A) ensures that (B) does not reuse the same the
2006 // shadow arguments (which would be incorrect).
2007 // instrumented_1(float a)
2008 // |
2009 // v
2010 // instrumented_2(float b) (A)
2011 // |
2012 // v
2013 // non_instrumented_3()
2014 // |
2015 // v
2016 // instrumented_2(float b) (B)
2017 //
2018 // - A shadow return slot. Any function that returns a floating-point value
2019 // places a shadow return value in __nsan_shadow_ret_val. Again, because
2020 // we might be calling non-instrumented functions, this value is guarded
2021 // by __nsan_shadow_ret_tag marker indicating which instrumented function
2022 // placed the value in __nsan_shadow_ret_val, so that the caller can check
2023 // that this corresponds to the callee. Both variables are thread local.
2024 //
2025 // For example, in the following example, the instrumentation in
2026 // `instrumented_1` rejects the shadow return value from `instrumented_3`
2027 // because it is not tagged as expected (`&instrumented_3` instead of
2028 // `non_instrumented_2`):
2029 //
2030 // instrumented_1()
2031 // |
2032 // v
2033 // float non_instrumented_2()
2034 // |
2035 // v
2036 // float instrumented_3()
2037 //
2038 // Calls of known math functions (sin, cos, exp, ...) are duplicated to call
2039 // their overload on the shadow type.
2040
2041 // Collect all instructions before processing, as creating shadow values
2042 // creates new instructions inside the function.
2043 std::vector<Instruction *> OriginalInstructions;
2044 for (BasicBlock &BB : F)
2045 for (Instruction &Inst : BB)
2046 OriginalInstructions.emplace_back(&Inst);
2047
2048 moveFastMathFlags(F, OriginalInstructions);
2049 ValueToShadowMap ValueToShadow(Config);
2050
2051 // In the first pass, we create shadow values for all FT function arguments
2052 // and all phis. This ensures that the DFS of the next pass does not have
2053 // any loops.
2054 std::vector<PHINode *> OriginalPhis;
2055 createShadowArguments(F, TLI, ValueToShadow);
2056 for (Instruction *I : OriginalInstructions) {
2057 if (PHINode *Phi = dyn_cast<PHINode>(I)) {
2058 if (PHINode *Shadow = maybeCreateShadowPhi(*Phi, TLI)) {
2059 OriginalPhis.push_back(Phi);
2060 ValueToShadow.setShadow(*Phi, *Shadow);
2061 }
2062 }
2063 }
2064
2065 // Create shadow values for all instructions creating FT values.
2066 for (Instruction *I : OriginalInstructions)
2067 maybeCreateShadowValue(*I, TLI, ValueToShadow);
2068
2069 // Propagate shadow values across stores, calls and rets.
2070 for (Instruction *I : OriginalInstructions)
2071 propagateShadowValues(*I, TLI, ValueToShadow);
2072
2073 // The last pass populates shadow phis with shadow values.
2074 for (PHINode *Phi : OriginalPhis) {
2075 PHINode *ShadowPhi = cast<PHINode>(ValueToShadow.getShadow(Phi));
2076 for (unsigned I : seq(Phi->getNumOperands())) {
2077 Value *V = Phi->getOperand(I);
2078 Value *Shadow = ValueToShadow.getShadow(V);
2079 BasicBlock *IncomingBB = Phi->getIncomingBlock(I);
2080 // For some instructions (e.g. invoke), we create the shadow in a separate
2081 // block, different from the block where the original value is created.
2082 // In that case, the shadow phi might need to refer to this block instead
2083 // of the original block.
2084 // Note that this can only happen for instructions as constant shadows are
2085 // always created in the same block.
2086 ShadowPhi->addIncoming(Shadow, IncomingBB);
2087 }
2088 }
2089
2090 return !ValueToShadow.empty();
2091}
2092
2094 uint64_t OpSize = 0;
2095 if (Constant *C = dyn_cast<Constant>(V)) {
2096 auto *CInt = dyn_cast<ConstantInt>(C);
2097 if (CInt && CInt->getValue().getBitWidth() <= 64)
2098 OpSize = CInt->getValue().getZExtValue();
2099 }
2100
2101 return OpSize;
2102}
2103
2104// Instrument the memory intrinsics so that they properly modify the shadow
2105// memory.
2106bool NumericalStabilitySanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
2107 IRBuilder<> Builder(MI);
2108 if (auto *M = dyn_cast<MemSetInst>(MI)) {
2109 FunctionCallee SetUnknownFn =
2110 NsanSetUnknownFns.getFunctionFor(GetMemOpSize(M->getArgOperand(2)));
2111 if (SetUnknownFn.getFunctionType()->getNumParams() == 1)
2112 Builder.CreateCall(SetUnknownFn, {/*Address=*/M->getArgOperand(0)});
2113 else
2114 Builder.CreateCall(SetUnknownFn,
2115 {/*Address=*/M->getArgOperand(0),
2116 /*Size=*/Builder.CreateIntCast(M->getArgOperand(2),
2117 IntptrTy, false)});
2118
2119 } else if (auto *M = dyn_cast<MemTransferInst>(MI)) {
2120 FunctionCallee CopyFn =
2121 NsanCopyFns.getFunctionFor(GetMemOpSize(M->getArgOperand(2)));
2122
2123 if (CopyFn.getFunctionType()->getNumParams() == 2)
2124 Builder.CreateCall(CopyFn, {/*Destination=*/M->getArgOperand(0),
2125 /*Source=*/M->getArgOperand(1)});
2126 else
2127 Builder.CreateCall(CopyFn, {/*Destination=*/M->getArgOperand(0),
2128 /*Source=*/M->getArgOperand(1),
2129 /*Size=*/
2130 Builder.CreateIntCast(M->getArgOperand(2),
2131 IntptrTy, false)});
2132 }
2133 return false;
2134}
2135
2136void NumericalStabilitySanitizer::maybeAddSuffixForNsanInterface(CallBase *CI) {
2137 Function *Fn = CI->getCalledFunction();
2138 if (Fn == nullptr)
2139 return;
2140
2141 if (!Fn->getName().starts_with("__nsan_"))
2142 return;
2143
2144 if (Fn->getName() == "__nsan_dump_shadow_mem") {
2145 assert(CI->arg_size() == 4 &&
2146 "invalid prototype for __nsan_dump_shadow_mem");
2147 // __nsan_dump_shadow_mem requires an extra parameter with the dynamic
2148 // configuration:
2149 // (shadow_type_id_for_long_double << 16) | (shadow_type_id_for_double << 8)
2150 // | shadow_type_id_for_double
2151 const uint64_t shadow_value_type_ids =
2152 (static_cast<size_t>(Config.byValueType(kLongDouble).getNsanTypeId())
2153 << 16) |
2154 (static_cast<size_t>(Config.byValueType(kDouble).getNsanTypeId())
2155 << 8) |
2156 static_cast<size_t>(Config.byValueType(kFloat).getNsanTypeId());
2157 CI->setArgOperand(3, ConstantInt::get(IntptrTy, shadow_value_type_ids));
2158 }
2159}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file defines the DenseMap class.
Hexagon Common GEP
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
static constexpr Value * getValue(Ty &ValueOrUse)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
This file contains the declarations for metadata subclasses.
static GlobalValue * createThreadLocalGV(const char *Name, Module &M, Type *Ty)
static FunctionType * makeDoubleDouble(LLVMContext &C)
constexpr int kMaxVectorWidth
static bool shouldCheckArgs(CallBase &CI, const TargetLibraryInfo &TLI, const std::optional< Regex > &CheckFunctionsFilter)
static FunctionType * makeX86FP80X86FP80(LLVMContext &C)
#define MOVE_FLAG(attr, setter)
static FunctionType * makeX86FP80X86FP80I32(LLVMContext &C)
constexpr int kMaxNumArgs
constexpr int kMaxShadowTypeSizeBytes
static const char * getIntrinsicFromLibfunc(Function &Fn, Type *VT, const TargetLibraryInfo &TLI)
static FunctionType * makeX86FP80X86FP80X86FP80(LLVMContext &C)
static FunctionType * makeX86FP80X86FP80X86FP80X86FP80(LLVMContext &C)
static uint64_t GetMemOpSize(Value *V)
constexpr StringLiteral kNsanInitName("__nsan_init")
static FunctionType * makeDoubleDoubleDouble(LLVMContext &C)
constexpr int kShadowScale
constexpr StringLiteral kNsanModuleCtorName("nsan.module_ctor")
static FunctionType * makeDoubleDoubleDoubleDouble(LLVMContext &C)
static FunctionType * makeDoubleDoubleI32(LLVMContext &C)
static void moveFastMathFlags(Function &F, std::vector< Instruction * > &Instructions)
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
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.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
Value * RHS
Value * LHS
static constexpr roundingMode rmTowardZero
Definition APFloat.h:365
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:6034
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM_ABI void replaceSuccessorsPhiUsesWith(BasicBlock *Old, BasicBlock *New)
Update all phi nodes in this basic block's successors to refer to basic block New instead of basic bl...
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
LLVM_ABI BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
const Instruction & back() const
Definition BasicBlock.h:471
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
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
bool isInlineAsm() const
Check if this call is an inline asm statement.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
Value * getCalledOperand() const
void setArgOperand(unsigned i, Value *v)
unsigned arg_size() const
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:758
bool empty() const
Definition DenseMap.h:717
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:767
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:857
This instruction compares its operands according to the predicate given to the constructor.
static bool isEquality(Predicate Pred)
This class represents an extension of floating point types.
This class represents a truncation of floating point types.
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
FunctionType * getFunctionType()
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:212
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Definition Function.h:247
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2678
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2666
Value * CreateFPTrunc(Value *V, Type *DestTy, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2210
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition IRBuilder.h:2725
LLVM_ABI Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Value * CreateConstGEP2_64(Type *Ty, Value *Ptr, uint64_t Idx0, uint64_t Idx1, const Twine &Name="")
Definition IRBuilder.h:2076
BasicBlock::iterator GetInsertPoint() const
Definition IRBuilder.h:180
Value * CreateFreeze(Value *V, const Twine &Name="")
Definition IRBuilder.h:2744
void SetCurrentDebugLocation(const DebugLoc &L)
Set location information used by debugging information.
Definition IRBuilder.h:238
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition IRBuilder.h:531
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="", MDNode *FPMathTag=nullptr, FMFSource FMFSource={})
Definition IRBuilder.h:2293
Value * CreateUnOp(Instruction::UnaryOps Opc, Value *V, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1863
UncondBrInst * CreateBr(BasicBlock *Dest)
Create an unconditional 'br label X' instruction.
Definition IRBuilder.h:1215
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2391
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2252
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:1916
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
Definition IRBuilder.h:2700
LLVM_ABI Value * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={}, function_ref< void(CallInst *)> SetFn=[](CallInst *) {})
Variant to create a possibly constant-folded intrinsic.
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition IRBuilder.h:1934
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2242
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2570
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1736
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
Definition IRBuilder.h:2332
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align, bool isVolatile=false)
Definition IRBuilder.h:1962
Value * CreateFPExt(Value *V, Type *DestTy, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2225
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1597
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2918
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI void replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB)
Replace specified successor OldBB to point at the provided block.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
iterator_range< user_iterator > users()
const char * getOpcodeName() const
LLVM_ABI void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction.
Class to represent integer types.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
An instruction for reading from memory.
This is the common base class for memset/memcpy/memmove.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
Definition StringRef.h:888
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
StringRef getName(LibFunc F) const
LibFunc getLibFunc(StringRef funcName) const
Searches for a particular function name.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:339
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI Type * getStructElementType(unsigned N) const
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isX86_FP80Ty() const
Return true if this is x86 long double.
Definition Type.h:161
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition Type.h:274
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
static LLVM_ABI Type * getPPC_FP128Ty(LLVMContext &C)
Definition Type.cpp:282
static LLVM_ABI Type * getFP128Ty(LLVMContext &C)
Definition Type.cpp:281
LLVM_ABI unsigned getStructNumElements() const
LLVM_ABI uint64_t getArrayNumElements() const
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:272
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:297
bool isStructTy() const
True if this is an instance of StructType.
Definition Type.h:271
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition Type.h:158
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
static LLVM_ABI Type * getDoubleTy(LLVMContext &C)
Definition Type.cpp:277
static LLVM_ABI Type * getX86_FP80Ty(LLVMContext &C)
Definition Type.cpp:280
static LLVM_ABI Type * getFloatTy(LLVMContext &C)
Definition Type.cpp:276
'undef' values are things that do not have specified contents.
Definition Constants.h:1657
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
op_range operands()
Definition User.h:267
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
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 StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
const ParentTy * getParent() const
Definition ilist_node.h:34
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI bool isSignatureValid(Intrinsic::ID ID, FunctionType *FT, SmallVectorImpl< Type * > &OverloadTys, raw_ostream &OS=nulls())
Returns true if FT is a valid function type for intrinsic ID.
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2570
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI std::pair< Function *, FunctionCallee > getOrCreateSanitizerCtorAndInitFunctions(Module &M, StringRef CtorName, StringRef InitName, ArrayRef< Type * > InitArgTypes, ArrayRef< Value * > InitArgs, function_ref< void(Function *, FunctionCallee)> FunctionsCreatedCallback, StringRef VersionCheckName=StringRef(), bool Weak=false)
Creates sanitizer constructor function lazily.
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
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 raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
DWARFExpression::Operation Op
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
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
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:3902
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)