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