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