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 {
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 const InstrumentationOptions &Opts = getInstrumentationOptions(M);
573 NumericalStabilitySanitizer Nsan(Opts, M);
574 auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
575 for (Function &F : M)
576 Nsan.sanitizeFunction(F, FAM.getResult<TargetLibraryAnalysis>(F));
577
579}
580
581static GlobalValue *createThreadLocalGV(const char *Name, Module &M, Type *Ty) {
582 return M.getOrInsertGlobal(Name, Ty, [&M, Ty, Name] {
583 return new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage,
584 nullptr, Name, nullptr,
586 });
587}
588
589NumericalStabilitySanitizer::NumericalStabilitySanitizer(
590 const InstrumentationOptions &Opts, Module &M)
591 : Opts(Opts), DL(M.getDataLayout()), Context(M.getContext()),
592 Config(Opts, Context),
593 NsanCopyFns(M, {"__nsan_copy_4", "__nsan_copy_8", "__nsan_copy_16"},
594 "__nsan_copy_values", /*NumArgs=*/3),
595 NsanSetUnknownFns(M,
596 {"__nsan_set_value_unknown_4",
597 "__nsan_set_value_unknown_8",
598 "__nsan_set_value_unknown_16"},
599 "__nsan_set_value_unknown", /*NumArgs=*/2) {
600 IntptrTy = DL.getIntPtrType(Context);
601 Type *PtrTy = PointerType::getUnqual(Context);
602 Type *Int32Ty = Type::getInt32Ty(Context);
603 Type *Int1Ty = Type::getInt1Ty(Context);
604 Type *VoidTy = Type::getVoidTy(Context);
605
606 AttributeList Attr;
607 Attr = Attr.addFnAttribute(Context, Attribute::NoUnwind);
608
609 Triple TT(M.getTargetTriple());
610 Attribute::AttrKind I32RetExtAttr =
611 TargetLibraryInfo::getExtAttrForI32Return(TT, /*Signed=*/true);
612 Attribute::AttrKind I32ArgExtAttr =
613 TargetLibraryInfo::getExtAttrForI32Param(TT, /*Signed=*/true);
614 Attribute::AttrKind BoolExtAttr =
616
617 // Initialize the runtime values (functions and global variables).
618 for (int I = 0; I < kNumValueTypes; ++I) {
619 const FTValueType VT = static_cast<FTValueType>(I);
620 const char *VTName = typeNameFromFTValueType(VT);
621 Type *VTTy = typeFromFTValueType(VT, Context);
622
623 // Load/store.
624 const std::string GetterPrefix =
625 std::string("__nsan_get_shadow_ptr_for_") + VTName;
626 NsanGetShadowPtrForStore[VT] = M.getOrInsertFunction(
627 GetterPrefix + "_store", Attr, PtrTy, PtrTy, IntptrTy);
628 NsanGetShadowPtrForLoad[VT] = M.getOrInsertFunction(
629 GetterPrefix + "_load", Attr, PtrTy, PtrTy, IntptrTy);
630
631 // Check.
632 const auto &ShadowConfig = Config.byValueType(VT);
633 Type *ShadowTy = ShadowConfig.getType(Context);
634 {
635 AttributeList AL = Attr;
636 AL = AL.maybeAddRetAttribute(Context, I32RetExtAttr);
637 AL = AL.maybeAddParamAttribute(Context, 2, I32ArgExtAttr);
638 NsanCheckValue[VT] =
639 M.getOrInsertFunction(std::string("__nsan_internal_check_") + VTName +
640 "_" + ShadowConfig.getNsanTypeId(),
641 AL, Int32Ty, VTTy, ShadowTy, Int32Ty, IntptrTy);
642 }
643
644 {
645 AttributeList AL = Attr;
646 AL = AL.maybeAddParamAttribute(Context, 4, I32ArgExtAttr);
647 AL = AL.maybeAddParamAttribute(Context, 5, BoolExtAttr);
648 AL = AL.maybeAddParamAttribute(Context, 6, BoolExtAttr);
649 NsanFCmpFail[VT] = M.getOrInsertFunction(
650 std::string("__nsan_fcmp_fail_") + VTName + "_" +
651 ShadowConfig.getNsanTypeId(),
652 AL, VoidTy, VTTy, VTTy, ShadowTy, ShadowTy, Int32Ty, Int1Ty, Int1Ty);
653 }
654 }
655
656 // TODO: Add attributes nofree, nosync, readnone, readonly,
657 NsanGetRawShadowTypePtr = M.getOrInsertFunction(
658 "__nsan_internal_get_raw_shadow_type_ptr", Attr, PtrTy, PtrTy);
659 NsanGetRawShadowPtr = M.getOrInsertFunction(
660 "__nsan_internal_get_raw_shadow_ptr", Attr, PtrTy, PtrTy);
661
662 NsanShadowRetTag = createThreadLocalGV("__nsan_shadow_ret_tag", M, IntptrTy);
663
664 NsanShadowRetType = ArrayType::get(Type::getInt8Ty(Context),
666 NsanShadowRetPtr =
667 createThreadLocalGV("__nsan_shadow_ret_ptr", M, NsanShadowRetType);
668
669 NsanShadowArgsTag =
670 createThreadLocalGV("__nsan_shadow_args_tag", M, IntptrTy);
671
672 NsanShadowArgsType =
675
676 NsanShadowArgsPtr =
677 createThreadLocalGV("__nsan_shadow_args_ptr", M, NsanShadowArgsType);
678
679 if (!Opts.check_functions_filter.empty()) {
680 Regex R = Regex(Opts.check_functions_filter);
681 std::string RegexError;
682 assert(R.isValid(RegexError));
683 CheckFunctionsFilter = std::move(R);
684 }
685}
686
687// Returns true if the given LLVM Value points to constant data (typically, a
688// global variable reference).
689bool NumericalStabilitySanitizer::addrPointsToConstantData(Value *Addr) {
690 // If this is a GEP, just analyze its pointer operand.
691 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr))
692 Addr = GEP->getPointerOperand();
693
694 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr))
695 return GV->isConstant();
696 return false;
697}
698
699// This instruments the function entry to create shadow arguments.
700// Pseudocode:
701// if (this_fn_ptr == __nsan_shadow_args_tag) {
702// s(arg0) = LOAD<sizeof(arg0)>(__nsan_shadow_args);
703// s(arg1) = LOAD<sizeof(arg1)>(__nsan_shadow_args + sizeof(arg0));
704// ...
705// __nsan_shadow_args_tag = 0;
706// } else {
707// s(arg0) = fext(arg0);
708// s(arg1) = fext(arg1);
709// ...
710// }
711void NumericalStabilitySanitizer::createShadowArguments(
712 Function &F, const TargetLibraryInfo &TLI, ValueToShadowMap &Map) {
713 assert(!F.getIntrinsicID() && "found a definition of an intrinsic");
714
715 // The copy of a `byval` argument lives in fresh stack memory that the caller
716 // never populated with shadow values, so it may overlap stale shadow memory
717 // from earlier frames. Reset it to unknown so that loads from it fall back
718 // to the native values instead of reading stale shadow.
719 IRBuilder<> ByValBuilder(F.getEntryBlock().getFirstNonPHIIt());
720 for (Argument &Arg : F.args()) {
721 if (!Arg.hasByValAttr())
722 continue;
723 TypeSize ByValSize = DL.getTypeAllocSize(Arg.getParamByValType());
724 assert(!ByValSize.isScalable() && "scalable byval is rejected by verifier");
725 const uint64_t Size = ByValSize.getFixedValue();
726 if (Size == 0)
727 continue;
728 FunctionCallee SetUnknownFn = NsanSetUnknownFns.getFunctionFor(Size);
729 if (SetUnknownFn.getFunctionType()->getNumParams() == 1)
730 ByValBuilder.CreateCall(SetUnknownFn, {&Arg});
731 else
732 ByValBuilder.CreateCall(SetUnknownFn,
733 {&Arg, ConstantInt::get(IntptrTy, Size)});
734 }
735
736 // Do not bother if there are no FP args.
737 if (all_of(F.args(), [this](const Argument &Arg) {
738 return Config.getExtendedFPType(Arg.getType()) == nullptr;
739 }))
740 return;
741
742 IRBuilder<> Builder(F.getEntryBlock().getFirstNonPHIIt());
743 // The function has shadow args if the shadow args tag matches the function
744 // address.
745 Value *HasShadowArgs = Builder.CreateICmpEQ(
746 Builder.CreateLoad(IntptrTy, NsanShadowArgsTag, /*isVolatile=*/false),
747 Builder.CreatePtrToInt(&F, IntptrTy));
748
749 unsigned ShadowArgsOffsetBytes = 0;
750 for (Argument &Arg : F.args()) {
751 Type *VT = Arg.getType();
752 Type *ExtendedVT = Config.getExtendedFPType(VT);
753 if (ExtendedVT == nullptr)
754 continue; // Not an FT value.
755 Value *L = Builder.CreateAlignedLoad(
756 ExtendedVT,
757 Builder.CreateConstGEP2_64(NsanShadowArgsType, NsanShadowArgsPtr, 0,
758 ShadowArgsOffsetBytes),
759 Align(1), /*isVolatile=*/false);
760 Value *Shadow = Builder.CreateSelect(HasShadowArgs, L,
761 Builder.CreateFPExt(&Arg, ExtendedVT));
762 Map.setShadow(Arg, *Shadow);
763 TypeSize SlotSize = DL.getTypeStoreSize(ExtendedVT);
764 assert(!SlotSize.isScalable() && "unsupported");
765 ShadowArgsOffsetBytes += SlotSize;
766 }
767 Builder.CreateStore(ConstantInt::get(IntptrTy, 0), NsanShadowArgsTag);
768}
769
770// Returns true if the instrumentation should emit code to check arguments
771// before a function call.
773 const std::optional<Regex> &CheckFunctionsFilter) {
774
775 Function *Fn = CI.getCalledFunction();
776
777 if (CheckFunctionsFilter) {
778 // Skip checking args of indirect calls.
779 if (Fn == nullptr)
780 return false;
781 if (CheckFunctionsFilter->match(Fn->getName()))
782 return true;
783 return false;
784 }
785
786 if (Fn == nullptr)
787 return true; // Always check args of indirect calls.
788
789 // Never check nsan functions, the user called them for a reason.
790 if (Fn->getName().starts_with("__nsan_"))
791 return false;
792
793 const auto ID = Fn->getIntrinsicID();
794 LibFunc LFunc = TLI.getLibFunc(*Fn);
795 // Always check args of unknown functions.
796 if (ID == Intrinsic::ID() && LFunc == NotLibFunc)
797 return true;
798
799 // Do not check args of an `fabs` call that is used for a comparison.
800 // This is typically used for `fabs(a-b) < tolerance`, where what matters is
801 // the result of the comparison, which is already caught be the fcmp checks.
802 if (ID == Intrinsic::fabs || LFunc == LibFunc_fabsf ||
803 LFunc == LibFunc_fabs || LFunc == LibFunc_fabsl)
804 for (const auto &U : CI.users())
805 if (isa<CmpInst>(U))
806 return false;
807
808 return true; // Default is check.
809}
810
811// Populates the shadow call stack (which contains shadow values for every
812// floating-point parameter to the function).
813void NumericalStabilitySanitizer::populateShadowStack(
814 CallBase &CI, const TargetLibraryInfo &TLI, const ValueToShadowMap &Map) {
815 // Do not create a shadow stack for inline asm.
816 if (CI.isInlineAsm())
817 return;
818
819 // Do not bother if there are no FP args.
820 if (all_of(CI.operands(), [this](const Value *Arg) {
821 return Config.getExtendedFPType(Arg->getType()) == nullptr;
822 }))
823 return;
824
825 IRBuilder<> Builder(&CI);
826 SmallVector<Value *, 8> ArgShadows;
827 const bool ShouldCheckArgs = shouldCheckArgs(CI, TLI, CheckFunctionsFilter);
828 for (auto [ArgIdx, Arg] : enumerate(CI.operands())) {
829 if (Config.getExtendedFPType(Arg->getType()) == nullptr)
830 continue; // Not an FT value.
831 Value *ArgShadow = Map.getShadow(Arg);
832 ArgShadows.push_back(ShouldCheckArgs ? emitCheck(Arg, ArgShadow, Builder,
833 CheckLoc::makeArg(ArgIdx))
834 : ArgShadow);
835 }
836
837 // Do not create shadow stacks for intrinsics/known lib funcs.
838 if (Function *Fn = CI.getCalledFunction()) {
839 if (Fn->isIntrinsic() || TLI.getLibFunc(*Fn) != NotLibFunc)
840 return;
841 }
842
843 // Set the shadow stack tag.
844 Builder.CreateStore(CI.getCalledOperand(), NsanShadowArgsTag);
845 TypeSize ShadowArgsOffsetBytes = TypeSize::getFixed(0);
846
847 unsigned ShadowArgId = 0;
848 for (const Value *Arg : CI.operands()) {
849 Type *VT = Arg->getType();
850 Type *ExtendedVT = Config.getExtendedFPType(VT);
851 if (ExtendedVT == nullptr)
852 continue; // Not an FT value.
853 Builder.CreateAlignedStore(
854 ArgShadows[ShadowArgId++],
855 Builder.CreateConstGEP2_64(NsanShadowArgsType, NsanShadowArgsPtr, 0,
856 ShadowArgsOffsetBytes),
857 Align(1), /*isVolatile=*/false);
858 TypeSize SlotSize = DL.getTypeStoreSize(ExtendedVT);
859 assert(!SlotSize.isScalable() && "unsupported");
860 ShadowArgsOffsetBytes += SlotSize;
861 }
862}
863
864// Internal part of emitCheck(). Returns a value that indicates whether
865// computation should continue with the shadow or resume by re-fextending the
866// value.
867enum class ContinuationType { // Keep in sync with runtime.
870};
871
872Value *NumericalStabilitySanitizer::emitCheckInternal(Value *V, Value *ShadowV,
873 IRBuilder<> &Builder,
874 CheckLoc Loc) {
875 // Do not emit checks for constant values, this is redundant.
876 if (isa<Constant>(V))
877 return ConstantInt::get(
878 Builder.getInt32Ty(),
879 static_cast<int>(ContinuationType::ContinueWithShadow));
880
881 Type *Ty = V->getType();
882 if (const auto VT = ftValueTypeFromType(Ty))
883 return Builder.CreateCall(
884 NsanCheckValue[*VT],
885 {V, ShadowV, Loc.getType(Context), Loc.getValue(IntptrTy, Builder)});
886
887 if (Ty->isVectorTy()) {
888 auto *VecTy = cast<VectorType>(Ty);
889 // We currently skip scalable vector types in MappingConfig,
890 // thus we should not encounter any such types here.
891 assert(!VecTy->isScalableTy() &&
892 "Scalable vector types are not supported yet");
893 Value *CheckResult = nullptr;
894 for (int I = 0, E = VecTy->getElementCount().getFixedValue(); I < E; ++I) {
895 // We resume if any element resumes. Another option would be to create a
896 // vector shuffle with the array of ContinueWithShadow, but that is too
897 // complex.
898 Value *ExtractV = Builder.CreateExtractElement(V, I);
899 Value *ExtractShadowV = Builder.CreateExtractElement(ShadowV, I);
900 Value *ComponentCheckResult =
901 emitCheckInternal(ExtractV, ExtractShadowV, Builder, Loc);
902 CheckResult = CheckResult
903 ? Builder.CreateOr(CheckResult, ComponentCheckResult)
904 : ComponentCheckResult;
905 }
906 return CheckResult;
907 }
908 if (Ty->isArrayTy()) {
909 Value *CheckResult = nullptr;
910 for (auto I : seq(Ty->getArrayNumElements())) {
911 Value *ExtractV = Builder.CreateExtractElement(V, I);
912 Value *ExtractShadowV = Builder.CreateExtractElement(ShadowV, I);
913 Value *ComponentCheckResult =
914 emitCheckInternal(ExtractV, ExtractShadowV, Builder, Loc);
915 CheckResult = CheckResult
916 ? Builder.CreateOr(CheckResult, ComponentCheckResult)
917 : ComponentCheckResult;
918 }
919 return CheckResult;
920 }
921 if (Ty->isStructTy()) {
922 Value *CheckResult = nullptr;
923 for (auto I : seq(Ty->getStructNumElements())) {
924 if (Config.getExtendedFPType(Ty->getStructElementType(I)) == nullptr)
925 continue; // Only check FT values.
926 Value *ExtractV = Builder.CreateExtractValue(V, I);
927 Value *ExtractShadowV = Builder.CreateExtractElement(ShadowV, I);
928 Value *ComponentCheckResult =
929 emitCheckInternal(ExtractV, ExtractShadowV, Builder, Loc);
930 CheckResult = CheckResult
931 ? Builder.CreateOr(CheckResult, ComponentCheckResult)
932 : ComponentCheckResult;
933 }
934 if (!CheckResult)
935 return ConstantInt::get(
936 Builder.getInt32Ty(),
937 static_cast<int>(ContinuationType::ContinueWithShadow));
938 return CheckResult;
939 }
940
941 llvm_unreachable("not implemented");
942}
943
944// Inserts a runtime check of V against its shadow value ShadowV.
945// We check values whenever they escape: on return, call, stores, and
946// insertvalue.
947// Returns the shadow value that should be used to continue the computations,
948// depending on the answer from the runtime.
949// TODO: Should we check on select ? phi ?
950Value *NumericalStabilitySanitizer::emitCheck(Value *V, Value *ShadowV,
951 IRBuilder<> &Builder,
952 CheckLoc Loc) {
953 // Do not emit checks for constant values, this is redundant.
954 if (isa<Constant>(V))
955 return ShadowV;
956
957 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
958 Function *F = Inst->getFunction();
959 if (CheckFunctionsFilter && !CheckFunctionsFilter->match(F->getName())) {
960 return ShadowV;
961 }
962 }
963
964 Value *CheckResult = emitCheckInternal(V, ShadowV, Builder, Loc);
965 Value *ICmpEQ = Builder.CreateICmpEQ(
966 CheckResult,
967 ConstantInt::get(Builder.getInt32Ty(),
968 static_cast<int>(ContinuationType::ResumeFromValue)));
969 return Builder.CreateSelect(
970 ICmpEQ, Builder.CreateFPExt(V, Config.getExtendedFPType(V->getType())),
971 ShadowV);
972}
973
974// Inserts a check that fcmp on shadow values are consistent with that on base
975// values.
976void NumericalStabilitySanitizer::emitFCmpCheck(FCmpInst &FCmp,
977 const ValueToShadowMap &Map) {
978 if (!Opts.nsan_instrument_fcmp)
979 return;
980
981 Function *F = FCmp.getFunction();
982 if (CheckFunctionsFilter && !CheckFunctionsFilter->match(F->getName()))
983 return;
984
985 Value *LHS = FCmp.getOperand(0);
986 if (Config.getExtendedFPType(LHS->getType()) == nullptr)
987 return;
988 Value *RHS = FCmp.getOperand(1);
989
990 // Split the basic block. On mismatch, we'll jump to the new basic block with
991 // a call to the runtime for error reporting.
992 BasicBlock *FCmpBB = FCmp.getParent();
993 BasicBlock *NextBB = FCmpBB->splitBasicBlock(FCmp.getNextNode());
994 // Remove the newly created terminator unconditional branch.
995 FCmpBB->back().eraseFromParent();
996 BasicBlock *FailBB =
997 BasicBlock::Create(Context, "", FCmpBB->getParent(), NextBB);
998
999 // Create the shadow fcmp and comparison between the fcmps.
1000 IRBuilder<> FCmpBuilder(FCmpBB);
1001 FCmpBuilder.SetCurrentDebugLocation(FCmp.getDebugLoc());
1002 Value *ShadowLHS = Map.getShadow(LHS);
1003 Value *ShadowRHS = Map.getShadow(RHS);
1004 // See the help text of -nsan-truncate-fcmp-eq.
1005 if (FCmp.isEquality() && Opts.nsan_truncate_fcmp_eq) {
1006 Type *Ty = ShadowLHS->getType();
1007 ShadowLHS = FCmpBuilder.CreateFPExt(
1008 FCmpBuilder.CreateFPTrunc(ShadowLHS, LHS->getType()), Ty);
1009 ShadowRHS = FCmpBuilder.CreateFPExt(
1010 FCmpBuilder.CreateFPTrunc(ShadowRHS, RHS->getType()), Ty);
1011 }
1012 Value *ShadowFCmp =
1013 FCmpBuilder.CreateFCmp(FCmp.getPredicate(), ShadowLHS, ShadowRHS);
1014 Value *OriginalAndShadowFcmpMatch =
1015 FCmpBuilder.CreateICmpEQ(&FCmp, ShadowFCmp);
1016
1017 if (OriginalAndShadowFcmpMatch->getType()->isVectorTy()) {
1018 // If we have a vector type, `OriginalAndShadowFcmpMatch` is a vector of i1,
1019 // where an element is true if the corresponding elements in original and
1020 // shadow are the same. We want all elements to be 1.
1021 OriginalAndShadowFcmpMatch =
1022 FCmpBuilder.CreateAndReduce(OriginalAndShadowFcmpMatch);
1023 }
1024
1025 // Use MDBuilder(*C).createLikelyBranchWeights() because "match" is the common
1026 // case.
1027 FCmpBuilder.CreateCondBr(OriginalAndShadowFcmpMatch, NextBB, FailBB,
1028 MDBuilder(Context).createLikelyBranchWeights());
1029
1030 // Fill in FailBB.
1031 IRBuilder<> FailBuilder(FailBB);
1032 FailBuilder.SetCurrentDebugLocation(FCmp.getDebugLoc());
1033
1034 const auto EmitFailCall = [this, &FCmp, &FCmpBuilder,
1035 &FailBuilder](Value *L, Value *R, Value *ShadowL,
1036 Value *ShadowR, Value *Result,
1037 Value *ShadowResult) {
1038 Type *FT = L->getType();
1039 FunctionCallee *Callee = nullptr;
1040 if (FT->isFloatTy()) {
1041 Callee = &(NsanFCmpFail[kFloat]);
1042 } else if (FT->isDoubleTy()) {
1043 Callee = &(NsanFCmpFail[kDouble]);
1044 } else if (FT->isX86_FP80Ty()) {
1045 // TODO: make NsanFCmpFailLongDouble work.
1046 Callee = &(NsanFCmpFail[kDouble]);
1047 L = FailBuilder.CreateFPTrunc(L, Type::getDoubleTy(Context));
1048 R = FailBuilder.CreateFPTrunc(L, Type::getDoubleTy(Context));
1049 } else {
1050 llvm_unreachable("not implemented");
1051 }
1052 FailBuilder.CreateCall(*Callee, {L, R, ShadowL, ShadowR,
1053 ConstantInt::get(FCmpBuilder.getInt32Ty(),
1054 FCmp.getPredicate()),
1055 Result, ShadowResult});
1056 };
1057 if (LHS->getType()->isVectorTy()) {
1058 for (int I = 0, E = cast<VectorType>(LHS->getType())
1059 ->getElementCount()
1060 .getFixedValue();
1061 I < E; ++I) {
1062 Value *ExtractLHS = FailBuilder.CreateExtractElement(LHS, I);
1063 Value *ExtractRHS = FailBuilder.CreateExtractElement(RHS, I);
1064 Value *ExtractShaodwLHS = FailBuilder.CreateExtractElement(ShadowLHS, I);
1065 Value *ExtractShaodwRHS = FailBuilder.CreateExtractElement(ShadowRHS, I);
1066 Value *ExtractFCmp = FailBuilder.CreateExtractElement(&FCmp, I);
1067 Value *ExtractShadowFCmp =
1068 FailBuilder.CreateExtractElement(ShadowFCmp, I);
1069 EmitFailCall(ExtractLHS, ExtractRHS, ExtractShaodwLHS, ExtractShaodwRHS,
1070 ExtractFCmp, ExtractShadowFCmp);
1071 }
1072 } else {
1073 EmitFailCall(LHS, RHS, ShadowLHS, ShadowRHS, &FCmp, ShadowFCmp);
1074 }
1075 FailBuilder.CreateBr(NextBB);
1076
1077 ++NumInstrumentedFCmp;
1078}
1079
1080// Creates a shadow phi value for any phi that defines a value of FT type.
1081PHINode *NumericalStabilitySanitizer::maybeCreateShadowPhi(
1082 PHINode &Phi, const TargetLibraryInfo &TLI) {
1083 Type *VT = Phi.getType();
1084 Type *ExtendedVT = Config.getExtendedFPType(VT);
1085 if (ExtendedVT == nullptr)
1086 return nullptr; // Not an FT value.
1087 // The phi operands are shadow values and are not available when the phi is
1088 // created. They will be populated in a final phase, once all shadow values
1089 // have been created.
1090 PHINode *Shadow = PHINode::Create(ExtendedVT, Phi.getNumIncomingValues());
1091 Shadow->insertAfter(Phi.getIterator());
1092 return Shadow;
1093}
1094
1095Value *NumericalStabilitySanitizer::handleLoad(LoadInst &Load, Type *VT,
1096 Type *ExtendedVT) {
1097 IRBuilder<> Builder(Load.getNextNode());
1098 Builder.SetCurrentDebugLocation(Load.getDebugLoc());
1099 if (addrPointsToConstantData(Load.getPointerOperand())) {
1100 // No need to look into the shadow memory, the value is a constant. Just
1101 // convert from FT to 2FT.
1102 return Builder.CreateFPExt(&Load, ExtendedVT);
1103 }
1104
1105 // if (%shadowptr == &)
1106 // %shadow = fpext %v
1107 // else
1108 // %shadow = load (ptrcast %shadow_ptr))
1109 // Considered options here:
1110 // - Have `NsanGetShadowPtrForLoad` return a fixed address
1111 // &__nsan_unknown_value_shadow_address that is valid to load from, and
1112 // use a select. This has the advantage that the generated IR is simpler.
1113 // - Have `NsanGetShadowPtrForLoad` return nullptr. Because `select` does
1114 // not short-circuit, dereferencing the returned pointer is no longer an
1115 // option, have to split and create a separate basic block. This has the
1116 // advantage of being easier to debug because it crashes if we ever mess
1117 // up.
1118
1119 const auto Extents = getMemoryExtentsOrDie(VT);
1120 Value *ShadowPtr = Builder.CreateCall(
1121 NsanGetShadowPtrForLoad[Extents.ValueType],
1122 {Load.getPointerOperand(), ConstantInt::get(IntptrTy, Extents.NumElts)});
1123 ++NumInstrumentedFTLoads;
1124
1125 // Split the basic block.
1126 BasicBlock *LoadBB = Load.getParent();
1127 BasicBlock *NextBB = LoadBB->splitBasicBlock(Builder.GetInsertPoint());
1128 // Create the two options for creating the shadow value.
1129 BasicBlock *ShadowLoadBB =
1130 BasicBlock::Create(Context, "", LoadBB->getParent(), NextBB);
1131 BasicBlock *FExtBB =
1132 BasicBlock::Create(Context, "", LoadBB->getParent(), NextBB);
1133
1134 // Replace the newly created terminator unconditional branch by a conditional
1135 // branch to one of the options.
1136 {
1137 LoadBB->back().eraseFromParent();
1138 IRBuilder<> LoadBBBuilder(LoadBB); // The old builder has been invalidated.
1139 LoadBBBuilder.SetCurrentDebugLocation(Load.getDebugLoc());
1140 LoadBBBuilder.CreateCondBr(LoadBBBuilder.CreateIsNull(ShadowPtr), FExtBB,
1141 ShadowLoadBB);
1142 }
1143
1144 // Fill in ShadowLoadBB.
1145 IRBuilder<> ShadowLoadBBBuilder(ShadowLoadBB);
1146 ShadowLoadBBBuilder.SetCurrentDebugLocation(Load.getDebugLoc());
1147 Value *ShadowLoad = ShadowLoadBBBuilder.CreateAlignedLoad(
1148 ExtendedVT, ShadowPtr, Align(1), Load.isVolatile());
1149 if (Opts.nsan_check_loads) {
1150 ShadowLoad = emitCheck(&Load, ShadowLoad, ShadowLoadBBBuilder,
1151 CheckLoc::makeLoad(Load.getPointerOperand()));
1152 }
1153 ShadowLoadBBBuilder.CreateBr(NextBB);
1154
1155 // Fill in FExtBB.
1156 IRBuilder<> FExtBBBuilder(FExtBB);
1157 FExtBBBuilder.SetCurrentDebugLocation(Load.getDebugLoc());
1158 Value *FExt = FExtBBBuilder.CreateFPExt(&Load, ExtendedVT);
1159 FExtBBBuilder.CreateBr(NextBB);
1160
1161 // The shadow value come from any of the options.
1162 IRBuilder<> NextBBBuilder(&*NextBB->begin());
1163 NextBBBuilder.SetCurrentDebugLocation(Load.getDebugLoc());
1164 PHINode *ShadowPhi = NextBBBuilder.CreatePHI(ExtendedVT, 2);
1165 ShadowPhi->addIncoming(ShadowLoad, ShadowLoadBB);
1166 ShadowPhi->addIncoming(FExt, FExtBB);
1167 return ShadowPhi;
1168}
1169
1170Value *NumericalStabilitySanitizer::handleTrunc(const FPTruncInst &Trunc,
1171 Type *VT, Type *ExtendedVT,
1172 const ValueToShadowMap &Map,
1173 IRBuilder<> &Builder) {
1174 Value *OrigSource = Trunc.getOperand(0);
1175 Type *OrigSourceTy = OrigSource->getType();
1176 Type *ExtendedSourceTy = Config.getExtendedFPType(OrigSourceTy);
1177
1178 // When truncating:
1179 // - (A) If the source has a shadow, we truncate from the shadow, else we
1180 // truncate from the original source.
1181 // - (B) If the shadow of the source is larger than the shadow of the dest,
1182 // we still need a truncate. Else, the shadow of the source is the same
1183 // type as the shadow of the dest (because mappings are non-decreasing), so
1184 // we don't need to emit a truncate.
1185 // Examples,
1186 // with a mapping of {f32->f64;f64->f80;f80->f128}
1187 // fptrunc double %1 to float -> fptrunc x86_fp80 s(%1) to double
1188 // fptrunc x86_fp80 %1 to float -> fptrunc fp128 s(%1) to double
1189 // fptrunc fp128 %1 to float -> fptrunc fp128 %1 to double
1190 // fptrunc x86_fp80 %1 to double -> x86_fp80 s(%1)
1191 // fptrunc fp128 %1 to double -> fptrunc fp128 %1 to x86_fp80
1192 // fptrunc fp128 %1 to x86_fp80 -> fp128 %1
1193 // with a mapping of {f32->f64;f64->f128;f80->f128}
1194 // fptrunc double %1 to float -> fptrunc fp128 s(%1) to double
1195 // fptrunc x86_fp80 %1 to float -> fptrunc fp128 s(%1) to double
1196 // fptrunc fp128 %1 to float -> fptrunc fp128 %1 to double
1197 // fptrunc x86_fp80 %1 to double -> fp128 %1
1198 // fptrunc fp128 %1 to double -> fp128 %1
1199 // fptrunc fp128 %1 to x86_fp80 -> fp128 %1
1200 // with a mapping of {f32->f32;f64->f32;f80->f64}
1201 // fptrunc double %1 to float -> float s(%1)
1202 // fptrunc x86_fp80 %1 to float -> fptrunc double s(%1) to float
1203 // fptrunc fp128 %1 to float -> fptrunc fp128 %1 to float
1204 // fptrunc x86_fp80 %1 to double -> fptrunc double s(%1) to float
1205 // fptrunc fp128 %1 to double -> fptrunc fp128 %1 to float
1206 // fptrunc fp128 %1 to x86_fp80 -> fptrunc fp128 %1 to double
1207
1208 // See (A) above.
1209 Value *Source = ExtendedSourceTy ? Map.getShadow(OrigSource) : OrigSource;
1210 Type *SourceTy = ExtendedSourceTy ? ExtendedSourceTy : OrigSourceTy;
1211 // See (B) above.
1212 if (SourceTy == ExtendedVT)
1213 return Source;
1214
1215 return Builder.CreateFPTrunc(Source, ExtendedVT);
1216}
1217
1218Value *NumericalStabilitySanitizer::handleExt(const FPExtInst &Ext, Type *VT,
1219 Type *ExtendedVT,
1220 const ValueToShadowMap &Map,
1221 IRBuilder<> &Builder) {
1222 Value *OrigSource = Ext.getOperand(0);
1223 Type *OrigSourceTy = OrigSource->getType();
1224 Type *ExtendedSourceTy = Config.getExtendedFPType(OrigSourceTy);
1225 // When extending:
1226 // - (A) If the source has a shadow, we extend from the shadow, else we
1227 // extend from the original source.
1228 // - (B) If the shadow of the dest is larger than the shadow of the source,
1229 // we still need an extend. Else, the shadow of the source is the same
1230 // type as the shadow of the dest (because mappings are non-decreasing), so
1231 // we don't need to emit an extend.
1232 // Examples,
1233 // with a mapping of {f32->f64;f64->f80;f80->f128}
1234 // fpext half %1 to float -> fpext half %1 to double
1235 // fpext half %1 to double -> fpext half %1 to x86_fp80
1236 // fpext half %1 to x86_fp80 -> fpext half %1 to fp128
1237 // fpext float %1 to double -> double s(%1)
1238 // fpext float %1 to x86_fp80 -> fpext double s(%1) to fp128
1239 // fpext double %1 to x86_fp80 -> fpext x86_fp80 s(%1) to fp128
1240 // with a mapping of {f32->f64;f64->f128;f80->f128}
1241 // fpext half %1 to float -> fpext half %1 to double
1242 // fpext half %1 to double -> fpext half %1 to fp128
1243 // fpext half %1 to x86_fp80 -> fpext half %1 to fp128
1244 // fpext float %1 to double -> fpext double s(%1) to fp128
1245 // fpext float %1 to x86_fp80 -> fpext double s(%1) to fp128
1246 // fpext double %1 to x86_fp80 -> fp128 s(%1)
1247 // with a mapping of {f32->f32;f64->f32;f80->f64}
1248 // fpext half %1 to float -> fpext half %1 to float
1249 // fpext half %1 to double -> fpext half %1 to float
1250 // fpext half %1 to x86_fp80 -> fpext half %1 to double
1251 // fpext float %1 to double -> s(%1)
1252 // fpext float %1 to x86_fp80 -> fpext float s(%1) to double
1253 // fpext double %1 to x86_fp80 -> fpext float s(%1) to double
1254
1255 // See (A) above.
1256 Value *Source = ExtendedSourceTy ? Map.getShadow(OrigSource) : OrigSource;
1257 Type *SourceTy = ExtendedSourceTy ? ExtendedSourceTy : OrigSourceTy;
1258 // See (B) above.
1259 if (SourceTy == ExtendedVT)
1260 return Source;
1261
1262 return Builder.CreateFPExt(Source, ExtendedVT);
1263}
1264
1265namespace {
1266// TODO: This should be tablegen-ed.
1267struct KnownIntrinsic {
1268 struct WidenedIntrinsic {
1269 const char *NarrowName;
1270 Intrinsic::ID ID; // wide id.
1271 using FnTypeFactory = FunctionType *(*)(LLVMContext &);
1272 FnTypeFactory MakeFnTy;
1273 };
1274
1275 static const char *get(LibFunc LFunc);
1276
1277 // Given an intrinsic with an `FT` argument, try to find a wider intrinsic
1278 // that applies the same operation on the shadow argument.
1279 // Options are:
1280 // - pass in the ID and full function type,
1281 // - pass in the name, which includes the function type through mangling.
1282 static const WidenedIntrinsic *widen(StringRef Name);
1283
1284private:
1285 struct LFEntry {
1286 LibFunc LFunc;
1287 const char *IntrinsicName;
1288 };
1289 static const LFEntry kLibfuncIntrinsics[];
1290
1291 static const WidenedIntrinsic kWidenedIntrinsics[];
1292};
1293} // namespace
1294
1298
1303
1308
1314
1319
1325
1332
1339
1340const KnownIntrinsic::WidenedIntrinsic KnownIntrinsic::kWidenedIntrinsics[] = {
1341 // TODO: Right now we ignore vector intrinsics.
1342 // This is hard because we have to model the semantics of the intrinsics,
1343 // e.g. llvm.x86.sse2.min.sd means extract first element, min, insert back.
1344 // Intrinsics that take any non-vector FT types:
1345 // NOTE: Right now because of
1346 // https://github.com/llvm/llvm-project/issues/44744
1347 // for f128 we need to use makeX86FP80X86FP80 (go to a lower precision and
1348 // come back).
1349 {"llvm.sqrt.f32", Intrinsic::sqrt, makeDoubleDouble},
1350 {"llvm.sqrt.f64", Intrinsic::sqrt, makeX86FP80X86FP80},
1351 {"llvm.sqrt.f80", Intrinsic::sqrt, makeX86FP80X86FP80},
1352 {"llvm.powi.f32", Intrinsic::powi, makeDoubleDoubleI32},
1353 {"llvm.powi.f64", Intrinsic::powi, makeX86FP80X86FP80I32},
1354 {"llvm.powi.f80", Intrinsic::powi, makeX86FP80X86FP80I32},
1355 {"llvm.sin.f32", Intrinsic::sin, makeDoubleDouble},
1356 {"llvm.sin.f64", Intrinsic::sin, makeX86FP80X86FP80},
1357 {"llvm.sin.f80", Intrinsic::sin, makeX86FP80X86FP80},
1358 {"llvm.cos.f32", Intrinsic::cos, makeDoubleDouble},
1359 {"llvm.cos.f64", Intrinsic::cos, makeX86FP80X86FP80},
1360 {"llvm.cos.f80", Intrinsic::cos, makeX86FP80X86FP80},
1361 {"llvm.pow.f32", Intrinsic::pow, makeDoubleDoubleDouble},
1362 {"llvm.pow.f64", Intrinsic::pow, makeX86FP80X86FP80X86FP80},
1363 {"llvm.pow.f80", Intrinsic::pow, makeX86FP80X86FP80X86FP80},
1364 {"llvm.exp.f32", Intrinsic::exp, makeDoubleDouble},
1365 {"llvm.exp.f64", Intrinsic::exp, makeX86FP80X86FP80},
1366 {"llvm.exp.f80", Intrinsic::exp, makeX86FP80X86FP80},
1367 {"llvm.exp2.f32", Intrinsic::exp2, makeDoubleDouble},
1368 {"llvm.exp2.f64", Intrinsic::exp2, makeX86FP80X86FP80},
1369 {"llvm.exp2.f80", Intrinsic::exp2, makeX86FP80X86FP80},
1370 {"llvm.log.f32", Intrinsic::log, makeDoubleDouble},
1371 {"llvm.log.f64", Intrinsic::log, makeX86FP80X86FP80},
1372 {"llvm.log.f80", Intrinsic::log, makeX86FP80X86FP80},
1373 {"llvm.log10.f32", Intrinsic::log10, makeDoubleDouble},
1374 {"llvm.log10.f64", Intrinsic::log10, makeX86FP80X86FP80},
1375 {"llvm.log10.f80", Intrinsic::log10, makeX86FP80X86FP80},
1376 {"llvm.log2.f32", Intrinsic::log2, makeDoubleDouble},
1377 {"llvm.log2.f64", Intrinsic::log2, makeX86FP80X86FP80},
1378 {"llvm.log2.f80", Intrinsic::log2, makeX86FP80X86FP80},
1379 {"llvm.fma.f32", Intrinsic::fma, makeDoubleDoubleDoubleDouble},
1380 {"llvm.fma.f64", Intrinsic::fma, makeX86FP80X86FP80X86FP80X86FP80},
1381 {"llvm.fma.f80", Intrinsic::fma, makeX86FP80X86FP80X86FP80X86FP80},
1382 {"llvm.fmuladd.f32", Intrinsic::fmuladd, makeDoubleDoubleDoubleDouble},
1383 {"llvm.fmuladd.f64", Intrinsic::fmuladd, makeX86FP80X86FP80X86FP80X86FP80},
1384 {"llvm.fmuladd.f80", Intrinsic::fmuladd, makeX86FP80X86FP80X86FP80X86FP80},
1385 {"llvm.fabs.f32", Intrinsic::fabs, makeDoubleDouble},
1386 {"llvm.fabs.f64", Intrinsic::fabs, makeX86FP80X86FP80},
1387 {"llvm.fabs.f80", Intrinsic::fabs, makeX86FP80X86FP80},
1388 {"llvm.minnum.f32", Intrinsic::minnum, makeDoubleDoubleDouble},
1389 {"llvm.minnum.f64", Intrinsic::minnum, makeX86FP80X86FP80X86FP80},
1390 {"llvm.minnum.f80", Intrinsic::minnum, makeX86FP80X86FP80X86FP80},
1391 {"llvm.maxnum.f32", Intrinsic::maxnum, makeDoubleDoubleDouble},
1392 {"llvm.maxnum.f64", Intrinsic::maxnum, makeX86FP80X86FP80X86FP80},
1393 {"llvm.maxnum.f80", Intrinsic::maxnum, makeX86FP80X86FP80X86FP80},
1394 {"llvm.minimum.f32", Intrinsic::minimum, makeDoubleDoubleDouble},
1395 {"llvm.minimum.f64", Intrinsic::minimum, makeX86FP80X86FP80X86FP80},
1396 {"llvm.minimum.f80", Intrinsic::minimum, makeX86FP80X86FP80X86FP80},
1397 {"llvm.maximum.f32", Intrinsic::maximum, makeDoubleDoubleDouble},
1398 {"llvm.maximum.f64", Intrinsic::maximum, makeX86FP80X86FP80X86FP80},
1399 {"llvm.maximum.f80", Intrinsic::maximum, makeX86FP80X86FP80X86FP80},
1400 {"llvm.minimumnum.f32", Intrinsic::minimumnum, makeDoubleDoubleDouble},
1401 {"llvm.minimumnum.f64", Intrinsic::minimumnum, makeX86FP80X86FP80X86FP80},
1402 {"llvm.minimumnum.f80", Intrinsic::minimumnum, makeX86FP80X86FP80X86FP80},
1403 {"llvm.maximumnum.f32", Intrinsic::maximumnum, makeDoubleDoubleDouble},
1404 {"llvm.maximumnum.f64", Intrinsic::maximumnum, makeX86FP80X86FP80X86FP80},
1405 {"llvm.maximumnum.f80", Intrinsic::maximumnum, makeX86FP80X86FP80X86FP80},
1406 {"llvm.copysign.f32", Intrinsic::copysign, makeDoubleDoubleDouble},
1407 {"llvm.copysign.f64", Intrinsic::copysign, makeX86FP80X86FP80X86FP80},
1408 {"llvm.copysign.f80", Intrinsic::copysign, makeX86FP80X86FP80X86FP80},
1409 {"llvm.floor.f32", Intrinsic::floor, makeDoubleDouble},
1410 {"llvm.floor.f64", Intrinsic::floor, makeX86FP80X86FP80},
1411 {"llvm.floor.f80", Intrinsic::floor, makeX86FP80X86FP80},
1412 {"llvm.ceil.f32", Intrinsic::ceil, makeDoubleDouble},
1413 {"llvm.ceil.f64", Intrinsic::ceil, makeX86FP80X86FP80},
1414 {"llvm.ceil.f80", Intrinsic::ceil, makeX86FP80X86FP80},
1415 {"llvm.trunc.f32", Intrinsic::trunc, makeDoubleDouble},
1416 {"llvm.trunc.f64", Intrinsic::trunc, makeX86FP80X86FP80},
1417 {"llvm.trunc.f80", Intrinsic::trunc, makeX86FP80X86FP80},
1418 {"llvm.rint.f32", Intrinsic::rint, makeDoubleDouble},
1419 {"llvm.rint.f64", Intrinsic::rint, makeX86FP80X86FP80},
1420 {"llvm.rint.f80", Intrinsic::rint, makeX86FP80X86FP80},
1421 {"llvm.nearbyint.f32", Intrinsic::nearbyint, makeDoubleDouble},
1422 {"llvm.nearbyint.f64", Intrinsic::nearbyint, makeX86FP80X86FP80},
1423 {"llvm.nearbyint.f80", Intrinsic::nearbyint, makeX86FP80X86FP80},
1424 {"llvm.round.f32", Intrinsic::round, makeDoubleDouble},
1425 {"llvm.round.f64", Intrinsic::round, makeX86FP80X86FP80},
1426 {"llvm.round.f80", Intrinsic::round, makeX86FP80X86FP80},
1427};
1428
1429const KnownIntrinsic::LFEntry KnownIntrinsic::kLibfuncIntrinsics[] = {
1430 {LibFunc_sqrtf, "llvm.sqrt.f32"},
1431 {LibFunc_sqrt, "llvm.sqrt.f64"},
1432 {LibFunc_sqrtl, "llvm.sqrt.f80"},
1433 {LibFunc_sinf, "llvm.sin.f32"},
1434 {LibFunc_sin, "llvm.sin.f64"},
1435 {LibFunc_sinl, "llvm.sin.f80"},
1436 {LibFunc_cosf, "llvm.cos.f32"},
1437 {LibFunc_cos, "llvm.cos.f64"},
1438 {LibFunc_cosl, "llvm.cos.f80"},
1439 {LibFunc_powf, "llvm.pow.f32"},
1440 {LibFunc_pow, "llvm.pow.f64"},
1441 {LibFunc_powl, "llvm.pow.f80"},
1442 {LibFunc_expf, "llvm.exp.f32"},
1443 {LibFunc_exp, "llvm.exp.f64"},
1444 {LibFunc_expl, "llvm.exp.f80"},
1445 {LibFunc_exp2f, "llvm.exp2.f32"},
1446 {LibFunc_exp2, "llvm.exp2.f64"},
1447 {LibFunc_exp2l, "llvm.exp2.f80"},
1448 {LibFunc_logf, "llvm.log.f32"},
1449 {LibFunc_log, "llvm.log.f64"},
1450 {LibFunc_logl, "llvm.log.f80"},
1451 {LibFunc_log10f, "llvm.log10.f32"},
1452 {LibFunc_log10, "llvm.log10.f64"},
1453 {LibFunc_log10l, "llvm.log10.f80"},
1454 {LibFunc_log2f, "llvm.log2.f32"},
1455 {LibFunc_log2, "llvm.log2.f64"},
1456 {LibFunc_log2l, "llvm.log2.f80"},
1457 {LibFunc_fabsf, "llvm.fabs.f32"},
1458 {LibFunc_fabs, "llvm.fabs.f64"},
1459 {LibFunc_fabsl, "llvm.fabs.f80"},
1460 {LibFunc_copysignf, "llvm.copysign.f32"},
1461 {LibFunc_copysign, "llvm.copysign.f64"},
1462 {LibFunc_copysignl, "llvm.copysign.f80"},
1463 {LibFunc_floorf, "llvm.floor.f32"},
1464 {LibFunc_floor, "llvm.floor.f64"},
1465 {LibFunc_floorl, "llvm.floor.f80"},
1466 {LibFunc_fmaxf, "llvm.maxnum.f32"},
1467 {LibFunc_fmax, "llvm.maxnum.f64"},
1468 {LibFunc_fmaxl, "llvm.maxnum.f80"},
1469 {LibFunc_fminf, "llvm.minnum.f32"},
1470 {LibFunc_fmin, "llvm.minnum.f64"},
1471 {LibFunc_fminl, "llvm.minnum.f80"},
1472 {LibFunc_fmaximum_numf, "llvm.maximumnum.f32"},
1473 {LibFunc_fmaximum_num, "llvm.maximumnum.f64"},
1474 {LibFunc_fmaximum_numl, "llvm.maximumnum.f80"},
1475 {LibFunc_fminimum_numf, "llvm.minimumnum.f32"},
1476 {LibFunc_fminimum_num, "llvm.minimumnum.f64"},
1477 {LibFunc_fminimum_numl, "llvm.minimumnum.f80"},
1478 {LibFunc_ceilf, "llvm.ceil.f32"},
1479 {LibFunc_ceil, "llvm.ceil.f64"},
1480 {LibFunc_ceill, "llvm.ceil.f80"},
1481 {LibFunc_truncf, "llvm.trunc.f32"},
1482 {LibFunc_trunc, "llvm.trunc.f64"},
1483 {LibFunc_truncl, "llvm.trunc.f80"},
1484 {LibFunc_rintf, "llvm.rint.f32"},
1485 {LibFunc_rint, "llvm.rint.f64"},
1486 {LibFunc_rintl, "llvm.rint.f80"},
1487 {LibFunc_nearbyintf, "llvm.nearbyint.f32"},
1488 {LibFunc_nearbyint, "llvm.nearbyint.f64"},
1489 {LibFunc_nearbyintl, "llvm.nearbyint.f80"},
1490 {LibFunc_roundf, "llvm.round.f32"},
1491 {LibFunc_round, "llvm.round.f64"},
1492 {LibFunc_roundl, "llvm.round.f80"},
1493};
1494
1495const char *KnownIntrinsic::get(LibFunc LFunc) {
1496 for (const auto &E : kLibfuncIntrinsics) {
1497 if (E.LFunc == LFunc)
1498 return E.IntrinsicName;
1499 }
1500 return nullptr;
1501}
1502
1503const KnownIntrinsic::WidenedIntrinsic *KnownIntrinsic::widen(StringRef Name) {
1504 for (const auto &E : kWidenedIntrinsics) {
1505 if (E.NarrowName == Name)
1506 return &E;
1507 }
1508 return nullptr;
1509}
1510
1511// Returns the name of the LLVM intrinsic corresponding to the given function.
1512static const char *getIntrinsicFromLibfunc(Function &Fn, Type *VT,
1513 const TargetLibraryInfo &TLI) {
1514 LibFunc LFunc = TLI.getLibFunc(Fn);
1515 if (LFunc == NotLibFunc)
1516 return nullptr;
1517
1518 if (const char *Name = KnownIntrinsic::get(LFunc))
1519 return Name;
1520
1521 LLVM_DEBUG(errs() << "TODO: LibFunc: " << TLI.getName(LFunc) << "\n");
1522 return nullptr;
1523}
1524
1525// Try to handle a known function call.
1526Value *NumericalStabilitySanitizer::maybeHandleKnownCallBase(
1527 CallBase &Call, Type *VT, Type *ExtendedVT, const TargetLibraryInfo &TLI,
1528 const ValueToShadowMap &Map, IRBuilder<> &Builder) {
1530 if (Fn == nullptr)
1531 return nullptr;
1532
1533 Intrinsic::ID WidenedId = Intrinsic::ID();
1534 FunctionType *WidenedFnTy = nullptr;
1535 if (const auto ID = Fn->getIntrinsicID()) {
1536 const auto *Widened = KnownIntrinsic::widen(Fn->getName());
1537 if (Widened) {
1538 WidenedId = Widened->ID;
1539 WidenedFnTy = Widened->MakeFnTy(Context);
1540 } else {
1541 // If we don't know how to widen the intrinsic, we have no choice but to
1542 // call the non-wide version on a truncated shadow and extend again
1543 // afterwards.
1544 WidenedId = ID;
1545 WidenedFnTy = Fn->getFunctionType();
1546 }
1547 } else if (const char *Name = getIntrinsicFromLibfunc(*Fn, VT, TLI)) {
1548 // We might have a call to a library function that we can replace with a
1549 // wider Intrinsic.
1550 const auto *Widened = KnownIntrinsic::widen(Name);
1551 assert(Widened && "make sure KnownIntrinsic entries are consistent");
1552 WidenedId = Widened->ID;
1553 WidenedFnTy = Widened->MakeFnTy(Context);
1554 } else {
1555 // This is not a known library function or intrinsic.
1556 return nullptr;
1557 }
1558
1559 // Check that the widened intrinsic is valid.
1560 SmallVector<Type *, 4> OverloadTys;
1561 [[maybe_unused]] bool IsValid =
1562 Intrinsic::isSignatureValid(WidenedId, WidenedFnTy, OverloadTys);
1563 assert(IsValid && "invalid widened intrinsic");
1564 // For known intrinsic functions, we create a second call to the same
1565 // intrinsic with a different type.
1566 SmallVector<Value *, 4> Args;
1567 // The last operand is the intrinsic itself, skip it.
1568 for (unsigned I = 0, E = Call.getNumOperands() - 1; I < E; ++I) {
1569 Value *Arg = Call.getOperand(I);
1570 Type *OrigArgTy = Arg->getType();
1571 Type *IntrinsicArgTy = WidenedFnTy->getParamType(I);
1572 if (OrigArgTy == IntrinsicArgTy) {
1573 Args.push_back(Arg); // The arg is passed as is.
1574 continue;
1575 }
1576 Type *ShadowArgTy = Config.getExtendedFPType(Arg->getType());
1577 assert(ShadowArgTy &&
1578 "don't know how to get the shadow value for a non-FT");
1579 Value *Shadow = Map.getShadow(Arg);
1580 if (ShadowArgTy == IntrinsicArgTy) {
1581 // The shadow is the right type for the intrinsic.
1582 assert(Shadow->getType() == ShadowArgTy);
1583 Args.push_back(Shadow);
1584 continue;
1585 }
1586 // There is no intrinsic with his level of precision, truncate the shadow.
1587 Args.push_back(Builder.CreateFPTrunc(Shadow, IntrinsicArgTy));
1588 }
1589 Value *IntrinsicCall = Builder.CreateIntrinsic(WidenedId, OverloadTys, Args);
1590 return WidenedFnTy->getReturnType() == ExtendedVT
1591 ? IntrinsicCall
1592 : Builder.CreateFPExt(IntrinsicCall, ExtendedVT);
1593}
1594
1595// Handle a CallBase, i.e. a function call, an inline asm sequence, or an
1596// invoke.
1597Value *NumericalStabilitySanitizer::handleCallBase(CallBase &Call, Type *VT,
1598 Type *ExtendedVT,
1599 const TargetLibraryInfo &TLI,
1600 const ValueToShadowMap &Map,
1601 IRBuilder<> &Builder) {
1602 // We cannot look inside inline asm, just expand the result again.
1603 if (Call.isInlineAsm())
1604 return Builder.CreateFPExt(&Call, ExtendedVT);
1605
1606 // Intrinsics and library functions (e.g. sin, exp) are handled
1607 // specifically, because we know their semantics and can do better than
1608 // blindly calling them (e.g. compute the sinus in the actual shadow domain).
1609 if (Value *V =
1610 maybeHandleKnownCallBase(Call, VT, ExtendedVT, TLI, Map, Builder))
1611 return V;
1612
1613 // If the return tag matches that of the called function, read the extended
1614 // return value from the shadow ret ptr. Else, just extend the return value.
1615 Value *L =
1616 Builder.CreateLoad(IntptrTy, NsanShadowRetTag, /*isVolatile=*/false);
1617 Value *HasShadowRet = Builder.CreateICmpEQ(
1618 L, Builder.CreatePtrToInt(Call.getCalledOperand(), IntptrTy));
1619
1620 Value *ShadowRetVal = Builder.CreateLoad(
1621 ExtendedVT,
1622 Builder.CreateConstGEP2_64(NsanShadowRetType, NsanShadowRetPtr, 0, 0),
1623 /*isVolatile=*/false);
1624 Value *Shadow = Builder.CreateSelect(HasShadowRet, ShadowRetVal,
1625 Builder.CreateFPExt(&Call, ExtendedVT));
1626 ++NumInstrumentedFTCalls;
1627 return Shadow;
1628}
1629
1630// Creates a shadow value for the given FT value. At that point all operands are
1631// guaranteed to be available.
1632Value *NumericalStabilitySanitizer::createShadowValueWithOperandsAvailable(
1633 Instruction &Inst, const TargetLibraryInfo &TLI,
1634 const ValueToShadowMap &Map) {
1635 Type *VT = Inst.getType();
1636 Type *ExtendedVT = Config.getExtendedFPType(VT);
1637 assert(ExtendedVT != nullptr && "trying to create a shadow for a non-FT");
1638
1639 if (auto *Load = dyn_cast<LoadInst>(&Inst))
1640 return handleLoad(*Load, VT, ExtendedVT);
1641
1642 if (auto *Call = dyn_cast<CallInst>(&Inst)) {
1643 // Insert after the call.
1644 BasicBlock::iterator It(Inst);
1645 IRBuilder<> Builder(++It);
1647 return handleCallBase(*Call, VT, ExtendedVT, TLI, Map, Builder);
1648 }
1649
1650 if (auto *Invoke = dyn_cast<InvokeInst>(&Inst)) {
1651 // The Invoke terminates the basic block, create a new basic block in
1652 // between the successful invoke and the next block.
1653 BasicBlock *InvokeBB = Invoke->getParent();
1654 BasicBlock *NextBB = Invoke->getNormalDest();
1655 BasicBlock *NewBB =
1656 BasicBlock::Create(Context, "", NextBB->getParent(), NextBB);
1657 Inst.replaceSuccessorWith(NextBB, NewBB);
1658
1659 IRBuilder<> Builder(NewBB);
1660 Builder.SetCurrentDebugLocation(Invoke->getDebugLoc());
1661 Value *Shadow = handleCallBase(*Invoke, VT, ExtendedVT, TLI, Map, Builder);
1662 Builder.CreateBr(NextBB);
1663 NewBB->replaceSuccessorsPhiUsesWith(InvokeBB, NewBB);
1664 return Shadow;
1665 }
1666
1667 IRBuilder<> Builder(Inst.getNextNode());
1668 Builder.SetCurrentDebugLocation(Inst.getDebugLoc());
1669
1670 if (auto *Trunc = dyn_cast<FPTruncInst>(&Inst))
1671 return handleTrunc(*Trunc, VT, ExtendedVT, Map, Builder);
1672 if (auto *Ext = dyn_cast<FPExtInst>(&Inst))
1673 return handleExt(*Ext, VT, ExtendedVT, Map, Builder);
1674
1675 if (auto *UnaryOp = dyn_cast<UnaryOperator>(&Inst))
1676 return Builder.CreateUnOp(UnaryOp->getOpcode(),
1677 Map.getShadow(UnaryOp->getOperand(0)));
1678
1679 if (auto *BinOp = dyn_cast<BinaryOperator>(&Inst))
1680 return Builder.CreateBinOp(BinOp->getOpcode(),
1681 Map.getShadow(BinOp->getOperand(0)),
1682 Map.getShadow(BinOp->getOperand(1)));
1683
1684 if (isa<UIToFPInst>(&Inst) || isa<SIToFPInst>(&Inst)) {
1685 auto *Cast = cast<CastInst>(&Inst);
1686 return Builder.CreateCast(Cast->getOpcode(), Cast->getOperand(0),
1687 ExtendedVT);
1688 }
1689
1690 if (auto *S = dyn_cast<SelectInst>(&Inst))
1691 return Builder.CreateSelect(S->getCondition(),
1692 Map.getShadow(S->getTrueValue()),
1693 Map.getShadow(S->getFalseValue()));
1694
1695 if (auto *Freeze = dyn_cast<FreezeInst>(&Inst))
1696 return Builder.CreateFreeze(Map.getShadow(Freeze->getOperand(0)));
1697
1698 if (auto *Extract = dyn_cast<ExtractElementInst>(&Inst))
1699 return Builder.CreateExtractElement(
1700 Map.getShadow(Extract->getVectorOperand()), Extract->getIndexOperand());
1701
1702 if (auto *Insert = dyn_cast<InsertElementInst>(&Inst))
1703 return Builder.CreateInsertElement(Map.getShadow(Insert->getOperand(0)),
1704 Map.getShadow(Insert->getOperand(1)),
1705 Insert->getOperand(2));
1706
1707 if (auto *Shuffle = dyn_cast<ShuffleVectorInst>(&Inst))
1708 return Builder.CreateShuffleVector(Map.getShadow(Shuffle->getOperand(0)),
1709 Map.getShadow(Shuffle->getOperand(1)),
1710 Shuffle->getShuffleMask());
1711 // TODO: We could make aggregate object first class citizens. For now we
1712 // just extend the extracted value.
1713 if (auto *Extract = dyn_cast<ExtractValueInst>(&Inst))
1714 return Builder.CreateFPExt(Extract, ExtendedVT);
1715
1716 if (auto *BC = dyn_cast<BitCastInst>(&Inst))
1717 return Builder.CreateFPExt(BC, ExtendedVT);
1718
1719 report_fatal_error("Unimplemented support for " +
1720 Twine(Inst.getOpcodeName()));
1721}
1722
1723// Creates a shadow value for an instruction that defines a value of FT type.
1724// FT operands that do not already have shadow values are created recursively.
1725// The DFS is guaranteed to not loop as phis and arguments already have
1726// shadows.
1727void NumericalStabilitySanitizer::maybeCreateShadowValue(
1728 Instruction &Root, const TargetLibraryInfo &TLI, ValueToShadowMap &Map) {
1729 Type *VT = Root.getType();
1730 Type *ExtendedVT = Config.getExtendedFPType(VT);
1731 if (ExtendedVT == nullptr)
1732 return; // Not an FT value.
1733
1734 if (Map.hasShadow(&Root))
1735 return; // Shadow already exists.
1736
1737 assert(!isa<PHINode>(Root) && "phi nodes should already have shadows");
1738
1739 std::vector<Instruction *> DfsStack(1, &Root);
1740 while (!DfsStack.empty()) {
1741 // Ensure that all operands to the instruction have shadows before
1742 // proceeding.
1743 Instruction *I = DfsStack.back();
1744 // The shadow for the instruction might have been created deeper in the DFS,
1745 // see `forward_use_with_two_uses` test.
1746 if (Map.hasShadow(I)) {
1747 DfsStack.pop_back();
1748 continue;
1749 }
1750
1751 bool MissingShadow = false;
1752 for (Value *Op : I->operands()) {
1753 Type *VT = Op->getType();
1754 if (!Config.getExtendedFPType(VT))
1755 continue; // Not an FT value.
1756 if (Map.hasShadow(Op))
1757 continue; // Shadow is already available.
1758 MissingShadow = true;
1759 DfsStack.push_back(cast<Instruction>(Op));
1760 }
1761 if (MissingShadow)
1762 continue; // Process operands and come back to this instruction later.
1763
1764 // All operands have shadows. Create a shadow for the current value.
1765 Value *Shadow = createShadowValueWithOperandsAvailable(*I, TLI, Map);
1766 Map.setShadow(*I, *Shadow);
1767 DfsStack.pop_back();
1768 }
1769}
1770
1771// A floating-point store needs its value and type written to shadow memory.
1772void NumericalStabilitySanitizer::propagateFTStore(
1773 StoreInst &Store, Type *VT, Type *ExtendedVT, const ValueToShadowMap &Map) {
1774 Value *StoredValue = Store.getValueOperand();
1775 IRBuilder<> Builder(&Store);
1776 Builder.SetCurrentDebugLocation(Store.getDebugLoc());
1777 const auto Extents = getMemoryExtentsOrDie(VT);
1778 Value *ShadowPtr = Builder.CreateCall(
1779 NsanGetShadowPtrForStore[Extents.ValueType],
1780 {Store.getPointerOperand(), ConstantInt::get(IntptrTy, Extents.NumElts)});
1781
1782 Value *StoredShadow = Map.getShadow(StoredValue);
1783 if (!Store.getParent()->getParent()->hasOptNone()) {
1784 // Only check stores when optimizing, because non-optimized code generates
1785 // too many stores to the stack, creating false positives.
1786 if (Opts.nsan_check_stores) {
1787 StoredShadow = emitCheck(StoredValue, StoredShadow, Builder,
1788 CheckLoc::makeStore(Store.getPointerOperand()));
1789 ++NumInstrumentedFTStores;
1790 }
1791 }
1792
1793 Builder.CreateAlignedStore(StoredShadow, ShadowPtr, Align(1),
1794 Store.isVolatile());
1795}
1796
1797// A non-ft store needs to invalidate shadow memory. Exceptions are:
1798// - memory transfers of floating-point data through other pointer types (llvm
1799// optimization passes transform `*(float*)a = *(float*)b` into
1800// `*(i32*)a = *(i32*)b` ). These have the same semantics as memcpy.
1801// - Writes of FT-sized constants. LLVM likes to do float stores as bitcasted
1802// ints. Note that this is not really necessary because if the value is
1803// unknown the framework will re-extend it on load anyway. It just felt
1804// easier to debug tests with vectors of FTs.
1805void NumericalStabilitySanitizer::propagateNonFTStore(
1806 StoreInst &Store, Type *VT, const ValueToShadowMap &Map) {
1807 Value *PtrOp = Store.getPointerOperand();
1808 IRBuilder<> Builder(Store.getNextNode());
1809 Builder.SetCurrentDebugLocation(Store.getDebugLoc());
1810 Value *Dst = PtrOp;
1811 TypeSize SlotSize = DL.getTypeStoreSize(VT);
1812 assert(!SlotSize.isScalable() && "unsupported");
1813 const auto LoadSizeBytes = SlotSize.getFixedValue();
1814 Value *ValueSize = Constant::getIntegerValue(
1815 IntptrTy, APInt(IntptrTy->getPrimitiveSizeInBits(), LoadSizeBytes));
1816
1817 ++NumInstrumentedNonFTStores;
1818 Value *StoredValue = Store.getValueOperand();
1819 if (LoadInst *Load = dyn_cast<LoadInst>(StoredValue)) {
1820 // TODO: Handle the case when the value is from a phi.
1821 // This is a memory transfer with memcpy semantics. Copy the type and
1822 // value from the source. Note that we cannot use __nsan_copy_values()
1823 // here, because that will not work when there is a write to memory in
1824 // between the load and the store, e.g. in the case of a swap.
1825 Type *ShadowTypeIntTy = Type::getIntNTy(Context, 8 * LoadSizeBytes);
1826 Type *ShadowValueIntTy =
1827 Type::getIntNTy(Context, 8 * kShadowScale * LoadSizeBytes);
1828 IRBuilder<> LoadBuilder(Load->getNextNode());
1829 Builder.SetCurrentDebugLocation(Store.getDebugLoc());
1830 Value *LoadSrc = Load->getPointerOperand();
1831 // Read the shadow type and value at load time. The type has the same size
1832 // as the FT value, the value has twice its size.
1833 // TODO: cache them to avoid re-creating them when a load is used by
1834 // several stores. Maybe create them like the FT shadows when a load is
1835 // encountered.
1836 Value *RawShadowType = LoadBuilder.CreateAlignedLoad(
1837 ShadowTypeIntTy,
1838 LoadBuilder.CreateCall(NsanGetRawShadowTypePtr, {LoadSrc}), Align(1),
1839 /*isVolatile=*/false);
1840 Value *RawShadowValue = LoadBuilder.CreateAlignedLoad(
1841 ShadowValueIntTy,
1842 LoadBuilder.CreateCall(NsanGetRawShadowPtr, {LoadSrc}), Align(1),
1843 /*isVolatile=*/false);
1844
1845 // Write back the shadow type and value at store time.
1846 Builder.CreateAlignedStore(
1847 RawShadowType, Builder.CreateCall(NsanGetRawShadowTypePtr, {Dst}),
1848 Align(1),
1849 /*isVolatile=*/false);
1850 Builder.CreateAlignedStore(RawShadowValue,
1851 Builder.CreateCall(NsanGetRawShadowPtr, {Dst}),
1852 Align(1),
1853 /*isVolatile=*/false);
1854
1855 ++NumInstrumentedNonFTMemcpyStores;
1856 return;
1857 }
1858 if (Constant *C; Opts.nsan_propagate_non_ft_const_stores_as_ft &&
1859 (C = dyn_cast<Constant>(StoredValue))) {
1860 // This might be a fp constant stored as an int. Bitcast and store if it has
1861 // appropriate size.
1862 Type *BitcastTy = nullptr; // The FT type to bitcast to.
1864 switch (C->getType()->getScalarSizeInBits()) {
1865 case 32:
1866 BitcastTy = Type::getFloatTy(Context);
1867 break;
1868 case 64:
1869 BitcastTy = Type::getDoubleTy(Context);
1870 break;
1871 case 80:
1872 BitcastTy = Type::getX86_FP80Ty(Context);
1873 break;
1874 default:
1875 break;
1876 }
1877
1878 if (BitcastTy)
1879 if (auto *VectorTy = dyn_cast<VectorType>(C->getType()))
1880 BitcastTy = VectorType::get(BitcastTy, VectorTy->getElementCount());
1881 }
1882 if (BitcastTy) {
1883 const MemoryExtents Extents = getMemoryExtentsOrDie(BitcastTy);
1884 Value *ShadowPtr = Builder.CreateCall(
1885 NsanGetShadowPtrForStore[Extents.ValueType],
1886 {PtrOp, ConstantInt::get(IntptrTy, Extents.NumElts)});
1887 // Bitcast the integer value to the appropriate FT type and extend to 2FT.
1888 Type *ExtVT = Config.getExtendedFPType(BitcastTy);
1889 Value *Shadow =
1890 Builder.CreateFPExt(Builder.CreateBitCast(C, BitcastTy), ExtVT);
1891 Builder.CreateAlignedStore(Shadow, ShadowPtr, Align(1),
1892 Store.isVolatile());
1893 return;
1894 }
1895 }
1896 // All other stores just reset the shadow value to unknown.
1897 Builder.CreateCall(NsanSetUnknownFns.getFallback(), {Dst, ValueSize});
1898}
1899
1900void NumericalStabilitySanitizer::propagateShadowValues(
1901 Instruction &Inst, const TargetLibraryInfo &TLI,
1902 const ValueToShadowMap &Map) {
1903 if (auto *Store = dyn_cast<StoreInst>(&Inst)) {
1904 Value *StoredValue = Store->getValueOperand();
1905 Type *VT = StoredValue->getType();
1906 Type *ExtendedVT = Config.getExtendedFPType(VT);
1907 if (ExtendedVT == nullptr)
1908 return propagateNonFTStore(*Store, VT, Map);
1909 return propagateFTStore(*Store, VT, ExtendedVT, Map);
1910 }
1911
1912 if (auto *FCmp = dyn_cast<FCmpInst>(&Inst)) {
1913 emitFCmpCheck(*FCmp, Map);
1914 return;
1915 }
1916
1917 if (auto *CB = dyn_cast<CallBase>(&Inst)) {
1918 maybeAddSuffixForNsanInterface(CB);
1919 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
1921 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&Inst)) {
1922 instrumentMemIntrinsic(MI);
1923 return;
1924 }
1925 populateShadowStack(*CB, TLI, Map);
1926 return;
1927 }
1928
1929 if (auto *RetInst = dyn_cast<ReturnInst>(&Inst)) {
1930 if (!Opts.nsan_check_ret)
1931 return;
1932
1933 Value *RV = RetInst->getReturnValue();
1934 if (RV == nullptr)
1935 return; // This is a `ret void`.
1936 Type *VT = RV->getType();
1937 Type *ExtendedVT = Config.getExtendedFPType(VT);
1938 if (ExtendedVT == nullptr)
1939 return; // Not an FT ret.
1940 Value *RVShadow = Map.getShadow(RV);
1941 IRBuilder<> Builder(RetInst);
1942
1943 RVShadow = emitCheck(RV, RVShadow, Builder, CheckLoc::makeRet());
1944 ++NumInstrumentedFTRets;
1945 // Store tag.
1946 Value *FnAddr =
1947 Builder.CreatePtrToInt(Inst.getParent()->getParent(), IntptrTy);
1948 Builder.CreateStore(FnAddr, NsanShadowRetTag);
1949 // Store value.
1950 Value *ShadowRetValPtr =
1951 Builder.CreateConstGEP2_64(NsanShadowRetType, NsanShadowRetPtr, 0, 0);
1952 Builder.CreateStore(RVShadow, ShadowRetValPtr);
1953 return;
1954 }
1955
1956 if (InsertValueInst *Insert = dyn_cast<InsertValueInst>(&Inst)) {
1957 Value *V = Insert->getOperand(1);
1958 Type *VT = V->getType();
1959 Type *ExtendedVT = Config.getExtendedFPType(VT);
1960 if (ExtendedVT == nullptr)
1961 return;
1962 IRBuilder<> Builder(Insert);
1963 emitCheck(V, Map.getShadow(V), Builder, CheckLoc::makeInsert());
1964 return;
1965 }
1966}
1967
1968// Moves fast math flags from the function to individual instructions, and
1969// removes the attribute from the function.
1970// TODO: Make this controllable with a flag.
1972 std::vector<Instruction *> &Instructions) {
1973 FastMathFlags FMF;
1974#define MOVE_FLAG(attr, setter) \
1975 if (F.getFnAttribute(attr).getValueAsString() == "true") { \
1976 F.removeFnAttr(attr); \
1977 FMF.set##setter(); \
1978 }
1979 MOVE_FLAG("no-signed-zeros-fp-math", NoSignedZeros)
1980#undef MOVE_FLAG
1981
1982 for (Instruction *I : Instructions)
1984 I->setFastMathFlags(FMF);
1985}
1986
1987bool NumericalStabilitySanitizer::sanitizeFunction(
1988 Function &F, const TargetLibraryInfo &TLI) {
1989 if (!F.hasFnAttribute(Attribute::SanitizeNumericalStability) ||
1990 F.isDeclaration())
1991 return false;
1992
1993 if (F.hasFnAttribute(Attribute::DisableSanitizerInstrumentation))
1994 return false;
1995
1996 // This is required to prevent instrumenting call to __nsan_init from within
1997 // the module constructor.
1998 if (F.getName() == kNsanModuleCtorName)
1999 return false;
2000
2001 // The instrumentation maintains:
2002 // - for each IR value `v` of floating-point (or vector floating-point) type
2003 // FT, a shadow IR value `s(v)` with twice the precision 2FT (e.g.
2004 // double for float and f128 for double).
2005 // - A shadow memory, which stores `s(v)` for any `v` that has been stored,
2006 // along with a shadow memory tag, which stores whether the value in the
2007 // corresponding shadow memory is valid. Note that this might be
2008 // incorrect if a non-instrumented function stores to memory, or if
2009 // memory is stored to through a char pointer.
2010 // - A shadow stack, which holds `s(v)` for any floating-point argument `v`
2011 // of a call to an instrumented function. This allows
2012 // instrumented functions to retrieve the shadow values for their
2013 // arguments.
2014 // Because instrumented functions can be called from non-instrumented
2015 // functions, the stack needs to include a tag so that the instrumented
2016 // function knows whether shadow values are available for their
2017 // parameters (i.e. whether is was called by an instrumented function).
2018 // When shadow arguments are not available, they have to be recreated by
2019 // extending the precision of the non-shadow arguments to the non-shadow
2020 // value. Non-instrumented functions do not modify (or even know about) the
2021 // shadow stack. The shadow stack pointer is __nsan_shadow_args. The shadow
2022 // stack tag is __nsan_shadow_args_tag. The tag is any unique identifier
2023 // for the function (we use the address of the function). Both variables
2024 // are thread local.
2025 // Example:
2026 // calls shadow stack tag shadow stack
2027 // =======================================================================
2028 // non_instrumented_1() 0 0
2029 // |
2030 // v
2031 // instrumented_2(float a) 0 0
2032 // |
2033 // v
2034 // instrumented_3(float b, double c) &instrumented_3 s(b),s(c)
2035 // |
2036 // v
2037 // instrumented_4(float d) &instrumented_4 s(d)
2038 // |
2039 // v
2040 // non_instrumented_5(float e) &non_instrumented_5 s(e)
2041 // |
2042 // v
2043 // instrumented_6(float f) &non_instrumented_5 s(e)
2044 //
2045 // On entry, instrumented_2 checks whether the tag corresponds to its
2046 // function ptr.
2047 // Note that functions reset the tag to 0 after reading shadow parameters.
2048 // This ensures that the function does not erroneously read invalid data if
2049 // called twice in the same stack, once from an instrumented function and
2050 // once from an uninstrumented one. For example, in the following example,
2051 // resetting the tag in (A) ensures that (B) does not reuse the same the
2052 // shadow arguments (which would be incorrect).
2053 // instrumented_1(float a)
2054 // |
2055 // v
2056 // instrumented_2(float b) (A)
2057 // |
2058 // v
2059 // non_instrumented_3()
2060 // |
2061 // v
2062 // instrumented_2(float b) (B)
2063 //
2064 // - A shadow return slot. Any function that returns a floating-point value
2065 // places a shadow return value in __nsan_shadow_ret_val. Again, because
2066 // we might be calling non-instrumented functions, this value is guarded
2067 // by __nsan_shadow_ret_tag marker indicating which instrumented function
2068 // placed the value in __nsan_shadow_ret_val, so that the caller can check
2069 // that this corresponds to the callee. Both variables are thread local.
2070 //
2071 // For example, in the following example, the instrumentation in
2072 // `instrumented_1` rejects the shadow return value from `instrumented_3`
2073 // because it is not tagged as expected (`&instrumented_3` instead of
2074 // `non_instrumented_2`):
2075 //
2076 // instrumented_1()
2077 // |
2078 // v
2079 // float non_instrumented_2()
2080 // |
2081 // v
2082 // float instrumented_3()
2083 //
2084 // Calls of known math functions (sin, cos, exp, ...) are duplicated to call
2085 // their overload on the shadow type.
2086
2087 // Collect all instructions before processing, as creating shadow values
2088 // creates new instructions inside the function.
2089 std::vector<Instruction *> OriginalInstructions;
2090 for (BasicBlock &BB : F)
2091 for (Instruction &Inst : BB)
2092 OriginalInstructions.emplace_back(&Inst);
2093
2094 moveFastMathFlags(F, OriginalInstructions);
2095 ValueToShadowMap ValueToShadow(Config);
2096
2097 // In the first pass, we create shadow values for all FT function arguments
2098 // and all phis. This ensures that the DFS of the next pass does not have
2099 // any loops.
2100 std::vector<PHINode *> OriginalPhis;
2101 createShadowArguments(F, TLI, ValueToShadow);
2102 for (Instruction *I : OriginalInstructions) {
2103 if (PHINode *Phi = dyn_cast<PHINode>(I)) {
2104 if (PHINode *Shadow = maybeCreateShadowPhi(*Phi, TLI)) {
2105 OriginalPhis.push_back(Phi);
2106 ValueToShadow.setShadow(*Phi, *Shadow);
2107 }
2108 }
2109 }
2110
2111 // Create shadow values for all instructions creating FT values.
2112 for (Instruction *I : OriginalInstructions)
2113 maybeCreateShadowValue(*I, TLI, ValueToShadow);
2114
2115 // Propagate shadow values across stores, calls and rets.
2116 for (Instruction *I : OriginalInstructions)
2117 propagateShadowValues(*I, TLI, ValueToShadow);
2118
2119 // The last pass populates shadow phis with shadow values.
2120 for (PHINode *Phi : OriginalPhis) {
2121 PHINode *ShadowPhi = cast<PHINode>(ValueToShadow.getShadow(Phi));
2122 for (unsigned I : seq(Phi->getNumOperands())) {
2123 Value *V = Phi->getOperand(I);
2124 Value *Shadow = ValueToShadow.getShadow(V);
2125 BasicBlock *IncomingBB = Phi->getIncomingBlock(I);
2126 // For some instructions (e.g. invoke), we create the shadow in a separate
2127 // block, different from the block where the original value is created.
2128 // In that case, the shadow phi might need to refer to this block instead
2129 // of the original block.
2130 // Note that this can only happen for instructions as constant shadows are
2131 // always created in the same block.
2132 ShadowPhi->addIncoming(Shadow, IncomingBB);
2133 }
2134 }
2135
2136 return !ValueToShadow.empty();
2137}
2138
2140 uint64_t OpSize = 0;
2141 if (Constant *C = dyn_cast<Constant>(V)) {
2142 auto *CInt = dyn_cast<ConstantInt>(C);
2143 if (CInt && CInt->getValue().getBitWidth() <= 64)
2144 OpSize = CInt->getValue().getZExtValue();
2145 }
2146
2147 return OpSize;
2148}
2149
2150// Instrument the memory intrinsics so that they properly modify the shadow
2151// memory.
2152bool NumericalStabilitySanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
2153 IRBuilder<> Builder(MI);
2154 if (auto *M = dyn_cast<MemSetInst>(MI)) {
2155 FunctionCallee SetUnknownFn =
2156 NsanSetUnknownFns.getFunctionFor(GetMemOpSize(M->getArgOperand(2)));
2157 if (SetUnknownFn.getFunctionType()->getNumParams() == 1)
2158 Builder.CreateCall(SetUnknownFn, {/*Address=*/M->getArgOperand(0)});
2159 else
2160 Builder.CreateCall(SetUnknownFn,
2161 {/*Address=*/M->getArgOperand(0),
2162 /*Size=*/Builder.CreateIntCast(M->getArgOperand(2),
2163 IntptrTy, false)});
2164
2165 } else if (auto *M = dyn_cast<MemTransferInst>(MI)) {
2166 FunctionCallee CopyFn =
2167 NsanCopyFns.getFunctionFor(GetMemOpSize(M->getArgOperand(2)));
2168
2169 if (CopyFn.getFunctionType()->getNumParams() == 2)
2170 Builder.CreateCall(CopyFn, {/*Destination=*/M->getArgOperand(0),
2171 /*Source=*/M->getArgOperand(1)});
2172 else
2173 Builder.CreateCall(CopyFn, {/*Destination=*/M->getArgOperand(0),
2174 /*Source=*/M->getArgOperand(1),
2175 /*Size=*/
2176 Builder.CreateIntCast(M->getArgOperand(2),
2177 IntptrTy, false)});
2178 }
2179 return false;
2180}
2181
2182void NumericalStabilitySanitizer::maybeAddSuffixForNsanInterface(CallBase *CI) {
2183 Function *Fn = CI->getCalledFunction();
2184 if (Fn == nullptr)
2185 return;
2186
2187 if (!Fn->getName().starts_with("__nsan_"))
2188 return;
2189
2190 if (Fn->getName() == "__nsan_dump_shadow_mem") {
2191 assert(CI->arg_size() == 4 &&
2192 "invalid prototype for __nsan_dump_shadow_mem");
2193 // __nsan_dump_shadow_mem requires an extra parameter with the dynamic
2194 // configuration:
2195 // (shadow_type_id_for_long_double << 16) | (shadow_type_id_for_double << 8)
2196 // | shadow_type_id_for_double
2197 const uint64_t shadow_value_type_ids =
2198 (static_cast<size_t>(Config.byValueType(kLongDouble).getNsanTypeId())
2199 << 16) |
2200 (static_cast<size_t>(Config.byValueType(kDouble).getNsanTypeId())
2201 << 8) |
2202 static_cast<size_t>(Config.byValueType(kFloat).getNsanTypeId());
2203 CI->setArgOperand(3, ConstantInt::get(IntptrTy, shadow_value_type_ids));
2204 }
2205}
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t 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:170
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:383
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:6103
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.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:125
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:439
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:212
const Instruction & back() const
Definition BasicBlock.h:464
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:205
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:169
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:44
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:63
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:757
bool empty() const
Definition DenseMap.h:716
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
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:2748
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2736
Value * CreateFPTrunc(Value *V, Type *DestTy, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2277
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition IRBuilder.h:2795
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:2069
BasicBlock::iterator GetInsertPoint() const
Definition IRBuilder.h:177
Value * CreateFreeze(Value *V, const Twine &Name="")
Definition IRBuilder.h:2814
void SetCurrentDebugLocation(const DebugLoc &L)
Set location information used by debugging information.
Definition IRBuilder.h:229
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition IRBuilder.h:528
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="", MDNode *FPMathTag=nullptr, FMFSource FMFSource={})
Definition IRBuilder.h:2360
Value * CreateUnOp(Instruction::UnaryOps Opc, Value *V, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1860
UncondBrInst * CreateBr(BasicBlock *Dest)
Create an unconditional 'br label X' instruction.
Definition IRBuilder.h:1212
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2458
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2319
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:1913
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
Definition IRBuilder.h:2770
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:1931
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2309
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2640
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1733
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
Definition IRBuilder.h:2399
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align, bool isVolatile=false)
Definition IRBuilder.h:1959
Value * CreateFPExt(Value *V, Type *DestTy, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2292
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1594
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
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:76
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:880
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.
static Attribute::AttrKind getExtAttrForBoolParam(const Triple &T)
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
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:352
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:294
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:277
static LLVM_ABI Type * getFP128Ty(LLVMContext &C)
Definition Type.cpp:276
LLVM_ABI unsigned getStructNumElements() const
LLVM_ABI uint64_t getArrayNumElements() const
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:267
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:292
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:291
static LLVM_ABI Type * getDoubleTy(LLVMContext &C)
Definition Type.cpp:272
static LLVM_ABI Type * getX86_FP80Ty(LLVMContext &C)
Definition Type.cpp:275
static LLVM_ABI Type * getFloatTy(LLVMContext &C)
Definition Type.cpp:271
'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:314
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:201
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
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.
const InstrumentationOptions & getInstrumentationOptions(const LLVMContext &C)
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:2575
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:3649
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)