LLVM API Documentation

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