Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/Instrumentation/ThreadSanitizer.cpp
35266 views
//===-- ThreadSanitizer.cpp - race detector -------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file is a part of ThreadSanitizer, a race detector.9//10// The tool is under development, for the details about previous versions see11// http://code.google.com/p/data-race-test12//13// The instrumentation phase is quite simple:14// - Insert calls to run-time library before every memory access.15// - Optimizations may apply to avoid instrumenting some of the accesses.16// - Insert calls at function entry/exit.17// The rest is handled by the run-time library.18//===----------------------------------------------------------------------===//1920#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"21#include "llvm/ADT/DenseMap.h"22#include "llvm/ADT/SmallString.h"23#include "llvm/ADT/SmallVector.h"24#include "llvm/ADT/Statistic.h"25#include "llvm/ADT/StringExtras.h"26#include "llvm/Analysis/CaptureTracking.h"27#include "llvm/Analysis/TargetLibraryInfo.h"28#include "llvm/Analysis/ValueTracking.h"29#include "llvm/IR/DataLayout.h"30#include "llvm/IR/Function.h"31#include "llvm/IR/IRBuilder.h"32#include "llvm/IR/Instructions.h"33#include "llvm/IR/IntrinsicInst.h"34#include "llvm/IR/Intrinsics.h"35#include "llvm/IR/LLVMContext.h"36#include "llvm/IR/Metadata.h"37#include "llvm/IR/Module.h"38#include "llvm/IR/Type.h"39#include "llvm/ProfileData/InstrProf.h"40#include "llvm/Support/CommandLine.h"41#include "llvm/Support/Debug.h"42#include "llvm/Support/MathExtras.h"43#include "llvm/Support/raw_ostream.h"44#include "llvm/Transforms/Instrumentation.h"45#include "llvm/Transforms/Utils/EscapeEnumerator.h"46#include "llvm/Transforms/Utils/Local.h"47#include "llvm/Transforms/Utils/ModuleUtils.h"4849using namespace llvm;5051#define DEBUG_TYPE "tsan"5253static cl::opt<bool> ClInstrumentMemoryAccesses(54"tsan-instrument-memory-accesses", cl::init(true),55cl::desc("Instrument memory accesses"), cl::Hidden);56static cl::opt<bool>57ClInstrumentFuncEntryExit("tsan-instrument-func-entry-exit", cl::init(true),58cl::desc("Instrument function entry and exit"),59cl::Hidden);60static cl::opt<bool> ClHandleCxxExceptions(61"tsan-handle-cxx-exceptions", cl::init(true),62cl::desc("Handle C++ exceptions (insert cleanup blocks for unwinding)"),63cl::Hidden);64static cl::opt<bool> ClInstrumentAtomics("tsan-instrument-atomics",65cl::init(true),66cl::desc("Instrument atomics"),67cl::Hidden);68static cl::opt<bool> ClInstrumentMemIntrinsics(69"tsan-instrument-memintrinsics", cl::init(true),70cl::desc("Instrument memintrinsics (memset/memcpy/memmove)"), cl::Hidden);71static cl::opt<bool> ClDistinguishVolatile(72"tsan-distinguish-volatile", cl::init(false),73cl::desc("Emit special instrumentation for accesses to volatiles"),74cl::Hidden);75static cl::opt<bool> ClInstrumentReadBeforeWrite(76"tsan-instrument-read-before-write", cl::init(false),77cl::desc("Do not eliminate read instrumentation for read-before-writes"),78cl::Hidden);79static cl::opt<bool> ClCompoundReadBeforeWrite(80"tsan-compound-read-before-write", cl::init(false),81cl::desc("Emit special compound instrumentation for reads-before-writes"),82cl::Hidden);8384STATISTIC(NumInstrumentedReads, "Number of instrumented reads");85STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");86STATISTIC(NumOmittedReadsBeforeWrite,87"Number of reads ignored due to following writes");88STATISTIC(NumAccessesWithBadSize, "Number of accesses with bad size");89STATISTIC(NumInstrumentedVtableWrites, "Number of vtable ptr writes");90STATISTIC(NumInstrumentedVtableReads, "Number of vtable ptr reads");91STATISTIC(NumOmittedReadsFromConstantGlobals,92"Number of reads from constant globals");93STATISTIC(NumOmittedReadsFromVtable, "Number of vtable reads");94STATISTIC(NumOmittedNonCaptured, "Number of accesses ignored due to capturing");9596const char kTsanModuleCtorName[] = "tsan.module_ctor";97const char kTsanInitName[] = "__tsan_init";9899namespace {100101/// ThreadSanitizer: instrument the code in module to find races.102///103/// Instantiating ThreadSanitizer inserts the tsan runtime library API function104/// declarations into the module if they don't exist already. Instantiating105/// ensures the __tsan_init function is in the list of global constructors for106/// the module.107struct ThreadSanitizer {108ThreadSanitizer() {109// Check options and warn user.110if (ClInstrumentReadBeforeWrite && ClCompoundReadBeforeWrite) {111errs()112<< "warning: Option -tsan-compound-read-before-write has no effect "113"when -tsan-instrument-read-before-write is set.\n";114}115}116117bool sanitizeFunction(Function &F, const TargetLibraryInfo &TLI);118119private:120// Internal Instruction wrapper that contains more information about the121// Instruction from prior analysis.122struct InstructionInfo {123// Instrumentation emitted for this instruction is for a compounded set of124// read and write operations in the same basic block.125static constexpr unsigned kCompoundRW = (1U << 0);126127explicit InstructionInfo(Instruction *Inst) : Inst(Inst) {}128129Instruction *Inst;130unsigned Flags = 0;131};132133void initialize(Module &M, const TargetLibraryInfo &TLI);134bool instrumentLoadOrStore(const InstructionInfo &II, const DataLayout &DL);135bool instrumentAtomic(Instruction *I, const DataLayout &DL);136bool instrumentMemIntrinsic(Instruction *I);137void chooseInstructionsToInstrument(SmallVectorImpl<Instruction *> &Local,138SmallVectorImpl<InstructionInfo> &All,139const DataLayout &DL);140bool addrPointsToConstantData(Value *Addr);141int getMemoryAccessFuncIndex(Type *OrigTy, Value *Addr, const DataLayout &DL);142void InsertRuntimeIgnores(Function &F);143144Type *IntptrTy;145FunctionCallee TsanFuncEntry;146FunctionCallee TsanFuncExit;147FunctionCallee TsanIgnoreBegin;148FunctionCallee TsanIgnoreEnd;149// Accesses sizes are powers of two: 1, 2, 4, 8, 16.150static const size_t kNumberOfAccessSizes = 5;151FunctionCallee TsanRead[kNumberOfAccessSizes];152FunctionCallee TsanWrite[kNumberOfAccessSizes];153FunctionCallee TsanUnalignedRead[kNumberOfAccessSizes];154FunctionCallee TsanUnalignedWrite[kNumberOfAccessSizes];155FunctionCallee TsanVolatileRead[kNumberOfAccessSizes];156FunctionCallee TsanVolatileWrite[kNumberOfAccessSizes];157FunctionCallee TsanUnalignedVolatileRead[kNumberOfAccessSizes];158FunctionCallee TsanUnalignedVolatileWrite[kNumberOfAccessSizes];159FunctionCallee TsanCompoundRW[kNumberOfAccessSizes];160FunctionCallee TsanUnalignedCompoundRW[kNumberOfAccessSizes];161FunctionCallee TsanAtomicLoad[kNumberOfAccessSizes];162FunctionCallee TsanAtomicStore[kNumberOfAccessSizes];163FunctionCallee TsanAtomicRMW[AtomicRMWInst::LAST_BINOP + 1]164[kNumberOfAccessSizes];165FunctionCallee TsanAtomicCAS[kNumberOfAccessSizes];166FunctionCallee TsanAtomicThreadFence;167FunctionCallee TsanAtomicSignalFence;168FunctionCallee TsanVptrUpdate;169FunctionCallee TsanVptrLoad;170FunctionCallee MemmoveFn, MemcpyFn, MemsetFn;171};172173void insertModuleCtor(Module &M) {174getOrCreateSanitizerCtorAndInitFunctions(175M, kTsanModuleCtorName, kTsanInitName, /*InitArgTypes=*/{},176/*InitArgs=*/{},177// This callback is invoked when the functions are created the first178// time. Hook them into the global ctors list in that case:179[&](Function *Ctor, FunctionCallee) { appendToGlobalCtors(M, Ctor, 0); });180}181} // namespace182183PreservedAnalyses ThreadSanitizerPass::run(Function &F,184FunctionAnalysisManager &FAM) {185ThreadSanitizer TSan;186if (TSan.sanitizeFunction(F, FAM.getResult<TargetLibraryAnalysis>(F)))187return PreservedAnalyses::none();188return PreservedAnalyses::all();189}190191PreservedAnalyses ModuleThreadSanitizerPass::run(Module &M,192ModuleAnalysisManager &MAM) {193insertModuleCtor(M);194return PreservedAnalyses::none();195}196void ThreadSanitizer::initialize(Module &M, const TargetLibraryInfo &TLI) {197const DataLayout &DL = M.getDataLayout();198LLVMContext &Ctx = M.getContext();199IntptrTy = DL.getIntPtrType(Ctx);200201IRBuilder<> IRB(Ctx);202AttributeList Attr;203Attr = Attr.addFnAttribute(Ctx, Attribute::NoUnwind);204// Initialize the callbacks.205TsanFuncEntry = M.getOrInsertFunction("__tsan_func_entry", Attr,206IRB.getVoidTy(), IRB.getPtrTy());207TsanFuncExit =208M.getOrInsertFunction("__tsan_func_exit", Attr, IRB.getVoidTy());209TsanIgnoreBegin = M.getOrInsertFunction("__tsan_ignore_thread_begin", Attr,210IRB.getVoidTy());211TsanIgnoreEnd =212M.getOrInsertFunction("__tsan_ignore_thread_end", Attr, IRB.getVoidTy());213IntegerType *OrdTy = IRB.getInt32Ty();214for (size_t i = 0; i < kNumberOfAccessSizes; ++i) {215const unsigned ByteSize = 1U << i;216const unsigned BitSize = ByteSize * 8;217std::string ByteSizeStr = utostr(ByteSize);218std::string BitSizeStr = utostr(BitSize);219SmallString<32> ReadName("__tsan_read" + ByteSizeStr);220TsanRead[i] = M.getOrInsertFunction(ReadName, Attr, IRB.getVoidTy(),221IRB.getPtrTy());222223SmallString<32> WriteName("__tsan_write" + ByteSizeStr);224TsanWrite[i] = M.getOrInsertFunction(WriteName, Attr, IRB.getVoidTy(),225IRB.getPtrTy());226227SmallString<64> UnalignedReadName("__tsan_unaligned_read" + ByteSizeStr);228TsanUnalignedRead[i] = M.getOrInsertFunction(229UnalignedReadName, Attr, IRB.getVoidTy(), IRB.getPtrTy());230231SmallString<64> UnalignedWriteName("__tsan_unaligned_write" + ByteSizeStr);232TsanUnalignedWrite[i] = M.getOrInsertFunction(233UnalignedWriteName, Attr, IRB.getVoidTy(), IRB.getPtrTy());234235SmallString<64> VolatileReadName("__tsan_volatile_read" + ByteSizeStr);236TsanVolatileRead[i] = M.getOrInsertFunction(237VolatileReadName, Attr, IRB.getVoidTy(), IRB.getPtrTy());238239SmallString<64> VolatileWriteName("__tsan_volatile_write" + ByteSizeStr);240TsanVolatileWrite[i] = M.getOrInsertFunction(241VolatileWriteName, Attr, IRB.getVoidTy(), IRB.getPtrTy());242243SmallString<64> UnalignedVolatileReadName("__tsan_unaligned_volatile_read" +244ByteSizeStr);245TsanUnalignedVolatileRead[i] = M.getOrInsertFunction(246UnalignedVolatileReadName, Attr, IRB.getVoidTy(), IRB.getPtrTy());247248SmallString<64> UnalignedVolatileWriteName(249"__tsan_unaligned_volatile_write" + ByteSizeStr);250TsanUnalignedVolatileWrite[i] = M.getOrInsertFunction(251UnalignedVolatileWriteName, Attr, IRB.getVoidTy(), IRB.getPtrTy());252253SmallString<64> CompoundRWName("__tsan_read_write" + ByteSizeStr);254TsanCompoundRW[i] = M.getOrInsertFunction(255CompoundRWName, Attr, IRB.getVoidTy(), IRB.getPtrTy());256257SmallString<64> UnalignedCompoundRWName("__tsan_unaligned_read_write" +258ByteSizeStr);259TsanUnalignedCompoundRW[i] = M.getOrInsertFunction(260UnalignedCompoundRWName, Attr, IRB.getVoidTy(), IRB.getPtrTy());261262Type *Ty = Type::getIntNTy(Ctx, BitSize);263Type *PtrTy = PointerType::get(Ctx, 0);264SmallString<32> AtomicLoadName("__tsan_atomic" + BitSizeStr + "_load");265TsanAtomicLoad[i] =266M.getOrInsertFunction(AtomicLoadName,267TLI.getAttrList(&Ctx, {1}, /*Signed=*/true,268/*Ret=*/BitSize <= 32, Attr),269Ty, PtrTy, OrdTy);270271// Args of type Ty need extension only when BitSize is 32 or less.272using Idxs = std::vector<unsigned>;273Idxs Idxs2Or12 ((BitSize <= 32) ? Idxs({1, 2}) : Idxs({2}));274Idxs Idxs34Or1234((BitSize <= 32) ? Idxs({1, 2, 3, 4}) : Idxs({3, 4}));275SmallString<32> AtomicStoreName("__tsan_atomic" + BitSizeStr + "_store");276TsanAtomicStore[i] = M.getOrInsertFunction(277AtomicStoreName,278TLI.getAttrList(&Ctx, Idxs2Or12, /*Signed=*/true, /*Ret=*/false, Attr),279IRB.getVoidTy(), PtrTy, Ty, OrdTy);280281for (unsigned Op = AtomicRMWInst::FIRST_BINOP;282Op <= AtomicRMWInst::LAST_BINOP; ++Op) {283TsanAtomicRMW[Op][i] = nullptr;284const char *NamePart = nullptr;285if (Op == AtomicRMWInst::Xchg)286NamePart = "_exchange";287else if (Op == AtomicRMWInst::Add)288NamePart = "_fetch_add";289else if (Op == AtomicRMWInst::Sub)290NamePart = "_fetch_sub";291else if (Op == AtomicRMWInst::And)292NamePart = "_fetch_and";293else if (Op == AtomicRMWInst::Or)294NamePart = "_fetch_or";295else if (Op == AtomicRMWInst::Xor)296NamePart = "_fetch_xor";297else if (Op == AtomicRMWInst::Nand)298NamePart = "_fetch_nand";299else300continue;301SmallString<32> RMWName("__tsan_atomic" + itostr(BitSize) + NamePart);302TsanAtomicRMW[Op][i] = M.getOrInsertFunction(303RMWName,304TLI.getAttrList(&Ctx, Idxs2Or12, /*Signed=*/true,305/*Ret=*/BitSize <= 32, Attr),306Ty, PtrTy, Ty, OrdTy);307}308309SmallString<32> AtomicCASName("__tsan_atomic" + BitSizeStr +310"_compare_exchange_val");311TsanAtomicCAS[i] = M.getOrInsertFunction(312AtomicCASName,313TLI.getAttrList(&Ctx, Idxs34Or1234, /*Signed=*/true,314/*Ret=*/BitSize <= 32, Attr),315Ty, PtrTy, Ty, Ty, OrdTy, OrdTy);316}317TsanVptrUpdate =318M.getOrInsertFunction("__tsan_vptr_update", Attr, IRB.getVoidTy(),319IRB.getPtrTy(), IRB.getPtrTy());320TsanVptrLoad = M.getOrInsertFunction("__tsan_vptr_read", Attr,321IRB.getVoidTy(), IRB.getPtrTy());322TsanAtomicThreadFence = M.getOrInsertFunction(323"__tsan_atomic_thread_fence",324TLI.getAttrList(&Ctx, {0}, /*Signed=*/true, /*Ret=*/false, Attr),325IRB.getVoidTy(), OrdTy);326327TsanAtomicSignalFence = M.getOrInsertFunction(328"__tsan_atomic_signal_fence",329TLI.getAttrList(&Ctx, {0}, /*Signed=*/true, /*Ret=*/false, Attr),330IRB.getVoidTy(), OrdTy);331332MemmoveFn =333M.getOrInsertFunction("__tsan_memmove", Attr, IRB.getPtrTy(),334IRB.getPtrTy(), IRB.getPtrTy(), IntptrTy);335MemcpyFn =336M.getOrInsertFunction("__tsan_memcpy", Attr, IRB.getPtrTy(),337IRB.getPtrTy(), IRB.getPtrTy(), IntptrTy);338MemsetFn = M.getOrInsertFunction(339"__tsan_memset",340TLI.getAttrList(&Ctx, {1}, /*Signed=*/true, /*Ret=*/false, Attr),341IRB.getPtrTy(), IRB.getPtrTy(), IRB.getInt32Ty(), IntptrTy);342}343344static bool isVtableAccess(Instruction *I) {345if (MDNode *Tag = I->getMetadata(LLVMContext::MD_tbaa))346return Tag->isTBAAVtableAccess();347return false;348}349350// Do not instrument known races/"benign races" that come from compiler351// instrumentatin. The user has no way of suppressing them.352static bool shouldInstrumentReadWriteFromAddress(const Module *M, Value *Addr) {353// Peel off GEPs and BitCasts.354Addr = Addr->stripInBoundsOffsets();355356if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {357if (GV->hasSection()) {358StringRef SectionName = GV->getSection();359// Check if the global is in the PGO counters section.360auto OF = Triple(M->getTargetTriple()).getObjectFormat();361if (SectionName.ends_with(362getInstrProfSectionName(IPSK_cnts, OF, /*AddSegmentInfo=*/false)))363return false;364}365}366367// Do not instrument accesses from different address spaces; we cannot deal368// with them.369if (Addr) {370Type *PtrTy = cast<PointerType>(Addr->getType()->getScalarType());371if (PtrTy->getPointerAddressSpace() != 0)372return false;373}374375return true;376}377378bool ThreadSanitizer::addrPointsToConstantData(Value *Addr) {379// If this is a GEP, just analyze its pointer operand.380if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr))381Addr = GEP->getPointerOperand();382383if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {384if (GV->isConstant()) {385// Reads from constant globals can not race with any writes.386NumOmittedReadsFromConstantGlobals++;387return true;388}389} else if (LoadInst *L = dyn_cast<LoadInst>(Addr)) {390if (isVtableAccess(L)) {391// Reads from a vtable pointer can not race with any writes.392NumOmittedReadsFromVtable++;393return true;394}395}396return false;397}398399// Instrumenting some of the accesses may be proven redundant.400// Currently handled:401// - read-before-write (within same BB, no calls between)402// - not captured variables403//404// We do not handle some of the patterns that should not survive405// after the classic compiler optimizations.406// E.g. two reads from the same temp should be eliminated by CSE,407// two writes should be eliminated by DSE, etc.408//409// 'Local' is a vector of insns within the same BB (no calls between).410// 'All' is a vector of insns that will be instrumented.411void ThreadSanitizer::chooseInstructionsToInstrument(412SmallVectorImpl<Instruction *> &Local,413SmallVectorImpl<InstructionInfo> &All, const DataLayout &DL) {414DenseMap<Value *, size_t> WriteTargets; // Map of addresses to index in All415// Iterate from the end.416for (Instruction *I : reverse(Local)) {417const bool IsWrite = isa<StoreInst>(*I);418Value *Addr = IsWrite ? cast<StoreInst>(I)->getPointerOperand()419: cast<LoadInst>(I)->getPointerOperand();420421if (!shouldInstrumentReadWriteFromAddress(I->getModule(), Addr))422continue;423424if (!IsWrite) {425const auto WriteEntry = WriteTargets.find(Addr);426if (!ClInstrumentReadBeforeWrite && WriteEntry != WriteTargets.end()) {427auto &WI = All[WriteEntry->second];428// If we distinguish volatile accesses and if either the read or write429// is volatile, do not omit any instrumentation.430const bool AnyVolatile =431ClDistinguishVolatile && (cast<LoadInst>(I)->isVolatile() ||432cast<StoreInst>(WI.Inst)->isVolatile());433if (!AnyVolatile) {434// We will write to this temp, so no reason to analyze the read.435// Mark the write instruction as compound.436WI.Flags |= InstructionInfo::kCompoundRW;437NumOmittedReadsBeforeWrite++;438continue;439}440}441442if (addrPointsToConstantData(Addr)) {443// Addr points to some constant data -- it can not race with any writes.444continue;445}446}447448if (isa<AllocaInst>(getUnderlyingObject(Addr)) &&449!PointerMayBeCaptured(Addr, true, true)) {450// The variable is addressable but not captured, so it cannot be451// referenced from a different thread and participate in a data race452// (see llvm/Analysis/CaptureTracking.h for details).453NumOmittedNonCaptured++;454continue;455}456457// Instrument this instruction.458All.emplace_back(I);459if (IsWrite) {460// For read-before-write and compound instrumentation we only need one461// write target, and we can override any previous entry if it exists.462WriteTargets[Addr] = All.size() - 1;463}464}465Local.clear();466}467468static bool isTsanAtomic(const Instruction *I) {469// TODO: Ask TTI whether synchronization scope is between threads.470auto SSID = getAtomicSyncScopeID(I);471if (!SSID)472return false;473if (isa<LoadInst>(I) || isa<StoreInst>(I))474return *SSID != SyncScope::SingleThread;475return true;476}477478void ThreadSanitizer::InsertRuntimeIgnores(Function &F) {479InstrumentationIRBuilder IRB(F.getEntryBlock().getFirstNonPHI());480IRB.CreateCall(TsanIgnoreBegin);481EscapeEnumerator EE(F, "tsan_ignore_cleanup", ClHandleCxxExceptions);482while (IRBuilder<> *AtExit = EE.Next()) {483InstrumentationIRBuilder::ensureDebugInfo(*AtExit, F);484AtExit->CreateCall(TsanIgnoreEnd);485}486}487488bool ThreadSanitizer::sanitizeFunction(Function &F,489const TargetLibraryInfo &TLI) {490// This is required to prevent instrumenting call to __tsan_init from within491// the module constructor.492if (F.getName() == kTsanModuleCtorName)493return false;494// Naked functions can not have prologue/epilogue495// (__tsan_func_entry/__tsan_func_exit) generated, so don't instrument them at496// all.497if (F.hasFnAttribute(Attribute::Naked))498return false;499500// __attribute__(disable_sanitizer_instrumentation) prevents all kinds of501// instrumentation.502if (F.hasFnAttribute(Attribute::DisableSanitizerInstrumentation))503return false;504505initialize(*F.getParent(), TLI);506SmallVector<InstructionInfo, 8> AllLoadsAndStores;507SmallVector<Instruction*, 8> LocalLoadsAndStores;508SmallVector<Instruction*, 8> AtomicAccesses;509SmallVector<Instruction*, 8> MemIntrinCalls;510bool Res = false;511bool HasCalls = false;512bool SanitizeFunction = F.hasFnAttribute(Attribute::SanitizeThread);513const DataLayout &DL = F.getDataLayout();514515// Traverse all instructions, collect loads/stores/returns, check for calls.516for (auto &BB : F) {517for (auto &Inst : BB) {518// Skip instructions inserted by another instrumentation.519if (Inst.hasMetadata(LLVMContext::MD_nosanitize))520continue;521if (isTsanAtomic(&Inst))522AtomicAccesses.push_back(&Inst);523else if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))524LocalLoadsAndStores.push_back(&Inst);525else if ((isa<CallInst>(Inst) && !isa<DbgInfoIntrinsic>(Inst)) ||526isa<InvokeInst>(Inst)) {527if (CallInst *CI = dyn_cast<CallInst>(&Inst))528maybeMarkSanitizerLibraryCallNoBuiltin(CI, &TLI);529if (isa<MemIntrinsic>(Inst))530MemIntrinCalls.push_back(&Inst);531HasCalls = true;532chooseInstructionsToInstrument(LocalLoadsAndStores, AllLoadsAndStores,533DL);534}535}536chooseInstructionsToInstrument(LocalLoadsAndStores, AllLoadsAndStores, DL);537}538539// We have collected all loads and stores.540// FIXME: many of these accesses do not need to be checked for races541// (e.g. variables that do not escape, etc).542543// Instrument memory accesses only if we want to report bugs in the function.544if (ClInstrumentMemoryAccesses && SanitizeFunction)545for (const auto &II : AllLoadsAndStores) {546Res |= instrumentLoadOrStore(II, DL);547}548549// Instrument atomic memory accesses in any case (they can be used to550// implement synchronization).551if (ClInstrumentAtomics)552for (auto *Inst : AtomicAccesses) {553Res |= instrumentAtomic(Inst, DL);554}555556if (ClInstrumentMemIntrinsics && SanitizeFunction)557for (auto *Inst : MemIntrinCalls) {558Res |= instrumentMemIntrinsic(Inst);559}560561if (F.hasFnAttribute("sanitize_thread_no_checking_at_run_time")) {562assert(!F.hasFnAttribute(Attribute::SanitizeThread));563if (HasCalls)564InsertRuntimeIgnores(F);565}566567// Instrument function entry/exit points if there were instrumented accesses.568if ((Res || HasCalls) && ClInstrumentFuncEntryExit) {569InstrumentationIRBuilder IRB(F.getEntryBlock().getFirstNonPHI());570Value *ReturnAddress = IRB.CreateCall(571Intrinsic::getDeclaration(F.getParent(), Intrinsic::returnaddress),572IRB.getInt32(0));573IRB.CreateCall(TsanFuncEntry, ReturnAddress);574575EscapeEnumerator EE(F, "tsan_cleanup", ClHandleCxxExceptions);576while (IRBuilder<> *AtExit = EE.Next()) {577InstrumentationIRBuilder::ensureDebugInfo(*AtExit, F);578AtExit->CreateCall(TsanFuncExit, {});579}580Res = true;581}582return Res;583}584585bool ThreadSanitizer::instrumentLoadOrStore(const InstructionInfo &II,586const DataLayout &DL) {587InstrumentationIRBuilder IRB(II.Inst);588const bool IsWrite = isa<StoreInst>(*II.Inst);589Value *Addr = IsWrite ? cast<StoreInst>(II.Inst)->getPointerOperand()590: cast<LoadInst>(II.Inst)->getPointerOperand();591Type *OrigTy = getLoadStoreType(II.Inst);592593// swifterror memory addresses are mem2reg promoted by instruction selection.594// As such they cannot have regular uses like an instrumentation function and595// it makes no sense to track them as memory.596if (Addr->isSwiftError())597return false;598599int Idx = getMemoryAccessFuncIndex(OrigTy, Addr, DL);600if (Idx < 0)601return false;602if (IsWrite && isVtableAccess(II.Inst)) {603LLVM_DEBUG(dbgs() << " VPTR : " << *II.Inst << "\n");604Value *StoredValue = cast<StoreInst>(II.Inst)->getValueOperand();605// StoredValue may be a vector type if we are storing several vptrs at once.606// In this case, just take the first element of the vector since this is607// enough to find vptr races.608if (isa<VectorType>(StoredValue->getType()))609StoredValue = IRB.CreateExtractElement(610StoredValue, ConstantInt::get(IRB.getInt32Ty(), 0));611if (StoredValue->getType()->isIntegerTy())612StoredValue = IRB.CreateIntToPtr(StoredValue, IRB.getPtrTy());613// Call TsanVptrUpdate.614IRB.CreateCall(TsanVptrUpdate, {Addr, StoredValue});615NumInstrumentedVtableWrites++;616return true;617}618if (!IsWrite && isVtableAccess(II.Inst)) {619IRB.CreateCall(TsanVptrLoad, Addr);620NumInstrumentedVtableReads++;621return true;622}623624const Align Alignment = IsWrite ? cast<StoreInst>(II.Inst)->getAlign()625: cast<LoadInst>(II.Inst)->getAlign();626const bool IsCompoundRW =627ClCompoundReadBeforeWrite && (II.Flags & InstructionInfo::kCompoundRW);628const bool IsVolatile = ClDistinguishVolatile &&629(IsWrite ? cast<StoreInst>(II.Inst)->isVolatile()630: cast<LoadInst>(II.Inst)->isVolatile());631assert((!IsVolatile || !IsCompoundRW) && "Compound volatile invalid!");632633const uint32_t TypeSize = DL.getTypeStoreSizeInBits(OrigTy);634FunctionCallee OnAccessFunc = nullptr;635if (Alignment >= Align(8) || (Alignment.value() % (TypeSize / 8)) == 0) {636if (IsCompoundRW)637OnAccessFunc = TsanCompoundRW[Idx];638else if (IsVolatile)639OnAccessFunc = IsWrite ? TsanVolatileWrite[Idx] : TsanVolatileRead[Idx];640else641OnAccessFunc = IsWrite ? TsanWrite[Idx] : TsanRead[Idx];642} else {643if (IsCompoundRW)644OnAccessFunc = TsanUnalignedCompoundRW[Idx];645else if (IsVolatile)646OnAccessFunc = IsWrite ? TsanUnalignedVolatileWrite[Idx]647: TsanUnalignedVolatileRead[Idx];648else649OnAccessFunc = IsWrite ? TsanUnalignedWrite[Idx] : TsanUnalignedRead[Idx];650}651IRB.CreateCall(OnAccessFunc, Addr);652if (IsCompoundRW || IsWrite)653NumInstrumentedWrites++;654if (IsCompoundRW || !IsWrite)655NumInstrumentedReads++;656return true;657}658659static ConstantInt *createOrdering(IRBuilder<> *IRB, AtomicOrdering ord) {660uint32_t v = 0;661switch (ord) {662case AtomicOrdering::NotAtomic:663llvm_unreachable("unexpected atomic ordering!");664case AtomicOrdering::Unordered: [[fallthrough]];665case AtomicOrdering::Monotonic: v = 0; break;666// Not specified yet:667// case AtomicOrdering::Consume: v = 1; break;668case AtomicOrdering::Acquire: v = 2; break;669case AtomicOrdering::Release: v = 3; break;670case AtomicOrdering::AcquireRelease: v = 4; break;671case AtomicOrdering::SequentiallyConsistent: v = 5; break;672}673return IRB->getInt32(v);674}675676// If a memset intrinsic gets inlined by the code gen, we will miss races on it.677// So, we either need to ensure the intrinsic is not inlined, or instrument it.678// We do not instrument memset/memmove/memcpy intrinsics (too complicated),679// instead we simply replace them with regular function calls, which are then680// intercepted by the run-time.681// Since tsan is running after everyone else, the calls should not be682// replaced back with intrinsics. If that becomes wrong at some point,683// we will need to call e.g. __tsan_memset to avoid the intrinsics.684bool ThreadSanitizer::instrumentMemIntrinsic(Instruction *I) {685InstrumentationIRBuilder IRB(I);686if (MemSetInst *M = dyn_cast<MemSetInst>(I)) {687Value *Cast1 = IRB.CreateIntCast(M->getArgOperand(1), IRB.getInt32Ty(), false);688Value *Cast2 = IRB.CreateIntCast(M->getArgOperand(2), IntptrTy, false);689IRB.CreateCall(690MemsetFn,691{M->getArgOperand(0),692Cast1,693Cast2});694I->eraseFromParent();695} else if (MemTransferInst *M = dyn_cast<MemTransferInst>(I)) {696IRB.CreateCall(697isa<MemCpyInst>(M) ? MemcpyFn : MemmoveFn,698{M->getArgOperand(0),699M->getArgOperand(1),700IRB.CreateIntCast(M->getArgOperand(2), IntptrTy, false)});701I->eraseFromParent();702}703return false;704}705706// Both llvm and ThreadSanitizer atomic operations are based on C++11/C1x707// standards. For background see C++11 standard. A slightly older, publicly708// available draft of the standard (not entirely up-to-date, but close enough709// for casual browsing) is available here:710// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3242.pdf711// The following page contains more background information:712// http://www.hpl.hp.com/personal/Hans_Boehm/c++mm/713714bool ThreadSanitizer::instrumentAtomic(Instruction *I, const DataLayout &DL) {715InstrumentationIRBuilder IRB(I);716if (LoadInst *LI = dyn_cast<LoadInst>(I)) {717Value *Addr = LI->getPointerOperand();718Type *OrigTy = LI->getType();719int Idx = getMemoryAccessFuncIndex(OrigTy, Addr, DL);720if (Idx < 0)721return false;722Value *Args[] = {Addr,723createOrdering(&IRB, LI->getOrdering())};724Value *C = IRB.CreateCall(TsanAtomicLoad[Idx], Args);725Value *Cast = IRB.CreateBitOrPointerCast(C, OrigTy);726I->replaceAllUsesWith(Cast);727} else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {728Value *Addr = SI->getPointerOperand();729int Idx =730getMemoryAccessFuncIndex(SI->getValueOperand()->getType(), Addr, DL);731if (Idx < 0)732return false;733const unsigned ByteSize = 1U << Idx;734const unsigned BitSize = ByteSize * 8;735Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);736Value *Args[] = {Addr,737IRB.CreateBitOrPointerCast(SI->getValueOperand(), Ty),738createOrdering(&IRB, SI->getOrdering())};739IRB.CreateCall(TsanAtomicStore[Idx], Args);740SI->eraseFromParent();741} else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I)) {742Value *Addr = RMWI->getPointerOperand();743int Idx =744getMemoryAccessFuncIndex(RMWI->getValOperand()->getType(), Addr, DL);745if (Idx < 0)746return false;747FunctionCallee F = TsanAtomicRMW[RMWI->getOperation()][Idx];748if (!F)749return false;750const unsigned ByteSize = 1U << Idx;751const unsigned BitSize = ByteSize * 8;752Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);753Value *Val = RMWI->getValOperand();754Value *Args[] = {Addr, IRB.CreateBitOrPointerCast(Val, Ty),755createOrdering(&IRB, RMWI->getOrdering())};756Value *C = IRB.CreateCall(F, Args);757I->replaceAllUsesWith(IRB.CreateBitOrPointerCast(C, Val->getType()));758I->eraseFromParent();759} else if (AtomicCmpXchgInst *CASI = dyn_cast<AtomicCmpXchgInst>(I)) {760Value *Addr = CASI->getPointerOperand();761Type *OrigOldValTy = CASI->getNewValOperand()->getType();762int Idx = getMemoryAccessFuncIndex(OrigOldValTy, Addr, DL);763if (Idx < 0)764return false;765const unsigned ByteSize = 1U << Idx;766const unsigned BitSize = ByteSize * 8;767Type *Ty = Type::getIntNTy(IRB.getContext(), BitSize);768Value *CmpOperand =769IRB.CreateBitOrPointerCast(CASI->getCompareOperand(), Ty);770Value *NewOperand =771IRB.CreateBitOrPointerCast(CASI->getNewValOperand(), Ty);772Value *Args[] = {Addr,773CmpOperand,774NewOperand,775createOrdering(&IRB, CASI->getSuccessOrdering()),776createOrdering(&IRB, CASI->getFailureOrdering())};777CallInst *C = IRB.CreateCall(TsanAtomicCAS[Idx], Args);778Value *Success = IRB.CreateICmpEQ(C, CmpOperand);779Value *OldVal = C;780if (Ty != OrigOldValTy) {781// The value is a pointer, so we need to cast the return value.782OldVal = IRB.CreateIntToPtr(C, OrigOldValTy);783}784785Value *Res =786IRB.CreateInsertValue(PoisonValue::get(CASI->getType()), OldVal, 0);787Res = IRB.CreateInsertValue(Res, Success, 1);788789I->replaceAllUsesWith(Res);790I->eraseFromParent();791} else if (FenceInst *FI = dyn_cast<FenceInst>(I)) {792Value *Args[] = {createOrdering(&IRB, FI->getOrdering())};793FunctionCallee F = FI->getSyncScopeID() == SyncScope::SingleThread794? TsanAtomicSignalFence795: TsanAtomicThreadFence;796IRB.CreateCall(F, Args);797FI->eraseFromParent();798}799return true;800}801802int ThreadSanitizer::getMemoryAccessFuncIndex(Type *OrigTy, Value *Addr,803const DataLayout &DL) {804assert(OrigTy->isSized());805if (OrigTy->isScalableTy()) {806// FIXME: support vscale.807return -1;808}809uint32_t TypeSize = DL.getTypeStoreSizeInBits(OrigTy);810if (TypeSize != 8 && TypeSize != 16 &&811TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {812NumAccessesWithBadSize++;813// Ignore all unusual sizes.814return -1;815}816size_t Idx = llvm::countr_zero(TypeSize / 8);817assert(Idx < kNumberOfAccessSizes);818return Idx;819}820821822