LLVM  mainline
MemorySanitizer.cpp
Go to the documentation of this file.
00001 //===-- MemorySanitizer.cpp - detector of uninitialized reads -------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 /// \file
00010 /// This file is a part of MemorySanitizer, a detector of uninitialized
00011 /// reads.
00012 ///
00013 /// The algorithm of the tool is similar to Memcheck
00014 /// (http://goo.gl/QKbem). We associate a few shadow bits with every
00015 /// byte of the application memory, poison the shadow of the malloc-ed
00016 /// or alloca-ed memory, load the shadow bits on every memory read,
00017 /// propagate the shadow bits through some of the arithmetic
00018 /// instruction (including MOV), store the shadow bits on every memory
00019 /// write, report a bug on some other instructions (e.g. JMP) if the
00020 /// associated shadow is poisoned.
00021 ///
00022 /// But there are differences too. The first and the major one:
00023 /// compiler instrumentation instead of binary instrumentation. This
00024 /// gives us much better register allocation, possible compiler
00025 /// optimizations and a fast start-up. But this brings the major issue
00026 /// as well: msan needs to see all program events, including system
00027 /// calls and reads/writes in system libraries, so we either need to
00028 /// compile *everything* with msan or use a binary translation
00029 /// component (e.g. DynamoRIO) to instrument pre-built libraries.
00030 /// Another difference from Memcheck is that we use 8 shadow bits per
00031 /// byte of application memory and use a direct shadow mapping. This
00032 /// greatly simplifies the instrumentation code and avoids races on
00033 /// shadow updates (Memcheck is single-threaded so races are not a
00034 /// concern there. Memcheck uses 2 shadow bits per byte with a slow
00035 /// path storage that uses 8 bits per byte).
00036 ///
00037 /// The default value of shadow is 0, which means "clean" (not poisoned).
00038 ///
00039 /// Every module initializer should call __msan_init to ensure that the
00040 /// shadow memory is ready. On error, __msan_warning is called. Since
00041 /// parameters and return values may be passed via registers, we have a
00042 /// specialized thread-local shadow for return values
00043 /// (__msan_retval_tls) and parameters (__msan_param_tls).
00044 ///
00045 ///                           Origin tracking.
00046 ///
00047 /// MemorySanitizer can track origins (allocation points) of all uninitialized
00048 /// values. This behavior is controlled with a flag (msan-track-origins) and is
00049 /// disabled by default.
00050 ///
00051 /// Origins are 4-byte values created and interpreted by the runtime library.
00052 /// They are stored in a second shadow mapping, one 4-byte value for 4 bytes
00053 /// of application memory. Propagation of origins is basically a bunch of
00054 /// "select" instructions that pick the origin of a dirty argument, if an
00055 /// instruction has one.
00056 ///
00057 /// Every 4 aligned, consecutive bytes of application memory have one origin
00058 /// value associated with them. If these bytes contain uninitialized data
00059 /// coming from 2 different allocations, the last store wins. Because of this,
00060 /// MemorySanitizer reports can show unrelated origins, but this is unlikely in
00061 /// practice.
00062 ///
00063 /// Origins are meaningless for fully initialized values, so MemorySanitizer
00064 /// avoids storing origin to memory when a fully initialized value is stored.
00065 /// This way it avoids needless overwritting origin of the 4-byte region on
00066 /// a short (i.e. 1 byte) clean store, and it is also good for performance.
00067 ///
00068 ///                            Atomic handling.
00069 ///
00070 /// Ideally, every atomic store of application value should update the
00071 /// corresponding shadow location in an atomic way. Unfortunately, atomic store
00072 /// of two disjoint locations can not be done without severe slowdown.
00073 ///
00074 /// Therefore, we implement an approximation that may err on the safe side.
00075 /// In this implementation, every atomically accessed location in the program
00076 /// may only change from (partially) uninitialized to fully initialized, but
00077 /// not the other way around. We load the shadow _after_ the application load,
00078 /// and we store the shadow _before_ the app store. Also, we always store clean
00079 /// shadow (if the application store is atomic). This way, if the store-load
00080 /// pair constitutes a happens-before arc, shadow store and load are correctly
00081 /// ordered such that the load will get either the value that was stored, or
00082 /// some later value (which is always clean).
00083 ///
00084 /// This does not work very well with Compare-And-Swap (CAS) and
00085 /// Read-Modify-Write (RMW) operations. To follow the above logic, CAS and RMW
00086 /// must store the new shadow before the app operation, and load the shadow
00087 /// after the app operation. Computers don't work this way. Current
00088 /// implementation ignores the load aspect of CAS/RMW, always returning a clean
00089 /// value. It implements the store part as a simple atomic store by storing a
00090 /// clean shadow.
00091 
00092 //===----------------------------------------------------------------------===//
00093 
00094 #include "llvm/Transforms/Instrumentation.h"
00095 #include "llvm/ADT/DepthFirstIterator.h"
00096 #include "llvm/ADT/SmallString.h"
00097 #include "llvm/ADT/SmallVector.h"
00098 #include "llvm/ADT/StringExtras.h"
00099 #include "llvm/ADT/Triple.h"
00100 #include "llvm/IR/DataLayout.h"
00101 #include "llvm/IR/Function.h"
00102 #include "llvm/IR/IRBuilder.h"
00103 #include "llvm/IR/InlineAsm.h"
00104 #include "llvm/IR/InstVisitor.h"
00105 #include "llvm/IR/IntrinsicInst.h"
00106 #include "llvm/IR/LLVMContext.h"
00107 #include "llvm/IR/MDBuilder.h"
00108 #include "llvm/IR/Module.h"
00109 #include "llvm/IR/Type.h"
00110 #include "llvm/IR/ValueMap.h"
00111 #include "llvm/Support/CommandLine.h"
00112 #include "llvm/Support/Compiler.h"
00113 #include "llvm/Support/Debug.h"
00114 #include "llvm/Support/raw_ostream.h"
00115 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00116 #include "llvm/Transforms/Utils/Local.h"
00117 #include "llvm/Transforms/Utils/ModuleUtils.h"
00118 
00119 using namespace llvm;
00120 
00121 #define DEBUG_TYPE "msan"
00122 
00123 static const unsigned kOriginSize = 4;
00124 static const unsigned kMinOriginAlignment = 4;
00125 static const unsigned kShadowTLSAlignment = 8;
00126 
00127 // These constants must be kept in sync with the ones in msan.h.
00128 static const unsigned kParamTLSSize = 800;
00129 static const unsigned kRetvalTLSSize = 800;
00130 
00131 // Accesses sizes are powers of two: 1, 2, 4, 8.
00132 static const size_t kNumberOfAccessSizes = 4;
00133 
00134 /// \brief Track origins of uninitialized values.
00135 ///
00136 /// Adds a section to MemorySanitizer report that points to the allocation
00137 /// (stack or heap) the uninitialized bits came from originally.
00138 static cl::opt<int> ClTrackOrigins("msan-track-origins",
00139        cl::desc("Track origins (allocation sites) of poisoned memory"),
00140        cl::Hidden, cl::init(0));
00141 static cl::opt<bool> ClKeepGoing("msan-keep-going",
00142        cl::desc("keep going after reporting a UMR"),
00143        cl::Hidden, cl::init(false));
00144 static cl::opt<bool> ClPoisonStack("msan-poison-stack",
00145        cl::desc("poison uninitialized stack variables"),
00146        cl::Hidden, cl::init(true));
00147 static cl::opt<bool> ClPoisonStackWithCall("msan-poison-stack-with-call",
00148        cl::desc("poison uninitialized stack variables with a call"),
00149        cl::Hidden, cl::init(false));
00150 static cl::opt<int> ClPoisonStackPattern("msan-poison-stack-pattern",
00151        cl::desc("poison uninitialized stack variables with the given patter"),
00152        cl::Hidden, cl::init(0xff));
00153 static cl::opt<bool> ClPoisonUndef("msan-poison-undef",
00154        cl::desc("poison undef temps"),
00155        cl::Hidden, cl::init(true));
00156 
00157 static cl::opt<bool> ClHandleICmp("msan-handle-icmp",
00158        cl::desc("propagate shadow through ICmpEQ and ICmpNE"),
00159        cl::Hidden, cl::init(true));
00160 
00161 static cl::opt<bool> ClHandleICmpExact("msan-handle-icmp-exact",
00162        cl::desc("exact handling of relational integer ICmp"),
00163        cl::Hidden, cl::init(false));
00164 
00165 // This flag controls whether we check the shadow of the address
00166 // operand of load or store. Such bugs are very rare, since load from
00167 // a garbage address typically results in SEGV, but still happen
00168 // (e.g. only lower bits of address are garbage, or the access happens
00169 // early at program startup where malloc-ed memory is more likely to
00170 // be zeroed. As of 2012-08-28 this flag adds 20% slowdown.
00171 static cl::opt<bool> ClCheckAccessAddress("msan-check-access-address",
00172        cl::desc("report accesses through a pointer which has poisoned shadow"),
00173        cl::Hidden, cl::init(true));
00174 
00175 static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions",
00176        cl::desc("print out instructions with default strict semantics"),
00177        cl::Hidden, cl::init(false));
00178 
00179 static cl::opt<int> ClInstrumentationWithCallThreshold(
00180     "msan-instrumentation-with-call-threshold",
00181     cl::desc(
00182         "If the function being instrumented requires more than "
00183         "this number of checks and origin stores, use callbacks instead of "
00184         "inline checks (-1 means never use callbacks)."),
00185     cl::Hidden, cl::init(3500));
00186 
00187 // This is an experiment to enable handling of cases where shadow is a non-zero
00188 // compile-time constant. For some unexplainable reason they were silently
00189 // ignored in the instrumentation.
00190 static cl::opt<bool> ClCheckConstantShadow("msan-check-constant-shadow",
00191        cl::desc("Insert checks for constant shadow values"),
00192        cl::Hidden, cl::init(false));
00193 
00194 static const char *const kMsanModuleCtorName = "msan.module_ctor";
00195 static const char *const kMsanInitName = "__msan_init";
00196 
00197 namespace {
00198 
00199 // Memory map parameters used in application-to-shadow address calculation.
00200 // Offset = (Addr & ~AndMask) ^ XorMask
00201 // Shadow = ShadowBase + Offset
00202 // Origin = OriginBase + Offset
00203 struct MemoryMapParams {
00204   uint64_t AndMask;
00205   uint64_t XorMask;
00206   uint64_t ShadowBase;
00207   uint64_t OriginBase;
00208 };
00209 
00210 struct PlatformMemoryMapParams {
00211   const MemoryMapParams *bits32;
00212   const MemoryMapParams *bits64;
00213 };
00214 
00215 // i386 Linux
00216 static const MemoryMapParams Linux_I386_MemoryMapParams = {
00217   0x000080000000,  // AndMask
00218   0,               // XorMask (not used)
00219   0,               // ShadowBase (not used)
00220   0x000040000000,  // OriginBase
00221 };
00222 
00223 // x86_64 Linux
00224 static const MemoryMapParams Linux_X86_64_MemoryMapParams = {
00225   0x400000000000,  // AndMask
00226   0,               // XorMask (not used)
00227   0,               // ShadowBase (not used)
00228   0x200000000000,  // OriginBase
00229 };
00230 
00231 // mips64 Linux
00232 static const MemoryMapParams Linux_MIPS64_MemoryMapParams = {
00233   0x004000000000,  // AndMask
00234   0,               // XorMask (not used)
00235   0,               // ShadowBase (not used)
00236   0x002000000000,  // OriginBase
00237 };
00238 
00239 // i386 FreeBSD
00240 static const MemoryMapParams FreeBSD_I386_MemoryMapParams = {
00241   0x000180000000,  // AndMask
00242   0x000040000000,  // XorMask
00243   0x000020000000,  // ShadowBase
00244   0x000700000000,  // OriginBase
00245 };
00246 
00247 // x86_64 FreeBSD
00248 static const MemoryMapParams FreeBSD_X86_64_MemoryMapParams = {
00249   0xc00000000000,  // AndMask
00250   0x200000000000,  // XorMask
00251   0x100000000000,  // ShadowBase
00252   0x380000000000,  // OriginBase
00253 };
00254 
00255 static const PlatformMemoryMapParams Linux_X86_MemoryMapParams = {
00256   &Linux_I386_MemoryMapParams,
00257   &Linux_X86_64_MemoryMapParams,
00258 };
00259 
00260 static const PlatformMemoryMapParams Linux_MIPS_MemoryMapParams = {
00261   NULL,
00262   &Linux_MIPS64_MemoryMapParams,
00263 };
00264 
00265 static const PlatformMemoryMapParams FreeBSD_X86_MemoryMapParams = {
00266   &FreeBSD_I386_MemoryMapParams,
00267   &FreeBSD_X86_64_MemoryMapParams,
00268 };
00269 
00270 /// \brief An instrumentation pass implementing detection of uninitialized
00271 /// reads.
00272 ///
00273 /// MemorySanitizer: instrument the code in module to find
00274 /// uninitialized reads.
00275 class MemorySanitizer : public FunctionPass {
00276  public:
00277   MemorySanitizer(int TrackOrigins = 0)
00278       : FunctionPass(ID),
00279         TrackOrigins(std::max(TrackOrigins, (int)ClTrackOrigins)),
00280         WarningFn(nullptr) {}
00281   const char *getPassName() const override { return "MemorySanitizer"; }
00282   bool runOnFunction(Function &F) override;
00283   bool doInitialization(Module &M) override;
00284   static char ID;  // Pass identification, replacement for typeid.
00285 
00286  private:
00287   void initializeCallbacks(Module &M);
00288 
00289   /// \brief Track origins (allocation points) of uninitialized values.
00290   int TrackOrigins;
00291 
00292   LLVMContext *C;
00293   Type *IntptrTy;
00294   Type *OriginTy;
00295   /// \brief Thread-local shadow storage for function parameters.
00296   GlobalVariable *ParamTLS;
00297   /// \brief Thread-local origin storage for function parameters.
00298   GlobalVariable *ParamOriginTLS;
00299   /// \brief Thread-local shadow storage for function return value.
00300   GlobalVariable *RetvalTLS;
00301   /// \brief Thread-local origin storage for function return value.
00302   GlobalVariable *RetvalOriginTLS;
00303   /// \brief Thread-local shadow storage for in-register va_arg function
00304   /// parameters (x86_64-specific).
00305   GlobalVariable *VAArgTLS;
00306   /// \brief Thread-local shadow storage for va_arg overflow area
00307   /// (x86_64-specific).
00308   GlobalVariable *VAArgOverflowSizeTLS;
00309   /// \brief Thread-local space used to pass origin value to the UMR reporting
00310   /// function.
00311   GlobalVariable *OriginTLS;
00312 
00313   /// \brief The run-time callback to print a warning.
00314   Value *WarningFn;
00315   // These arrays are indexed by log2(AccessSize).
00316   Value *MaybeWarningFn[kNumberOfAccessSizes];
00317   Value *MaybeStoreOriginFn[kNumberOfAccessSizes];
00318 
00319   /// \brief Run-time helper that generates a new origin value for a stack
00320   /// allocation.
00321   Value *MsanSetAllocaOrigin4Fn;
00322   /// \brief Run-time helper that poisons stack on function entry.
00323   Value *MsanPoisonStackFn;
00324   /// \brief Run-time helper that records a store (or any event) of an
00325   /// uninitialized value and returns an updated origin id encoding this info.
00326   Value *MsanChainOriginFn;
00327   /// \brief MSan runtime replacements for memmove, memcpy and memset.
00328   Value *MemmoveFn, *MemcpyFn, *MemsetFn;
00329 
00330   /// \brief Memory map parameters used in application-to-shadow calculation.
00331   const MemoryMapParams *MapParams;
00332 
00333   MDNode *ColdCallWeights;
00334   /// \brief Branch weights for origin store.
00335   MDNode *OriginStoreWeights;
00336   /// \brief An empty volatile inline asm that prevents callback merge.
00337   InlineAsm *EmptyAsm;
00338   Function *MsanCtorFunction;
00339 
00340   friend struct MemorySanitizerVisitor;
00341   friend struct VarArgAMD64Helper;
00342   friend struct VarArgMIPS64Helper;
00343 };
00344 }  // namespace
00345 
00346 char MemorySanitizer::ID = 0;
00347 INITIALIZE_PASS(MemorySanitizer, "msan",
00348                 "MemorySanitizer: detects uninitialized reads.",
00349                 false, false)
00350 
00351 FunctionPass *llvm::createMemorySanitizerPass(int TrackOrigins) {
00352   return new MemorySanitizer(TrackOrigins);
00353 }
00354 
00355 /// \brief Create a non-const global initialized with the given string.
00356 ///
00357 /// Creates a writable global for Str so that we can pass it to the
00358 /// run-time lib. Runtime uses first 4 bytes of the string to store the
00359 /// frame ID, so the string needs to be mutable.
00360 static GlobalVariable *createPrivateNonConstGlobalForString(Module &M,
00361                                                             StringRef Str) {
00362   Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
00363   return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false,
00364                             GlobalValue::PrivateLinkage, StrConst, "");
00365 }
00366 
00367 
00368 /// \brief Insert extern declaration of runtime-provided functions and globals.
00369 void MemorySanitizer::initializeCallbacks(Module &M) {
00370   // Only do this once.
00371   if (WarningFn)
00372     return;
00373 
00374   IRBuilder<> IRB(*C);
00375   // Create the callback.
00376   // FIXME: this function should have "Cold" calling conv,
00377   // which is not yet implemented.
00378   StringRef WarningFnName = ClKeepGoing ? "__msan_warning"
00379                                         : "__msan_warning_noreturn";
00380   WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy(), nullptr);
00381 
00382   for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
00383        AccessSizeIndex++) {
00384     unsigned AccessSize = 1 << AccessSizeIndex;
00385     std::string FunctionName = "__msan_maybe_warning_" + itostr(AccessSize);
00386     MaybeWarningFn[AccessSizeIndex] = M.getOrInsertFunction(
00387         FunctionName, IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8),
00388         IRB.getInt32Ty(), nullptr);
00389 
00390     FunctionName = "__msan_maybe_store_origin_" + itostr(AccessSize);
00391     MaybeStoreOriginFn[AccessSizeIndex] = M.getOrInsertFunction(
00392         FunctionName, IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8),
00393         IRB.getInt8PtrTy(), IRB.getInt32Ty(), nullptr);
00394   }
00395 
00396   MsanSetAllocaOrigin4Fn = M.getOrInsertFunction(
00397     "__msan_set_alloca_origin4", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy,
00398     IRB.getInt8PtrTy(), IntptrTy, nullptr);
00399   MsanPoisonStackFn =
00400       M.getOrInsertFunction("__msan_poison_stack", IRB.getVoidTy(),
00401                             IRB.getInt8PtrTy(), IntptrTy, nullptr);
00402   MsanChainOriginFn = M.getOrInsertFunction(
00403     "__msan_chain_origin", IRB.getInt32Ty(), IRB.getInt32Ty(), nullptr);
00404   MemmoveFn = M.getOrInsertFunction(
00405     "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
00406     IRB.getInt8PtrTy(), IntptrTy, nullptr);
00407   MemcpyFn = M.getOrInsertFunction(
00408     "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
00409     IntptrTy, nullptr);
00410   MemsetFn = M.getOrInsertFunction(
00411     "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
00412     IntptrTy, nullptr);
00413 
00414   // Create globals.
00415   RetvalTLS = new GlobalVariable(
00416     M, ArrayType::get(IRB.getInt64Ty(), kRetvalTLSSize / 8), false,
00417     GlobalVariable::ExternalLinkage, nullptr, "__msan_retval_tls", nullptr,
00418     GlobalVariable::InitialExecTLSModel);
00419   RetvalOriginTLS = new GlobalVariable(
00420     M, OriginTy, false, GlobalVariable::ExternalLinkage, nullptr,
00421     "__msan_retval_origin_tls", nullptr, GlobalVariable::InitialExecTLSModel);
00422 
00423   ParamTLS = new GlobalVariable(
00424     M, ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), false,
00425     GlobalVariable::ExternalLinkage, nullptr, "__msan_param_tls", nullptr,
00426     GlobalVariable::InitialExecTLSModel);
00427   ParamOriginTLS = new GlobalVariable(
00428     M, ArrayType::get(OriginTy, kParamTLSSize / 4), false,
00429     GlobalVariable::ExternalLinkage, nullptr, "__msan_param_origin_tls",
00430     nullptr, GlobalVariable::InitialExecTLSModel);
00431 
00432   VAArgTLS = new GlobalVariable(
00433     M, ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), false,
00434     GlobalVariable::ExternalLinkage, nullptr, "__msan_va_arg_tls", nullptr,
00435     GlobalVariable::InitialExecTLSModel);
00436   VAArgOverflowSizeTLS = new GlobalVariable(
00437     M, IRB.getInt64Ty(), false, GlobalVariable::ExternalLinkage, nullptr,
00438     "__msan_va_arg_overflow_size_tls", nullptr,
00439     GlobalVariable::InitialExecTLSModel);
00440   OriginTLS = new GlobalVariable(
00441     M, IRB.getInt32Ty(), false, GlobalVariable::ExternalLinkage, nullptr,
00442     "__msan_origin_tls", nullptr, GlobalVariable::InitialExecTLSModel);
00443 
00444   // We insert an empty inline asm after __msan_report* to avoid callback merge.
00445   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
00446                             StringRef(""), StringRef(""),
00447                             /*hasSideEffects=*/true);
00448 }
00449 
00450 /// \brief Module-level initialization.
00451 ///
00452 /// inserts a call to __msan_init to the module's constructor list.
00453 bool MemorySanitizer::doInitialization(Module &M) {
00454   auto &DL = M.getDataLayout();
00455 
00456   Triple TargetTriple(M.getTargetTriple());
00457   switch (TargetTriple.getOS()) {
00458     case Triple::FreeBSD:
00459       switch (TargetTriple.getArch()) {
00460         case Triple::x86_64:
00461           MapParams = FreeBSD_X86_MemoryMapParams.bits64;
00462           break;
00463         case Triple::x86:
00464           MapParams = FreeBSD_X86_MemoryMapParams.bits32;
00465           break;
00466         default:
00467           report_fatal_error("unsupported architecture");
00468       }
00469       break;
00470     case Triple::Linux:
00471       switch (TargetTriple.getArch()) {
00472         case Triple::x86_64:
00473           MapParams = Linux_X86_MemoryMapParams.bits64;
00474           break;
00475         case Triple::x86:
00476           MapParams = Linux_X86_MemoryMapParams.bits32;
00477           break;
00478         case Triple::mips64:
00479         case Triple::mips64el:
00480           MapParams = Linux_MIPS_MemoryMapParams.bits64;
00481           break;
00482         default:
00483           report_fatal_error("unsupported architecture");
00484       }
00485       break;
00486     default:
00487       report_fatal_error("unsupported operating system");
00488   }
00489 
00490   C = &(M.getContext());
00491   IRBuilder<> IRB(*C);
00492   IntptrTy = IRB.getIntPtrTy(DL);
00493   OriginTy = IRB.getInt32Ty();
00494 
00495   ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000);
00496   OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000);
00497 
00498   std::tie(MsanCtorFunction, std::ignore) =
00499       createSanitizerCtorAndInitFunctions(M, kMsanModuleCtorName, kMsanInitName,
00500                                           /*InitArgTypes=*/{},
00501                                           /*InitArgs=*/{});
00502 
00503   appendToGlobalCtors(M, MsanCtorFunction, 0);
00504 
00505   if (TrackOrigins)
00506     new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
00507                        IRB.getInt32(TrackOrigins), "__msan_track_origins");
00508 
00509   if (ClKeepGoing)
00510     new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
00511                        IRB.getInt32(ClKeepGoing), "__msan_keep_going");
00512 
00513   return true;
00514 }
00515 
00516 namespace {
00517 
00518 /// \brief A helper class that handles instrumentation of VarArg
00519 /// functions on a particular platform.
00520 ///
00521 /// Implementations are expected to insert the instrumentation
00522 /// necessary to propagate argument shadow through VarArg function
00523 /// calls. Visit* methods are called during an InstVisitor pass over
00524 /// the function, and should avoid creating new basic blocks. A new
00525 /// instance of this class is created for each instrumented function.
00526 struct VarArgHelper {
00527   /// \brief Visit a CallSite.
00528   virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0;
00529 
00530   /// \brief Visit a va_start call.
00531   virtual void visitVAStartInst(VAStartInst &I) = 0;
00532 
00533   /// \brief Visit a va_copy call.
00534   virtual void visitVACopyInst(VACopyInst &I) = 0;
00535 
00536   /// \brief Finalize function instrumentation.
00537   ///
00538   /// This method is called after visiting all interesting (see above)
00539   /// instructions in a function.
00540   virtual void finalizeInstrumentation() = 0;
00541 
00542   virtual ~VarArgHelper() {}
00543 };
00544 
00545 struct MemorySanitizerVisitor;
00546 
00547 VarArgHelper*
00548 CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
00549                    MemorySanitizerVisitor &Visitor);
00550 
00551 unsigned TypeSizeToSizeIndex(unsigned TypeSize) {
00552   if (TypeSize <= 8) return 0;
00553   return Log2_32_Ceil(TypeSize / 8);
00554 }
00555 
00556 /// This class does all the work for a given function. Store and Load
00557 /// instructions store and load corresponding shadow and origin
00558 /// values. Most instructions propagate shadow from arguments to their
00559 /// return values. Certain instructions (most importantly, BranchInst)
00560 /// test their argument shadow and print reports (with a runtime call) if it's
00561 /// non-zero.
00562 struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
00563   Function &F;
00564   MemorySanitizer &MS;
00565   SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
00566   ValueMap<Value*, Value*> ShadowMap, OriginMap;
00567   std::unique_ptr<VarArgHelper> VAHelper;
00568 
00569   // The following flags disable parts of MSan instrumentation based on
00570   // blacklist contents and command-line options.
00571   bool InsertChecks;
00572   bool PropagateShadow;
00573   bool PoisonStack;
00574   bool PoisonUndef;
00575   bool CheckReturnValue;
00576 
00577   struct ShadowOriginAndInsertPoint {
00578     Value *Shadow;
00579     Value *Origin;
00580     Instruction *OrigIns;
00581     ShadowOriginAndInsertPoint(Value *S, Value *O, Instruction *I)
00582       : Shadow(S), Origin(O), OrigIns(I) { }
00583   };
00584   SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
00585   SmallVector<Instruction*, 16> StoreList;
00586 
00587   MemorySanitizerVisitor(Function &F, MemorySanitizer &MS)
00588       : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)) {
00589     bool SanitizeFunction = F.hasFnAttribute(Attribute::SanitizeMemory);
00590     InsertChecks = SanitizeFunction;
00591     PropagateShadow = SanitizeFunction;
00592     PoisonStack = SanitizeFunction && ClPoisonStack;
00593     PoisonUndef = SanitizeFunction && ClPoisonUndef;
00594     // FIXME: Consider using SpecialCaseList to specify a list of functions that
00595     // must always return fully initialized values. For now, we hardcode "main".
00596     CheckReturnValue = SanitizeFunction && (F.getName() == "main");
00597 
00598     DEBUG(if (!InsertChecks)
00599           dbgs() << "MemorySanitizer is not inserting checks into '"
00600                  << F.getName() << "'\n");
00601   }
00602 
00603   Value *updateOrigin(Value *V, IRBuilder<> &IRB) {
00604     if (MS.TrackOrigins <= 1) return V;
00605     return IRB.CreateCall(MS.MsanChainOriginFn, V);
00606   }
00607 
00608   Value *originToIntptr(IRBuilder<> &IRB, Value *Origin) {
00609     const DataLayout &DL = F.getParent()->getDataLayout();
00610     unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
00611     if (IntptrSize == kOriginSize) return Origin;
00612     assert(IntptrSize == kOriginSize * 2);
00613     Origin = IRB.CreateIntCast(Origin, MS.IntptrTy, /* isSigned */ false);
00614     return IRB.CreateOr(Origin, IRB.CreateShl(Origin, kOriginSize * 8));
00615   }
00616 
00617   /// \brief Fill memory range with the given origin value.
00618   void paintOrigin(IRBuilder<> &IRB, Value *Origin, Value *OriginPtr,
00619                    unsigned Size, unsigned Alignment) {
00620     const DataLayout &DL = F.getParent()->getDataLayout();
00621     unsigned IntptrAlignment = DL.getABITypeAlignment(MS.IntptrTy);
00622     unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
00623     assert(IntptrAlignment >= kMinOriginAlignment);
00624     assert(IntptrSize >= kOriginSize);
00625 
00626     unsigned Ofs = 0;
00627     unsigned CurrentAlignment = Alignment;
00628     if (Alignment >= IntptrAlignment && IntptrSize > kOriginSize) {
00629       Value *IntptrOrigin = originToIntptr(IRB, Origin);
00630       Value *IntptrOriginPtr =
00631           IRB.CreatePointerCast(OriginPtr, PointerType::get(MS.IntptrTy, 0));
00632       for (unsigned i = 0; i < Size / IntptrSize; ++i) {
00633         Value *Ptr = i ? IRB.CreateConstGEP1_32(MS.IntptrTy, IntptrOriginPtr, i)
00634                        : IntptrOriginPtr;
00635         IRB.CreateAlignedStore(IntptrOrigin, Ptr, CurrentAlignment);
00636         Ofs += IntptrSize / kOriginSize;
00637         CurrentAlignment = IntptrAlignment;
00638       }
00639     }
00640 
00641     for (unsigned i = Ofs; i < (Size + kOriginSize - 1) / kOriginSize; ++i) {
00642       Value *GEP =
00643           i ? IRB.CreateConstGEP1_32(nullptr, OriginPtr, i) : OriginPtr;
00644       IRB.CreateAlignedStore(Origin, GEP, CurrentAlignment);
00645       CurrentAlignment = kMinOriginAlignment;
00646     }
00647   }
00648 
00649   void storeOrigin(IRBuilder<> &IRB, Value *Addr, Value *Shadow, Value *Origin,
00650                    unsigned Alignment, bool AsCall) {
00651     const DataLayout &DL = F.getParent()->getDataLayout();
00652     unsigned OriginAlignment = std::max(kMinOriginAlignment, Alignment);
00653     unsigned StoreSize = DL.getTypeStoreSize(Shadow->getType());
00654     if (isa<StructType>(Shadow->getType())) {
00655       paintOrigin(IRB, updateOrigin(Origin, IRB),
00656                   getOriginPtr(Addr, IRB, Alignment), StoreSize,
00657                   OriginAlignment);
00658     } else {
00659       Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
00660       Constant *ConstantShadow = dyn_cast_or_null<Constant>(ConvertedShadow);
00661       if (ConstantShadow) {
00662         if (ClCheckConstantShadow && !ConstantShadow->isZeroValue())
00663           paintOrigin(IRB, updateOrigin(Origin, IRB),
00664                       getOriginPtr(Addr, IRB, Alignment), StoreSize,
00665                       OriginAlignment);
00666         return;
00667       }
00668 
00669       unsigned TypeSizeInBits =
00670           DL.getTypeSizeInBits(ConvertedShadow->getType());
00671       unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
00672       if (AsCall && SizeIndex < kNumberOfAccessSizes) {
00673         Value *Fn = MS.MaybeStoreOriginFn[SizeIndex];
00674         Value *ConvertedShadow2 = IRB.CreateZExt(
00675             ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
00676         IRB.CreateCall(Fn, {ConvertedShadow2,
00677                             IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
00678                             Origin});
00679       } else {
00680         Value *Cmp = IRB.CreateICmpNE(
00681             ConvertedShadow, getCleanShadow(ConvertedShadow), "_mscmp");
00682         Instruction *CheckTerm = SplitBlockAndInsertIfThen(
00683             Cmp, IRB.GetInsertPoint(), false, MS.OriginStoreWeights);
00684         IRBuilder<> IRBNew(CheckTerm);
00685         paintOrigin(IRBNew, updateOrigin(Origin, IRBNew),
00686                     getOriginPtr(Addr, IRBNew, Alignment), StoreSize,
00687                     OriginAlignment);
00688       }
00689     }
00690   }
00691 
00692   void materializeStores(bool InstrumentWithCalls) {
00693     for (auto Inst : StoreList) {
00694       StoreInst &SI = *dyn_cast<StoreInst>(Inst);
00695 
00696       IRBuilder<> IRB(&SI);
00697       Value *Val = SI.getValueOperand();
00698       Value *Addr = SI.getPointerOperand();
00699       Value *Shadow = SI.isAtomic() ? getCleanShadow(Val) : getShadow(Val);
00700       Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
00701 
00702       StoreInst *NewSI =
00703           IRB.CreateAlignedStore(Shadow, ShadowPtr, SI.getAlignment());
00704       DEBUG(dbgs() << "  STORE: " << *NewSI << "\n");
00705       (void)NewSI;
00706 
00707       if (ClCheckAccessAddress) insertShadowCheck(Addr, &SI);
00708 
00709       if (SI.isAtomic()) SI.setOrdering(addReleaseOrdering(SI.getOrdering()));
00710 
00711       if (MS.TrackOrigins && !SI.isAtomic())
00712         storeOrigin(IRB, Addr, Shadow, getOrigin(Val), SI.getAlignment(),
00713                     InstrumentWithCalls);
00714     }
00715   }
00716 
00717   void materializeOneCheck(Instruction *OrigIns, Value *Shadow, Value *Origin,
00718                            bool AsCall) {
00719     IRBuilder<> IRB(OrigIns);
00720     DEBUG(dbgs() << "  SHAD0 : " << *Shadow << "\n");
00721     Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
00722     DEBUG(dbgs() << "  SHAD1 : " << *ConvertedShadow << "\n");
00723 
00724     Constant *ConstantShadow = dyn_cast_or_null<Constant>(ConvertedShadow);
00725     if (ConstantShadow) {
00726       if (ClCheckConstantShadow && !ConstantShadow->isZeroValue()) {
00727         if (MS.TrackOrigins) {
00728           IRB.CreateStore(Origin ? (Value *)Origin : (Value *)IRB.getInt32(0),
00729                           MS.OriginTLS);
00730         }
00731         IRB.CreateCall(MS.WarningFn, {});
00732         IRB.CreateCall(MS.EmptyAsm, {});
00733         // FIXME: Insert UnreachableInst if !ClKeepGoing?
00734         // This may invalidate some of the following checks and needs to be done
00735         // at the very end.
00736       }
00737       return;
00738     }
00739 
00740     const DataLayout &DL = OrigIns->getModule()->getDataLayout();
00741 
00742     unsigned TypeSizeInBits = DL.getTypeSizeInBits(ConvertedShadow->getType());
00743     unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
00744     if (AsCall && SizeIndex < kNumberOfAccessSizes) {
00745       Value *Fn = MS.MaybeWarningFn[SizeIndex];
00746       Value *ConvertedShadow2 =
00747           IRB.CreateZExt(ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
00748       IRB.CreateCall(Fn, {ConvertedShadow2, MS.TrackOrigins && Origin
00749                                                 ? Origin
00750                                                 : (Value *)IRB.getInt32(0)});
00751     } else {
00752       Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
00753                                     getCleanShadow(ConvertedShadow), "_mscmp");
00754       Instruction *CheckTerm = SplitBlockAndInsertIfThen(
00755           Cmp, OrigIns,
00756           /* Unreachable */ !ClKeepGoing, MS.ColdCallWeights);
00757 
00758       IRB.SetInsertPoint(CheckTerm);
00759       if (MS.TrackOrigins) {
00760         IRB.CreateStore(Origin ? (Value *)Origin : (Value *)IRB.getInt32(0),
00761                         MS.OriginTLS);
00762       }
00763       IRB.CreateCall(MS.WarningFn, {});
00764       IRB.CreateCall(MS.EmptyAsm, {});
00765       DEBUG(dbgs() << "  CHECK: " << *Cmp << "\n");
00766     }
00767   }
00768 
00769   void materializeChecks(bool InstrumentWithCalls) {
00770     for (const auto &ShadowData : InstrumentationList) {
00771       Instruction *OrigIns = ShadowData.OrigIns;
00772       Value *Shadow = ShadowData.Shadow;
00773       Value *Origin = ShadowData.Origin;
00774       materializeOneCheck(OrigIns, Shadow, Origin, InstrumentWithCalls);
00775     }
00776     DEBUG(dbgs() << "DONE:\n" << F);
00777   }
00778 
00779   /// \brief Add MemorySanitizer instrumentation to a function.
00780   bool runOnFunction() {
00781     MS.initializeCallbacks(*F.getParent());
00782 
00783     // In the presence of unreachable blocks, we may see Phi nodes with
00784     // incoming nodes from such blocks. Since InstVisitor skips unreachable
00785     // blocks, such nodes will not have any shadow value associated with them.
00786     // It's easier to remove unreachable blocks than deal with missing shadow.
00787     removeUnreachableBlocks(F);
00788 
00789     // Iterate all BBs in depth-first order and create shadow instructions
00790     // for all instructions (where applicable).
00791     // For PHI nodes we create dummy shadow PHIs which will be finalized later.
00792     for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
00793       visit(*BB);
00794 
00795 
00796     // Finalize PHI nodes.
00797     for (PHINode *PN : ShadowPHINodes) {
00798       PHINode *PNS = cast<PHINode>(getShadow(PN));
00799       PHINode *PNO = MS.TrackOrigins ? cast<PHINode>(getOrigin(PN)) : nullptr;
00800       size_t NumValues = PN->getNumIncomingValues();
00801       for (size_t v = 0; v < NumValues; v++) {
00802         PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
00803         if (PNO) PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
00804       }
00805     }
00806 
00807     VAHelper->finalizeInstrumentation();
00808 
00809     bool InstrumentWithCalls = ClInstrumentationWithCallThreshold >= 0 &&
00810                                InstrumentationList.size() + StoreList.size() >
00811                                    (unsigned)ClInstrumentationWithCallThreshold;
00812 
00813     // Delayed instrumentation of StoreInst.
00814     // This may add new checks to be inserted later.
00815     materializeStores(InstrumentWithCalls);
00816 
00817     // Insert shadow value checks.
00818     materializeChecks(InstrumentWithCalls);
00819 
00820     return true;
00821   }
00822 
00823   /// \brief Compute the shadow type that corresponds to a given Value.
00824   Type *getShadowTy(Value *V) {
00825     return getShadowTy(V->getType());
00826   }
00827 
00828   /// \brief Compute the shadow type that corresponds to a given Type.
00829   Type *getShadowTy(Type *OrigTy) {
00830     if (!OrigTy->isSized()) {
00831       return nullptr;
00832     }
00833     // For integer type, shadow is the same as the original type.
00834     // This may return weird-sized types like i1.
00835     if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
00836       return IT;
00837     const DataLayout &DL = F.getParent()->getDataLayout();
00838     if (VectorType *VT = dyn_cast<VectorType>(OrigTy)) {
00839       uint32_t EltSize = DL.getTypeSizeInBits(VT->getElementType());
00840       return VectorType::get(IntegerType::get(*MS.C, EltSize),
00841                              VT->getNumElements());
00842     }
00843     if (ArrayType *AT = dyn_cast<ArrayType>(OrigTy)) {
00844       return ArrayType::get(getShadowTy(AT->getElementType()),
00845                             AT->getNumElements());
00846     }
00847     if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
00848       SmallVector<Type*, 4> Elements;
00849       for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
00850         Elements.push_back(getShadowTy(ST->getElementType(i)));
00851       StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
00852       DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
00853       return Res;
00854     }
00855     uint32_t TypeSize = DL.getTypeSizeInBits(OrigTy);
00856     return IntegerType::get(*MS.C, TypeSize);
00857   }
00858 
00859   /// \brief Flatten a vector type.
00860   Type *getShadowTyNoVec(Type *ty) {
00861     if (VectorType *vt = dyn_cast<VectorType>(ty))
00862       return IntegerType::get(*MS.C, vt->getBitWidth());
00863     return ty;
00864   }
00865 
00866   /// \brief Convert a shadow value to it's flattened variant.
00867   Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
00868     Type *Ty = V->getType();
00869     Type *NoVecTy = getShadowTyNoVec(Ty);
00870     if (Ty == NoVecTy) return V;
00871     return IRB.CreateBitCast(V, NoVecTy);
00872   }
00873 
00874   /// \brief Compute the integer shadow offset that corresponds to a given
00875   /// application address.
00876   ///
00877   /// Offset = (Addr & ~AndMask) ^ XorMask
00878   Value *getShadowPtrOffset(Value *Addr, IRBuilder<> &IRB) {
00879     uint64_t AndMask = MS.MapParams->AndMask;
00880     assert(AndMask != 0 && "AndMask shall be specified");
00881     Value *OffsetLong =
00882       IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
00883                     ConstantInt::get(MS.IntptrTy, ~AndMask));
00884 
00885     uint64_t XorMask = MS.MapParams->XorMask;
00886     if (XorMask != 0)
00887       OffsetLong = IRB.CreateXor(OffsetLong,
00888                                  ConstantInt::get(MS.IntptrTy, XorMask));
00889     return OffsetLong;
00890   }
00891 
00892   /// \brief Compute the shadow address that corresponds to a given application
00893   /// address.
00894   ///
00895   /// Shadow = ShadowBase + Offset
00896   Value *getShadowPtr(Value *Addr, Type *ShadowTy,
00897                       IRBuilder<> &IRB) {
00898     Value *ShadowLong = getShadowPtrOffset(Addr, IRB);
00899     uint64_t ShadowBase = MS.MapParams->ShadowBase;
00900     if (ShadowBase != 0)
00901       ShadowLong =
00902         IRB.CreateAdd(ShadowLong,
00903                       ConstantInt::get(MS.IntptrTy, ShadowBase));
00904     return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
00905   }
00906 
00907   /// \brief Compute the origin address that corresponds to a given application
00908   /// address.
00909   ///
00910   /// OriginAddr = (OriginBase + Offset) & ~3ULL
00911   Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB, unsigned Alignment) {
00912     Value *OriginLong = getShadowPtrOffset(Addr, IRB);
00913     uint64_t OriginBase = MS.MapParams->OriginBase;
00914     if (OriginBase != 0)
00915       OriginLong =
00916         IRB.CreateAdd(OriginLong,
00917                       ConstantInt::get(MS.IntptrTy, OriginBase));
00918     if (Alignment < kMinOriginAlignment) {
00919       uint64_t Mask = kMinOriginAlignment - 1;
00920       OriginLong = IRB.CreateAnd(OriginLong,
00921                                  ConstantInt::get(MS.IntptrTy, ~Mask));
00922     }
00923     return IRB.CreateIntToPtr(OriginLong,
00924                               PointerType::get(IRB.getInt32Ty(), 0));
00925   }
00926 
00927   /// \brief Compute the shadow address for a given function argument.
00928   ///
00929   /// Shadow = ParamTLS+ArgOffset.
00930   Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
00931                                  int ArgOffset) {
00932     Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
00933     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
00934     return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
00935                               "_msarg");
00936   }
00937 
00938   /// \brief Compute the origin address for a given function argument.
00939   Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
00940                                  int ArgOffset) {
00941     if (!MS.TrackOrigins) return nullptr;
00942     Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
00943     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
00944     return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
00945                               "_msarg_o");
00946   }
00947 
00948   /// \brief Compute the shadow address for a retval.
00949   Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
00950     Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy);
00951     return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
00952                               "_msret");
00953   }
00954 
00955   /// \brief Compute the origin address for a retval.
00956   Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
00957     // We keep a single origin for the entire retval. Might be too optimistic.
00958     return MS.RetvalOriginTLS;
00959   }
00960 
00961   /// \brief Set SV to be the shadow value for V.
00962   void setShadow(Value *V, Value *SV) {
00963     assert(!ShadowMap.count(V) && "Values may only have one shadow");
00964     ShadowMap[V] = PropagateShadow ? SV : getCleanShadow(V);
00965   }
00966 
00967   /// \brief Set Origin to be the origin value for V.
00968   void setOrigin(Value *V, Value *Origin) {
00969     if (!MS.TrackOrigins) return;
00970     assert(!OriginMap.count(V) && "Values may only have one origin");
00971     DEBUG(dbgs() << "ORIGIN: " << *V << "  ==> " << *Origin << "\n");
00972     OriginMap[V] = Origin;
00973   }
00974 
00975   /// \brief Create a clean shadow value for a given value.
00976   ///
00977   /// Clean shadow (all zeroes) means all bits of the value are defined
00978   /// (initialized).
00979   Constant *getCleanShadow(Value *V) {
00980     Type *ShadowTy = getShadowTy(V);
00981     if (!ShadowTy)
00982       return nullptr;
00983     return Constant::getNullValue(ShadowTy);
00984   }
00985 
00986   /// \brief Create a dirty shadow of a given shadow type.
00987   Constant *getPoisonedShadow(Type *ShadowTy) {
00988     assert(ShadowTy);
00989     if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
00990       return Constant::getAllOnesValue(ShadowTy);
00991     if (ArrayType *AT = dyn_cast<ArrayType>(ShadowTy)) {
00992       SmallVector<Constant *, 4> Vals(AT->getNumElements(),
00993                                       getPoisonedShadow(AT->getElementType()));
00994       return ConstantArray::get(AT, Vals);
00995     }
00996     if (StructType *ST = dyn_cast<StructType>(ShadowTy)) {
00997       SmallVector<Constant *, 4> Vals;
00998       for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
00999         Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
01000       return ConstantStruct::get(ST, Vals);
01001     }
01002     llvm_unreachable("Unexpected shadow type");
01003   }
01004 
01005   /// \brief Create a dirty shadow for a given value.
01006   Constant *getPoisonedShadow(Value *V) {
01007     Type *ShadowTy = getShadowTy(V);
01008     if (!ShadowTy)
01009       return nullptr;
01010     return getPoisonedShadow(ShadowTy);
01011   }
01012 
01013   /// \brief Create a clean (zero) origin.
01014   Value *getCleanOrigin() {
01015     return Constant::getNullValue(MS.OriginTy);
01016   }
01017 
01018   /// \brief Get the shadow value for a given Value.
01019   ///
01020   /// This function either returns the value set earlier with setShadow,
01021   /// or extracts if from ParamTLS (for function arguments).
01022   Value *getShadow(Value *V) {
01023     if (!PropagateShadow) return getCleanShadow(V);
01024     if (Instruction *I = dyn_cast<Instruction>(V)) {
01025       // For instructions the shadow is already stored in the map.
01026       Value *Shadow = ShadowMap[V];
01027       if (!Shadow) {
01028         DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
01029         (void)I;
01030         assert(Shadow && "No shadow for a value");
01031       }
01032       return Shadow;
01033     }
01034     if (UndefValue *U = dyn_cast<UndefValue>(V)) {
01035       Value *AllOnes = PoisonUndef ? getPoisonedShadow(V) : getCleanShadow(V);
01036       DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
01037       (void)U;
01038       return AllOnes;
01039     }
01040     if (Argument *A = dyn_cast<Argument>(V)) {
01041       // For arguments we compute the shadow on demand and store it in the map.
01042       Value **ShadowPtr = &ShadowMap[V];
01043       if (*ShadowPtr)
01044         return *ShadowPtr;
01045       Function *F = A->getParent();
01046       IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI());
01047       unsigned ArgOffset = 0;
01048       const DataLayout &DL = F->getParent()->getDataLayout();
01049       for (auto &FArg : F->args()) {
01050         if (!FArg.getType()->isSized()) {
01051           DEBUG(dbgs() << "Arg is not sized\n");
01052           continue;
01053         }
01054         unsigned Size =
01055             FArg.hasByValAttr()
01056                 ? DL.getTypeAllocSize(FArg.getType()->getPointerElementType())
01057                 : DL.getTypeAllocSize(FArg.getType());
01058         if (A == &FArg) {
01059           bool Overflow = ArgOffset + Size > kParamTLSSize;
01060           Value *Base = getShadowPtrForArgument(&FArg, EntryIRB, ArgOffset);
01061           if (FArg.hasByValAttr()) {
01062             // ByVal pointer itself has clean shadow. We copy the actual
01063             // argument shadow to the underlying memory.
01064             // Figure out maximal valid memcpy alignment.
01065             unsigned ArgAlign = FArg.getParamAlignment();
01066             if (ArgAlign == 0) {
01067               Type *EltType = A->getType()->getPointerElementType();
01068               ArgAlign = DL.getABITypeAlignment(EltType);
01069             }
01070             if (Overflow) {
01071               // ParamTLS overflow.
01072               EntryIRB.CreateMemSet(
01073                   getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB),
01074                   Constant::getNullValue(EntryIRB.getInt8Ty()), Size, ArgAlign);
01075             } else {
01076               unsigned CopyAlign = std::min(ArgAlign, kShadowTLSAlignment);
01077               Value *Cpy = EntryIRB.CreateMemCpy(
01078                   getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB), Base, Size,
01079                   CopyAlign);
01080               DEBUG(dbgs() << "  ByValCpy: " << *Cpy << "\n");
01081               (void)Cpy;
01082             }
01083             *ShadowPtr = getCleanShadow(V);
01084           } else {
01085             if (Overflow) {
01086               // ParamTLS overflow.
01087               *ShadowPtr = getCleanShadow(V);
01088             } else {
01089               *ShadowPtr =
01090                   EntryIRB.CreateAlignedLoad(Base, kShadowTLSAlignment);
01091             }
01092           }
01093           DEBUG(dbgs() << "  ARG:    "  << FArg << " ==> " <<
01094                 **ShadowPtr << "\n");
01095           if (MS.TrackOrigins && !Overflow) {
01096             Value *OriginPtr =
01097                 getOriginPtrForArgument(&FArg, EntryIRB, ArgOffset);
01098             setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
01099           } else {
01100             setOrigin(A, getCleanOrigin());
01101           }
01102         }
01103         ArgOffset += RoundUpToAlignment(Size, kShadowTLSAlignment);
01104       }
01105       assert(*ShadowPtr && "Could not find shadow for an argument");
01106       return *ShadowPtr;
01107     }
01108     // For everything else the shadow is zero.
01109     return getCleanShadow(V);
01110   }
01111 
01112   /// \brief Get the shadow for i-th argument of the instruction I.
01113   Value *getShadow(Instruction *I, int i) {
01114     return getShadow(I->getOperand(i));
01115   }
01116 
01117   /// \brief Get the origin for a value.
01118   Value *getOrigin(Value *V) {
01119     if (!MS.TrackOrigins) return nullptr;
01120     if (!PropagateShadow) return getCleanOrigin();
01121     if (isa<Constant>(V)) return getCleanOrigin();
01122     assert((isa<Instruction>(V) || isa<Argument>(V)) &&
01123            "Unexpected value type in getOrigin()");
01124     Value *Origin = OriginMap[V];
01125     assert(Origin && "Missing origin");
01126     return Origin;
01127   }
01128 
01129   /// \brief Get the origin for i-th argument of the instruction I.
01130   Value *getOrigin(Instruction *I, int i) {
01131     return getOrigin(I->getOperand(i));
01132   }
01133 
01134   /// \brief Remember the place where a shadow check should be inserted.
01135   ///
01136   /// This location will be later instrumented with a check that will print a
01137   /// UMR warning in runtime if the shadow value is not 0.
01138   void insertShadowCheck(Value *Shadow, Value *Origin, Instruction *OrigIns) {
01139     assert(Shadow);
01140     if (!InsertChecks) return;
01141 #ifndef NDEBUG
01142     Type *ShadowTy = Shadow->getType();
01143     assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
01144            "Can only insert checks for integer and vector shadow types");
01145 #endif
01146     InstrumentationList.push_back(
01147         ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
01148   }
01149 
01150   /// \brief Remember the place where a shadow check should be inserted.
01151   ///
01152   /// This location will be later instrumented with a check that will print a
01153   /// UMR warning in runtime if the value is not fully defined.
01154   void insertShadowCheck(Value *Val, Instruction *OrigIns) {
01155     assert(Val);
01156     Value *Shadow, *Origin;
01157     if (ClCheckConstantShadow) {
01158       Shadow = getShadow(Val);
01159       if (!Shadow) return;
01160       Origin = getOrigin(Val);
01161     } else {
01162       Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
01163       if (!Shadow) return;
01164       Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
01165     }
01166     insertShadowCheck(Shadow, Origin, OrigIns);
01167   }
01168 
01169   AtomicOrdering addReleaseOrdering(AtomicOrdering a) {
01170     switch (a) {
01171       case NotAtomic:
01172         return NotAtomic;
01173       case Unordered:
01174       case Monotonic:
01175       case Release:
01176         return Release;
01177       case Acquire:
01178       case AcquireRelease:
01179         return AcquireRelease;
01180       case SequentiallyConsistent:
01181         return SequentiallyConsistent;
01182     }
01183     llvm_unreachable("Unknown ordering");
01184   }
01185 
01186   AtomicOrdering addAcquireOrdering(AtomicOrdering a) {
01187     switch (a) {
01188       case NotAtomic:
01189         return NotAtomic;
01190       case Unordered:
01191       case Monotonic:
01192       case Acquire:
01193         return Acquire;
01194       case Release:
01195       case AcquireRelease:
01196         return AcquireRelease;
01197       case SequentiallyConsistent:
01198         return SequentiallyConsistent;
01199     }
01200     llvm_unreachable("Unknown ordering");
01201   }
01202 
01203   // ------------------- Visitors.
01204 
01205   /// \brief Instrument LoadInst
01206   ///
01207   /// Loads the corresponding shadow and (optionally) origin.
01208   /// Optionally, checks that the load address is fully defined.
01209   void visitLoadInst(LoadInst &I) {
01210     assert(I.getType()->isSized() && "Load type must have size");
01211     IRBuilder<> IRB(I.getNextNode());
01212     Type *ShadowTy = getShadowTy(&I);
01213     Value *Addr = I.getPointerOperand();
01214     if (PropagateShadow && !I.getMetadata("nosanitize")) {
01215       Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
01216       setShadow(&I,
01217                 IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld"));
01218     } else {
01219       setShadow(&I, getCleanShadow(&I));
01220     }
01221 
01222     if (ClCheckAccessAddress)
01223       insertShadowCheck(I.getPointerOperand(), &I);
01224 
01225     if (I.isAtomic())
01226       I.setOrdering(addAcquireOrdering(I.getOrdering()));
01227 
01228     if (MS.TrackOrigins) {
01229       if (PropagateShadow) {
01230         unsigned Alignment = I.getAlignment();
01231         unsigned OriginAlignment = std::max(kMinOriginAlignment, Alignment);
01232         setOrigin(&I, IRB.CreateAlignedLoad(getOriginPtr(Addr, IRB, Alignment),
01233                                             OriginAlignment));
01234       } else {
01235         setOrigin(&I, getCleanOrigin());
01236       }
01237     }
01238   }
01239 
01240   /// \brief Instrument StoreInst
01241   ///
01242   /// Stores the corresponding shadow and (optionally) origin.
01243   /// Optionally, checks that the store address is fully defined.
01244   void visitStoreInst(StoreInst &I) {
01245     StoreList.push_back(&I);
01246   }
01247 
01248   void handleCASOrRMW(Instruction &I) {
01249     assert(isa<AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I));
01250 
01251     IRBuilder<> IRB(&I);
01252     Value *Addr = I.getOperand(0);
01253     Value *ShadowPtr = getShadowPtr(Addr, I.getType(), IRB);
01254 
01255     if (ClCheckAccessAddress)
01256       insertShadowCheck(Addr, &I);
01257 
01258     // Only test the conditional argument of cmpxchg instruction.
01259     // The other argument can potentially be uninitialized, but we can not
01260     // detect this situation reliably without possible false positives.
01261     if (isa<AtomicCmpXchgInst>(I))
01262       insertShadowCheck(I.getOperand(1), &I);
01263 
01264     IRB.CreateStore(getCleanShadow(&I), ShadowPtr);
01265 
01266     setShadow(&I, getCleanShadow(&I));
01267     setOrigin(&I, getCleanOrigin());
01268   }
01269 
01270   void visitAtomicRMWInst(AtomicRMWInst &I) {
01271     handleCASOrRMW(I);
01272     I.setOrdering(addReleaseOrdering(I.getOrdering()));
01273   }
01274 
01275   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
01276     handleCASOrRMW(I);
01277     I.setSuccessOrdering(addReleaseOrdering(I.getSuccessOrdering()));
01278   }
01279 
01280   // Vector manipulation.
01281   void visitExtractElementInst(ExtractElementInst &I) {
01282     insertShadowCheck(I.getOperand(1), &I);
01283     IRBuilder<> IRB(&I);
01284     setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
01285               "_msprop"));
01286     setOrigin(&I, getOrigin(&I, 0));
01287   }
01288 
01289   void visitInsertElementInst(InsertElementInst &I) {
01290     insertShadowCheck(I.getOperand(2), &I);
01291     IRBuilder<> IRB(&I);
01292     setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
01293               I.getOperand(2), "_msprop"));
01294     setOriginForNaryOp(I);
01295   }
01296 
01297   void visitShuffleVectorInst(ShuffleVectorInst &I) {
01298     insertShadowCheck(I.getOperand(2), &I);
01299     IRBuilder<> IRB(&I);
01300     setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
01301               I.getOperand(2), "_msprop"));
01302     setOriginForNaryOp(I);
01303   }
01304 
01305   // Casts.
01306   void visitSExtInst(SExtInst &I) {
01307     IRBuilder<> IRB(&I);
01308     setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
01309     setOrigin(&I, getOrigin(&I, 0));
01310   }
01311 
01312   void visitZExtInst(ZExtInst &I) {
01313     IRBuilder<> IRB(&I);
01314     setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
01315     setOrigin(&I, getOrigin(&I, 0));
01316   }
01317 
01318   void visitTruncInst(TruncInst &I) {
01319     IRBuilder<> IRB(&I);
01320     setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
01321     setOrigin(&I, getOrigin(&I, 0));
01322   }
01323 
01324   void visitBitCastInst(BitCastInst &I) {
01325     IRBuilder<> IRB(&I);
01326     setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
01327     setOrigin(&I, getOrigin(&I, 0));
01328   }
01329 
01330   void visitPtrToIntInst(PtrToIntInst &I) {
01331     IRBuilder<> IRB(&I);
01332     setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
01333              "_msprop_ptrtoint"));
01334     setOrigin(&I, getOrigin(&I, 0));
01335   }
01336 
01337   void visitIntToPtrInst(IntToPtrInst &I) {
01338     IRBuilder<> IRB(&I);
01339     setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
01340              "_msprop_inttoptr"));
01341     setOrigin(&I, getOrigin(&I, 0));
01342   }
01343 
01344   void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
01345   void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
01346   void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
01347   void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
01348   void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
01349   void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
01350 
01351   /// \brief Propagate shadow for bitwise AND.
01352   ///
01353   /// This code is exact, i.e. if, for example, a bit in the left argument
01354   /// is defined and 0, then neither the value not definedness of the
01355   /// corresponding bit in B don't affect the resulting shadow.
01356   void visitAnd(BinaryOperator &I) {
01357     IRBuilder<> IRB(&I);
01358     //  "And" of 0 and a poisoned value results in unpoisoned value.
01359     //  1&1 => 1;     0&1 => 0;     p&1 => p;
01360     //  1&0 => 0;     0&0 => 0;     p&0 => 0;
01361     //  1&p => p;     0&p => 0;     p&p => p;
01362     //  S = (S1 & S2) | (V1 & S2) | (S1 & V2)
01363     Value *S1 = getShadow(&I, 0);
01364     Value *S2 = getShadow(&I, 1);
01365     Value *V1 = I.getOperand(0);
01366     Value *V2 = I.getOperand(1);
01367     if (V1->getType() != S1->getType()) {
01368       V1 = IRB.CreateIntCast(V1, S1->getType(), false);
01369       V2 = IRB.CreateIntCast(V2, S2->getType(), false);
01370     }
01371     Value *S1S2 = IRB.CreateAnd(S1, S2);
01372     Value *V1S2 = IRB.CreateAnd(V1, S2);
01373     Value *S1V2 = IRB.CreateAnd(S1, V2);
01374     setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
01375     setOriginForNaryOp(I);
01376   }
01377 
01378   void visitOr(BinaryOperator &I) {
01379     IRBuilder<> IRB(&I);
01380     //  "Or" of 1 and a poisoned value results in unpoisoned value.
01381     //  1|1 => 1;     0|1 => 1;     p|1 => 1;
01382     //  1|0 => 1;     0|0 => 0;     p|0 => p;
01383     //  1|p => 1;     0|p => p;     p|p => p;
01384     //  S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
01385     Value *S1 = getShadow(&I, 0);
01386     Value *S2 = getShadow(&I, 1);
01387     Value *V1 = IRB.CreateNot(I.getOperand(0));
01388     Value *V2 = IRB.CreateNot(I.getOperand(1));
01389     if (V1->getType() != S1->getType()) {
01390       V1 = IRB.CreateIntCast(V1, S1->getType(), false);
01391       V2 = IRB.CreateIntCast(V2, S2->getType(), false);
01392     }
01393     Value *S1S2 = IRB.CreateAnd(S1, S2);
01394     Value *V1S2 = IRB.CreateAnd(V1, S2);
01395     Value *S1V2 = IRB.CreateAnd(S1, V2);
01396     setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
01397     setOriginForNaryOp(I);
01398   }
01399 
01400   /// \brief Default propagation of shadow and/or origin.
01401   ///
01402   /// This class implements the general case of shadow propagation, used in all
01403   /// cases where we don't know and/or don't care about what the operation
01404   /// actually does. It converts all input shadow values to a common type
01405   /// (extending or truncating as necessary), and bitwise OR's them.
01406   ///
01407   /// This is much cheaper than inserting checks (i.e. requiring inputs to be
01408   /// fully initialized), and less prone to false positives.
01409   ///
01410   /// This class also implements the general case of origin propagation. For a
01411   /// Nary operation, result origin is set to the origin of an argument that is
01412   /// not entirely initialized. If there is more than one such arguments, the
01413   /// rightmost of them is picked. It does not matter which one is picked if all
01414   /// arguments are initialized.
01415   template <bool CombineShadow>
01416   class Combiner {
01417     Value *Shadow;
01418     Value *Origin;
01419     IRBuilder<> &IRB;
01420     MemorySanitizerVisitor *MSV;
01421 
01422   public:
01423     Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB) :
01424       Shadow(nullptr), Origin(nullptr), IRB(IRB), MSV(MSV) {}
01425 
01426     /// \brief Add a pair of shadow and origin values to the mix.
01427     Combiner &Add(Value *OpShadow, Value *OpOrigin) {
01428       if (CombineShadow) {
01429         assert(OpShadow);
01430         if (!Shadow)
01431           Shadow = OpShadow;
01432         else {
01433           OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
01434           Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
01435         }
01436       }
01437 
01438       if (MSV->MS.TrackOrigins) {
01439         assert(OpOrigin);
01440         if (!Origin) {
01441           Origin = OpOrigin;
01442         } else {
01443           Constant *ConstOrigin = dyn_cast<Constant>(OpOrigin);
01444           // No point in adding something that might result in 0 origin value.
01445           if (!ConstOrigin || !ConstOrigin->isNullValue()) {
01446             Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB);
01447             Value *Cond =
01448                 IRB.CreateICmpNE(FlatShadow, MSV->getCleanShadow(FlatShadow));
01449             Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
01450           }
01451         }
01452       }
01453       return *this;
01454     }
01455 
01456     /// \brief Add an application value to the mix.
01457     Combiner &Add(Value *V) {
01458       Value *OpShadow = MSV->getShadow(V);
01459       Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : nullptr;
01460       return Add(OpShadow, OpOrigin);
01461     }
01462 
01463     /// \brief Set the current combined values as the given instruction's shadow
01464     /// and origin.
01465     void Done(Instruction *I) {
01466       if (CombineShadow) {
01467         assert(Shadow);
01468         Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
01469         MSV->setShadow(I, Shadow);
01470       }
01471       if (MSV->MS.TrackOrigins) {
01472         assert(Origin);
01473         MSV->setOrigin(I, Origin);
01474       }
01475     }
01476   };
01477 
01478   typedef Combiner<true> ShadowAndOriginCombiner;
01479   typedef Combiner<false> OriginCombiner;
01480 
01481   /// \brief Propagate origin for arbitrary operation.
01482   void setOriginForNaryOp(Instruction &I) {
01483     if (!MS.TrackOrigins) return;
01484     IRBuilder<> IRB(&I);
01485     OriginCombiner OC(this, IRB);
01486     for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
01487       OC.Add(OI->get());
01488     OC.Done(&I);
01489   }
01490 
01491   size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
01492     assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) &&
01493            "Vector of pointers is not a valid shadow type");
01494     return Ty->isVectorTy() ?
01495       Ty->getVectorNumElements() * Ty->getScalarSizeInBits() :
01496       Ty->getPrimitiveSizeInBits();
01497   }
01498 
01499   /// \brief Cast between two shadow types, extending or truncating as
01500   /// necessary.
01501   Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy,
01502                           bool Signed = false) {
01503     Type *srcTy = V->getType();
01504     if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
01505       return IRB.CreateIntCast(V, dstTy, Signed);
01506     if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
01507         dstTy->getVectorNumElements() == srcTy->getVectorNumElements())
01508       return IRB.CreateIntCast(V, dstTy, Signed);
01509     size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
01510     size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
01511     Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
01512     Value *V2 =
01513       IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), Signed);
01514     return IRB.CreateBitCast(V2, dstTy);
01515     // TODO: handle struct types.
01516   }
01517 
01518   /// \brief Cast an application value to the type of its own shadow.
01519   Value *CreateAppToShadowCast(IRBuilder<> &IRB, Value *V) {
01520     Type *ShadowTy = getShadowTy(V);
01521     if (V->getType() == ShadowTy)
01522       return V;
01523     if (V->getType()->isPtrOrPtrVectorTy())
01524       return IRB.CreatePtrToInt(V, ShadowTy);
01525     else
01526       return IRB.CreateBitCast(V, ShadowTy);
01527   }
01528 
01529   /// \brief Propagate shadow for arbitrary operation.
01530   void handleShadowOr(Instruction &I) {
01531     IRBuilder<> IRB(&I);
01532     ShadowAndOriginCombiner SC(this, IRB);
01533     for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
01534       SC.Add(OI->get());
01535     SC.Done(&I);
01536   }
01537 
01538   // \brief Handle multiplication by constant.
01539   //
01540   // Handle a special case of multiplication by constant that may have one or
01541   // more zeros in the lower bits. This makes corresponding number of lower bits
01542   // of the result zero as well. We model it by shifting the other operand
01543   // shadow left by the required number of bits. Effectively, we transform
01544   // (X * (A * 2**B)) to ((X << B) * A) and instrument (X << B) as (Sx << B).
01545   // We use multiplication by 2**N instead of shift to cover the case of
01546   // multiplication by 0, which may occur in some elements of a vector operand.
01547   void handleMulByConstant(BinaryOperator &I, Constant *ConstArg,
01548                            Value *OtherArg) {
01549     Constant *ShadowMul;
01550     Type *Ty = ConstArg->getType();
01551     if (Ty->isVectorTy()) {
01552       unsigned NumElements = Ty->getVectorNumElements();
01553       Type *EltTy = Ty->getSequentialElementType();
01554       SmallVector<Constant *, 16> Elements;
01555       for (unsigned Idx = 0; Idx < NumElements; ++Idx) {
01556         ConstantInt *Elt =
01557             dyn_cast<ConstantInt>(ConstArg->getAggregateElement(Idx));
01558         APInt V = Elt->getValue();
01559         APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
01560         Elements.push_back(ConstantInt::get(EltTy, V2));
01561       }
01562       ShadowMul = ConstantVector::get(Elements);
01563     } else {
01564       ConstantInt *Elt = dyn_cast<ConstantInt>(ConstArg);
01565       APInt V = Elt->getValue();
01566       APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
01567       ShadowMul = ConstantInt::get(Elt->getType(), V2);
01568     }
01569 
01570     IRBuilder<> IRB(&I);
01571     setShadow(&I,
01572               IRB.CreateMul(getShadow(OtherArg), ShadowMul, "msprop_mul_cst"));
01573     setOrigin(&I, getOrigin(OtherArg));
01574   }
01575 
01576   void visitMul(BinaryOperator &I) {
01577     Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
01578     Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
01579     if (constOp0 && !constOp1)
01580       handleMulByConstant(I, constOp0, I.getOperand(1));
01581     else if (constOp1 && !constOp0)
01582       handleMulByConstant(I, constOp1, I.getOperand(0));
01583     else
01584       handleShadowOr(I);
01585   }
01586 
01587   void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
01588   void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
01589   void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
01590   void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
01591   void visitSub(BinaryOperator &I) { handleShadowOr(I); }
01592   void visitXor(BinaryOperator &I) { handleShadowOr(I); }
01593 
01594   void handleDiv(Instruction &I) {
01595     IRBuilder<> IRB(&I);
01596     // Strict on the second argument.
01597     insertShadowCheck(I.getOperand(1), &I);
01598     setShadow(&I, getShadow(&I, 0));
01599     setOrigin(&I, getOrigin(&I, 0));
01600   }
01601 
01602   void visitUDiv(BinaryOperator &I) { handleDiv(I); }
01603   void visitSDiv(BinaryOperator &I) { handleDiv(I); }
01604   void visitFDiv(BinaryOperator &I) { handleDiv(I); }
01605   void visitURem(BinaryOperator &I) { handleDiv(I); }
01606   void visitSRem(BinaryOperator &I) { handleDiv(I); }
01607   void visitFRem(BinaryOperator &I) { handleDiv(I); }
01608 
01609   /// \brief Instrument == and != comparisons.
01610   ///
01611   /// Sometimes the comparison result is known even if some of the bits of the
01612   /// arguments are not.
01613   void handleEqualityComparison(ICmpInst &I) {
01614     IRBuilder<> IRB(&I);
01615     Value *A = I.getOperand(0);
01616     Value *B = I.getOperand(1);
01617     Value *Sa = getShadow(A);
01618     Value *Sb = getShadow(B);
01619 
01620     // Get rid of pointers and vectors of pointers.
01621     // For ints (and vectors of ints), types of A and Sa match,
01622     // and this is a no-op.
01623     A = IRB.CreatePointerCast(A, Sa->getType());
01624     B = IRB.CreatePointerCast(B, Sb->getType());
01625 
01626     // A == B  <==>  (C = A^B) == 0
01627     // A != B  <==>  (C = A^B) != 0
01628     // Sc = Sa | Sb
01629     Value *C = IRB.CreateXor(A, B);
01630     Value *Sc = IRB.CreateOr(Sa, Sb);
01631     // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
01632     // Result is defined if one of the following is true
01633     // * there is a defined 1 bit in C
01634     // * C is fully defined
01635     // Si = !(C & ~Sc) && Sc
01636     Value *Zero = Constant::getNullValue(Sc->getType());
01637     Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
01638     Value *Si =
01639       IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
01640                     IRB.CreateICmpEQ(
01641                       IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
01642     Si->setName("_msprop_icmp");
01643     setShadow(&I, Si);
01644     setOriginForNaryOp(I);
01645   }
01646 
01647   /// \brief Build the lowest possible value of V, taking into account V's
01648   ///        uninitialized bits.
01649   Value *getLowestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
01650                                 bool isSigned) {
01651     if (isSigned) {
01652       // Split shadow into sign bit and other bits.
01653       Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
01654       Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
01655       // Maximise the undefined shadow bit, minimize other undefined bits.
01656       return
01657         IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaOtherBits)), SaSignBit);
01658     } else {
01659       // Minimize undefined bits.
01660       return IRB.CreateAnd(A, IRB.CreateNot(Sa));
01661     }
01662   }
01663 
01664   /// \brief Build the highest possible value of V, taking into account V's
01665   ///        uninitialized bits.
01666   Value *getHighestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
01667                                 bool isSigned) {
01668     if (isSigned) {
01669       // Split shadow into sign bit and other bits.
01670       Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
01671       Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
01672       // Minimise the undefined shadow bit, maximise other undefined bits.
01673       return
01674         IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaSignBit)), SaOtherBits);
01675     } else {
01676       // Maximize undefined bits.
01677       return IRB.CreateOr(A, Sa);
01678     }
01679   }
01680 
01681   /// \brief Instrument relational comparisons.
01682   ///
01683   /// This function does exact shadow propagation for all relational
01684   /// comparisons of integers, pointers and vectors of those.
01685   /// FIXME: output seems suboptimal when one of the operands is a constant
01686   void handleRelationalComparisonExact(ICmpInst &I) {
01687     IRBuilder<> IRB(&I);
01688     Value *A = I.getOperand(0);
01689     Value *B = I.getOperand(1);
01690     Value *Sa = getShadow(A);
01691     Value *Sb = getShadow(B);
01692 
01693     // Get rid of pointers and vectors of pointers.
01694     // For ints (and vectors of ints), types of A and Sa match,
01695     // and this is a no-op.
01696     A = IRB.CreatePointerCast(A, Sa->getType());
01697     B = IRB.CreatePointerCast(B, Sb->getType());
01698 
01699     // Let [a0, a1] be the interval of possible values of A, taking into account
01700     // its undefined bits. Let [b0, b1] be the interval of possible values of B.
01701     // Then (A cmp B) is defined iff (a0 cmp b1) == (a1 cmp b0).
01702     bool IsSigned = I.isSigned();
01703     Value *S1 = IRB.CreateICmp(I.getPredicate(),
01704                                getLowestPossibleValue(IRB, A, Sa, IsSigned),
01705                                getHighestPossibleValue(IRB, B, Sb, IsSigned));
01706     Value *S2 = IRB.CreateICmp(I.getPredicate(),
01707                                getHighestPossibleValue(IRB, A, Sa, IsSigned),
01708                                getLowestPossibleValue(IRB, B, Sb, IsSigned));
01709     Value *Si = IRB.CreateXor(S1, S2);
01710     setShadow(&I, Si);
01711     setOriginForNaryOp(I);
01712   }
01713 
01714   /// \brief Instrument signed relational comparisons.
01715   ///
01716   /// Handle (x<0) and (x>=0) comparisons (essentially, sign bit tests) by
01717   /// propagating the highest bit of the shadow. Everything else is delegated
01718   /// to handleShadowOr().
01719   void handleSignedRelationalComparison(ICmpInst &I) {
01720     Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
01721     Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
01722     Value* op = nullptr;
01723     CmpInst::Predicate pre = I.getPredicate();
01724     if (constOp0 && constOp0->isNullValue() &&
01725         (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE)) {
01726       op = I.getOperand(1);
01727     } else if (constOp1 && constOp1->isNullValue() &&
01728                (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) {
01729       op = I.getOperand(0);
01730     }
01731     if (op) {
01732       IRBuilder<> IRB(&I);
01733       Value* Shadow =
01734         IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op), "_msprop_icmpslt");
01735       setShadow(&I, Shadow);
01736       setOrigin(&I, getOrigin(op));
01737     } else {
01738       handleShadowOr(I);
01739     }
01740   }
01741 
01742   void visitICmpInst(ICmpInst &I) {
01743     if (!ClHandleICmp) {
01744       handleShadowOr(I);
01745       return;
01746     }
01747     if (I.isEquality()) {
01748       handleEqualityComparison(I);
01749       return;
01750     }
01751 
01752     assert(I.isRelational());
01753     if (ClHandleICmpExact) {
01754       handleRelationalComparisonExact(I);
01755       return;
01756     }
01757     if (I.isSigned()) {
01758       handleSignedRelationalComparison(I);
01759       return;
01760     }
01761 
01762     assert(I.isUnsigned());
01763     if ((isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
01764       handleRelationalComparisonExact(I);
01765       return;
01766     }
01767 
01768     handleShadowOr(I);
01769   }
01770 
01771   void visitFCmpInst(FCmpInst &I) {
01772     handleShadowOr(I);
01773   }
01774 
01775   void handleShift(BinaryOperator &I) {
01776     IRBuilder<> IRB(&I);
01777     // If any of the S2 bits are poisoned, the whole thing is poisoned.
01778     // Otherwise perform the same shift on S1.
01779     Value *S1 = getShadow(&I, 0);
01780     Value *S2 = getShadow(&I, 1);
01781     Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
01782                                    S2->getType());
01783     Value *V2 = I.getOperand(1);
01784     Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
01785     setShadow(&I, IRB.CreateOr(Shift, S2Conv));
01786     setOriginForNaryOp(I);
01787   }
01788 
01789   void visitShl(BinaryOperator &I) { handleShift(I); }
01790   void visitAShr(BinaryOperator &I) { handleShift(I); }
01791   void visitLShr(BinaryOperator &I) { handleShift(I); }
01792 
01793   /// \brief Instrument llvm.memmove
01794   ///
01795   /// At this point we don't know if llvm.memmove will be inlined or not.
01796   /// If we don't instrument it and it gets inlined,
01797   /// our interceptor will not kick in and we will lose the memmove.
01798   /// If we instrument the call here, but it does not get inlined,
01799   /// we will memove the shadow twice: which is bad in case
01800   /// of overlapping regions. So, we simply lower the intrinsic to a call.
01801   ///
01802   /// Similar situation exists for memcpy and memset.
01803   void visitMemMoveInst(MemMoveInst &I) {
01804     IRBuilder<> IRB(&I);
01805     IRB.CreateCall(
01806         MS.MemmoveFn,
01807         {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
01808          IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
01809          IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
01810     I.eraseFromParent();
01811   }
01812 
01813   // Similar to memmove: avoid copying shadow twice.
01814   // This is somewhat unfortunate as it may slowdown small constant memcpys.
01815   // FIXME: consider doing manual inline for small constant sizes and proper
01816   // alignment.
01817   void visitMemCpyInst(MemCpyInst &I) {
01818     IRBuilder<> IRB(&I);
01819     IRB.CreateCall(
01820         MS.MemcpyFn,
01821         {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
01822          IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
01823          IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
01824     I.eraseFromParent();
01825   }
01826 
01827   // Same as memcpy.
01828   void visitMemSetInst(MemSetInst &I) {
01829     IRBuilder<> IRB(&I);
01830     IRB.CreateCall(
01831         MS.MemsetFn,
01832         {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
01833          IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
01834          IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
01835     I.eraseFromParent();
01836   }
01837 
01838   void visitVAStartInst(VAStartInst &I) {
01839     VAHelper->visitVAStartInst(I);
01840   }
01841 
01842   void visitVACopyInst(VACopyInst &I) {
01843     VAHelper->visitVACopyInst(I);
01844   }
01845 
01846   enum IntrinsicKind {
01847     IK_DoesNotAccessMemory,
01848     IK_OnlyReadsMemory,
01849     IK_WritesMemory
01850   };
01851 
01852   static IntrinsicKind getIntrinsicKind(Intrinsic::ID iid) {
01853     const int DoesNotAccessMemory = IK_DoesNotAccessMemory;
01854     const int OnlyReadsArgumentPointees = IK_OnlyReadsMemory;
01855     const int OnlyReadsMemory = IK_OnlyReadsMemory;
01856     const int OnlyAccessesArgumentPointees = IK_WritesMemory;
01857     const int UnknownModRefBehavior = IK_WritesMemory;
01858 #define GET_INTRINSIC_MODREF_BEHAVIOR
01859 #define ModRefBehavior IntrinsicKind
01860 #include "llvm/IR/Intrinsics.gen"
01861 #undef ModRefBehavior
01862 #undef GET_INTRINSIC_MODREF_BEHAVIOR
01863   }
01864 
01865   /// \brief Handle vector store-like intrinsics.
01866   ///
01867   /// Instrument intrinsics that look like a simple SIMD store: writes memory,
01868   /// has 1 pointer argument and 1 vector argument, returns void.
01869   bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
01870     IRBuilder<> IRB(&I);
01871     Value* Addr = I.getArgOperand(0);
01872     Value *Shadow = getShadow(&I, 1);
01873     Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
01874 
01875     // We don't know the pointer alignment (could be unaligned SSE store!).
01876     // Have to assume to worst case.
01877     IRB.CreateAlignedStore(Shadow, ShadowPtr, 1);
01878 
01879     if (ClCheckAccessAddress)
01880       insertShadowCheck(Addr, &I);
01881 
01882     // FIXME: use ClStoreCleanOrigin
01883     // FIXME: factor out common code from materializeStores
01884     if (MS.TrackOrigins)
01885       IRB.CreateStore(getOrigin(&I, 1), getOriginPtr(Addr, IRB, 1));
01886     return true;
01887   }
01888 
01889   /// \brief Handle vector load-like intrinsics.
01890   ///
01891   /// Instrument intrinsics that look like a simple SIMD load: reads memory,
01892   /// has 1 pointer argument, returns a vector.
01893   bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
01894     IRBuilder<> IRB(&I);
01895     Value *Addr = I.getArgOperand(0);
01896 
01897     Type *ShadowTy = getShadowTy(&I);
01898     if (PropagateShadow) {
01899       Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
01900       // We don't know the pointer alignment (could be unaligned SSE load!).
01901       // Have to assume to worst case.
01902       setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, 1, "_msld"));
01903     } else {
01904       setShadow(&I, getCleanShadow(&I));
01905     }
01906 
01907     if (ClCheckAccessAddress)
01908       insertShadowCheck(Addr, &I);
01909 
01910     if (MS.TrackOrigins) {
01911       if (PropagateShadow)
01912         setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB, 1)));
01913       else
01914         setOrigin(&I, getCleanOrigin());
01915     }
01916     return true;
01917   }
01918 
01919   /// \brief Handle (SIMD arithmetic)-like intrinsics.
01920   ///
01921   /// Instrument intrinsics with any number of arguments of the same type,
01922   /// equal to the return type. The type should be simple (no aggregates or
01923   /// pointers; vectors are fine).
01924   /// Caller guarantees that this intrinsic does not access memory.
01925   bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) {
01926     Type *RetTy = I.getType();
01927     if (!(RetTy->isIntOrIntVectorTy() ||
01928           RetTy->isFPOrFPVectorTy() ||
01929           RetTy->isX86_MMXTy()))
01930       return false;
01931 
01932     unsigned NumArgOperands = I.getNumArgOperands();
01933 
01934     for (unsigned i = 0; i < NumArgOperands; ++i) {
01935       Type *Ty = I.getArgOperand(i)->getType();
01936       if (Ty != RetTy)
01937         return false;
01938     }
01939 
01940     IRBuilder<> IRB(&I);
01941     ShadowAndOriginCombiner SC(this, IRB);
01942     for (unsigned i = 0; i < NumArgOperands; ++i)
01943       SC.Add(I.getArgOperand(i));
01944     SC.Done(&I);
01945 
01946     return true;
01947   }
01948 
01949   /// \brief Heuristically instrument unknown intrinsics.
01950   ///
01951   /// The main purpose of this code is to do something reasonable with all
01952   /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
01953   /// We recognize several classes of intrinsics by their argument types and
01954   /// ModRefBehaviour and apply special intrumentation when we are reasonably
01955   /// sure that we know what the intrinsic does.
01956   ///
01957   /// We special-case intrinsics where this approach fails. See llvm.bswap
01958   /// handling as an example of that.
01959   bool handleUnknownIntrinsic(IntrinsicInst &I) {
01960     unsigned NumArgOperands = I.getNumArgOperands();
01961     if (NumArgOperands == 0)
01962       return false;
01963 
01964     Intrinsic::ID iid = I.getIntrinsicID();
01965     IntrinsicKind IK = getIntrinsicKind(iid);
01966     bool OnlyReadsMemory = IK == IK_OnlyReadsMemory;
01967     bool WritesMemory = IK == IK_WritesMemory;
01968     assert(!(OnlyReadsMemory && WritesMemory));
01969 
01970     if (NumArgOperands == 2 &&
01971         I.getArgOperand(0)->getType()->isPointerTy() &&
01972         I.getArgOperand(1)->getType()->isVectorTy() &&
01973         I.getType()->isVoidTy() &&
01974         WritesMemory) {
01975       // This looks like a vector store.
01976       return handleVectorStoreIntrinsic(I);
01977     }
01978 
01979     if (NumArgOperands == 1 &&
01980         I.getArgOperand(0)->getType()->isPointerTy() &&
01981         I.getType()->isVectorTy() &&
01982         OnlyReadsMemory) {
01983       // This looks like a vector load.
01984       return handleVectorLoadIntrinsic(I);
01985     }
01986 
01987     if (!OnlyReadsMemory && !WritesMemory)
01988       if (maybeHandleSimpleNomemIntrinsic(I))
01989         return true;
01990 
01991     // FIXME: detect and handle SSE maskstore/maskload
01992     return false;
01993   }
01994 
01995   void handleBswap(IntrinsicInst &I) {
01996     IRBuilder<> IRB(&I);
01997     Value *Op = I.getArgOperand(0);
01998     Type *OpType = Op->getType();
01999     Function *BswapFunc = Intrinsic::getDeclaration(
02000       F.getParent(), Intrinsic::bswap, makeArrayRef(&OpType, 1));
02001     setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
02002     setOrigin(&I, getOrigin(Op));
02003   }
02004 
02005   // \brief Instrument vector convert instrinsic.
02006   //
02007   // This function instruments intrinsics like cvtsi2ss:
02008   // %Out = int_xxx_cvtyyy(%ConvertOp)
02009   // or
02010   // %Out = int_xxx_cvtyyy(%CopyOp, %ConvertOp)
02011   // Intrinsic converts \p NumUsedElements elements of \p ConvertOp to the same
02012   // number \p Out elements, and (if has 2 arguments) copies the rest of the
02013   // elements from \p CopyOp.
02014   // In most cases conversion involves floating-point value which may trigger a
02015   // hardware exception when not fully initialized. For this reason we require
02016   // \p ConvertOp[0:NumUsedElements] to be fully initialized and trap otherwise.
02017   // We copy the shadow of \p CopyOp[NumUsedElements:] to \p
02018   // Out[NumUsedElements:]. This means that intrinsics without \p CopyOp always
02019   // return a fully initialized value.
02020   void handleVectorConvertIntrinsic(IntrinsicInst &I, int NumUsedElements) {
02021     IRBuilder<> IRB(&I);
02022     Value *CopyOp, *ConvertOp;
02023 
02024     switch (I.getNumArgOperands()) {
02025     case 2:
02026       CopyOp = I.getArgOperand(0);
02027       ConvertOp = I.getArgOperand(1);
02028       break;
02029     case 1:
02030       ConvertOp = I.getArgOperand(0);
02031       CopyOp = nullptr;
02032       break;
02033     default:
02034       llvm_unreachable("Cvt intrinsic with unsupported number of arguments.");
02035     }
02036 
02037     // The first *NumUsedElements* elements of ConvertOp are converted to the
02038     // same number of output elements. The rest of the output is copied from
02039     // CopyOp, or (if not available) filled with zeroes.
02040     // Combine shadow for elements of ConvertOp that are used in this operation,
02041     // and insert a check.
02042     // FIXME: consider propagating shadow of ConvertOp, at least in the case of
02043     // int->any conversion.
02044     Value *ConvertShadow = getShadow(ConvertOp);
02045     Value *AggShadow = nullptr;
02046     if (ConvertOp->getType()->isVectorTy()) {
02047       AggShadow = IRB.CreateExtractElement(
02048           ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), 0));
02049       for (int i = 1; i < NumUsedElements; ++i) {
02050         Value *MoreShadow = IRB.CreateExtractElement(
02051             ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), i));
02052         AggShadow = IRB.CreateOr(AggShadow, MoreShadow);
02053       }
02054     } else {
02055       AggShadow = ConvertShadow;
02056     }
02057     assert(AggShadow->getType()->isIntegerTy());
02058     insertShadowCheck(AggShadow, getOrigin(ConvertOp), &I);
02059 
02060     // Build result shadow by zero-filling parts of CopyOp shadow that come from
02061     // ConvertOp.
02062     if (CopyOp) {
02063       assert(CopyOp->getType() == I.getType());
02064       assert(CopyOp->getType()->isVectorTy());
02065       Value *ResultShadow = getShadow(CopyOp);
02066       Type *EltTy = ResultShadow->getType()->getVectorElementType();
02067       for (int i = 0; i < NumUsedElements; ++i) {
02068         ResultShadow = IRB.CreateInsertElement(
02069             ResultShadow, ConstantInt::getNullValue(EltTy),
02070             ConstantInt::get(IRB.getInt32Ty(), i));
02071       }
02072       setShadow(&I, ResultShadow);
02073       setOrigin(&I, getOrigin(CopyOp));
02074     } else {
02075       setShadow(&I, getCleanShadow(&I));
02076       setOrigin(&I, getCleanOrigin());
02077     }
02078   }
02079 
02080   // Given a scalar or vector, extract lower 64 bits (or less), and return all
02081   // zeroes if it is zero, and all ones otherwise.
02082   Value *Lower64ShadowExtend(IRBuilder<> &IRB, Value *S, Type *T) {
02083     if (S->getType()->isVectorTy())
02084       S = CreateShadowCast(IRB, S, IRB.getInt64Ty(), /* Signed */ true);
02085     assert(S->getType()->getPrimitiveSizeInBits() <= 64);
02086     Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
02087     return CreateShadowCast(IRB, S2, T, /* Signed */ true);
02088   }
02089 
02090   Value *VariableShadowExtend(IRBuilder<> &IRB, Value *S) {
02091     Type *T = S->getType();
02092     assert(T->isVectorTy());
02093     Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
02094     return IRB.CreateSExt(S2, T);
02095   }
02096 
02097   // \brief Instrument vector shift instrinsic.
02098   //
02099   // This function instruments intrinsics like int_x86_avx2_psll_w.
02100   // Intrinsic shifts %In by %ShiftSize bits.
02101   // %ShiftSize may be a vector. In that case the lower 64 bits determine shift
02102   // size, and the rest is ignored. Behavior is defined even if shift size is
02103   // greater than register (or field) width.
02104   void handleVectorShiftIntrinsic(IntrinsicInst &I, bool Variable) {
02105     assert(I.getNumArgOperands() == 2);
02106     IRBuilder<> IRB(&I);
02107     // If any of the S2 bits are poisoned, the whole thing is poisoned.
02108     // Otherwise perform the same shift on S1.
02109     Value *S1 = getShadow(&I, 0);
02110     Value *S2 = getShadow(&I, 1);
02111     Value *S2Conv = Variable ? VariableShadowExtend(IRB, S2)
02112                              : Lower64ShadowExtend(IRB, S2, getShadowTy(&I));
02113     Value *V1 = I.getOperand(0);
02114     Value *V2 = I.getOperand(1);
02115     Value *Shift = IRB.CreateCall(I.getCalledValue(),
02116                                   {IRB.CreateBitCast(S1, V1->getType()), V2});
02117     Shift = IRB.CreateBitCast(Shift, getShadowTy(&I));
02118     setShadow(&I, IRB.CreateOr(Shift, S2Conv));
02119     setOriginForNaryOp(I);
02120   }
02121 
02122   // \brief Get an X86_MMX-sized vector type.
02123   Type *getMMXVectorTy(unsigned EltSizeInBits) {
02124     const unsigned X86_MMXSizeInBits = 64;
02125     return VectorType::get(IntegerType::get(*MS.C, EltSizeInBits),
02126                            X86_MMXSizeInBits / EltSizeInBits);
02127   }
02128 
02129   // \brief Returns a signed counterpart for an (un)signed-saturate-and-pack
02130   // intrinsic.
02131   Intrinsic::ID getSignedPackIntrinsic(Intrinsic::ID id) {
02132     switch (id) {
02133       case llvm::Intrinsic::x86_sse2_packsswb_128:
02134       case llvm::Intrinsic::x86_sse2_packuswb_128:
02135         return llvm::Intrinsic::x86_sse2_packsswb_128;
02136 
02137       case llvm::Intrinsic::x86_sse2_packssdw_128:
02138       case llvm::Intrinsic::x86_sse41_packusdw:
02139         return llvm::Intrinsic::x86_sse2_packssdw_128;
02140 
02141       case llvm::Intrinsic::x86_avx2_packsswb:
02142       case llvm::Intrinsic::x86_avx2_packuswb:
02143         return llvm::Intrinsic::x86_avx2_packsswb;
02144 
02145       case llvm::Intrinsic::x86_avx2_packssdw:
02146       case llvm::Intrinsic::x86_avx2_packusdw:
02147         return llvm::Intrinsic::x86_avx2_packssdw;
02148 
02149       case llvm::Intrinsic::x86_mmx_packsswb:
02150       case llvm::Intrinsic::x86_mmx_packuswb:
02151         return llvm::Intrinsic::x86_mmx_packsswb;
02152 
02153       case llvm::Intrinsic::x86_mmx_packssdw:
02154         return llvm::Intrinsic::x86_mmx_packssdw;
02155       default:
02156         llvm_unreachable("unexpected intrinsic id");
02157     }
02158   }
02159 
02160   // \brief Instrument vector pack instrinsic.
02161   //
02162   // This function instruments intrinsics like x86_mmx_packsswb, that
02163   // packs elements of 2 input vectors into half as many bits with saturation.
02164   // Shadow is propagated with the signed variant of the same intrinsic applied
02165   // to sext(Sa != zeroinitializer), sext(Sb != zeroinitializer).
02166   // EltSizeInBits is used only for x86mmx arguments.
02167   void handleVectorPackIntrinsic(IntrinsicInst &I, unsigned EltSizeInBits = 0) {
02168     assert(I.getNumArgOperands() == 2);
02169     bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
02170     IRBuilder<> IRB(&I);
02171     Value *S1 = getShadow(&I, 0);
02172     Value *S2 = getShadow(&I, 1);
02173     assert(isX86_MMX || S1->getType()->isVectorTy());
02174 
02175     // SExt and ICmpNE below must apply to individual elements of input vectors.
02176     // In case of x86mmx arguments, cast them to appropriate vector types and
02177     // back.
02178     Type *T = isX86_MMX ? getMMXVectorTy(EltSizeInBits) : S1->getType();
02179     if (isX86_MMX) {
02180       S1 = IRB.CreateBitCast(S1, T);
02181       S2 = IRB.CreateBitCast(S2, T);
02182     }
02183     Value *S1_ext = IRB.CreateSExt(
02184         IRB.CreateICmpNE(S1, llvm::Constant::getNullValue(T)), T);
02185     Value *S2_ext = IRB.CreateSExt(
02186         IRB.CreateICmpNE(S2, llvm::Constant::getNullValue(T)), T);
02187     if (isX86_MMX) {
02188       Type *X86_MMXTy = Type::getX86_MMXTy(*MS.C);
02189       S1_ext = IRB.CreateBitCast(S1_ext, X86_MMXTy);
02190       S2_ext = IRB.CreateBitCast(S2_ext, X86_MMXTy);
02191     }
02192 
02193     Function *ShadowFn = Intrinsic::getDeclaration(
02194         F.getParent(), getSignedPackIntrinsic(I.getIntrinsicID()));
02195 
02196     Value *S =
02197         IRB.CreateCall(ShadowFn, {S1_ext, S2_ext}, "_msprop_vector_pack");
02198     if (isX86_MMX) S = IRB.CreateBitCast(S, getShadowTy(&I));
02199     setShadow(&I, S);
02200     setOriginForNaryOp(I);
02201   }
02202 
02203   // \brief Instrument sum-of-absolute-differencies intrinsic.
02204   void handleVectorSadIntrinsic(IntrinsicInst &I) {
02205     const unsigned SignificantBitsPerResultElement = 16;
02206     bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
02207     Type *ResTy = isX86_MMX ? IntegerType::get(*MS.C, 64) : I.getType();
02208     unsigned ZeroBitsPerResultElement =
02209         ResTy->getScalarSizeInBits() - SignificantBitsPerResultElement;
02210 
02211     IRBuilder<> IRB(&I);
02212     Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
02213     S = IRB.CreateBitCast(S, ResTy);
02214     S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
02215                        ResTy);
02216     S = IRB.CreateLShr(S, ZeroBitsPerResultElement);
02217     S = IRB.CreateBitCast(S, getShadowTy(&I));
02218     setShadow(&I, S);
02219     setOriginForNaryOp(I);
02220   }
02221 
02222   // \brief Instrument multiply-add intrinsic.
02223   void handleVectorPmaddIntrinsic(IntrinsicInst &I,
02224                                   unsigned EltSizeInBits = 0) {
02225     bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
02226     Type *ResTy = isX86_MMX ? getMMXVectorTy(EltSizeInBits * 2) : I.getType();
02227     IRBuilder<> IRB(&I);
02228     Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
02229     S = IRB.CreateBitCast(S, ResTy);
02230     S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
02231                        ResTy);
02232     S = IRB.CreateBitCast(S, getShadowTy(&I));
02233     setShadow(&I, S);
02234     setOriginForNaryOp(I);
02235   }
02236 
02237   void visitIntrinsicInst(IntrinsicInst &I) {
02238     switch (I.getIntrinsicID()) {
02239     case llvm::Intrinsic::bswap:
02240       handleBswap(I);
02241       break;
02242     case llvm::Intrinsic::x86_avx512_cvtsd2usi64:
02243     case llvm::Intrinsic::x86_avx512_cvtsd2usi:
02244     case llvm::Intrinsic::x86_avx512_cvtss2usi64:
02245     case llvm::Intrinsic::x86_avx512_cvtss2usi:
02246     case llvm::Intrinsic::x86_avx512_cvttss2usi64:
02247     case llvm::Intrinsic::x86_avx512_cvttss2usi:
02248     case llvm::Intrinsic::x86_avx512_cvttsd2usi64:
02249     case llvm::Intrinsic::x86_avx512_cvttsd2usi:
02250     case llvm::Intrinsic::x86_avx512_cvtusi2sd:
02251     case llvm::Intrinsic::x86_avx512_cvtusi2ss:
02252     case llvm::Intrinsic::x86_avx512_cvtusi642sd:
02253     case llvm::Intrinsic::x86_avx512_cvtusi642ss:
02254     case llvm::Intrinsic::x86_sse2_cvtsd2si64:
02255     case llvm::Intrinsic::x86_sse2_cvtsd2si:
02256     case llvm::Intrinsic::x86_sse2_cvtsd2ss:
02257     case llvm::Intrinsic::x86_sse2_cvtsi2sd:
02258     case llvm::Intrinsic::x86_sse2_cvtsi642sd:
02259     case llvm::Intrinsic::x86_sse2_cvtss2sd:
02260     case llvm::Intrinsic::x86_sse2_cvttsd2si64:
02261     case llvm::Intrinsic::x86_sse2_cvttsd2si:
02262     case llvm::Intrinsic::x86_sse_cvtsi2ss:
02263     case llvm::Intrinsic::x86_sse_cvtsi642ss:
02264     case llvm::Intrinsic::x86_sse_cvtss2si64:
02265     case llvm::Intrinsic::x86_sse_cvtss2si:
02266     case llvm::Intrinsic::x86_sse_cvttss2si64:
02267     case llvm::Intrinsic::x86_sse_cvttss2si:
02268       handleVectorConvertIntrinsic(I, 1);
02269       break;
02270     case llvm::Intrinsic::x86_sse2_cvtdq2pd:
02271     case llvm::Intrinsic::x86_sse2_cvtps2pd:
02272     case llvm::Intrinsic::x86_sse_cvtps2pi:
02273     case llvm::Intrinsic::x86_sse_cvttps2pi:
02274       handleVectorConvertIntrinsic(I, 2);
02275       break;
02276     case llvm::Intrinsic::x86_avx2_psll_w:
02277     case llvm::Intrinsic::x86_avx2_psll_d:
02278     case llvm::Intrinsic::x86_avx2_psll_q:
02279     case llvm::Intrinsic::x86_avx2_pslli_w:
02280     case llvm::Intrinsic::x86_avx2_pslli_d:
02281     case llvm::Intrinsic::x86_avx2_pslli_q:
02282     case llvm::Intrinsic::x86_avx2_psrl_w:
02283     case llvm::Intrinsic::x86_avx2_psrl_d:
02284     case llvm::Intrinsic::x86_avx2_psrl_q:
02285     case llvm::Intrinsic::x86_avx2_psra_w:
02286     case llvm::Intrinsic::x86_avx2_psra_d:
02287     case llvm::Intrinsic::x86_avx2_psrli_w:
02288     case llvm::Intrinsic::x86_avx2_psrli_d:
02289     case llvm::Intrinsic::x86_avx2_psrli_q:
02290     case llvm::Intrinsic::x86_avx2_psrai_w:
02291     case llvm::Intrinsic::x86_avx2_psrai_d:
02292     case llvm::Intrinsic::x86_sse2_psll_w:
02293     case llvm::Intrinsic::x86_sse2_psll_d:
02294     case llvm::Intrinsic::x86_sse2_psll_q:
02295     case llvm::Intrinsic::x86_sse2_pslli_w:
02296     case llvm::Intrinsic::x86_sse2_pslli_d:
02297     case llvm::Intrinsic::x86_sse2_pslli_q:
02298     case llvm::Intrinsic::x86_sse2_psrl_w:
02299     case llvm::Intrinsic::x86_sse2_psrl_d:
02300     case llvm::Intrinsic::x86_sse2_psrl_q:
02301     case llvm::Intrinsic::x86_sse2_psra_w:
02302     case llvm::Intrinsic::x86_sse2_psra_d:
02303     case llvm::Intrinsic::x86_sse2_psrli_w:
02304     case llvm::Intrinsic::x86_sse2_psrli_d:
02305     case llvm::Intrinsic::x86_sse2_psrli_q:
02306     case llvm::Intrinsic::x86_sse2_psrai_w:
02307     case llvm::Intrinsic::x86_sse2_psrai_d:
02308     case llvm::Intrinsic::x86_mmx_psll_w:
02309     case llvm::Intrinsic::x86_mmx_psll_d:
02310     case llvm::Intrinsic::x86_mmx_psll_q:
02311     case llvm::Intrinsic::x86_mmx_pslli_w:
02312     case llvm::Intrinsic::x86_mmx_pslli_d:
02313     case llvm::Intrinsic::x86_mmx_pslli_q:
02314     case llvm::Intrinsic::x86_mmx_psrl_w:
02315     case llvm::Intrinsic::x86_mmx_psrl_d:
02316     case llvm::Intrinsic::x86_mmx_psrl_q:
02317     case llvm::Intrinsic::x86_mmx_psra_w:
02318     case llvm::Intrinsic::x86_mmx_psra_d:
02319     case llvm::Intrinsic::x86_mmx_psrli_w:
02320     case llvm::Intrinsic::x86_mmx_psrli_d:
02321     case llvm::Intrinsic::x86_mmx_psrli_q:
02322     case llvm::Intrinsic::x86_mmx_psrai_w:
02323     case llvm::Intrinsic::x86_mmx_psrai_d:
02324       handleVectorShiftIntrinsic(I, /* Variable */ false);
02325       break;
02326     case llvm::Intrinsic::x86_avx2_psllv_d:
02327     case llvm::Intrinsic::x86_avx2_psllv_d_256:
02328     case llvm::Intrinsic::x86_avx2_psllv_q:
02329     case llvm::Intrinsic::x86_avx2_psllv_q_256:
02330     case llvm::Intrinsic::x86_avx2_psrlv_d:
02331     case llvm::Intrinsic::x86_avx2_psrlv_d_256:
02332     case llvm::Intrinsic::x86_avx2_psrlv_q:
02333     case llvm::Intrinsic::x86_avx2_psrlv_q_256:
02334     case llvm::Intrinsic::x86_avx2_psrav_d:
02335     case llvm::Intrinsic::x86_avx2_psrav_d_256:
02336       handleVectorShiftIntrinsic(I, /* Variable */ true);
02337       break;
02338 
02339     case llvm::Intrinsic::x86_sse2_packsswb_128:
02340     case llvm::Intrinsic::x86_sse2_packssdw_128:
02341     case llvm::Intrinsic::x86_sse2_packuswb_128:
02342     case llvm::Intrinsic::x86_sse41_packusdw:
02343     case llvm::Intrinsic::x86_avx2_packsswb:
02344     case llvm::Intrinsic::x86_avx2_packssdw:
02345     case llvm::Intrinsic::x86_avx2_packuswb:
02346     case llvm::Intrinsic::x86_avx2_packusdw:
02347       handleVectorPackIntrinsic(I);
02348       break;
02349 
02350     case llvm::Intrinsic::x86_mmx_packsswb:
02351     case llvm::Intrinsic::x86_mmx_packuswb:
02352       handleVectorPackIntrinsic(I, 16);
02353       break;
02354 
02355     case llvm::Intrinsic::x86_mmx_packssdw:
02356       handleVectorPackIntrinsic(I, 32);
02357       break;
02358 
02359     case llvm::Intrinsic::x86_mmx_psad_bw:
02360     case llvm::Intrinsic::x86_sse2_psad_bw:
02361     case llvm::Intrinsic::x86_avx2_psad_bw:
02362       handleVectorSadIntrinsic(I);
02363       break;
02364 
02365     case llvm::Intrinsic::x86_sse2_pmadd_wd:
02366     case llvm::Intrinsic::x86_avx2_pmadd_wd:
02367     case llvm::Intrinsic::x86_ssse3_pmadd_ub_sw_128:
02368     case llvm::Intrinsic::x86_avx2_pmadd_ub_sw:
02369       handleVectorPmaddIntrinsic(I);
02370       break;
02371 
02372     case llvm::Intrinsic::x86_ssse3_pmadd_ub_sw:
02373       handleVectorPmaddIntrinsic(I, 8);
02374       break;
02375 
02376     case llvm::Intrinsic::x86_mmx_pmadd_wd:
02377       handleVectorPmaddIntrinsic(I, 16);
02378       break;
02379 
02380     default:
02381       if (!handleUnknownIntrinsic(I))
02382         visitInstruction(I);
02383       break;
02384     }
02385   }
02386 
02387   void visitCallSite(CallSite CS) {
02388     Instruction &I = *CS.getInstruction();
02389     assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
02390     if (CS.isCall()) {
02391       CallInst *Call = cast<CallInst>(&I);
02392 
02393       // For inline asm, do the usual thing: check argument shadow and mark all
02394       // outputs as clean. Note that any side effects of the inline asm that are
02395       // not immediately visible in its constraints are not handled.
02396       if (Call->isInlineAsm()) {
02397         visitInstruction(I);
02398         return;
02399       }
02400 
02401       assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
02402 
02403       // We are going to insert code that relies on the fact that the callee
02404       // will become a non-readonly function after it is instrumented by us. To
02405       // prevent this code from being optimized out, mark that function
02406       // non-readonly in advance.
02407       if (Function *Func = Call->getCalledFunction()) {
02408         // Clear out readonly/readnone attributes.
02409         AttrBuilder B;
02410         B.addAttribute(Attribute::ReadOnly)
02411           .addAttribute(Attribute::ReadNone);
02412         Func->removeAttributes(AttributeSet::FunctionIndex,
02413                                AttributeSet::get(Func->getContext(),
02414                                                  AttributeSet::FunctionIndex,
02415                                                  B));
02416       }
02417     }
02418     IRBuilder<> IRB(&I);
02419 
02420     unsigned ArgOffset = 0;
02421     DEBUG(dbgs() << "  CallSite: " << I << "\n");
02422     for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
02423          ArgIt != End; ++ArgIt) {
02424       Value *A = *ArgIt;
02425       unsigned i = ArgIt - CS.arg_begin();
02426       if (!A->getType()->isSized()) {
02427         DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
02428         continue;
02429       }
02430       unsigned Size = 0;
02431       Value *Store = nullptr;
02432       // Compute the Shadow for arg even if it is ByVal, because
02433       // in that case getShadow() will copy the actual arg shadow to
02434       // __msan_param_tls.
02435       Value *ArgShadow = getShadow(A);
02436       Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
02437       DEBUG(dbgs() << "  Arg#" << i << ": " << *A <<
02438             " Shadow: " << *ArgShadow << "\n");
02439       bool ArgIsInitialized = false;
02440       const DataLayout &DL = F.getParent()->getDataLayout();
02441       if (CS.paramHasAttr(i + 1, Attribute::ByVal)) {
02442         assert(A->getType()->isPointerTy() &&
02443                "ByVal argument is not a pointer!");
02444         Size = DL.getTypeAllocSize(A->getType()->getPointerElementType());
02445         if (ArgOffset + Size > kParamTLSSize) break;
02446         unsigned ParamAlignment = CS.getParamAlignment(i + 1);
02447         unsigned Alignment = std::min(ParamAlignment, kShadowTLSAlignment);
02448         Store = IRB.CreateMemCpy(ArgShadowBase,
02449                                  getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
02450                                  Size, Alignment);
02451       } else {
02452         Size = DL.getTypeAllocSize(A->getType());
02453         if (ArgOffset + Size > kParamTLSSize) break;
02454         Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
02455                                        kShadowTLSAlignment);
02456         Constant *Cst = dyn_cast<Constant>(ArgShadow);
02457         if (Cst && Cst->isNullValue()) ArgIsInitialized = true;
02458       }
02459       if (MS.TrackOrigins && !ArgIsInitialized)
02460         IRB.CreateStore(getOrigin(A),
02461                         getOriginPtrForArgument(A, IRB, ArgOffset));
02462       (void)Store;
02463       assert(Size != 0 && Store != nullptr);
02464       DEBUG(dbgs() << "  Param:" << *Store << "\n");
02465       ArgOffset += RoundUpToAlignment(Size, 8);
02466     }
02467     DEBUG(dbgs() << "  done with call args\n");
02468 
02469     FunctionType *FT =
02470       cast<FunctionType>(CS.getCalledValue()->getType()->getContainedType(0));
02471     if (FT->isVarArg()) {
02472       VAHelper->visitCallSite(CS, IRB);
02473     }
02474 
02475     // Now, get the shadow for the RetVal.
02476     if (!I.getType()->isSized()) return;
02477     IRBuilder<> IRBBefore(&I);
02478     // Until we have full dynamic coverage, make sure the retval shadow is 0.
02479     Value *Base = getShadowPtrForRetval(&I, IRBBefore);
02480     IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
02481     Instruction *NextInsn = nullptr;
02482     if (CS.isCall()) {
02483       NextInsn = I.getNextNode();
02484     } else {
02485       BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
02486       if (!NormalDest->getSinglePredecessor()) {
02487         // FIXME: this case is tricky, so we are just conservative here.
02488         // Perhaps we need to split the edge between this BB and NormalDest,
02489         // but a naive attempt to use SplitEdge leads to a crash.
02490         setShadow(&I, getCleanShadow(&I));
02491         setOrigin(&I, getCleanOrigin());
02492         return;
02493       }
02494       NextInsn = NormalDest->getFirstInsertionPt();
02495       assert(NextInsn &&
02496              "Could not find insertion point for retval shadow load");
02497     }
02498     IRBuilder<> IRBAfter(NextInsn);
02499     Value *RetvalShadow =
02500       IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
02501                                  kShadowTLSAlignment, "_msret");
02502     setShadow(&I, RetvalShadow);
02503     if (MS.TrackOrigins)
02504       setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
02505   }
02506 
02507   void visitReturnInst(ReturnInst &I) {
02508     IRBuilder<> IRB(&I);
02509     Value *RetVal = I.getReturnValue();
02510     if (!RetVal) return;
02511     Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
02512     if (CheckReturnValue) {
02513       insertShadowCheck(RetVal, &I);
02514       Value *Shadow = getCleanShadow(RetVal);
02515       IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
02516     } else {
02517       Value *Shadow = getShadow(RetVal);
02518       IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
02519       // FIXME: make it conditional if ClStoreCleanOrigin==0
02520       if (MS.TrackOrigins)
02521         IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
02522     }
02523   }
02524 
02525   void visitPHINode(PHINode &I) {
02526     IRBuilder<> IRB(&I);
02527     if (!PropagateShadow) {
02528       setShadow(&I, getCleanShadow(&I));
02529       setOrigin(&I, getCleanOrigin());
02530       return;
02531     }
02532 
02533     ShadowPHINodes.push_back(&I);
02534     setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
02535                                 "_msphi_s"));
02536     if (MS.TrackOrigins)
02537       setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
02538                                   "_msphi_o"));
02539   }
02540 
02541   void visitAllocaInst(AllocaInst &I) {
02542     setShadow(&I, getCleanShadow(&I));
02543     setOrigin(&I, getCleanOrigin());
02544     IRBuilder<> IRB(I.getNextNode());
02545     const DataLayout &DL = F.getParent()->getDataLayout();
02546     uint64_t Size = DL.getTypeAllocSize(I.getAllocatedType());
02547     if (PoisonStack && ClPoisonStackWithCall) {
02548       IRB.CreateCall(MS.MsanPoisonStackFn,
02549                      {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
02550                       ConstantInt::get(MS.IntptrTy, Size)});
02551     } else {
02552       Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
02553       Value *PoisonValue = IRB.getInt8(PoisonStack ? ClPoisonStackPattern : 0);
02554       IRB.CreateMemSet(ShadowBase, PoisonValue, Size, I.getAlignment());
02555     }
02556 
02557     if (PoisonStack && MS.TrackOrigins) {
02558       SmallString<2048> StackDescriptionStorage;
02559       raw_svector_ostream StackDescription(StackDescriptionStorage);
02560       // We create a string with a description of the stack allocation and
02561       // pass it into __msan_set_alloca_origin.
02562       // It will be printed by the run-time if stack-originated UMR is found.
02563       // The first 4 bytes of the string are set to '----' and will be replaced
02564       // by __msan_va_arg_overflow_size_tls at the first call.
02565       StackDescription << "----" << I.getName() << "@" << F.getName();
02566       Value *Descr =
02567           createPrivateNonConstGlobalForString(*F.getParent(),
02568                                                StackDescription.str());
02569 
02570       IRB.CreateCall(MS.MsanSetAllocaOrigin4Fn,
02571                      {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
02572                       ConstantInt::get(MS.IntptrTy, Size),
02573                       IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()),
02574                       IRB.CreatePointerCast(&F, MS.IntptrTy)});
02575     }
02576   }
02577 
02578   void visitSelectInst(SelectInst& I) {
02579     IRBuilder<> IRB(&I);
02580     // a = select b, c, d
02581     Value *B = I.getCondition();
02582     Value *C = I.getTrueValue();
02583     Value *D = I.getFalseValue();
02584     Value *Sb = getShadow(B);
02585     Value *Sc = getShadow(C);
02586     Value *Sd = getShadow(D);
02587 
02588     // Result shadow if condition shadow is 0.
02589     Value *Sa0 = IRB.CreateSelect(B, Sc, Sd);
02590     Value *Sa1;
02591     if (I.getType()->isAggregateType()) {
02592       // To avoid "sign extending" i1 to an arbitrary aggregate type, we just do
02593       // an extra "select". This results in much more compact IR.
02594       // Sa = select Sb, poisoned, (select b, Sc, Sd)
02595       Sa1 = getPoisonedShadow(getShadowTy(I.getType()));
02596     } else {
02597       // Sa = select Sb, [ (c^d) | Sc | Sd ], [ b ? Sc : Sd ]
02598       // If Sb (condition is poisoned), look for bits in c and d that are equal
02599       // and both unpoisoned.
02600       // If !Sb (condition is unpoisoned), simply pick one of Sc and Sd.
02601 
02602       // Cast arguments to shadow-compatible type.
02603       C = CreateAppToShadowCast(IRB, C);
02604       D = CreateAppToShadowCast(IRB, D);
02605 
02606       // Result shadow if condition shadow is 1.
02607       Sa1 = IRB.CreateOr(IRB.CreateXor(C, D), IRB.CreateOr(Sc, Sd));
02608     }
02609     Value *Sa = IRB.CreateSelect(Sb, Sa1, Sa0, "_msprop_select");
02610     setShadow(&I, Sa);
02611     if (MS.TrackOrigins) {
02612       // Origins are always i32, so any vector conditions must be flattened.
02613       // FIXME: consider tracking vector origins for app vectors?
02614       if (B->getType()->isVectorTy()) {
02615         Type *FlatTy = getShadowTyNoVec(B->getType());
02616         B = IRB.CreateICmpNE(IRB.CreateBitCast(B, FlatTy),
02617                                 ConstantInt::getNullValue(FlatTy));
02618         Sb = IRB.CreateICmpNE(IRB.CreateBitCast(Sb, FlatTy),
02619                                       ConstantInt::getNullValue(FlatTy));
02620       }
02621       // a = select b, c, d
02622       // Oa = Sb ? Ob : (b ? Oc : Od)
02623       setOrigin(
02624           &I, IRB.CreateSelect(Sb, getOrigin(I.getCondition()),
02625                                IRB.CreateSelect(B, getOrigin(I.getTrueValue()),
02626                                                 getOrigin(I.getFalseValue()))));
02627     }
02628   }
02629 
02630   void visitLandingPadInst(LandingPadInst &I) {
02631     // Do nothing.
02632     // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
02633     setShadow(&I, getCleanShadow(&I));
02634     setOrigin(&I, getCleanOrigin());
02635   }
02636 
02637   void visitGetElementPtrInst(GetElementPtrInst &I) {
02638     handleShadowOr(I);
02639   }
02640 
02641   void visitExtractValueInst(ExtractValueInst &I) {
02642     IRBuilder<> IRB(&I);
02643     Value *Agg = I.getAggregateOperand();
02644     DEBUG(dbgs() << "ExtractValue:  " << I << "\n");
02645     Value *AggShadow = getShadow(Agg);
02646     DEBUG(dbgs() << "   AggShadow:  " << *AggShadow << "\n");
02647     Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
02648     DEBUG(dbgs() << "   ResShadow:  " << *ResShadow << "\n");
02649     setShadow(&I, ResShadow);
02650     setOriginForNaryOp(I);
02651   }
02652 
02653   void visitInsertValueInst(InsertValueInst &I) {
02654     IRBuilder<> IRB(&I);
02655     DEBUG(dbgs() << "InsertValue:  " << I << "\n");
02656     Value *AggShadow = getShadow(I.getAggregateOperand());
02657     Value *InsShadow = getShadow(I.getInsertedValueOperand());
02658     DEBUG(dbgs() << "   AggShadow:  " << *AggShadow << "\n");
02659     DEBUG(dbgs() << "   InsShadow:  " << *InsShadow << "\n");
02660     Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
02661     DEBUG(dbgs() << "   Res:        " << *Res << "\n");
02662     setShadow(&I, Res);
02663     setOriginForNaryOp(I);
02664   }
02665 
02666   void dumpInst(Instruction &I) {
02667     if (CallInst *CI = dyn_cast<CallInst>(&I)) {
02668       errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
02669     } else {
02670       errs() << "ZZZ " << I.getOpcodeName() << "\n";
02671     }
02672     errs() << "QQQ " << I << "\n";
02673   }
02674 
02675   void visitResumeInst(ResumeInst &I) {
02676     DEBUG(dbgs() << "Resume: " << I << "\n");
02677     // Nothing to do here.
02678   }
02679 
02680   void visitInstruction(Instruction &I) {
02681     // Everything else: stop propagating and check for poisoned shadow.
02682     if (ClDumpStrictInstructions)
02683       dumpInst(I);
02684     DEBUG(dbgs() << "DEFAULT: " << I << "\n");
02685     for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
02686       insertShadowCheck(I.getOperand(i), &I);
02687     setShadow(&I, getCleanShadow(&I));
02688     setOrigin(&I, getCleanOrigin());
02689   }
02690 };
02691 
02692 /// \brief AMD64-specific implementation of VarArgHelper.
02693 struct VarArgAMD64Helper : public VarArgHelper {
02694   // An unfortunate workaround for asymmetric lowering of va_arg stuff.
02695   // See a comment in visitCallSite for more details.
02696   static const unsigned AMD64GpEndOffset = 48;  // AMD64 ABI Draft 0.99.6 p3.5.7
02697   static const unsigned AMD64FpEndOffset = 176;
02698 
02699   Function &F;
02700   MemorySanitizer &MS;
02701   MemorySanitizerVisitor &MSV;
02702   Value *VAArgTLSCopy;
02703   Value *VAArgOverflowSize;
02704 
02705   SmallVector<CallInst*, 16> VAStartInstrumentationList;
02706 
02707   VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
02708                     MemorySanitizerVisitor &MSV)
02709     : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(nullptr),
02710       VAArgOverflowSize(nullptr) {}
02711 
02712   enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
02713 
02714   ArgKind classifyArgument(Value* arg) {
02715     // A very rough approximation of X86_64 argument classification rules.
02716     Type *T = arg->getType();
02717     if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
02718       return AK_FloatingPoint;
02719     if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
02720       return AK_GeneralPurpose;
02721     if (T->isPointerTy())
02722       return AK_GeneralPurpose;
02723     return AK_Memory;
02724   }
02725 
02726   // For VarArg functions, store the argument shadow in an ABI-specific format
02727   // that corresponds to va_list layout.
02728   // We do this because Clang lowers va_arg in the frontend, and this pass
02729   // only sees the low level code that deals with va_list internals.
02730   // A much easier alternative (provided that Clang emits va_arg instructions)
02731   // would have been to associate each live instance of va_list with a copy of
02732   // MSanParamTLS, and extract shadow on va_arg() call in the argument list
02733   // order.
02734   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
02735     unsigned GpOffset = 0;
02736     unsigned FpOffset = AMD64GpEndOffset;
02737     unsigned OverflowOffset = AMD64FpEndOffset;
02738     const DataLayout &DL = F.getParent()->getDataLayout();
02739     for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
02740          ArgIt != End; ++ArgIt) {
02741       Value *A = *ArgIt;
02742       unsigned ArgNo = CS.getArgumentNo(ArgIt);
02743       bool IsByVal = CS.paramHasAttr(ArgNo + 1, Attribute::ByVal);
02744       if (IsByVal) {
02745         // ByVal arguments always go to the overflow area.
02746         assert(A->getType()->isPointerTy());
02747         Type *RealTy = A->getType()->getPointerElementType();
02748         uint64_t ArgSize = DL.getTypeAllocSize(RealTy);
02749         Value *Base = getShadowPtrForVAArgument(RealTy, IRB, OverflowOffset);
02750         OverflowOffset += RoundUpToAlignment(ArgSize, 8);
02751         IRB.CreateMemCpy(Base, MSV.getShadowPtr(A, IRB.getInt8Ty(), IRB),
02752                          ArgSize, kShadowTLSAlignment);
02753       } else {
02754         ArgKind AK = classifyArgument(A);
02755         if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
02756           AK = AK_Memory;
02757         if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
02758           AK = AK_Memory;
02759         Value *Base;
02760         switch (AK) {
02761           case AK_GeneralPurpose:
02762             Base = getShadowPtrForVAArgument(A->getType(), IRB, GpOffset);
02763             GpOffset += 8;
02764             break;
02765           case AK_FloatingPoint:
02766             Base = getShadowPtrForVAArgument(A->getType(), IRB, FpOffset);
02767             FpOffset += 16;
02768             break;
02769           case AK_Memory:
02770             uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
02771             Base = getShadowPtrForVAArgument(A->getType(), IRB, OverflowOffset);
02772             OverflowOffset += RoundUpToAlignment(ArgSize, 8);
02773         }
02774         IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
02775       }
02776     }
02777     Constant *OverflowSize =
02778       ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
02779     IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
02780   }
02781 
02782   /// \brief Compute the shadow address for a given va_arg.
02783   Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
02784                                    int ArgOffset) {
02785     Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
02786     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
02787     return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
02788                               "_msarg");
02789   }
02790 
02791   void visitVAStartInst(VAStartInst &I) override {
02792     IRBuilder<> IRB(&I);
02793     VAStartInstrumentationList.push_back(&I);
02794     Value *VAListTag = I.getArgOperand(0);
02795     Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
02796 
02797     // Unpoison the whole __va_list_tag.
02798     // FIXME: magic ABI constants.
02799     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
02800                      /* size */24, /* alignment */8, false);
02801   }
02802 
02803   void visitVACopyInst(VACopyInst &I) override {
02804     IRBuilder<> IRB(&I);
02805     Value *VAListTag = I.getArgOperand(0);
02806     Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
02807 
02808     // Unpoison the whole __va_list_tag.
02809     // FIXME: magic ABI constants.
02810     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
02811                      /* size */24, /* alignment */8, false);
02812   }
02813 
02814   void finalizeInstrumentation() override {
02815     assert(!VAArgOverflowSize && !VAArgTLSCopy &&
02816            "finalizeInstrumentation called twice");
02817     if (!VAStartInstrumentationList.empty()) {
02818       // If there is a va_start in this function, make a backup copy of
02819       // va_arg_tls somewhere in the function entry block.
02820       IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
02821       VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
02822       Value *CopySize =
02823         IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
02824                       VAArgOverflowSize);
02825       VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
02826       IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
02827     }
02828 
02829     // Instrument va_start.
02830     // Copy va_list shadow from the backup copy of the TLS contents.
02831     for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
02832       CallInst *OrigInst = VAStartInstrumentationList[i];
02833       IRBuilder<> IRB(OrigInst->getNextNode());
02834       Value *VAListTag = OrigInst->getArgOperand(0);
02835 
02836       Value *RegSaveAreaPtrPtr =
02837         IRB.CreateIntToPtr(
02838           IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
02839                         ConstantInt::get(MS.IntptrTy, 16)),
02840           Type::getInt64PtrTy(*MS.C));
02841       Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
02842       Value *RegSaveAreaShadowPtr =
02843         MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
02844       IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy,
02845                        AMD64FpEndOffset, 16);
02846 
02847       Value *OverflowArgAreaPtrPtr =
02848         IRB.CreateIntToPtr(
02849           IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
02850                         ConstantInt::get(MS.IntptrTy, 8)),
02851           Type::getInt64PtrTy(*MS.C));
02852       Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
02853       Value *OverflowArgAreaShadowPtr =
02854         MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
02855       Value *SrcPtr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), VAArgTLSCopy,
02856                                              AMD64FpEndOffset);
02857       IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
02858     }
02859   }
02860 };
02861 
02862 /// \brief MIPS64-specific implementation of VarArgHelper.
02863 struct VarArgMIPS64Helper : public VarArgHelper {
02864   Function &F;
02865   MemorySanitizer &MS;
02866   MemorySanitizerVisitor &MSV;
02867   Value *VAArgTLSCopy;
02868   Value *VAArgSize;
02869 
02870   SmallVector<CallInst*, 16> VAStartInstrumentationList;
02871 
02872   VarArgMIPS64Helper(Function &F, MemorySanitizer &MS,
02873                     MemorySanitizerVisitor &MSV)
02874     : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(nullptr),
02875       VAArgSize(nullptr) {}
02876 
02877   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
02878     unsigned VAArgOffset = 0;
02879     const DataLayout &DL = F.getParent()->getDataLayout();
02880     for (CallSite::arg_iterator ArgIt = CS.arg_begin() + 1, End = CS.arg_end();
02881          ArgIt != End; ++ArgIt) {
02882       Value *A = *ArgIt;
02883       Value *Base;
02884       uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
02885 #if defined(__MIPSEB__) || defined(MIPSEB)
02886       // Adjusting the shadow for argument with size < 8 to match the placement
02887       // of bits in big endian system
02888       if (ArgSize < 8)
02889         VAArgOffset += (8 - ArgSize);
02890 #endif
02891       Base = getShadowPtrForVAArgument(A->getType(), IRB, VAArgOffset);
02892       VAArgOffset += ArgSize;
02893       VAArgOffset = RoundUpToAlignment(VAArgOffset, 8);
02894       IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
02895     }
02896 
02897     Constant *TotalVAArgSize = ConstantInt::get(IRB.getInt64Ty(), VAArgOffset);
02898     // Here using VAArgOverflowSizeTLS as VAArgSizeTLS to avoid creation of
02899     // a new class member i.e. it is the total size of all VarArgs.
02900     IRB.CreateStore(TotalVAArgSize, MS.VAArgOverflowSizeTLS);
02901   }
02902 
02903   /// \brief Compute the shadow address for a given va_arg.
02904   Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
02905                                    int ArgOffset) {
02906     Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
02907     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
02908     return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
02909                               "_msarg");
02910   }
02911 
02912   void visitVAStartInst(VAStartInst &I) override {
02913     IRBuilder<> IRB(&I);
02914     VAStartInstrumentationList.push_back(&I);
02915     Value *VAListTag = I.getArgOperand(0);
02916     Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
02917     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
02918                      /* size */8, /* alignment */8, false);
02919   }
02920 
02921   void visitVACopyInst(VACopyInst &I) override {
02922     IRBuilder<> IRB(&I);
02923     Value *VAListTag = I.getArgOperand(0);
02924     Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
02925     // Unpoison the whole __va_list_tag.
02926     // FIXME: magic ABI constants.
02927     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
02928                      /* size */8, /* alignment */8, false);
02929   }
02930 
02931   void finalizeInstrumentation() override {
02932     assert(!VAArgSize && !VAArgTLSCopy &&
02933            "finalizeInstrumentation called twice");
02934     IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
02935     VAArgSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
02936     Value *CopySize = IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, 0),
02937                                     VAArgSize);
02938 
02939     if (!VAStartInstrumentationList.empty()) {
02940       // If there is a va_start in this function, make a backup copy of
02941       // va_arg_tls somewhere in the function entry block.
02942       VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
02943       IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
02944     }
02945 
02946     // Instrument va_start.
02947     // Copy va_list shadow from the backup copy of the TLS contents.
02948     for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
02949       CallInst *OrigInst = VAStartInstrumentationList[i];
02950       IRBuilder<> IRB(OrigInst->getNextNode());
02951       Value *VAListTag = OrigInst->getArgOperand(0);
02952       Value *RegSaveAreaPtrPtr =
02953         IRB.CreateIntToPtr(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
02954                         Type::getInt64PtrTy(*MS.C));
02955       Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
02956       Value *RegSaveAreaShadowPtr =
02957       MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
02958       IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy, CopySize, 8);
02959     }
02960   }
02961 };
02962 
02963 /// \brief A no-op implementation of VarArgHelper.
02964 struct VarArgNoOpHelper : public VarArgHelper {
02965   VarArgNoOpHelper(Function &F, MemorySanitizer &MS,
02966                    MemorySanitizerVisitor &MSV) {}
02967 
02968   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {}
02969 
02970   void visitVAStartInst(VAStartInst &I) override {}
02971 
02972   void visitVACopyInst(VACopyInst &I) override {}
02973 
02974   void finalizeInstrumentation() override {}
02975 };
02976 
02977 VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
02978                                  MemorySanitizerVisitor &Visitor) {
02979   // VarArg handling is only implemented on AMD64. False positives are possible
02980   // on other platforms.
02981   llvm::Triple TargetTriple(Func.getParent()->getTargetTriple());
02982   if (TargetTriple.getArch() == llvm::Triple::x86_64)
02983     return new VarArgAMD64Helper(Func, Msan, Visitor);
02984   else if (TargetTriple.getArch() == llvm::Triple::mips64 ||
02985            TargetTriple.getArch() == llvm::Triple::mips64el)
02986     return new VarArgMIPS64Helper(Func, Msan, Visitor);
02987   else
02988     return new VarArgNoOpHelper(Func, Msan, Visitor);
02989 }
02990 
02991 }  // namespace
02992 
02993 bool MemorySanitizer::runOnFunction(Function &F) {
02994   if (&F == MsanCtorFunction)
02995     return false;
02996   MemorySanitizerVisitor Visitor(F, *this);
02997 
02998   // Clear out readonly/readnone attributes.
02999   AttrBuilder B;
03000   B.addAttribute(Attribute::ReadOnly)
03001     .addAttribute(Attribute::ReadNone);
03002   F.removeAttributes(AttributeSet::FunctionIndex,
03003                      AttributeSet::get(F.getContext(),
03004                                        AttributeSet::FunctionIndex, B));
03005 
03006   return Visitor.runOnFunction();
03007 }