xref: /freebsd/contrib/llvm-project/llvm/lib/Transforms/Instrumentation/MemProfiler.cpp (revision 4824e7fd18a1223177218d4aec1b3c6c5c4a444e)
1 //===- MemProfiler.cpp - memory allocation and access profiler ------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file is a part of MemProfiler. Memory accesses are instrumented
10 // to increment the access count held in a shadow memory location, or
11 // alternatively to call into the runtime. Memory intrinsic calls (memmove,
12 // memcpy, memset) are changed to call the memory profiling runtime version
13 // instead.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "llvm/Transforms/Instrumentation/MemProfiler.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/IR/Constant.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/GlobalValue.h"
27 #include "llvm/IR/IRBuilder.h"
28 #include "llvm/IR/Instruction.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/Type.h"
32 #include "llvm/IR/Value.h"
33 #include "llvm/InitializePasses.h"
34 #include "llvm/Pass.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Transforms/Instrumentation.h"
38 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
39 #include "llvm/Transforms/Utils/ModuleUtils.h"
40 
41 using namespace llvm;
42 
43 #define DEBUG_TYPE "memprof"
44 
45 constexpr int LLVM_MEM_PROFILER_VERSION = 1;
46 
47 // Size of memory mapped to a single shadow location.
48 constexpr uint64_t DefaultShadowGranularity = 64;
49 
50 // Scale from granularity down to shadow size.
51 constexpr uint64_t DefaultShadowScale = 3;
52 
53 constexpr char MemProfModuleCtorName[] = "memprof.module_ctor";
54 constexpr uint64_t MemProfCtorAndDtorPriority = 1;
55 // On Emscripten, the system needs more than one priorities for constructors.
56 constexpr uint64_t MemProfEmscriptenCtorAndDtorPriority = 50;
57 constexpr char MemProfInitName[] = "__memprof_init";
58 constexpr char MemProfVersionCheckNamePrefix[] =
59     "__memprof_version_mismatch_check_v";
60 
61 constexpr char MemProfShadowMemoryDynamicAddress[] =
62     "__memprof_shadow_memory_dynamic_address";
63 
64 constexpr char MemProfFilenameVar[] = "__memprof_profile_filename";
65 
66 // Command-line flags.
67 
68 static cl::opt<bool> ClInsertVersionCheck(
69     "memprof-guard-against-version-mismatch",
70     cl::desc("Guard against compiler/runtime version mismatch."), cl::Hidden,
71     cl::init(true));
72 
73 // This flag may need to be replaced with -f[no-]memprof-reads.
74 static cl::opt<bool> ClInstrumentReads("memprof-instrument-reads",
75                                        cl::desc("instrument read instructions"),
76                                        cl::Hidden, cl::init(true));
77 
78 static cl::opt<bool>
79     ClInstrumentWrites("memprof-instrument-writes",
80                        cl::desc("instrument write instructions"), cl::Hidden,
81                        cl::init(true));
82 
83 static cl::opt<bool> ClInstrumentAtomics(
84     "memprof-instrument-atomics",
85     cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
86     cl::init(true));
87 
88 static cl::opt<bool> ClUseCalls(
89     "memprof-use-callbacks",
90     cl::desc("Use callbacks instead of inline instrumentation sequences."),
91     cl::Hidden, cl::init(false));
92 
93 static cl::opt<std::string>
94     ClMemoryAccessCallbackPrefix("memprof-memory-access-callback-prefix",
95                                  cl::desc("Prefix for memory access callbacks"),
96                                  cl::Hidden, cl::init("__memprof_"));
97 
98 // These flags allow to change the shadow mapping.
99 // The shadow mapping looks like
100 //    Shadow = ((Mem & mask) >> scale) + offset
101 
102 static cl::opt<int> ClMappingScale("memprof-mapping-scale",
103                                    cl::desc("scale of memprof shadow mapping"),
104                                    cl::Hidden, cl::init(DefaultShadowScale));
105 
106 static cl::opt<int>
107     ClMappingGranularity("memprof-mapping-granularity",
108                          cl::desc("granularity of memprof shadow mapping"),
109                          cl::Hidden, cl::init(DefaultShadowGranularity));
110 
111 static cl::opt<bool> ClStack("memprof-instrument-stack",
112                              cl::desc("Instrument scalar stack variables"),
113                              cl::Hidden, cl::init(false));
114 
115 // Debug flags.
116 
117 static cl::opt<int> ClDebug("memprof-debug", cl::desc("debug"), cl::Hidden,
118                             cl::init(0));
119 
120 static cl::opt<std::string> ClDebugFunc("memprof-debug-func", cl::Hidden,
121                                         cl::desc("Debug func"));
122 
123 static cl::opt<int> ClDebugMin("memprof-debug-min", cl::desc("Debug min inst"),
124                                cl::Hidden, cl::init(-1));
125 
126 static cl::opt<int> ClDebugMax("memprof-debug-max", cl::desc("Debug max inst"),
127                                cl::Hidden, cl::init(-1));
128 
129 STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
130 STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
131 STATISTIC(NumSkippedStackReads, "Number of non-instrumented stack reads");
132 STATISTIC(NumSkippedStackWrites, "Number of non-instrumented stack writes");
133 
134 namespace {
135 
136 /// This struct defines the shadow mapping using the rule:
137 ///   shadow = ((mem & mask) >> Scale) ADD DynamicShadowOffset.
138 struct ShadowMapping {
139   ShadowMapping() {
140     Scale = ClMappingScale;
141     Granularity = ClMappingGranularity;
142     Mask = ~(Granularity - 1);
143   }
144 
145   int Scale;
146   int Granularity;
147   uint64_t Mask; // Computed as ~(Granularity-1)
148 };
149 
150 static uint64_t getCtorAndDtorPriority(Triple &TargetTriple) {
151   return TargetTriple.isOSEmscripten() ? MemProfEmscriptenCtorAndDtorPriority
152                                        : MemProfCtorAndDtorPriority;
153 }
154 
155 struct InterestingMemoryAccess {
156   Value *Addr = nullptr;
157   bool IsWrite;
158   unsigned Alignment;
159   uint64_t TypeSize;
160   Value *MaybeMask = nullptr;
161 };
162 
163 /// Instrument the code in module to profile memory accesses.
164 class MemProfiler {
165 public:
166   MemProfiler(Module &M) {
167     C = &(M.getContext());
168     LongSize = M.getDataLayout().getPointerSizeInBits();
169     IntptrTy = Type::getIntNTy(*C, LongSize);
170   }
171 
172   /// If it is an interesting memory access, populate information
173   /// about the access and return a InterestingMemoryAccess struct.
174   /// Otherwise return None.
175   Optional<InterestingMemoryAccess>
176   isInterestingMemoryAccess(Instruction *I) const;
177 
178   void instrumentMop(Instruction *I, const DataLayout &DL,
179                      InterestingMemoryAccess &Access);
180   void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
181                          Value *Addr, uint32_t TypeSize, bool IsWrite);
182   void instrumentMaskedLoadOrStore(const DataLayout &DL, Value *Mask,
183                                    Instruction *I, Value *Addr,
184                                    unsigned Alignment, uint32_t TypeSize,
185                                    bool IsWrite);
186   void instrumentMemIntrinsic(MemIntrinsic *MI);
187   Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
188   bool instrumentFunction(Function &F);
189   bool maybeInsertMemProfInitAtFunctionEntry(Function &F);
190   bool insertDynamicShadowAtFunctionEntry(Function &F);
191 
192 private:
193   void initializeCallbacks(Module &M);
194 
195   LLVMContext *C;
196   int LongSize;
197   Type *IntptrTy;
198   ShadowMapping Mapping;
199 
200   // These arrays is indexed by AccessIsWrite
201   FunctionCallee MemProfMemoryAccessCallback[2];
202   FunctionCallee MemProfMemoryAccessCallbackSized[2];
203 
204   FunctionCallee MemProfMemmove, MemProfMemcpy, MemProfMemset;
205   Value *DynamicShadowOffset = nullptr;
206 };
207 
208 class MemProfilerLegacyPass : public FunctionPass {
209 public:
210   static char ID;
211 
212   explicit MemProfilerLegacyPass() : FunctionPass(ID) {
213     initializeMemProfilerLegacyPassPass(*PassRegistry::getPassRegistry());
214   }
215 
216   StringRef getPassName() const override { return "MemProfilerFunctionPass"; }
217 
218   bool runOnFunction(Function &F) override {
219     MemProfiler Profiler(*F.getParent());
220     return Profiler.instrumentFunction(F);
221   }
222 };
223 
224 class ModuleMemProfiler {
225 public:
226   ModuleMemProfiler(Module &M) { TargetTriple = Triple(M.getTargetTriple()); }
227 
228   bool instrumentModule(Module &);
229 
230 private:
231   Triple TargetTriple;
232   ShadowMapping Mapping;
233   Function *MemProfCtorFunction = nullptr;
234 };
235 
236 class ModuleMemProfilerLegacyPass : public ModulePass {
237 public:
238   static char ID;
239 
240   explicit ModuleMemProfilerLegacyPass() : ModulePass(ID) {
241     initializeModuleMemProfilerLegacyPassPass(*PassRegistry::getPassRegistry());
242   }
243 
244   StringRef getPassName() const override { return "ModuleMemProfiler"; }
245 
246   void getAnalysisUsage(AnalysisUsage &AU) const override {}
247 
248   bool runOnModule(Module &M) override {
249     ModuleMemProfiler MemProfiler(M);
250     return MemProfiler.instrumentModule(M);
251   }
252 };
253 
254 } // end anonymous namespace
255 
256 MemProfilerPass::MemProfilerPass() {}
257 
258 PreservedAnalyses MemProfilerPass::run(Function &F,
259                                        AnalysisManager<Function> &AM) {
260   Module &M = *F.getParent();
261   MemProfiler Profiler(M);
262   if (Profiler.instrumentFunction(F))
263     return PreservedAnalyses::none();
264   return PreservedAnalyses::all();
265 }
266 
267 ModuleMemProfilerPass::ModuleMemProfilerPass() {}
268 
269 PreservedAnalyses ModuleMemProfilerPass::run(Module &M,
270                                              AnalysisManager<Module> &AM) {
271   ModuleMemProfiler Profiler(M);
272   if (Profiler.instrumentModule(M))
273     return PreservedAnalyses::none();
274   return PreservedAnalyses::all();
275 }
276 
277 char MemProfilerLegacyPass::ID = 0;
278 
279 INITIALIZE_PASS_BEGIN(MemProfilerLegacyPass, "memprof",
280                       "MemProfiler: profile memory allocations and accesses.",
281                       false, false)
282 INITIALIZE_PASS_END(MemProfilerLegacyPass, "memprof",
283                     "MemProfiler: profile memory allocations and accesses.",
284                     false, false)
285 
286 FunctionPass *llvm::createMemProfilerFunctionPass() {
287   return new MemProfilerLegacyPass();
288 }
289 
290 char ModuleMemProfilerLegacyPass::ID = 0;
291 
292 INITIALIZE_PASS(ModuleMemProfilerLegacyPass, "memprof-module",
293                 "MemProfiler: profile memory allocations and accesses."
294                 "ModulePass",
295                 false, false)
296 
297 ModulePass *llvm::createModuleMemProfilerLegacyPassPass() {
298   return new ModuleMemProfilerLegacyPass();
299 }
300 
301 Value *MemProfiler::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
302   // (Shadow & mask) >> scale
303   Shadow = IRB.CreateAnd(Shadow, Mapping.Mask);
304   Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
305   // (Shadow >> scale) | offset
306   assert(DynamicShadowOffset);
307   return IRB.CreateAdd(Shadow, DynamicShadowOffset);
308 }
309 
310 // Instrument memset/memmove/memcpy
311 void MemProfiler::instrumentMemIntrinsic(MemIntrinsic *MI) {
312   IRBuilder<> IRB(MI);
313   if (isa<MemTransferInst>(MI)) {
314     IRB.CreateCall(
315         isa<MemMoveInst>(MI) ? MemProfMemmove : MemProfMemcpy,
316         {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
317          IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
318          IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
319   } else if (isa<MemSetInst>(MI)) {
320     IRB.CreateCall(
321         MemProfMemset,
322         {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
323          IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
324          IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
325   }
326   MI->eraseFromParent();
327 }
328 
329 Optional<InterestingMemoryAccess>
330 MemProfiler::isInterestingMemoryAccess(Instruction *I) const {
331   // Do not instrument the load fetching the dynamic shadow address.
332   if (DynamicShadowOffset == I)
333     return None;
334 
335   InterestingMemoryAccess Access;
336 
337   const DataLayout &DL = I->getModule()->getDataLayout();
338   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
339     if (!ClInstrumentReads)
340       return None;
341     Access.IsWrite = false;
342     Access.TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
343     Access.Alignment = LI->getAlignment();
344     Access.Addr = LI->getPointerOperand();
345   } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
346     if (!ClInstrumentWrites)
347       return None;
348     Access.IsWrite = true;
349     Access.TypeSize =
350         DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
351     Access.Alignment = SI->getAlignment();
352     Access.Addr = SI->getPointerOperand();
353   } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
354     if (!ClInstrumentAtomics)
355       return None;
356     Access.IsWrite = true;
357     Access.TypeSize =
358         DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
359     Access.Alignment = 0;
360     Access.Addr = RMW->getPointerOperand();
361   } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
362     if (!ClInstrumentAtomics)
363       return None;
364     Access.IsWrite = true;
365     Access.TypeSize =
366         DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
367     Access.Alignment = 0;
368     Access.Addr = XCHG->getPointerOperand();
369   } else if (auto *CI = dyn_cast<CallInst>(I)) {
370     auto *F = CI->getCalledFunction();
371     if (F && (F->getIntrinsicID() == Intrinsic::masked_load ||
372               F->getIntrinsicID() == Intrinsic::masked_store)) {
373       unsigned OpOffset = 0;
374       if (F->getIntrinsicID() == Intrinsic::masked_store) {
375         if (!ClInstrumentWrites)
376           return None;
377         // Masked store has an initial operand for the value.
378         OpOffset = 1;
379         Access.IsWrite = true;
380       } else {
381         if (!ClInstrumentReads)
382           return None;
383         Access.IsWrite = false;
384       }
385 
386       auto *BasePtr = CI->getOperand(0 + OpOffset);
387       auto *Ty = cast<PointerType>(BasePtr->getType())->getElementType();
388       Access.TypeSize = DL.getTypeStoreSizeInBits(Ty);
389       if (auto *AlignmentConstant =
390               dyn_cast<ConstantInt>(CI->getOperand(1 + OpOffset)))
391         Access.Alignment = (unsigned)AlignmentConstant->getZExtValue();
392       else
393         Access.Alignment = 1; // No alignment guarantees. We probably got Undef
394       Access.MaybeMask = CI->getOperand(2 + OpOffset);
395       Access.Addr = BasePtr;
396     }
397   }
398 
399   if (!Access.Addr)
400     return None;
401 
402   // Do not instrument acesses from different address spaces; we cannot deal
403   // with them.
404   Type *PtrTy = cast<PointerType>(Access.Addr->getType()->getScalarType());
405   if (PtrTy->getPointerAddressSpace() != 0)
406     return None;
407 
408   // Ignore swifterror addresses.
409   // swifterror memory addresses are mem2reg promoted by instruction
410   // selection. As such they cannot have regular uses like an instrumentation
411   // function and it makes no sense to track them as memory.
412   if (Access.Addr->isSwiftError())
413     return None;
414 
415   return Access;
416 }
417 
418 void MemProfiler::instrumentMaskedLoadOrStore(const DataLayout &DL, Value *Mask,
419                                               Instruction *I, Value *Addr,
420                                               unsigned Alignment,
421                                               uint32_t TypeSize, bool IsWrite) {
422   auto *VTy = cast<FixedVectorType>(
423       cast<PointerType>(Addr->getType())->getElementType());
424   uint64_t ElemTypeSize = DL.getTypeStoreSizeInBits(VTy->getScalarType());
425   unsigned Num = VTy->getNumElements();
426   auto *Zero = ConstantInt::get(IntptrTy, 0);
427   for (unsigned Idx = 0; Idx < Num; ++Idx) {
428     Value *InstrumentedAddress = nullptr;
429     Instruction *InsertBefore = I;
430     if (auto *Vector = dyn_cast<ConstantVector>(Mask)) {
431       // dyn_cast as we might get UndefValue
432       if (auto *Masked = dyn_cast<ConstantInt>(Vector->getOperand(Idx))) {
433         if (Masked->isZero())
434           // Mask is constant false, so no instrumentation needed.
435           continue;
436         // If we have a true or undef value, fall through to instrumentAddress.
437         // with InsertBefore == I
438       }
439     } else {
440       IRBuilder<> IRB(I);
441       Value *MaskElem = IRB.CreateExtractElement(Mask, Idx);
442       Instruction *ThenTerm = SplitBlockAndInsertIfThen(MaskElem, I, false);
443       InsertBefore = ThenTerm;
444     }
445 
446     IRBuilder<> IRB(InsertBefore);
447     InstrumentedAddress =
448         IRB.CreateGEP(VTy, Addr, {Zero, ConstantInt::get(IntptrTy, Idx)});
449     instrumentAddress(I, InsertBefore, InstrumentedAddress, ElemTypeSize,
450                       IsWrite);
451   }
452 }
453 
454 void MemProfiler::instrumentMop(Instruction *I, const DataLayout &DL,
455                                 InterestingMemoryAccess &Access) {
456   // Skip instrumentation of stack accesses unless requested.
457   if (!ClStack && isa<AllocaInst>(getUnderlyingObject(Access.Addr))) {
458     if (Access.IsWrite)
459       ++NumSkippedStackWrites;
460     else
461       ++NumSkippedStackReads;
462     return;
463   }
464 
465   if (Access.IsWrite)
466     NumInstrumentedWrites++;
467   else
468     NumInstrumentedReads++;
469 
470   if (Access.MaybeMask) {
471     instrumentMaskedLoadOrStore(DL, Access.MaybeMask, I, Access.Addr,
472                                 Access.Alignment, Access.TypeSize,
473                                 Access.IsWrite);
474   } else {
475     // Since the access counts will be accumulated across the entire allocation,
476     // we only update the shadow access count for the first location and thus
477     // don't need to worry about alignment and type size.
478     instrumentAddress(I, I, Access.Addr, Access.TypeSize, Access.IsWrite);
479   }
480 }
481 
482 void MemProfiler::instrumentAddress(Instruction *OrigIns,
483                                     Instruction *InsertBefore, Value *Addr,
484                                     uint32_t TypeSize, bool IsWrite) {
485   IRBuilder<> IRB(InsertBefore);
486   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
487 
488   if (ClUseCalls) {
489     IRB.CreateCall(MemProfMemoryAccessCallback[IsWrite], AddrLong);
490     return;
491   }
492 
493   // Create an inline sequence to compute shadow location, and increment the
494   // value by one.
495   Type *ShadowTy = Type::getInt64Ty(*C);
496   Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
497   Value *ShadowPtr = memToShadow(AddrLong, IRB);
498   Value *ShadowAddr = IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy);
499   Value *ShadowValue = IRB.CreateLoad(ShadowTy, ShadowAddr);
500   Value *Inc = ConstantInt::get(Type::getInt64Ty(*C), 1);
501   ShadowValue = IRB.CreateAdd(ShadowValue, Inc);
502   IRB.CreateStore(ShadowValue, ShadowAddr);
503 }
504 
505 // Create the variable for the profile file name.
506 void createProfileFileNameVar(Module &M) {
507   const MDString *MemProfFilename =
508       dyn_cast_or_null<MDString>(M.getModuleFlag("MemProfProfileFilename"));
509   if (!MemProfFilename)
510     return;
511   assert(!MemProfFilename->getString().empty() &&
512          "Unexpected MemProfProfileFilename metadata with empty string");
513   Constant *ProfileNameConst = ConstantDataArray::getString(
514       M.getContext(), MemProfFilename->getString(), true);
515   GlobalVariable *ProfileNameVar = new GlobalVariable(
516       M, ProfileNameConst->getType(), /*isConstant=*/true,
517       GlobalValue::WeakAnyLinkage, ProfileNameConst, MemProfFilenameVar);
518   Triple TT(M.getTargetTriple());
519   if (TT.supportsCOMDAT()) {
520     ProfileNameVar->setLinkage(GlobalValue::ExternalLinkage);
521     ProfileNameVar->setComdat(M.getOrInsertComdat(MemProfFilenameVar));
522   }
523 }
524 
525 bool ModuleMemProfiler::instrumentModule(Module &M) {
526   // Create a module constructor.
527   std::string MemProfVersion = std::to_string(LLVM_MEM_PROFILER_VERSION);
528   std::string VersionCheckName =
529       ClInsertVersionCheck ? (MemProfVersionCheckNamePrefix + MemProfVersion)
530                            : "";
531   std::tie(MemProfCtorFunction, std::ignore) =
532       createSanitizerCtorAndInitFunctions(M, MemProfModuleCtorName,
533                                           MemProfInitName, /*InitArgTypes=*/{},
534                                           /*InitArgs=*/{}, VersionCheckName);
535 
536   const uint64_t Priority = getCtorAndDtorPriority(TargetTriple);
537   appendToGlobalCtors(M, MemProfCtorFunction, Priority);
538 
539   createProfileFileNameVar(M);
540 
541   return true;
542 }
543 
544 void MemProfiler::initializeCallbacks(Module &M) {
545   IRBuilder<> IRB(*C);
546 
547   for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
548     const std::string TypeStr = AccessIsWrite ? "store" : "load";
549 
550     SmallVector<Type *, 3> Args2 = {IntptrTy, IntptrTy};
551     SmallVector<Type *, 2> Args1{1, IntptrTy};
552     MemProfMemoryAccessCallbackSized[AccessIsWrite] =
553         M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + TypeStr + "N",
554                               FunctionType::get(IRB.getVoidTy(), Args2, false));
555 
556     MemProfMemoryAccessCallback[AccessIsWrite] =
557         M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + TypeStr,
558                               FunctionType::get(IRB.getVoidTy(), Args1, false));
559   }
560   MemProfMemmove = M.getOrInsertFunction(
561       ClMemoryAccessCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
562       IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy);
563   MemProfMemcpy = M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "memcpy",
564                                         IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
565                                         IRB.getInt8PtrTy(), IntptrTy);
566   MemProfMemset = M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "memset",
567                                         IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
568                                         IRB.getInt32Ty(), IntptrTy);
569 }
570 
571 bool MemProfiler::maybeInsertMemProfInitAtFunctionEntry(Function &F) {
572   // For each NSObject descendant having a +load method, this method is invoked
573   // by the ObjC runtime before any of the static constructors is called.
574   // Therefore we need to instrument such methods with a call to __memprof_init
575   // at the beginning in order to initialize our runtime before any access to
576   // the shadow memory.
577   // We cannot just ignore these methods, because they may call other
578   // instrumented functions.
579   if (F.getName().find(" load]") != std::string::npos) {
580     FunctionCallee MemProfInitFunction =
581         declareSanitizerInitFunction(*F.getParent(), MemProfInitName, {});
582     IRBuilder<> IRB(&F.front(), F.front().begin());
583     IRB.CreateCall(MemProfInitFunction, {});
584     return true;
585   }
586   return false;
587 }
588 
589 bool MemProfiler::insertDynamicShadowAtFunctionEntry(Function &F) {
590   IRBuilder<> IRB(&F.front().front());
591   Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
592       MemProfShadowMemoryDynamicAddress, IntptrTy);
593   if (F.getParent()->getPICLevel() == PICLevel::NotPIC)
594     cast<GlobalVariable>(GlobalDynamicAddress)->setDSOLocal(true);
595   DynamicShadowOffset = IRB.CreateLoad(IntptrTy, GlobalDynamicAddress);
596   return true;
597 }
598 
599 bool MemProfiler::instrumentFunction(Function &F) {
600   if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage)
601     return false;
602   if (ClDebugFunc == F.getName())
603     return false;
604   if (F.getName().startswith("__memprof_"))
605     return false;
606 
607   bool FunctionModified = false;
608 
609   // If needed, insert __memprof_init.
610   // This function needs to be called even if the function body is not
611   // instrumented.
612   if (maybeInsertMemProfInitAtFunctionEntry(F))
613     FunctionModified = true;
614 
615   LLVM_DEBUG(dbgs() << "MEMPROF instrumenting:\n" << F << "\n");
616 
617   initializeCallbacks(*F.getParent());
618 
619   FunctionModified |= insertDynamicShadowAtFunctionEntry(F);
620 
621   SmallVector<Instruction *, 16> ToInstrument;
622 
623   // Fill the set of memory operations to instrument.
624   for (auto &BB : F) {
625     for (auto &Inst : BB) {
626       if (isInterestingMemoryAccess(&Inst) || isa<MemIntrinsic>(Inst))
627         ToInstrument.push_back(&Inst);
628     }
629   }
630 
631   int NumInstrumented = 0;
632   for (auto *Inst : ToInstrument) {
633     if (ClDebugMin < 0 || ClDebugMax < 0 ||
634         (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
635       Optional<InterestingMemoryAccess> Access =
636           isInterestingMemoryAccess(Inst);
637       if (Access)
638         instrumentMop(Inst, F.getParent()->getDataLayout(), *Access);
639       else
640         instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
641     }
642     NumInstrumented++;
643   }
644 
645   if (NumInstrumented > 0)
646     FunctionModified = true;
647 
648   LLVM_DEBUG(dbgs() << "MEMPROF done instrumenting: " << FunctionModified << " "
649                     << F << "\n");
650 
651   return FunctionModified;
652 }
653