LLVM API Documentation

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