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