blob: 45f1df738103749ebbe34152281f1536a163ab75 [file] [log] [blame]
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001//===-- MemorySanitizer.cpp - detector of uninitialized reads -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// This file is a part of MemorySanitizer, a detector of uninitialized
11/// reads.
12///
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +000013/// The algorithm of the tool is similar to Memcheck
14/// (http://goo.gl/QKbem). We associate a few shadow bits with every
15/// byte of the application memory, poison the shadow of the malloc-ed
16/// or alloca-ed memory, load the shadow bits on every memory read,
17/// propagate the shadow bits through some of the arithmetic
18/// instruction (including MOV), store the shadow bits on every memory
19/// write, report a bug on some other instructions (e.g. JMP) if the
20/// associated shadow is poisoned.
21///
22/// But there are differences too. The first and the major one:
23/// compiler instrumentation instead of binary instrumentation. This
24/// gives us much better register allocation, possible compiler
25/// optimizations and a fast start-up. But this brings the major issue
26/// as well: msan needs to see all program events, including system
27/// calls and reads/writes in system libraries, so we either need to
28/// compile *everything* with msan or use a binary translation
29/// component (e.g. DynamoRIO) to instrument pre-built libraries.
30/// Another difference from Memcheck is that we use 8 shadow bits per
31/// byte of application memory and use a direct shadow mapping. This
32/// greatly simplifies the instrumentation code and avoids races on
33/// shadow updates (Memcheck is single-threaded so races are not a
34/// concern there. Memcheck uses 2 shadow bits per byte with a slow
35/// path storage that uses 8 bits per byte).
36///
37/// The default value of shadow is 0, which means "clean" (not poisoned).
38///
39/// Every module initializer should call __msan_init to ensure that the
40/// shadow memory is ready. On error, __msan_warning is called. Since
41/// parameters and return values may be passed via registers, we have a
42/// specialized thread-local shadow for return values
43/// (__msan_retval_tls) and parameters (__msan_param_tls).
Evgeniy Stepanovd8be0c52012-12-26 10:59:00 +000044///
45/// Origin tracking.
46///
47/// MemorySanitizer can track origins (allocation points) of all uninitialized
48/// values. This behavior is controlled with a flag (msan-track-origins) and is
49/// disabled by default.
50///
51/// Origins are 4-byte values created and interpreted by the runtime library.
52/// They are stored in a second shadow mapping, one 4-byte value for 4 bytes
53/// of application memory. Propagation of origins is basically a bunch of
54/// "select" instructions that pick the origin of a dirty argument, if an
55/// instruction has one.
56///
57/// Every 4 aligned, consecutive bytes of application memory have one origin
58/// value associated with them. If these bytes contain uninitialized data
59/// coming from 2 different allocations, the last store wins. Because of this,
60/// MemorySanitizer reports can show unrelated origins, but this is unlikely in
Alexey Samsonov3efc87e2012-12-28 09:30:44 +000061/// practice.
Evgeniy Stepanovd8be0c52012-12-26 10:59:00 +000062///
63/// Origins are meaningless for fully initialized values, so MemorySanitizer
64/// avoids storing origin to memory when a fully initialized value is stored.
65/// This way it avoids needless overwritting origin of the 4-byte region on
66/// a short (i.e. 1 byte) clean store, and it is also good for performance.
Evgeniy Stepanov5522a702013-09-24 11:20:27 +000067///
68/// Atomic handling.
69///
70/// Ideally, every atomic store of application value should update the
71/// corresponding shadow location in an atomic way. Unfortunately, atomic store
72/// of two disjoint locations can not be done without severe slowdown.
73///
74/// Therefore, we implement an approximation that may err on the safe side.
75/// In this implementation, every atomically accessed location in the program
76/// may only change from (partially) uninitialized to fully initialized, but
77/// not the other way around. We load the shadow _after_ the application load,
78/// and we store the shadow _before_ the app store. Also, we always store clean
79/// shadow (if the application store is atomic). This way, if the store-load
80/// pair constitutes a happens-before arc, shadow store and load are correctly
81/// ordered such that the load will get either the value that was stored, or
82/// some later value (which is always clean).
83///
84/// This does not work very well with Compare-And-Swap (CAS) and
85/// Read-Modify-Write (RMW) operations. To follow the above logic, CAS and RMW
86/// must store the new shadow before the app operation, and load the shadow
87/// after the app operation. Computers don't work this way. Current
88/// implementation ignores the load aspect of CAS/RMW, always returning a clean
89/// value. It implements the store part as a simple atomic store by storing a
90/// clean shadow.
91
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +000092//===----------------------------------------------------------------------===//
93
Chandler Carruthed0881b2012-12-03 16:50:05 +000094#include "llvm/Transforms/Instrumentation.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +000095#include "llvm/ADT/DepthFirstIterator.h"
96#include "llvm/ADT/SmallString.h"
97#include "llvm/ADT/SmallVector.h"
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +000098#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +000099#include "llvm/ADT/Triple.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +0000100#include "llvm/IR/DataLayout.h"
101#include "llvm/IR/Function.h"
102#include "llvm/IR/IRBuilder.h"
103#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +0000104#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +0000105#include "llvm/IR/IntrinsicInst.h"
106#include "llvm/IR/LLVMContext.h"
107#include "llvm/IR/MDBuilder.h"
108#include "llvm/IR/Module.h"
109#include "llvm/IR/Type.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +0000110#include "llvm/IR/ValueMap.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000111#include "llvm/Support/CommandLine.h"
112#include "llvm/Support/Compiler.h"
113#include "llvm/Support/Debug.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000114#include "llvm/Support/raw_ostream.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000115#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +0000116#include "llvm/Transforms/Utils/Local.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000117#include "llvm/Transforms/Utils/ModuleUtils.h"
118
119using namespace llvm;
120
Chandler Carruth964daaa2014-04-22 02:55:47 +0000121#define DEBUG_TYPE "msan"
122
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000123static const uint64_t kShadowMask32 = 1ULL << 31;
124static const uint64_t kShadowMask64 = 1ULL << 46;
125static const uint64_t kOriginOffset32 = 1ULL << 30;
126static const uint64_t kOriginOffset64 = 1ULL << 45;
Evgeniy Stepanov5eb5bf82012-12-26 11:55:09 +0000127static const unsigned kMinOriginAlignment = 4;
128static const unsigned kShadowTLSAlignment = 8;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000129
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +0000130// These constants must be kept in sync with the ones in msan.h.
131static const unsigned kParamTLSSize = 800;
132static const unsigned kRetvalTLSSize = 800;
133
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000134// Accesses sizes are powers of two: 1, 2, 4, 8.
135static const size_t kNumberOfAccessSizes = 4;
136
Evgeniy Stepanovd8be0c52012-12-26 10:59:00 +0000137/// \brief Track origins of uninitialized values.
Alexey Samsonov3efc87e2012-12-28 09:30:44 +0000138///
Evgeniy Stepanovd8be0c52012-12-26 10:59:00 +0000139/// Adds a section to MemorySanitizer report that points to the allocation
140/// (stack or heap) the uninitialized bits came from originally.
Evgeniy Stepanov302964e2014-03-18 13:30:56 +0000141static cl::opt<int> ClTrackOrigins("msan-track-origins",
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000142 cl::desc("Track origins (allocation sites) of poisoned memory"),
Evgeniy Stepanov302964e2014-03-18 13:30:56 +0000143 cl::Hidden, cl::init(0));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000144static cl::opt<bool> ClKeepGoing("msan-keep-going",
145 cl::desc("keep going after reporting a UMR"),
146 cl::Hidden, cl::init(false));
147static cl::opt<bool> ClPoisonStack("msan-poison-stack",
148 cl::desc("poison uninitialized stack variables"),
149 cl::Hidden, cl::init(true));
150static cl::opt<bool> ClPoisonStackWithCall("msan-poison-stack-with-call",
151 cl::desc("poison uninitialized stack variables with a call"),
152 cl::Hidden, cl::init(false));
153static cl::opt<int> ClPoisonStackPattern("msan-poison-stack-pattern",
154 cl::desc("poison uninitialized stack variables with the given patter"),
155 cl::Hidden, cl::init(0xff));
Evgeniy Stepanova9a962c2013-03-21 09:38:26 +0000156static cl::opt<bool> ClPoisonUndef("msan-poison-undef",
157 cl::desc("poison undef temps"),
158 cl::Hidden, cl::init(true));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000159
160static cl::opt<bool> ClHandleICmp("msan-handle-icmp",
161 cl::desc("propagate shadow through ICmpEQ and ICmpNE"),
162 cl::Hidden, cl::init(true));
163
Evgeniy Stepanovfac84032013-01-25 15:31:10 +0000164static cl::opt<bool> ClHandleICmpExact("msan-handle-icmp-exact",
165 cl::desc("exact handling of relational integer ICmp"),
Evgeniy Stepanov6f85ef32013-01-28 11:42:28 +0000166 cl::Hidden, cl::init(false));
Evgeniy Stepanovfac84032013-01-25 15:31:10 +0000167
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000168// This flag controls whether we check the shadow of the address
169// operand of load or store. Such bugs are very rare, since load from
170// a garbage address typically results in SEGV, but still happen
171// (e.g. only lower bits of address are garbage, or the access happens
172// early at program startup where malloc-ed memory is more likely to
173// be zeroed. As of 2012-08-28 this flag adds 20% slowdown.
174static cl::opt<bool> ClCheckAccessAddress("msan-check-access-address",
175 cl::desc("report accesses through a pointer which has poisoned shadow"),
176 cl::Hidden, cl::init(true));
177
178static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions",
179 cl::desc("print out instructions with default strict semantics"),
180 cl::Hidden, cl::init(false));
181
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000182static cl::opt<int> ClInstrumentationWithCallThreshold(
183 "msan-instrumentation-with-call-threshold",
184 cl::desc(
185 "If the function being instrumented requires more than "
186 "this number of checks and origin stores, use callbacks instead of "
187 "inline checks (-1 means never use callbacks)."),
Evgeniy Stepanov3939f542014-04-21 15:04:05 +0000188 cl::Hidden, cl::init(3500));
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000189
Evgeniy Stepanov37b86452013-09-19 15:22:35 +0000190// Experimental. Wraps all indirect calls in the instrumented code with
191// a call to the given function. This is needed to assist the dynamic
192// helper tool (MSanDR) to regain control on transition between instrumented and
193// non-instrumented code.
194static cl::opt<std::string> ClWrapIndirectCalls("msan-wrap-indirect-calls",
195 cl::desc("Wrap indirect calls with a given function"),
196 cl::Hidden);
197
Evgeniy Stepanov585813e2013-11-14 12:29:04 +0000198static cl::opt<bool> ClWrapIndirectCallsFast("msan-wrap-indirect-calls-fast",
199 cl::desc("Do not wrap indirect calls with target in the same module"),
200 cl::Hidden, cl::init(true));
201
Evgeniy Stepanov7db296e2014-10-23 01:05:46 +0000202// This is an experiment to enable handling of cases where shadow is a non-zero
203// compile-time constant. For some unexplainable reason they were silently
204// ignored in the instrumentation.
205static cl::opt<bool> ClCheckConstantShadow("msan-check-constant-shadow",
206 cl::desc("Insert checks for constant shadow values"),
207 cl::Hidden, cl::init(false));
208
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000209namespace {
210
211/// \brief An instrumentation pass implementing detection of uninitialized
212/// reads.
213///
214/// MemorySanitizer: instrument the code in module to find
215/// uninitialized reads.
216class MemorySanitizer : public FunctionPass {
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000217 public:
Alexey Samsonov6d8bab82014-06-02 18:08:27 +0000218 MemorySanitizer(int TrackOrigins = 0)
Evgeniy Stepanov37b86452013-09-19 15:22:35 +0000219 : FunctionPass(ID),
Evgeniy Stepanov302964e2014-03-18 13:30:56 +0000220 TrackOrigins(std::max(TrackOrigins, (int)ClTrackOrigins)),
Craig Topperf40110f2014-04-25 05:29:35 +0000221 DL(nullptr),
222 WarningFn(nullptr),
Evgeniy Stepanov37b86452013-09-19 15:22:35 +0000223 WrapIndirectCalls(!ClWrapIndirectCalls.empty()) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000224 const char *getPassName() const override { return "MemorySanitizer"; }
225 bool runOnFunction(Function &F) override;
226 bool doInitialization(Module &M) override;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000227 static char ID; // Pass identification, replacement for typeid.
228
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000229 private:
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000230 void initializeCallbacks(Module &M);
231
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000232 /// \brief Track origins (allocation points) of uninitialized values.
Evgeniy Stepanov302964e2014-03-18 13:30:56 +0000233 int TrackOrigins;
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000234
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000235 const DataLayout *DL;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000236 LLVMContext *C;
237 Type *IntptrTy;
238 Type *OriginTy;
239 /// \brief Thread-local shadow storage for function parameters.
240 GlobalVariable *ParamTLS;
241 /// \brief Thread-local origin storage for function parameters.
242 GlobalVariable *ParamOriginTLS;
243 /// \brief Thread-local shadow storage for function return value.
244 GlobalVariable *RetvalTLS;
245 /// \brief Thread-local origin storage for function return value.
246 GlobalVariable *RetvalOriginTLS;
247 /// \brief Thread-local shadow storage for in-register va_arg function
248 /// parameters (x86_64-specific).
249 GlobalVariable *VAArgTLS;
250 /// \brief Thread-local shadow storage for va_arg overflow area
251 /// (x86_64-specific).
252 GlobalVariable *VAArgOverflowSizeTLS;
253 /// \brief Thread-local space used to pass origin value to the UMR reporting
254 /// function.
255 GlobalVariable *OriginTLS;
256
Evgeniy Stepanov585813e2013-11-14 12:29:04 +0000257 GlobalVariable *MsandrModuleStart;
258 GlobalVariable *MsandrModuleEnd;
259
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000260 /// \brief The run-time callback to print a warning.
261 Value *WarningFn;
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000262 // These arrays are indexed by log2(AccessSize).
263 Value *MaybeWarningFn[kNumberOfAccessSizes];
264 Value *MaybeStoreOriginFn[kNumberOfAccessSizes];
265
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000266 /// \brief Run-time helper that generates a new origin value for a stack
267 /// allocation.
Evgeniy Stepanov0435ecd2013-09-13 12:54:49 +0000268 Value *MsanSetAllocaOrigin4Fn;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000269 /// \brief Run-time helper that poisons stack on function entry.
270 Value *MsanPoisonStackFn;
Evgeniy Stepanov302964e2014-03-18 13:30:56 +0000271 /// \brief Run-time helper that records a store (or any event) of an
272 /// uninitialized value and returns an updated origin id encoding this info.
273 Value *MsanChainOriginFn;
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +0000274 /// \brief MSan runtime replacements for memmove, memcpy and memset.
275 Value *MemmoveFn, *MemcpyFn, *MemsetFn;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000276
277 /// \brief Address mask used in application-to-shadow address calculation.
278 /// ShadowAddr is computed as ApplicationAddr & ~ShadowMask.
279 uint64_t ShadowMask;
280 /// \brief Offset of the origin shadow from the "normal" shadow.
281 /// OriginAddr is computed as (ShadowAddr + OriginOffset) & ~3ULL
282 uint64_t OriginOffset;
283 /// \brief Branch weights for error reporting.
284 MDNode *ColdCallWeights;
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000285 /// \brief Branch weights for origin store.
286 MDNode *OriginStoreWeights;
Evgeniy Stepanov1d2da652012-11-29 12:30:18 +0000287 /// \brief An empty volatile inline asm that prevents callback merge.
288 InlineAsm *EmptyAsm;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000289
Evgeniy Stepanov37b86452013-09-19 15:22:35 +0000290 bool WrapIndirectCalls;
291 /// \brief Run-time wrapper for indirect calls.
292 Value *IndirectCallWrapperFn;
293 // Argument and return type of IndirectCallWrapperFn: void (*f)(void).
294 Type *AnyFunctionPtrTy;
295
Evgeniy Stepanovda0072b2012-11-29 13:12:03 +0000296 friend struct MemorySanitizerVisitor;
297 friend struct VarArgAMD64Helper;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000298};
299} // namespace
300
301char MemorySanitizer::ID = 0;
302INITIALIZE_PASS(MemorySanitizer, "msan",
303 "MemorySanitizer: detects uninitialized reads.",
304 false, false)
305
Alexey Samsonov6d8bab82014-06-02 18:08:27 +0000306FunctionPass *llvm::createMemorySanitizerPass(int TrackOrigins) {
307 return new MemorySanitizer(TrackOrigins);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000308}
309
310/// \brief Create a non-const global initialized with the given string.
311///
312/// Creates a writable global for Str so that we can pass it to the
313/// run-time lib. Runtime uses first 4 bytes of the string to store the
314/// frame ID, so the string needs to be mutable.
315static GlobalVariable *createPrivateNonConstGlobalForString(Module &M,
316 StringRef Str) {
317 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
318 return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false,
319 GlobalValue::PrivateLinkage, StrConst, "");
320}
321
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000322
323/// \brief Insert extern declaration of runtime-provided functions and globals.
324void MemorySanitizer::initializeCallbacks(Module &M) {
325 // Only do this once.
326 if (WarningFn)
327 return;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000328
329 IRBuilder<> IRB(*C);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000330 // Create the callback.
331 // FIXME: this function should have "Cold" calling conv,
332 // which is not yet implemented.
333 StringRef WarningFnName = ClKeepGoing ? "__msan_warning"
334 : "__msan_warning_noreturn";
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000335 WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy(), nullptr);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000336
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000337 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
338 AccessSizeIndex++) {
339 unsigned AccessSize = 1 << AccessSizeIndex;
340 std::string FunctionName = "__msan_maybe_warning_" + itostr(AccessSize);
341 MaybeWarningFn[AccessSizeIndex] = M.getOrInsertFunction(
342 FunctionName, IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8),
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000343 IRB.getInt32Ty(), nullptr);
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000344
345 FunctionName = "__msan_maybe_store_origin_" + itostr(AccessSize);
346 MaybeStoreOriginFn[AccessSizeIndex] = M.getOrInsertFunction(
347 FunctionName, IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8),
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000348 IRB.getInt8PtrTy(), IRB.getInt32Ty(), nullptr);
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000349 }
350
Evgeniy Stepanov0435ecd2013-09-13 12:54:49 +0000351 MsanSetAllocaOrigin4Fn = M.getOrInsertFunction(
352 "__msan_set_alloca_origin4", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy,
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000353 IRB.getInt8PtrTy(), IntptrTy, nullptr);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000354 MsanPoisonStackFn = M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000355 "__msan_poison_stack", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr);
Evgeniy Stepanov302964e2014-03-18 13:30:56 +0000356 MsanChainOriginFn = M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000357 "__msan_chain_origin", IRB.getInt32Ty(), IRB.getInt32Ty(), nullptr);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000358 MemmoveFn = M.getOrInsertFunction(
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000359 "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000360 IRB.getInt8PtrTy(), IntptrTy, nullptr);
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +0000361 MemcpyFn = M.getOrInsertFunction(
362 "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000363 IntptrTy, nullptr);
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +0000364 MemsetFn = M.getOrInsertFunction(
365 "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000366 IntptrTy, nullptr);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000367
368 // Create globals.
369 RetvalTLS = new GlobalVariable(
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +0000370 M, ArrayType::get(IRB.getInt64Ty(), kRetvalTLSSize / 8), false,
Craig Topperf40110f2014-04-25 05:29:35 +0000371 GlobalVariable::ExternalLinkage, nullptr, "__msan_retval_tls", nullptr,
Evgeniy Stepanov1e764322013-05-16 09:14:05 +0000372 GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000373 RetvalOriginTLS = new GlobalVariable(
Craig Topperf40110f2014-04-25 05:29:35 +0000374 M, OriginTy, false, GlobalVariable::ExternalLinkage, nullptr,
375 "__msan_retval_origin_tls", nullptr, GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000376
377 ParamTLS = new GlobalVariable(
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +0000378 M, ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), false,
Craig Topperf40110f2014-04-25 05:29:35 +0000379 GlobalVariable::ExternalLinkage, nullptr, "__msan_param_tls", nullptr,
Evgeniy Stepanov1e764322013-05-16 09:14:05 +0000380 GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000381 ParamOriginTLS = new GlobalVariable(
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +0000382 M, ArrayType::get(OriginTy, kParamTLSSize / 4), false,
383 GlobalVariable::ExternalLinkage, nullptr, "__msan_param_origin_tls",
384 nullptr, GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000385
386 VAArgTLS = new GlobalVariable(
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +0000387 M, ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), false,
Craig Topperf40110f2014-04-25 05:29:35 +0000388 GlobalVariable::ExternalLinkage, nullptr, "__msan_va_arg_tls", nullptr,
Evgeniy Stepanov1e764322013-05-16 09:14:05 +0000389 GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000390 VAArgOverflowSizeTLS = new GlobalVariable(
Craig Topperf40110f2014-04-25 05:29:35 +0000391 M, IRB.getInt64Ty(), false, GlobalVariable::ExternalLinkage, nullptr,
392 "__msan_va_arg_overflow_size_tls", nullptr,
Evgeniy Stepanov1e764322013-05-16 09:14:05 +0000393 GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000394 OriginTLS = new GlobalVariable(
Craig Topperf40110f2014-04-25 05:29:35 +0000395 M, IRB.getInt32Ty(), false, GlobalVariable::ExternalLinkage, nullptr,
396 "__msan_origin_tls", nullptr, GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanov1d2da652012-11-29 12:30:18 +0000397
398 // We insert an empty inline asm after __msan_report* to avoid callback merge.
399 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
400 StringRef(""), StringRef(""),
401 /*hasSideEffects=*/true);
Evgeniy Stepanov37b86452013-09-19 15:22:35 +0000402
403 if (WrapIndirectCalls) {
404 AnyFunctionPtrTy =
405 PointerType::getUnqual(FunctionType::get(IRB.getVoidTy(), false));
406 IndirectCallWrapperFn = M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000407 ClWrapIndirectCalls, AnyFunctionPtrTy, AnyFunctionPtrTy, nullptr);
Evgeniy Stepanov37b86452013-09-19 15:22:35 +0000408 }
Evgeniy Stepanov585813e2013-11-14 12:29:04 +0000409
Evgeniy Stepanovc14fc422014-05-07 14:10:51 +0000410 if (WrapIndirectCalls && ClWrapIndirectCallsFast) {
Evgeniy Stepanov585813e2013-11-14 12:29:04 +0000411 MsandrModuleStart = new GlobalVariable(
412 M, IRB.getInt32Ty(), false, GlobalValue::ExternalLinkage,
Craig Topperf40110f2014-04-25 05:29:35 +0000413 nullptr, "__executable_start");
Evgeniy Stepanov585813e2013-11-14 12:29:04 +0000414 MsandrModuleStart->setVisibility(GlobalVariable::HiddenVisibility);
415 MsandrModuleEnd = new GlobalVariable(
416 M, IRB.getInt32Ty(), false, GlobalValue::ExternalLinkage,
Craig Topperf40110f2014-04-25 05:29:35 +0000417 nullptr, "_end");
Evgeniy Stepanov585813e2013-11-14 12:29:04 +0000418 MsandrModuleEnd->setVisibility(GlobalVariable::HiddenVisibility);
419 }
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000420}
421
422/// \brief Module-level initialization.
423///
424/// inserts a call to __msan_init to the module's constructor list.
425bool MemorySanitizer::doInitialization(Module &M) {
Rafael Espindola93512512014-02-25 17:30:31 +0000426 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
427 if (!DLP)
Evgeniy Stepanov119cb2e2014-04-23 12:51:32 +0000428 report_fatal_error("data layout missing");
Rafael Espindola93512512014-02-25 17:30:31 +0000429 DL = &DLP->getDataLayout();
430
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000431 C = &(M.getContext());
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000432 unsigned PtrSize = DL->getPointerSizeInBits(/* AddressSpace */0);
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000433 switch (PtrSize) {
434 case 64:
435 ShadowMask = kShadowMask64;
436 OriginOffset = kOriginOffset64;
437 break;
438 case 32:
439 ShadowMask = kShadowMask32;
440 OriginOffset = kOriginOffset32;
441 break;
442 default:
443 report_fatal_error("unsupported pointer size");
444 break;
445 }
446
447 IRBuilder<> IRB(*C);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000448 IntptrTy = IRB.getIntPtrTy(DL);
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000449 OriginTy = IRB.getInt32Ty();
450
451 ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000452 OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000);
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000453
454 // Insert a call to __msan_init/__msan_track_origins into the module's CTORs.
455 appendToGlobalCtors(M, cast<Function>(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000456 "__msan_init", IRB.getVoidTy(), nullptr)), 0);
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000457
Evgeniy Stepanov888385e2013-05-31 12:04:29 +0000458 if (TrackOrigins)
459 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
460 IRB.getInt32(TrackOrigins), "__msan_track_origins");
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000461
Evgeniy Stepanov888385e2013-05-31 12:04:29 +0000462 if (ClKeepGoing)
463 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
464 IRB.getInt32(ClKeepGoing), "__msan_keep_going");
Evgeniy Stepanovdcf6bcb2013-01-22 13:26:53 +0000465
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000466 return true;
467}
468
469namespace {
470
471/// \brief A helper class that handles instrumentation of VarArg
472/// functions on a particular platform.
473///
474/// Implementations are expected to insert the instrumentation
475/// necessary to propagate argument shadow through VarArg function
476/// calls. Visit* methods are called during an InstVisitor pass over
477/// the function, and should avoid creating new basic blocks. A new
478/// instance of this class is created for each instrumented function.
479struct VarArgHelper {
480 /// \brief Visit a CallSite.
481 virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0;
482
483 /// \brief Visit a va_start call.
484 virtual void visitVAStartInst(VAStartInst &I) = 0;
485
486 /// \brief Visit a va_copy call.
487 virtual void visitVACopyInst(VACopyInst &I) = 0;
488
489 /// \brief Finalize function instrumentation.
490 ///
491 /// This method is called after visiting all interesting (see above)
492 /// instructions in a function.
493 virtual void finalizeInstrumentation() = 0;
Evgeniy Stepanovda0072b2012-11-29 13:12:03 +0000494
495 virtual ~VarArgHelper() {}
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000496};
497
498struct MemorySanitizerVisitor;
499
500VarArgHelper*
501CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
502 MemorySanitizerVisitor &Visitor);
503
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000504unsigned TypeSizeToSizeIndex(unsigned TypeSize) {
505 if (TypeSize <= 8) return 0;
506 return Log2_32_Ceil(TypeSize / 8);
507}
508
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000509/// This class does all the work for a given function. Store and Load
510/// instructions store and load corresponding shadow and origin
511/// values. Most instructions propagate shadow from arguments to their
512/// return values. Certain instructions (most importantly, BranchInst)
513/// test their argument shadow and print reports (with a runtime call) if it's
514/// non-zero.
515struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
516 Function &F;
517 MemorySanitizer &MS;
518 SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
519 ValueMap<Value*, Value*> ShadowMap, OriginMap;
Ahmed Charles56440fd2014-03-06 05:51:42 +0000520 std::unique_ptr<VarArgHelper> VAHelper;
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +0000521
522 // The following flags disable parts of MSan instrumentation based on
523 // blacklist contents and command-line options.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000524 bool InsertChecks;
Evgeniy Stepanov174242c2014-07-03 11:56:30 +0000525 bool PropagateShadow;
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +0000526 bool PoisonStack;
527 bool PoisonUndef;
Evgeniy Stepanov604293f2013-09-16 13:24:32 +0000528 bool CheckReturnValue;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000529
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000530 struct ShadowOriginAndInsertPoint {
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +0000531 Value *Shadow;
532 Value *Origin;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000533 Instruction *OrigIns;
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +0000534 ShadowOriginAndInsertPoint(Value *S, Value *O, Instruction *I)
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000535 : Shadow(S), Origin(O), OrigIns(I) { }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000536 };
537 SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000538 SmallVector<Instruction*, 16> StoreList;
Evgeniy Stepanov585813e2013-11-14 12:29:04 +0000539 SmallVector<CallSite, 16> IndirectCallList;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000540
541 MemorySanitizerVisitor(Function &F, MemorySanitizer &MS)
Evgeniy Stepanov00062b42013-02-28 11:25:14 +0000542 : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)) {
Alexey Samsonov6d8bab82014-06-02 18:08:27 +0000543 bool SanitizeFunction = F.getAttributes().hasAttribute(
544 AttributeSet::FunctionIndex, Attribute::SanitizeMemory);
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +0000545 InsertChecks = SanitizeFunction;
Evgeniy Stepanov174242c2014-07-03 11:56:30 +0000546 PropagateShadow = SanitizeFunction;
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +0000547 PoisonStack = SanitizeFunction && ClPoisonStack;
548 PoisonUndef = SanitizeFunction && ClPoisonUndef;
Evgeniy Stepanov604293f2013-09-16 13:24:32 +0000549 // FIXME: Consider using SpecialCaseList to specify a list of functions that
550 // must always return fully initialized values. For now, we hardcode "main".
551 CheckReturnValue = SanitizeFunction && (F.getName() == "main");
Evgeniy Stepanov00062b42013-02-28 11:25:14 +0000552
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000553 DEBUG(if (!InsertChecks)
Evgeniy Stepanov00062b42013-02-28 11:25:14 +0000554 dbgs() << "MemorySanitizer is not inserting checks into '"
555 << F.getName() << "'\n");
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000556 }
557
Evgeniy Stepanov302964e2014-03-18 13:30:56 +0000558 Value *updateOrigin(Value *V, IRBuilder<> &IRB) {
559 if (MS.TrackOrigins <= 1) return V;
560 return IRB.CreateCall(MS.MsanChainOriginFn, V);
561 }
562
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000563 void storeOrigin(IRBuilder<> &IRB, Value *Addr, Value *Shadow, Value *Origin,
564 unsigned Alignment, bool AsCall) {
565 if (isa<StructType>(Shadow->getType())) {
566 IRB.CreateAlignedStore(updateOrigin(Origin, IRB), getOriginPtr(Addr, IRB),
567 Alignment);
568 } else {
569 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
570 // TODO(eugenis): handle non-zero constant shadow by inserting an
571 // unconditional check (can not simply fail compilation as this could
572 // be in the dead code).
Evgeniy Stepanov7db296e2014-10-23 01:05:46 +0000573 if (!ClCheckConstantShadow)
574 if (isa<Constant>(ConvertedShadow)) return;
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000575 unsigned TypeSizeInBits =
576 MS.DL->getTypeSizeInBits(ConvertedShadow->getType());
577 unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
578 if (AsCall && SizeIndex < kNumberOfAccessSizes) {
579 Value *Fn = MS.MaybeStoreOriginFn[SizeIndex];
580 Value *ConvertedShadow2 = IRB.CreateZExt(
581 ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
582 IRB.CreateCall3(Fn, ConvertedShadow2,
583 IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
Evgeniy Stepanovb163f022014-06-25 14:41:57 +0000584 Origin);
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000585 } else {
586 Value *Cmp = IRB.CreateICmpNE(
587 ConvertedShadow, getCleanShadow(ConvertedShadow), "_mscmp");
588 Instruction *CheckTerm = SplitBlockAndInsertIfThen(
589 Cmp, IRB.GetInsertPoint(), false, MS.OriginStoreWeights);
590 IRBuilder<> IRBNew(CheckTerm);
591 IRBNew.CreateAlignedStore(updateOrigin(Origin, IRBNew),
592 getOriginPtr(Addr, IRBNew), Alignment);
593 }
594 }
595 }
596
597 void materializeStores(bool InstrumentWithCalls) {
Alexey Samsonova02e6642014-05-29 18:40:48 +0000598 for (auto Inst : StoreList) {
599 StoreInst &SI = *dyn_cast<StoreInst>(Inst);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000600
Alexey Samsonova02e6642014-05-29 18:40:48 +0000601 IRBuilder<> IRB(&SI);
602 Value *Val = SI.getValueOperand();
603 Value *Addr = SI.getPointerOperand();
604 Value *Shadow = SI.isAtomic() ? getCleanShadow(Val) : getShadow(Val);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000605 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
606
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000607 StoreInst *NewSI =
Alexey Samsonova02e6642014-05-29 18:40:48 +0000608 IRB.CreateAlignedStore(Shadow, ShadowPtr, SI.getAlignment());
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000609 DEBUG(dbgs() << " STORE: " << *NewSI << "\n");
NAKAMURA Takumie0b1b462012-12-06 13:38:00 +0000610 (void)NewSI;
Evgeniy Stepanovc4415592013-01-22 12:30:52 +0000611
Alexey Samsonova02e6642014-05-29 18:40:48 +0000612 if (ClCheckAccessAddress) insertShadowCheck(Addr, &SI);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000613
Alexey Samsonova02e6642014-05-29 18:40:48 +0000614 if (SI.isAtomic()) SI.setOrdering(addReleaseOrdering(SI.getOrdering()));
Evgeniy Stepanov5522a702013-09-24 11:20:27 +0000615
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000616 if (MS.TrackOrigins) {
Alexey Samsonova02e6642014-05-29 18:40:48 +0000617 unsigned Alignment = std::max(kMinOriginAlignment, SI.getAlignment());
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000618 storeOrigin(IRB, Addr, Shadow, getOrigin(Val), Alignment,
619 InstrumentWithCalls);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000620 }
621 }
622 }
623
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000624 void materializeOneCheck(Instruction *OrigIns, Value *Shadow, Value *Origin,
625 bool AsCall) {
626 IRBuilder<> IRB(OrigIns);
627 DEBUG(dbgs() << " SHAD0 : " << *Shadow << "\n");
628 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
629 DEBUG(dbgs() << " SHAD1 : " << *ConvertedShadow << "\n");
Evgeniy Stepanov7db296e2014-10-23 01:05:46 +0000630 // See the comment in storeOrigin().
631 if (!ClCheckConstantShadow)
632 if (isa<Constant>(ConvertedShadow)) return;
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000633 unsigned TypeSizeInBits =
634 MS.DL->getTypeSizeInBits(ConvertedShadow->getType());
635 unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
636 if (AsCall && SizeIndex < kNumberOfAccessSizes) {
637 Value *Fn = MS.MaybeWarningFn[SizeIndex];
638 Value *ConvertedShadow2 =
639 IRB.CreateZExt(ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
640 IRB.CreateCall2(Fn, ConvertedShadow2, MS.TrackOrigins && Origin
641 ? Origin
642 : (Value *)IRB.getInt32(0));
643 } else {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000644 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
645 getCleanShadow(ConvertedShadow), "_mscmp");
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000646 Instruction *CheckTerm = SplitBlockAndInsertIfThen(
647 Cmp, OrigIns,
648 /* Unreachable */ !ClKeepGoing, MS.ColdCallWeights);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000649
650 IRB.SetInsertPoint(CheckTerm);
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000651 if (MS.TrackOrigins) {
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000652 IRB.CreateStore(Origin ? (Value *)Origin : (Value *)IRB.getInt32(0),
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000653 MS.OriginTLS);
654 }
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000655 IRB.CreateCall(MS.WarningFn);
Evgeniy Stepanov1d2da652012-11-29 12:30:18 +0000656 IRB.CreateCall(MS.EmptyAsm);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000657 DEBUG(dbgs() << " CHECK: " << *Cmp << "\n");
658 }
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000659 }
660
661 void materializeChecks(bool InstrumentWithCalls) {
Alexey Samsonova02e6642014-05-29 18:40:48 +0000662 for (const auto &ShadowData : InstrumentationList) {
663 Instruction *OrigIns = ShadowData.OrigIns;
664 Value *Shadow = ShadowData.Shadow;
665 Value *Origin = ShadowData.Origin;
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000666 materializeOneCheck(OrigIns, Shadow, Origin, InstrumentWithCalls);
667 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000668 DEBUG(dbgs() << "DONE:\n" << F);
669 }
670
Evgeniy Stepanov585813e2013-11-14 12:29:04 +0000671 void materializeIndirectCalls() {
Alexey Samsonova02e6642014-05-29 18:40:48 +0000672 for (auto &CS : IndirectCallList) {
Evgeniy Stepanov585813e2013-11-14 12:29:04 +0000673 Instruction *I = CS.getInstruction();
674 BasicBlock *B = I->getParent();
675 IRBuilder<> IRB(I);
676 Value *Fn0 = CS.getCalledValue();
677 Value *Fn = IRB.CreateBitCast(Fn0, MS.AnyFunctionPtrTy);
678
679 if (ClWrapIndirectCallsFast) {
680 // Check that call target is inside this module limits.
681 Value *Start =
682 IRB.CreateBitCast(MS.MsandrModuleStart, MS.AnyFunctionPtrTy);
683 Value *End = IRB.CreateBitCast(MS.MsandrModuleEnd, MS.AnyFunctionPtrTy);
684
685 Value *NotInThisModule = IRB.CreateOr(IRB.CreateICmpULT(Fn, Start),
686 IRB.CreateICmpUGE(Fn, End));
687
688 PHINode *NewFnPhi =
689 IRB.CreatePHI(Fn0->getType(), 2, "msandr.indirect_target");
690
691 Instruction *CheckTerm = SplitBlockAndInsertIfThen(
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000692 NotInThisModule, NewFnPhi,
Evgeniy Stepanov585813e2013-11-14 12:29:04 +0000693 /* Unreachable */ false, MS.ColdCallWeights);
694
695 IRB.SetInsertPoint(CheckTerm);
696 // Slow path: call wrapper function to possibly transform the call
697 // target.
698 Value *NewFn = IRB.CreateBitCast(
699 IRB.CreateCall(MS.IndirectCallWrapperFn, Fn), Fn0->getType());
700
701 NewFnPhi->addIncoming(Fn0, B);
702 NewFnPhi->addIncoming(NewFn, dyn_cast<Instruction>(NewFn)->getParent());
703 CS.setCalledFunction(NewFnPhi);
704 } else {
705 Value *NewFn = IRB.CreateBitCast(
706 IRB.CreateCall(MS.IndirectCallWrapperFn, Fn), Fn0->getType());
707 CS.setCalledFunction(NewFn);
708 }
709 }
710 }
711
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000712 /// \brief Add MemorySanitizer instrumentation to a function.
713 bool runOnFunction() {
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000714 MS.initializeCallbacks(*F.getParent());
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000715 if (!MS.DL) return false;
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +0000716
717 // In the presence of unreachable blocks, we may see Phi nodes with
718 // incoming nodes from such blocks. Since InstVisitor skips unreachable
719 // blocks, such nodes will not have any shadow value associated with them.
720 // It's easier to remove unreachable blocks than deal with missing shadow.
721 removeUnreachableBlocks(F);
722
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000723 // Iterate all BBs in depth-first order and create shadow instructions
724 // for all instructions (where applicable).
725 // For PHI nodes we create dummy shadow PHIs which will be finalized later.
David Blaikieceec2bd2014-04-11 01:50:01 +0000726 for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000727 visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000728
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000729
730 // Finalize PHI nodes.
Alexey Samsonova02e6642014-05-29 18:40:48 +0000731 for (PHINode *PN : ShadowPHINodes) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000732 PHINode *PNS = cast<PHINode>(getShadow(PN));
Craig Topperf40110f2014-04-25 05:29:35 +0000733 PHINode *PNO = MS.TrackOrigins ? cast<PHINode>(getOrigin(PN)) : nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000734 size_t NumValues = PN->getNumIncomingValues();
735 for (size_t v = 0; v < NumValues; v++) {
736 PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
Evgeniy Stepanov174242c2014-07-03 11:56:30 +0000737 if (PNO) PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000738 }
739 }
740
741 VAHelper->finalizeInstrumentation();
742
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000743 bool InstrumentWithCalls = ClInstrumentationWithCallThreshold >= 0 &&
744 InstrumentationList.size() + StoreList.size() >
745 (unsigned)ClInstrumentationWithCallThreshold;
746
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000747 // Delayed instrumentation of StoreInst.
Evgeniy Stepanov47ac9ba2012-12-06 11:58:59 +0000748 // This may add new checks to be inserted later.
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000749 materializeStores(InstrumentWithCalls);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000750
751 // Insert shadow value checks.
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000752 materializeChecks(InstrumentWithCalls);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000753
Evgeniy Stepanov585813e2013-11-14 12:29:04 +0000754 // Wrap indirect calls.
755 materializeIndirectCalls();
756
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000757 return true;
758 }
759
760 /// \brief Compute the shadow type that corresponds to a given Value.
761 Type *getShadowTy(Value *V) {
762 return getShadowTy(V->getType());
763 }
764
765 /// \brief Compute the shadow type that corresponds to a given Type.
766 Type *getShadowTy(Type *OrigTy) {
767 if (!OrigTy->isSized()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000768 return nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000769 }
770 // For integer type, shadow is the same as the original type.
771 // This may return weird-sized types like i1.
772 if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
773 return IT;
Evgeniy Stepanovf19c0862012-12-25 16:04:38 +0000774 if (VectorType *VT = dyn_cast<VectorType>(OrigTy)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000775 uint32_t EltSize = MS.DL->getTypeSizeInBits(VT->getElementType());
Evgeniy Stepanovf19c0862012-12-25 16:04:38 +0000776 return VectorType::get(IntegerType::get(*MS.C, EltSize),
777 VT->getNumElements());
778 }
Evgeniy Stepanov5997feb2014-07-31 11:02:27 +0000779 if (ArrayType *AT = dyn_cast<ArrayType>(OrigTy)) {
780 return ArrayType::get(getShadowTy(AT->getElementType()),
781 AT->getNumElements());
782 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000783 if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
784 SmallVector<Type*, 4> Elements;
785 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
786 Elements.push_back(getShadowTy(ST->getElementType(i)));
787 StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
788 DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
789 return Res;
790 }
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000791 uint32_t TypeSize = MS.DL->getTypeSizeInBits(OrigTy);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000792 return IntegerType::get(*MS.C, TypeSize);
793 }
794
795 /// \brief Flatten a vector type.
796 Type *getShadowTyNoVec(Type *ty) {
797 if (VectorType *vt = dyn_cast<VectorType>(ty))
798 return IntegerType::get(*MS.C, vt->getBitWidth());
799 return ty;
800 }
801
802 /// \brief Convert a shadow value to it's flattened variant.
803 Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
804 Type *Ty = V->getType();
805 Type *NoVecTy = getShadowTyNoVec(Ty);
806 if (Ty == NoVecTy) return V;
807 return IRB.CreateBitCast(V, NoVecTy);
808 }
809
810 /// \brief Compute the shadow address that corresponds to a given application
811 /// address.
812 ///
813 /// Shadow = Addr & ~ShadowMask.
814 Value *getShadowPtr(Value *Addr, Type *ShadowTy,
815 IRBuilder<> &IRB) {
816 Value *ShadowLong =
817 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
818 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
819 return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
820 }
821
822 /// \brief Compute the origin address that corresponds to a given application
823 /// address.
824 ///
825 /// OriginAddr = (ShadowAddr + OriginOffset) & ~3ULL
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000826 Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB) {
827 Value *ShadowLong =
828 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
Evgeniy Stepanov62ba6112012-11-29 13:43:05 +0000829 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000830 Value *Add =
831 IRB.CreateAdd(ShadowLong,
832 ConstantInt::get(MS.IntptrTy, MS.OriginOffset));
Evgeniy Stepanov62ba6112012-11-29 13:43:05 +0000833 Value *SecondAnd =
834 IRB.CreateAnd(Add, ConstantInt::get(MS.IntptrTy, ~3ULL));
835 return IRB.CreateIntToPtr(SecondAnd, PointerType::get(IRB.getInt32Ty(), 0));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000836 }
837
838 /// \brief Compute the shadow address for a given function argument.
839 ///
840 /// Shadow = ParamTLS+ArgOffset.
841 Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
842 int ArgOffset) {
843 Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
844 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
845 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
846 "_msarg");
847 }
848
849 /// \brief Compute the origin address for a given function argument.
850 Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
851 int ArgOffset) {
Craig Topperf40110f2014-04-25 05:29:35 +0000852 if (!MS.TrackOrigins) return nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000853 Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
854 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
855 return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
856 "_msarg_o");
857 }
858
859 /// \brief Compute the shadow address for a retval.
860 Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
861 Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy);
862 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
863 "_msret");
864 }
865
866 /// \brief Compute the origin address for a retval.
867 Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
868 // We keep a single origin for the entire retval. Might be too optimistic.
869 return MS.RetvalOriginTLS;
870 }
871
872 /// \brief Set SV to be the shadow value for V.
873 void setShadow(Value *V, Value *SV) {
874 assert(!ShadowMap.count(V) && "Values may only have one shadow");
Evgeniy Stepanov174242c2014-07-03 11:56:30 +0000875 ShadowMap[V] = PropagateShadow ? SV : getCleanShadow(V);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000876 }
877
878 /// \brief Set Origin to be the origin value for V.
879 void setOrigin(Value *V, Value *Origin) {
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000880 if (!MS.TrackOrigins) return;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000881 assert(!OriginMap.count(V) && "Values may only have one origin");
882 DEBUG(dbgs() << "ORIGIN: " << *V << " ==> " << *Origin << "\n");
883 OriginMap[V] = Origin;
884 }
885
886 /// \brief Create a clean shadow value for a given value.
887 ///
888 /// Clean shadow (all zeroes) means all bits of the value are defined
889 /// (initialized).
Evgeniy Stepanova9a962c2013-03-21 09:38:26 +0000890 Constant *getCleanShadow(Value *V) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000891 Type *ShadowTy = getShadowTy(V);
892 if (!ShadowTy)
Craig Topperf40110f2014-04-25 05:29:35 +0000893 return nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000894 return Constant::getNullValue(ShadowTy);
895 }
896
897 /// \brief Create a dirty shadow of a given shadow type.
898 Constant *getPoisonedShadow(Type *ShadowTy) {
899 assert(ShadowTy);
900 if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
901 return Constant::getAllOnesValue(ShadowTy);
Evgeniy Stepanov5997feb2014-07-31 11:02:27 +0000902 if (ArrayType *AT = dyn_cast<ArrayType>(ShadowTy)) {
903 SmallVector<Constant *, 4> Vals(AT->getNumElements(),
904 getPoisonedShadow(AT->getElementType()));
905 return ConstantArray::get(AT, Vals);
906 }
907 if (StructType *ST = dyn_cast<StructType>(ShadowTy)) {
908 SmallVector<Constant *, 4> Vals;
909 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
910 Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
911 return ConstantStruct::get(ST, Vals);
912 }
913 llvm_unreachable("Unexpected shadow type");
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000914 }
915
Evgeniy Stepanova9a962c2013-03-21 09:38:26 +0000916 /// \brief Create a dirty shadow for a given value.
917 Constant *getPoisonedShadow(Value *V) {
918 Type *ShadowTy = getShadowTy(V);
919 if (!ShadowTy)
Craig Topperf40110f2014-04-25 05:29:35 +0000920 return nullptr;
Evgeniy Stepanova9a962c2013-03-21 09:38:26 +0000921 return getPoisonedShadow(ShadowTy);
922 }
923
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000924 /// \brief Create a clean (zero) origin.
925 Value *getCleanOrigin() {
926 return Constant::getNullValue(MS.OriginTy);
927 }
928
929 /// \brief Get the shadow value for a given Value.
930 ///
931 /// This function either returns the value set earlier with setShadow,
932 /// or extracts if from ParamTLS (for function arguments).
933 Value *getShadow(Value *V) {
Evgeniy Stepanov174242c2014-07-03 11:56:30 +0000934 if (!PropagateShadow) return getCleanShadow(V);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000935 if (Instruction *I = dyn_cast<Instruction>(V)) {
936 // For instructions the shadow is already stored in the map.
937 Value *Shadow = ShadowMap[V];
938 if (!Shadow) {
939 DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +0000940 (void)I;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000941 assert(Shadow && "No shadow for a value");
942 }
943 return Shadow;
944 }
945 if (UndefValue *U = dyn_cast<UndefValue>(V)) {
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +0000946 Value *AllOnes = PoisonUndef ? getPoisonedShadow(V) : getCleanShadow(V);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000947 DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +0000948 (void)U;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000949 return AllOnes;
950 }
951 if (Argument *A = dyn_cast<Argument>(V)) {
952 // For arguments we compute the shadow on demand and store it in the map.
953 Value **ShadowPtr = &ShadowMap[V];
954 if (*ShadowPtr)
955 return *ShadowPtr;
956 Function *F = A->getParent();
957 IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI());
958 unsigned ArgOffset = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +0000959 for (auto &FArg : F->args()) {
960 if (!FArg.getType()->isSized()) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000961 DEBUG(dbgs() << "Arg is not sized\n");
962 continue;
963 }
Alexey Samsonova02e6642014-05-29 18:40:48 +0000964 unsigned Size = FArg.hasByValAttr()
965 ? MS.DL->getTypeAllocSize(FArg.getType()->getPointerElementType())
966 : MS.DL->getTypeAllocSize(FArg.getType());
967 if (A == &FArg) {
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +0000968 bool Overflow = ArgOffset + Size > kParamTLSSize;
Alexey Samsonova02e6642014-05-29 18:40:48 +0000969 Value *Base = getShadowPtrForArgument(&FArg, EntryIRB, ArgOffset);
970 if (FArg.hasByValAttr()) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000971 // ByVal pointer itself has clean shadow. We copy the actual
972 // argument shadow to the underlying memory.
Evgeniy Stepanovfca01232013-05-28 13:07:43 +0000973 // Figure out maximal valid memcpy alignment.
Alexey Samsonova02e6642014-05-29 18:40:48 +0000974 unsigned ArgAlign = FArg.getParamAlignment();
Evgeniy Stepanovfca01232013-05-28 13:07:43 +0000975 if (ArgAlign == 0) {
976 Type *EltType = A->getType()->getPointerElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000977 ArgAlign = MS.DL->getABITypeAlignment(EltType);
Evgeniy Stepanovfca01232013-05-28 13:07:43 +0000978 }
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +0000979 if (Overflow) {
980 // ParamTLS overflow.
981 EntryIRB.CreateMemSet(
982 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB),
983 Constant::getNullValue(EntryIRB.getInt8Ty()), Size, ArgAlign);
984 } else {
985 unsigned CopyAlign = std::min(ArgAlign, kShadowTLSAlignment);
986 Value *Cpy = EntryIRB.CreateMemCpy(
987 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB), Base, Size,
988 CopyAlign);
989 DEBUG(dbgs() << " ByValCpy: " << *Cpy << "\n");
990 (void)Cpy;
991 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000992 *ShadowPtr = getCleanShadow(V);
993 } else {
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +0000994 if (Overflow) {
995 // ParamTLS overflow.
996 *ShadowPtr = getCleanShadow(V);
997 } else {
998 *ShadowPtr =
999 EntryIRB.CreateAlignedLoad(Base, kShadowTLSAlignment);
1000 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001001 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001002 DEBUG(dbgs() << " ARG: " << FArg << " ==> " <<
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001003 **ShadowPtr << "\n");
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +00001004 if (MS.TrackOrigins && !Overflow) {
Alexey Samsonova02e6642014-05-29 18:40:48 +00001005 Value *OriginPtr =
1006 getOriginPtrForArgument(&FArg, EntryIRB, ArgOffset);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001007 setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
1008 }
1009 }
David Majnemerf3cadce2014-10-20 06:13:33 +00001010 ArgOffset += RoundUpToAlignment(Size, kShadowTLSAlignment);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001011 }
1012 assert(*ShadowPtr && "Could not find shadow for an argument");
1013 return *ShadowPtr;
1014 }
1015 // For everything else the shadow is zero.
1016 return getCleanShadow(V);
1017 }
1018
1019 /// \brief Get the shadow for i-th argument of the instruction I.
1020 Value *getShadow(Instruction *I, int i) {
1021 return getShadow(I->getOperand(i));
1022 }
1023
1024 /// \brief Get the origin for a value.
1025 Value *getOrigin(Value *V) {
Craig Topperf40110f2014-04-25 05:29:35 +00001026 if (!MS.TrackOrigins) return nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001027 if (isa<Instruction>(V) || isa<Argument>(V)) {
1028 Value *Origin = OriginMap[V];
1029 if (!Origin) {
1030 DEBUG(dbgs() << "NO ORIGIN: " << *V << "\n");
1031 Origin = getCleanOrigin();
1032 }
1033 return Origin;
1034 }
1035 return getCleanOrigin();
1036 }
1037
1038 /// \brief Get the origin for i-th argument of the instruction I.
1039 Value *getOrigin(Instruction *I, int i) {
1040 return getOrigin(I->getOperand(i));
1041 }
1042
1043 /// \brief Remember the place where a shadow check should be inserted.
1044 ///
1045 /// This location will be later instrumented with a check that will print a
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001046 /// UMR warning in runtime if the shadow value is not 0.
1047 void insertShadowCheck(Value *Shadow, Value *Origin, Instruction *OrigIns) {
1048 assert(Shadow);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001049 if (!InsertChecks) return;
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +00001050#ifndef NDEBUG
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001051 Type *ShadowTy = Shadow->getType();
1052 assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
1053 "Can only insert checks for integer and vector shadow types");
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +00001054#endif
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001055 InstrumentationList.push_back(
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001056 ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
1057 }
1058
1059 /// \brief Remember the place where a shadow check should be inserted.
1060 ///
1061 /// This location will be later instrumented with a check that will print a
1062 /// UMR warning in runtime if the value is not fully defined.
1063 void insertShadowCheck(Value *Val, Instruction *OrigIns) {
1064 assert(Val);
Evgeniy Stepanovd337a592014-10-24 23:34:15 +00001065 Value *Shadow, *Origin;
1066 if (ClCheckConstantShadow) {
1067 Shadow = getShadow(Val);
1068 if (!Shadow) return;
1069 Origin = getOrigin(Val);
1070 } else {
1071 Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
1072 if (!Shadow) return;
1073 Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
1074 }
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001075 insertShadowCheck(Shadow, Origin, OrigIns);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001076 }
1077
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001078 AtomicOrdering addReleaseOrdering(AtomicOrdering a) {
1079 switch (a) {
1080 case NotAtomic:
1081 return NotAtomic;
1082 case Unordered:
1083 case Monotonic:
1084 case Release:
1085 return Release;
1086 case Acquire:
1087 case AcquireRelease:
1088 return AcquireRelease;
1089 case SequentiallyConsistent:
1090 return SequentiallyConsistent;
1091 }
Evgeniy Stepanov32be0342013-09-25 08:56:00 +00001092 llvm_unreachable("Unknown ordering");
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001093 }
1094
1095 AtomicOrdering addAcquireOrdering(AtomicOrdering a) {
1096 switch (a) {
1097 case NotAtomic:
1098 return NotAtomic;
1099 case Unordered:
1100 case Monotonic:
1101 case Acquire:
1102 return Acquire;
1103 case Release:
1104 case AcquireRelease:
1105 return AcquireRelease;
1106 case SequentiallyConsistent:
1107 return SequentiallyConsistent;
1108 }
Evgeniy Stepanov32be0342013-09-25 08:56:00 +00001109 llvm_unreachable("Unknown ordering");
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001110 }
1111
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +00001112 // ------------------- Visitors.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001113
1114 /// \brief Instrument LoadInst
1115 ///
1116 /// Loads the corresponding shadow and (optionally) origin.
1117 /// Optionally, checks that the load address is fully defined.
1118 void visitLoadInst(LoadInst &I) {
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +00001119 assert(I.getType()->isSized() && "Load type must have size");
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001120 IRBuilder<> IRB(I.getNextNode());
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001121 Type *ShadowTy = getShadowTy(&I);
1122 Value *Addr = I.getPointerOperand();
Evgeniy Stepanov174242c2014-07-03 11:56:30 +00001123 if (PropagateShadow) {
Evgeniy Stepanov00062b42013-02-28 11:25:14 +00001124 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1125 setShadow(&I,
1126 IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld"));
1127 } else {
1128 setShadow(&I, getCleanShadow(&I));
1129 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001130
1131 if (ClCheckAccessAddress)
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001132 insertShadowCheck(I.getPointerOperand(), &I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001133
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001134 if (I.isAtomic())
1135 I.setOrdering(addAcquireOrdering(I.getOrdering()));
1136
Evgeniy Stepanov5eb5bf82012-12-26 11:55:09 +00001137 if (MS.TrackOrigins) {
Evgeniy Stepanov174242c2014-07-03 11:56:30 +00001138 if (PropagateShadow) {
Evgeniy Stepanov00062b42013-02-28 11:25:14 +00001139 unsigned Alignment = std::max(kMinOriginAlignment, I.getAlignment());
1140 setOrigin(&I,
1141 IRB.CreateAlignedLoad(getOriginPtr(Addr, IRB), Alignment));
1142 } else {
1143 setOrigin(&I, getCleanOrigin());
1144 }
Evgeniy Stepanov5eb5bf82012-12-26 11:55:09 +00001145 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001146 }
1147
1148 /// \brief Instrument StoreInst
1149 ///
1150 /// Stores the corresponding shadow and (optionally) origin.
1151 /// Optionally, checks that the store address is fully defined.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001152 void visitStoreInst(StoreInst &I) {
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +00001153 StoreList.push_back(&I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001154 }
1155
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001156 void handleCASOrRMW(Instruction &I) {
1157 assert(isa<AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I));
1158
1159 IRBuilder<> IRB(&I);
1160 Value *Addr = I.getOperand(0);
1161 Value *ShadowPtr = getShadowPtr(Addr, I.getType(), IRB);
1162
1163 if (ClCheckAccessAddress)
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001164 insertShadowCheck(Addr, &I);
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001165
1166 // Only test the conditional argument of cmpxchg instruction.
1167 // The other argument can potentially be uninitialized, but we can not
1168 // detect this situation reliably without possible false positives.
1169 if (isa<AtomicCmpXchgInst>(I))
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001170 insertShadowCheck(I.getOperand(1), &I);
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001171
1172 IRB.CreateStore(getCleanShadow(&I), ShadowPtr);
1173
1174 setShadow(&I, getCleanShadow(&I));
1175 }
1176
1177 void visitAtomicRMWInst(AtomicRMWInst &I) {
1178 handleCASOrRMW(I);
1179 I.setOrdering(addReleaseOrdering(I.getOrdering()));
1180 }
1181
1182 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
1183 handleCASOrRMW(I);
Tim Northovere94a5182014-03-11 10:48:52 +00001184 I.setSuccessOrdering(addReleaseOrdering(I.getSuccessOrdering()));
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001185 }
1186
Evgeniy Stepanov30484fc2012-11-29 15:22:06 +00001187 // Vector manipulation.
1188 void visitExtractElementInst(ExtractElementInst &I) {
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001189 insertShadowCheck(I.getOperand(1), &I);
Evgeniy Stepanov30484fc2012-11-29 15:22:06 +00001190 IRBuilder<> IRB(&I);
1191 setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
1192 "_msprop"));
1193 setOrigin(&I, getOrigin(&I, 0));
1194 }
1195
1196 void visitInsertElementInst(InsertElementInst &I) {
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001197 insertShadowCheck(I.getOperand(2), &I);
Evgeniy Stepanov30484fc2012-11-29 15:22:06 +00001198 IRBuilder<> IRB(&I);
1199 setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
1200 I.getOperand(2), "_msprop"));
1201 setOriginForNaryOp(I);
1202 }
1203
1204 void visitShuffleVectorInst(ShuffleVectorInst &I) {
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001205 insertShadowCheck(I.getOperand(2), &I);
Evgeniy Stepanov30484fc2012-11-29 15:22:06 +00001206 IRBuilder<> IRB(&I);
1207 setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
1208 I.getOperand(2), "_msprop"));
1209 setOriginForNaryOp(I);
1210 }
1211
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001212 // Casts.
1213 void visitSExtInst(SExtInst &I) {
1214 IRBuilder<> IRB(&I);
1215 setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
1216 setOrigin(&I, getOrigin(&I, 0));
1217 }
1218
1219 void visitZExtInst(ZExtInst &I) {
1220 IRBuilder<> IRB(&I);
1221 setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
1222 setOrigin(&I, getOrigin(&I, 0));
1223 }
1224
1225 void visitTruncInst(TruncInst &I) {
1226 IRBuilder<> IRB(&I);
1227 setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
1228 setOrigin(&I, getOrigin(&I, 0));
1229 }
1230
1231 void visitBitCastInst(BitCastInst &I) {
1232 IRBuilder<> IRB(&I);
1233 setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
1234 setOrigin(&I, getOrigin(&I, 0));
1235 }
1236
1237 void visitPtrToIntInst(PtrToIntInst &I) {
1238 IRBuilder<> IRB(&I);
1239 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1240 "_msprop_ptrtoint"));
1241 setOrigin(&I, getOrigin(&I, 0));
1242 }
1243
1244 void visitIntToPtrInst(IntToPtrInst &I) {
1245 IRBuilder<> IRB(&I);
1246 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1247 "_msprop_inttoptr"));
1248 setOrigin(&I, getOrigin(&I, 0));
1249 }
1250
1251 void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
1252 void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
1253 void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
1254 void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
1255 void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
1256 void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
1257
1258 /// \brief Propagate shadow for bitwise AND.
1259 ///
1260 /// This code is exact, i.e. if, for example, a bit in the left argument
1261 /// is defined and 0, then neither the value not definedness of the
1262 /// corresponding bit in B don't affect the resulting shadow.
1263 void visitAnd(BinaryOperator &I) {
1264 IRBuilder<> IRB(&I);
1265 // "And" of 0 and a poisoned value results in unpoisoned value.
1266 // 1&1 => 1; 0&1 => 0; p&1 => p;
1267 // 1&0 => 0; 0&0 => 0; p&0 => 0;
1268 // 1&p => p; 0&p => 0; p&p => p;
1269 // S = (S1 & S2) | (V1 & S2) | (S1 & V2)
1270 Value *S1 = getShadow(&I, 0);
1271 Value *S2 = getShadow(&I, 1);
1272 Value *V1 = I.getOperand(0);
1273 Value *V2 = I.getOperand(1);
1274 if (V1->getType() != S1->getType()) {
1275 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1276 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1277 }
1278 Value *S1S2 = IRB.CreateAnd(S1, S2);
1279 Value *V1S2 = IRB.CreateAnd(V1, S2);
1280 Value *S1V2 = IRB.CreateAnd(S1, V2);
1281 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1282 setOriginForNaryOp(I);
1283 }
1284
1285 void visitOr(BinaryOperator &I) {
1286 IRBuilder<> IRB(&I);
1287 // "Or" of 1 and a poisoned value results in unpoisoned value.
1288 // 1|1 => 1; 0|1 => 1; p|1 => 1;
1289 // 1|0 => 1; 0|0 => 0; p|0 => p;
1290 // 1|p => 1; 0|p => p; p|p => p;
1291 // S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
1292 Value *S1 = getShadow(&I, 0);
1293 Value *S2 = getShadow(&I, 1);
1294 Value *V1 = IRB.CreateNot(I.getOperand(0));
1295 Value *V2 = IRB.CreateNot(I.getOperand(1));
1296 if (V1->getType() != S1->getType()) {
1297 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1298 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1299 }
1300 Value *S1S2 = IRB.CreateAnd(S1, S2);
1301 Value *V1S2 = IRB.CreateAnd(V1, S2);
1302 Value *S1V2 = IRB.CreateAnd(S1, V2);
1303 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1304 setOriginForNaryOp(I);
1305 }
1306
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001307 /// \brief Default propagation of shadow and/or origin.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001308 ///
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001309 /// This class implements the general case of shadow propagation, used in all
1310 /// cases where we don't know and/or don't care about what the operation
1311 /// actually does. It converts all input shadow values to a common type
1312 /// (extending or truncating as necessary), and bitwise OR's them.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001313 ///
1314 /// This is much cheaper than inserting checks (i.e. requiring inputs to be
1315 /// fully initialized), and less prone to false positives.
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001316 ///
1317 /// This class also implements the general case of origin propagation. For a
1318 /// Nary operation, result origin is set to the origin of an argument that is
1319 /// not entirely initialized. If there is more than one such arguments, the
1320 /// rightmost of them is picked. It does not matter which one is picked if all
1321 /// arguments are initialized.
1322 template <bool CombineShadow>
1323 class Combiner {
1324 Value *Shadow;
1325 Value *Origin;
1326 IRBuilder<> &IRB;
1327 MemorySanitizerVisitor *MSV;
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +00001328
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001329 public:
1330 Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB) :
Craig Topperf40110f2014-04-25 05:29:35 +00001331 Shadow(nullptr), Origin(nullptr), IRB(IRB), MSV(MSV) {}
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001332
1333 /// \brief Add a pair of shadow and origin values to the mix.
1334 Combiner &Add(Value *OpShadow, Value *OpOrigin) {
1335 if (CombineShadow) {
1336 assert(OpShadow);
1337 if (!Shadow)
1338 Shadow = OpShadow;
1339 else {
1340 OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
1341 Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
1342 }
1343 }
1344
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001345 if (MSV->MS.TrackOrigins) {
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001346 assert(OpOrigin);
1347 if (!Origin) {
1348 Origin = OpOrigin;
1349 } else {
Evgeniy Stepanov70d1b0a2014-06-09 14:29:34 +00001350 Constant *ConstOrigin = dyn_cast<Constant>(OpOrigin);
1351 // No point in adding something that might result in 0 origin value.
1352 if (!ConstOrigin || !ConstOrigin->isNullValue()) {
1353 Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB);
1354 Value *Cond =
1355 IRB.CreateICmpNE(FlatShadow, MSV->getCleanShadow(FlatShadow));
1356 Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
1357 }
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001358 }
1359 }
1360 return *this;
1361 }
1362
1363 /// \brief Add an application value to the mix.
1364 Combiner &Add(Value *V) {
1365 Value *OpShadow = MSV->getShadow(V);
Craig Topperf40110f2014-04-25 05:29:35 +00001366 Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : nullptr;
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001367 return Add(OpShadow, OpOrigin);
1368 }
1369
1370 /// \brief Set the current combined values as the given instruction's shadow
1371 /// and origin.
1372 void Done(Instruction *I) {
1373 if (CombineShadow) {
1374 assert(Shadow);
1375 Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
1376 MSV->setShadow(I, Shadow);
1377 }
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001378 if (MSV->MS.TrackOrigins) {
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001379 assert(Origin);
1380 MSV->setOrigin(I, Origin);
1381 }
1382 }
1383 };
1384
1385 typedef Combiner<true> ShadowAndOriginCombiner;
1386 typedef Combiner<false> OriginCombiner;
1387
1388 /// \brief Propagate origin for arbitrary operation.
1389 void setOriginForNaryOp(Instruction &I) {
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001390 if (!MS.TrackOrigins) return;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001391 IRBuilder<> IRB(&I);
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001392 OriginCombiner OC(this, IRB);
1393 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1394 OC.Add(OI->get());
1395 OC.Done(&I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001396 }
1397
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001398 size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
Evgeniy Stepanovf19c0862012-12-25 16:04:38 +00001399 assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) &&
1400 "Vector of pointers is not a valid shadow type");
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001401 return Ty->isVectorTy() ?
1402 Ty->getVectorNumElements() * Ty->getScalarSizeInBits() :
1403 Ty->getPrimitiveSizeInBits();
1404 }
1405
1406 /// \brief Cast between two shadow types, extending or truncating as
1407 /// necessary.
Evgeniy Stepanov21a9c932013-10-17 10:53:50 +00001408 Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy,
1409 bool Signed = false) {
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001410 Type *srcTy = V->getType();
1411 if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
Evgeniy Stepanov21a9c932013-10-17 10:53:50 +00001412 return IRB.CreateIntCast(V, dstTy, Signed);
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001413 if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
1414 dstTy->getVectorNumElements() == srcTy->getVectorNumElements())
Evgeniy Stepanov21a9c932013-10-17 10:53:50 +00001415 return IRB.CreateIntCast(V, dstTy, Signed);
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001416 size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
1417 size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
1418 Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
1419 Value *V2 =
Evgeniy Stepanov21a9c932013-10-17 10:53:50 +00001420 IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), Signed);
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001421 return IRB.CreateBitCast(V2, dstTy);
1422 // TODO: handle struct types.
1423 }
1424
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00001425 /// \brief Cast an application value to the type of its own shadow.
1426 Value *CreateAppToShadowCast(IRBuilder<> &IRB, Value *V) {
1427 Type *ShadowTy = getShadowTy(V);
1428 if (V->getType() == ShadowTy)
1429 return V;
1430 if (V->getType()->isPtrOrPtrVectorTy())
1431 return IRB.CreatePtrToInt(V, ShadowTy);
1432 else
1433 return IRB.CreateBitCast(V, ShadowTy);
1434 }
1435
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001436 /// \brief Propagate shadow for arbitrary operation.
1437 void handleShadowOr(Instruction &I) {
1438 IRBuilder<> IRB(&I);
1439 ShadowAndOriginCombiner SC(this, IRB);
1440 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1441 SC.Add(OI->get());
1442 SC.Done(&I);
1443 }
1444
Evgeniy Stepanovdf187fe2014-06-17 09:23:12 +00001445 // \brief Handle multiplication by constant.
1446 //
1447 // Handle a special case of multiplication by constant that may have one or
1448 // more zeros in the lower bits. This makes corresponding number of lower bits
1449 // of the result zero as well. We model it by shifting the other operand
1450 // shadow left by the required number of bits. Effectively, we transform
1451 // (X * (A * 2**B)) to ((X << B) * A) and instrument (X << B) as (Sx << B).
1452 // We use multiplication by 2**N instead of shift to cover the case of
1453 // multiplication by 0, which may occur in some elements of a vector operand.
1454 void handleMulByConstant(BinaryOperator &I, Constant *ConstArg,
1455 Value *OtherArg) {
1456 Constant *ShadowMul;
1457 Type *Ty = ConstArg->getType();
1458 if (Ty->isVectorTy()) {
1459 unsigned NumElements = Ty->getVectorNumElements();
1460 Type *EltTy = Ty->getSequentialElementType();
1461 SmallVector<Constant *, 16> Elements;
1462 for (unsigned Idx = 0; Idx < NumElements; ++Idx) {
1463 ConstantInt *Elt =
1464 dyn_cast<ConstantInt>(ConstArg->getAggregateElement(Idx));
1465 APInt V = Elt->getValue();
1466 APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
1467 Elements.push_back(ConstantInt::get(EltTy, V2));
1468 }
1469 ShadowMul = ConstantVector::get(Elements);
1470 } else {
1471 ConstantInt *Elt = dyn_cast<ConstantInt>(ConstArg);
1472 APInt V = Elt->getValue();
1473 APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
1474 ShadowMul = ConstantInt::get(Elt->getType(), V2);
1475 }
1476
1477 IRBuilder<> IRB(&I);
1478 setShadow(&I,
1479 IRB.CreateMul(getShadow(OtherArg), ShadowMul, "msprop_mul_cst"));
1480 setOrigin(&I, getOrigin(OtherArg));
1481 }
1482
1483 void visitMul(BinaryOperator &I) {
1484 Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1485 Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
1486 if (constOp0 && !constOp1)
1487 handleMulByConstant(I, constOp0, I.getOperand(1));
1488 else if (constOp1 && !constOp0)
1489 handleMulByConstant(I, constOp1, I.getOperand(0));
1490 else
1491 handleShadowOr(I);
1492 }
1493
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001494 void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
1495 void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
1496 void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
1497 void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
1498 void visitSub(BinaryOperator &I) { handleShadowOr(I); }
1499 void visitXor(BinaryOperator &I) { handleShadowOr(I); }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001500
1501 void handleDiv(Instruction &I) {
1502 IRBuilder<> IRB(&I);
1503 // Strict on the second argument.
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001504 insertShadowCheck(I.getOperand(1), &I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001505 setShadow(&I, getShadow(&I, 0));
1506 setOrigin(&I, getOrigin(&I, 0));
1507 }
1508
1509 void visitUDiv(BinaryOperator &I) { handleDiv(I); }
1510 void visitSDiv(BinaryOperator &I) { handleDiv(I); }
1511 void visitFDiv(BinaryOperator &I) { handleDiv(I); }
1512 void visitURem(BinaryOperator &I) { handleDiv(I); }
1513 void visitSRem(BinaryOperator &I) { handleDiv(I); }
1514 void visitFRem(BinaryOperator &I) { handleDiv(I); }
1515
1516 /// \brief Instrument == and != comparisons.
1517 ///
1518 /// Sometimes the comparison result is known even if some of the bits of the
1519 /// arguments are not.
1520 void handleEqualityComparison(ICmpInst &I) {
1521 IRBuilder<> IRB(&I);
1522 Value *A = I.getOperand(0);
1523 Value *B = I.getOperand(1);
1524 Value *Sa = getShadow(A);
1525 Value *Sb = getShadow(B);
Evgeniy Stepanovd14e47b2013-01-15 16:44:52 +00001526
1527 // Get rid of pointers and vectors of pointers.
1528 // For ints (and vectors of ints), types of A and Sa match,
1529 // and this is a no-op.
1530 A = IRB.CreatePointerCast(A, Sa->getType());
1531 B = IRB.CreatePointerCast(B, Sb->getType());
1532
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001533 // A == B <==> (C = A^B) == 0
1534 // A != B <==> (C = A^B) != 0
1535 // Sc = Sa | Sb
1536 Value *C = IRB.CreateXor(A, B);
1537 Value *Sc = IRB.CreateOr(Sa, Sb);
1538 // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
1539 // Result is defined if one of the following is true
1540 // * there is a defined 1 bit in C
1541 // * C is fully defined
1542 // Si = !(C & ~Sc) && Sc
1543 Value *Zero = Constant::getNullValue(Sc->getType());
1544 Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
1545 Value *Si =
1546 IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
1547 IRB.CreateICmpEQ(
1548 IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
1549 Si->setName("_msprop_icmp");
1550 setShadow(&I, Si);
1551 setOriginForNaryOp(I);
1552 }
1553
Evgeniy Stepanovfac84032013-01-25 15:31:10 +00001554 /// \brief Build the lowest possible value of V, taking into account V's
1555 /// uninitialized bits.
1556 Value *getLowestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1557 bool isSigned) {
1558 if (isSigned) {
1559 // Split shadow into sign bit and other bits.
1560 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1561 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1562 // Maximise the undefined shadow bit, minimize other undefined bits.
1563 return
1564 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaOtherBits)), SaSignBit);
1565 } else {
1566 // Minimize undefined bits.
1567 return IRB.CreateAnd(A, IRB.CreateNot(Sa));
1568 }
1569 }
1570
1571 /// \brief Build the highest possible value of V, taking into account V's
1572 /// uninitialized bits.
1573 Value *getHighestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1574 bool isSigned) {
1575 if (isSigned) {
1576 // Split shadow into sign bit and other bits.
1577 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1578 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1579 // Minimise the undefined shadow bit, maximise other undefined bits.
1580 return
1581 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaSignBit)), SaOtherBits);
1582 } else {
1583 // Maximize undefined bits.
1584 return IRB.CreateOr(A, Sa);
1585 }
1586 }
1587
1588 /// \brief Instrument relational comparisons.
1589 ///
1590 /// This function does exact shadow propagation for all relational
1591 /// comparisons of integers, pointers and vectors of those.
1592 /// FIXME: output seems suboptimal when one of the operands is a constant
1593 void handleRelationalComparisonExact(ICmpInst &I) {
1594 IRBuilder<> IRB(&I);
1595 Value *A = I.getOperand(0);
1596 Value *B = I.getOperand(1);
1597 Value *Sa = getShadow(A);
1598 Value *Sb = getShadow(B);
1599
1600 // Get rid of pointers and vectors of pointers.
1601 // For ints (and vectors of ints), types of A and Sa match,
1602 // and this is a no-op.
1603 A = IRB.CreatePointerCast(A, Sa->getType());
1604 B = IRB.CreatePointerCast(B, Sb->getType());
1605
Evgeniy Stepanov2cb0fa12013-01-25 15:35:29 +00001606 // Let [a0, a1] be the interval of possible values of A, taking into account
1607 // its undefined bits. Let [b0, b1] be the interval of possible values of B.
1608 // Then (A cmp B) is defined iff (a0 cmp b1) == (a1 cmp b0).
Evgeniy Stepanovfac84032013-01-25 15:31:10 +00001609 bool IsSigned = I.isSigned();
1610 Value *S1 = IRB.CreateICmp(I.getPredicate(),
1611 getLowestPossibleValue(IRB, A, Sa, IsSigned),
1612 getHighestPossibleValue(IRB, B, Sb, IsSigned));
1613 Value *S2 = IRB.CreateICmp(I.getPredicate(),
1614 getHighestPossibleValue(IRB, A, Sa, IsSigned),
1615 getLowestPossibleValue(IRB, B, Sb, IsSigned));
1616 Value *Si = IRB.CreateXor(S1, S2);
1617 setShadow(&I, Si);
1618 setOriginForNaryOp(I);
1619 }
1620
Evgeniy Stepanov857d9d22012-11-29 14:25:47 +00001621 /// \brief Instrument signed relational comparisons.
1622 ///
1623 /// Handle (x<0) and (x>=0) comparisons (essentially, sign bit tests) by
1624 /// propagating the highest bit of the shadow. Everything else is delegated
1625 /// to handleShadowOr().
1626 void handleSignedRelationalComparison(ICmpInst &I) {
1627 Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1628 Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
Craig Topperf40110f2014-04-25 05:29:35 +00001629 Value* op = nullptr;
Evgeniy Stepanov857d9d22012-11-29 14:25:47 +00001630 CmpInst::Predicate pre = I.getPredicate();
1631 if (constOp0 && constOp0->isNullValue() &&
1632 (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE)) {
1633 op = I.getOperand(1);
1634 } else if (constOp1 && constOp1->isNullValue() &&
1635 (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) {
1636 op = I.getOperand(0);
1637 }
1638 if (op) {
1639 IRBuilder<> IRB(&I);
1640 Value* Shadow =
1641 IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op), "_msprop_icmpslt");
1642 setShadow(&I, Shadow);
1643 setOrigin(&I, getOrigin(op));
1644 } else {
1645 handleShadowOr(I);
1646 }
1647 }
1648
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001649 void visitICmpInst(ICmpInst &I) {
Evgeniy Stepanov6f85ef32013-01-28 11:42:28 +00001650 if (!ClHandleICmp) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001651 handleShadowOr(I);
Evgeniy Stepanov6f85ef32013-01-28 11:42:28 +00001652 return;
1653 }
1654 if (I.isEquality()) {
1655 handleEqualityComparison(I);
1656 return;
1657 }
1658
1659 assert(I.isRelational());
1660 if (ClHandleICmpExact) {
1661 handleRelationalComparisonExact(I);
1662 return;
1663 }
1664 if (I.isSigned()) {
1665 handleSignedRelationalComparison(I);
1666 return;
1667 }
1668
1669 assert(I.isUnsigned());
1670 if ((isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
1671 handleRelationalComparisonExact(I);
1672 return;
1673 }
1674
1675 handleShadowOr(I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001676 }
1677
1678 void visitFCmpInst(FCmpInst &I) {
1679 handleShadowOr(I);
1680 }
1681
1682 void handleShift(BinaryOperator &I) {
1683 IRBuilder<> IRB(&I);
1684 // If any of the S2 bits are poisoned, the whole thing is poisoned.
1685 // Otherwise perform the same shift on S1.
1686 Value *S1 = getShadow(&I, 0);
1687 Value *S2 = getShadow(&I, 1);
1688 Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
1689 S2->getType());
1690 Value *V2 = I.getOperand(1);
1691 Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
1692 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1693 setOriginForNaryOp(I);
1694 }
1695
1696 void visitShl(BinaryOperator &I) { handleShift(I); }
1697 void visitAShr(BinaryOperator &I) { handleShift(I); }
1698 void visitLShr(BinaryOperator &I) { handleShift(I); }
1699
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001700 /// \brief Instrument llvm.memmove
1701 ///
1702 /// At this point we don't know if llvm.memmove will be inlined or not.
1703 /// If we don't instrument it and it gets inlined,
1704 /// our interceptor will not kick in and we will lose the memmove.
1705 /// If we instrument the call here, but it does not get inlined,
1706 /// we will memove the shadow twice: which is bad in case
1707 /// of overlapping regions. So, we simply lower the intrinsic to a call.
1708 ///
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +00001709 /// Similar situation exists for memcpy and memset.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001710 void visitMemMoveInst(MemMoveInst &I) {
1711 IRBuilder<> IRB(&I);
1712 IRB.CreateCall3(
1713 MS.MemmoveFn,
1714 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1715 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1716 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1717 I.eraseFromParent();
1718 }
1719
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +00001720 // Similar to memmove: avoid copying shadow twice.
1721 // This is somewhat unfortunate as it may slowdown small constant memcpys.
1722 // FIXME: consider doing manual inline for small constant sizes and proper
1723 // alignment.
1724 void visitMemCpyInst(MemCpyInst &I) {
1725 IRBuilder<> IRB(&I);
1726 IRB.CreateCall3(
1727 MS.MemcpyFn,
1728 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1729 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1730 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1731 I.eraseFromParent();
1732 }
1733
1734 // Same as memcpy.
1735 void visitMemSetInst(MemSetInst &I) {
1736 IRBuilder<> IRB(&I);
1737 IRB.CreateCall3(
1738 MS.MemsetFn,
1739 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1740 IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
1741 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1742 I.eraseFromParent();
1743 }
1744
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001745 void visitVAStartInst(VAStartInst &I) {
1746 VAHelper->visitVAStartInst(I);
1747 }
1748
1749 void visitVACopyInst(VACopyInst &I) {
1750 VAHelper->visitVACopyInst(I);
1751 }
1752
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001753 enum IntrinsicKind {
1754 IK_DoesNotAccessMemory,
1755 IK_OnlyReadsMemory,
1756 IK_WritesMemory
1757 };
1758
1759 static IntrinsicKind getIntrinsicKind(Intrinsic::ID iid) {
1760 const int DoesNotAccessMemory = IK_DoesNotAccessMemory;
1761 const int OnlyReadsArgumentPointees = IK_OnlyReadsMemory;
1762 const int OnlyReadsMemory = IK_OnlyReadsMemory;
1763 const int OnlyAccessesArgumentPointees = IK_WritesMemory;
1764 const int UnknownModRefBehavior = IK_WritesMemory;
1765#define GET_INTRINSIC_MODREF_BEHAVIOR
1766#define ModRefBehavior IntrinsicKind
Chandler Carruthdb25c6c2013-01-02 12:09:16 +00001767#include "llvm/IR/Intrinsics.gen"
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001768#undef ModRefBehavior
1769#undef GET_INTRINSIC_MODREF_BEHAVIOR
1770 }
1771
1772 /// \brief Handle vector store-like intrinsics.
1773 ///
1774 /// Instrument intrinsics that look like a simple SIMD store: writes memory,
1775 /// has 1 pointer argument and 1 vector argument, returns void.
1776 bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
1777 IRBuilder<> IRB(&I);
1778 Value* Addr = I.getArgOperand(0);
1779 Value *Shadow = getShadow(&I, 1);
1780 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
1781
1782 // We don't know the pointer alignment (could be unaligned SSE store!).
1783 // Have to assume to worst case.
1784 IRB.CreateAlignedStore(Shadow, ShadowPtr, 1);
1785
1786 if (ClCheckAccessAddress)
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001787 insertShadowCheck(Addr, &I);
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001788
1789 // FIXME: use ClStoreCleanOrigin
1790 // FIXME: factor out common code from materializeStores
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001791 if (MS.TrackOrigins)
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001792 IRB.CreateStore(getOrigin(&I, 1), getOriginPtr(Addr, IRB));
1793 return true;
1794 }
1795
1796 /// \brief Handle vector load-like intrinsics.
1797 ///
1798 /// Instrument intrinsics that look like a simple SIMD load: reads memory,
1799 /// has 1 pointer argument, returns a vector.
1800 bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
1801 IRBuilder<> IRB(&I);
1802 Value *Addr = I.getArgOperand(0);
1803
1804 Type *ShadowTy = getShadowTy(&I);
Evgeniy Stepanov174242c2014-07-03 11:56:30 +00001805 if (PropagateShadow) {
Evgeniy Stepanov00062b42013-02-28 11:25:14 +00001806 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1807 // We don't know the pointer alignment (could be unaligned SSE load!).
1808 // Have to assume to worst case.
1809 setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, 1, "_msld"));
1810 } else {
1811 setShadow(&I, getCleanShadow(&I));
1812 }
1813
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001814 if (ClCheckAccessAddress)
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001815 insertShadowCheck(Addr, &I);
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001816
Evgeniy Stepanov00062b42013-02-28 11:25:14 +00001817 if (MS.TrackOrigins) {
Evgeniy Stepanov174242c2014-07-03 11:56:30 +00001818 if (PropagateShadow)
Evgeniy Stepanov00062b42013-02-28 11:25:14 +00001819 setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB)));
1820 else
1821 setOrigin(&I, getCleanOrigin());
1822 }
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001823 return true;
1824 }
1825
1826 /// \brief Handle (SIMD arithmetic)-like intrinsics.
1827 ///
1828 /// Instrument intrinsics with any number of arguments of the same type,
1829 /// equal to the return type. The type should be simple (no aggregates or
1830 /// pointers; vectors are fine).
1831 /// Caller guarantees that this intrinsic does not access memory.
1832 bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) {
1833 Type *RetTy = I.getType();
1834 if (!(RetTy->isIntOrIntVectorTy() ||
1835 RetTy->isFPOrFPVectorTy() ||
1836 RetTy->isX86_MMXTy()))
1837 return false;
1838
1839 unsigned NumArgOperands = I.getNumArgOperands();
1840
1841 for (unsigned i = 0; i < NumArgOperands; ++i) {
1842 Type *Ty = I.getArgOperand(i)->getType();
1843 if (Ty != RetTy)
1844 return false;
1845 }
1846
1847 IRBuilder<> IRB(&I);
1848 ShadowAndOriginCombiner SC(this, IRB);
1849 for (unsigned i = 0; i < NumArgOperands; ++i)
1850 SC.Add(I.getArgOperand(i));
1851 SC.Done(&I);
1852
1853 return true;
1854 }
1855
1856 /// \brief Heuristically instrument unknown intrinsics.
1857 ///
1858 /// The main purpose of this code is to do something reasonable with all
1859 /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
1860 /// We recognize several classes of intrinsics by their argument types and
1861 /// ModRefBehaviour and apply special intrumentation when we are reasonably
1862 /// sure that we know what the intrinsic does.
1863 ///
1864 /// We special-case intrinsics where this approach fails. See llvm.bswap
1865 /// handling as an example of that.
1866 bool handleUnknownIntrinsic(IntrinsicInst &I) {
1867 unsigned NumArgOperands = I.getNumArgOperands();
1868 if (NumArgOperands == 0)
1869 return false;
1870
1871 Intrinsic::ID iid = I.getIntrinsicID();
1872 IntrinsicKind IK = getIntrinsicKind(iid);
1873 bool OnlyReadsMemory = IK == IK_OnlyReadsMemory;
1874 bool WritesMemory = IK == IK_WritesMemory;
1875 assert(!(OnlyReadsMemory && WritesMemory));
1876
1877 if (NumArgOperands == 2 &&
1878 I.getArgOperand(0)->getType()->isPointerTy() &&
1879 I.getArgOperand(1)->getType()->isVectorTy() &&
1880 I.getType()->isVoidTy() &&
1881 WritesMemory) {
1882 // This looks like a vector store.
1883 return handleVectorStoreIntrinsic(I);
1884 }
1885
1886 if (NumArgOperands == 1 &&
1887 I.getArgOperand(0)->getType()->isPointerTy() &&
1888 I.getType()->isVectorTy() &&
1889 OnlyReadsMemory) {
1890 // This looks like a vector load.
1891 return handleVectorLoadIntrinsic(I);
1892 }
1893
1894 if (!OnlyReadsMemory && !WritesMemory)
1895 if (maybeHandleSimpleNomemIntrinsic(I))
1896 return true;
1897
1898 // FIXME: detect and handle SSE maskstore/maskload
1899 return false;
1900 }
1901
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00001902 void handleBswap(IntrinsicInst &I) {
1903 IRBuilder<> IRB(&I);
1904 Value *Op = I.getArgOperand(0);
1905 Type *OpType = Op->getType();
1906 Function *BswapFunc = Intrinsic::getDeclaration(
Craig Toppere1d12942014-08-27 05:25:25 +00001907 F.getParent(), Intrinsic::bswap, makeArrayRef(&OpType, 1));
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00001908 setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
1909 setOrigin(&I, getOrigin(Op));
1910 }
1911
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001912 // \brief Instrument vector convert instrinsic.
1913 //
1914 // This function instruments intrinsics like cvtsi2ss:
1915 // %Out = int_xxx_cvtyyy(%ConvertOp)
1916 // or
1917 // %Out = int_xxx_cvtyyy(%CopyOp, %ConvertOp)
1918 // Intrinsic converts \p NumUsedElements elements of \p ConvertOp to the same
1919 // number \p Out elements, and (if has 2 arguments) copies the rest of the
1920 // elements from \p CopyOp.
1921 // In most cases conversion involves floating-point value which may trigger a
1922 // hardware exception when not fully initialized. For this reason we require
1923 // \p ConvertOp[0:NumUsedElements] to be fully initialized and trap otherwise.
1924 // We copy the shadow of \p CopyOp[NumUsedElements:] to \p
1925 // Out[NumUsedElements:]. This means that intrinsics without \p CopyOp always
1926 // return a fully initialized value.
1927 void handleVectorConvertIntrinsic(IntrinsicInst &I, int NumUsedElements) {
1928 IRBuilder<> IRB(&I);
1929 Value *CopyOp, *ConvertOp;
1930
1931 switch (I.getNumArgOperands()) {
1932 case 2:
1933 CopyOp = I.getArgOperand(0);
1934 ConvertOp = I.getArgOperand(1);
1935 break;
1936 case 1:
1937 ConvertOp = I.getArgOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +00001938 CopyOp = nullptr;
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001939 break;
1940 default:
1941 llvm_unreachable("Cvt intrinsic with unsupported number of arguments.");
1942 }
1943
1944 // The first *NumUsedElements* elements of ConvertOp are converted to the
1945 // same number of output elements. The rest of the output is copied from
1946 // CopyOp, or (if not available) filled with zeroes.
1947 // Combine shadow for elements of ConvertOp that are used in this operation,
1948 // and insert a check.
1949 // FIXME: consider propagating shadow of ConvertOp, at least in the case of
1950 // int->any conversion.
1951 Value *ConvertShadow = getShadow(ConvertOp);
Craig Topperf40110f2014-04-25 05:29:35 +00001952 Value *AggShadow = nullptr;
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001953 if (ConvertOp->getType()->isVectorTy()) {
1954 AggShadow = IRB.CreateExtractElement(
1955 ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), 0));
1956 for (int i = 1; i < NumUsedElements; ++i) {
1957 Value *MoreShadow = IRB.CreateExtractElement(
1958 ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), i));
1959 AggShadow = IRB.CreateOr(AggShadow, MoreShadow);
1960 }
1961 } else {
1962 AggShadow = ConvertShadow;
1963 }
1964 assert(AggShadow->getType()->isIntegerTy());
1965 insertShadowCheck(AggShadow, getOrigin(ConvertOp), &I);
1966
1967 // Build result shadow by zero-filling parts of CopyOp shadow that come from
1968 // ConvertOp.
1969 if (CopyOp) {
1970 assert(CopyOp->getType() == I.getType());
1971 assert(CopyOp->getType()->isVectorTy());
1972 Value *ResultShadow = getShadow(CopyOp);
1973 Type *EltTy = ResultShadow->getType()->getVectorElementType();
1974 for (int i = 0; i < NumUsedElements; ++i) {
1975 ResultShadow = IRB.CreateInsertElement(
1976 ResultShadow, ConstantInt::getNullValue(EltTy),
1977 ConstantInt::get(IRB.getInt32Ty(), i));
1978 }
1979 setShadow(&I, ResultShadow);
1980 setOrigin(&I, getOrigin(CopyOp));
1981 } else {
1982 setShadow(&I, getCleanShadow(&I));
1983 }
1984 }
1985
Evgeniy Stepanov77be5322014-03-03 13:47:42 +00001986 // Given a scalar or vector, extract lower 64 bits (or less), and return all
1987 // zeroes if it is zero, and all ones otherwise.
1988 Value *Lower64ShadowExtend(IRBuilder<> &IRB, Value *S, Type *T) {
1989 if (S->getType()->isVectorTy())
1990 S = CreateShadowCast(IRB, S, IRB.getInt64Ty(), /* Signed */ true);
1991 assert(S->getType()->getPrimitiveSizeInBits() <= 64);
1992 Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
1993 return CreateShadowCast(IRB, S2, T, /* Signed */ true);
1994 }
1995
1996 Value *VariableShadowExtend(IRBuilder<> &IRB, Value *S) {
1997 Type *T = S->getType();
1998 assert(T->isVectorTy());
1999 Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
2000 return IRB.CreateSExt(S2, T);
2001 }
2002
2003 // \brief Instrument vector shift instrinsic.
2004 //
2005 // This function instruments intrinsics like int_x86_avx2_psll_w.
2006 // Intrinsic shifts %In by %ShiftSize bits.
2007 // %ShiftSize may be a vector. In that case the lower 64 bits determine shift
2008 // size, and the rest is ignored. Behavior is defined even if shift size is
2009 // greater than register (or field) width.
2010 void handleVectorShiftIntrinsic(IntrinsicInst &I, bool Variable) {
2011 assert(I.getNumArgOperands() == 2);
2012 IRBuilder<> IRB(&I);
2013 // If any of the S2 bits are poisoned, the whole thing is poisoned.
2014 // Otherwise perform the same shift on S1.
2015 Value *S1 = getShadow(&I, 0);
2016 Value *S2 = getShadow(&I, 1);
2017 Value *S2Conv = Variable ? VariableShadowExtend(IRB, S2)
2018 : Lower64ShadowExtend(IRB, S2, getShadowTy(&I));
2019 Value *V1 = I.getOperand(0);
2020 Value *V2 = I.getOperand(1);
2021 Value *Shift = IRB.CreateCall2(I.getCalledValue(),
2022 IRB.CreateBitCast(S1, V1->getType()), V2);
2023 Shift = IRB.CreateBitCast(Shift, getShadowTy(&I));
2024 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
2025 setOriginForNaryOp(I);
2026 }
2027
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002028 // \brief Get an X86_MMX-sized vector type.
2029 Type *getMMXVectorTy(unsigned EltSizeInBits) {
2030 const unsigned X86_MMXSizeInBits = 64;
2031 return VectorType::get(IntegerType::get(*MS.C, EltSizeInBits),
2032 X86_MMXSizeInBits / EltSizeInBits);
2033 }
2034
2035 // \brief Returns a signed counterpart for an (un)signed-saturate-and-pack
2036 // intrinsic.
2037 Intrinsic::ID getSignedPackIntrinsic(Intrinsic::ID id) {
2038 switch (id) {
2039 case llvm::Intrinsic::x86_sse2_packsswb_128:
2040 case llvm::Intrinsic::x86_sse2_packuswb_128:
2041 return llvm::Intrinsic::x86_sse2_packsswb_128;
2042
2043 case llvm::Intrinsic::x86_sse2_packssdw_128:
2044 case llvm::Intrinsic::x86_sse41_packusdw:
2045 return llvm::Intrinsic::x86_sse2_packssdw_128;
2046
2047 case llvm::Intrinsic::x86_avx2_packsswb:
2048 case llvm::Intrinsic::x86_avx2_packuswb:
2049 return llvm::Intrinsic::x86_avx2_packsswb;
2050
2051 case llvm::Intrinsic::x86_avx2_packssdw:
2052 case llvm::Intrinsic::x86_avx2_packusdw:
2053 return llvm::Intrinsic::x86_avx2_packssdw;
2054
2055 case llvm::Intrinsic::x86_mmx_packsswb:
2056 case llvm::Intrinsic::x86_mmx_packuswb:
2057 return llvm::Intrinsic::x86_mmx_packsswb;
2058
2059 case llvm::Intrinsic::x86_mmx_packssdw:
2060 return llvm::Intrinsic::x86_mmx_packssdw;
2061 default:
2062 llvm_unreachable("unexpected intrinsic id");
2063 }
2064 }
2065
Evgeniy Stepanov5d972932014-06-17 11:26:00 +00002066 // \brief Instrument vector pack instrinsic.
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002067 //
2068 // This function instruments intrinsics like x86_mmx_packsswb, that
Evgeniy Stepanov5d972932014-06-17 11:26:00 +00002069 // packs elements of 2 input vectors into half as many bits with saturation.
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002070 // Shadow is propagated with the signed variant of the same intrinsic applied
2071 // to sext(Sa != zeroinitializer), sext(Sb != zeroinitializer).
2072 // EltSizeInBits is used only for x86mmx arguments.
2073 void handleVectorPackIntrinsic(IntrinsicInst &I, unsigned EltSizeInBits = 0) {
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002074 assert(I.getNumArgOperands() == 2);
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002075 bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002076 IRBuilder<> IRB(&I);
2077 Value *S1 = getShadow(&I, 0);
2078 Value *S2 = getShadow(&I, 1);
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002079 assert(isX86_MMX || S1->getType()->isVectorTy());
2080
2081 // SExt and ICmpNE below must apply to individual elements of input vectors.
2082 // In case of x86mmx arguments, cast them to appropriate vector types and
2083 // back.
2084 Type *T = isX86_MMX ? getMMXVectorTy(EltSizeInBits) : S1->getType();
2085 if (isX86_MMX) {
2086 S1 = IRB.CreateBitCast(S1, T);
2087 S2 = IRB.CreateBitCast(S2, T);
2088 }
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002089 Value *S1_ext = IRB.CreateSExt(
2090 IRB.CreateICmpNE(S1, llvm::Constant::getNullValue(T)), T);
2091 Value *S2_ext = IRB.CreateSExt(
2092 IRB.CreateICmpNE(S2, llvm::Constant::getNullValue(T)), T);
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002093 if (isX86_MMX) {
2094 Type *X86_MMXTy = Type::getX86_MMXTy(*MS.C);
2095 S1_ext = IRB.CreateBitCast(S1_ext, X86_MMXTy);
2096 S2_ext = IRB.CreateBitCast(S2_ext, X86_MMXTy);
2097 }
2098
2099 Function *ShadowFn = Intrinsic::getDeclaration(
2100 F.getParent(), getSignedPackIntrinsic(I.getIntrinsicID()));
2101
2102 Value *S = IRB.CreateCall2(ShadowFn, S1_ext, S2_ext, "_msprop_vector_pack");
2103 if (isX86_MMX) S = IRB.CreateBitCast(S, getShadowTy(&I));
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002104 setShadow(&I, S);
2105 setOriginForNaryOp(I);
2106 }
2107
Evgeniy Stepanov4ea16472014-06-18 12:02:29 +00002108 // \brief Instrument sum-of-absolute-differencies intrinsic.
2109 void handleVectorSadIntrinsic(IntrinsicInst &I) {
2110 const unsigned SignificantBitsPerResultElement = 16;
2111 bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2112 Type *ResTy = isX86_MMX ? IntegerType::get(*MS.C, 64) : I.getType();
2113 unsigned ZeroBitsPerResultElement =
2114 ResTy->getScalarSizeInBits() - SignificantBitsPerResultElement;
2115
2116 IRBuilder<> IRB(&I);
2117 Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2118 S = IRB.CreateBitCast(S, ResTy);
2119 S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
2120 ResTy);
2121 S = IRB.CreateLShr(S, ZeroBitsPerResultElement);
2122 S = IRB.CreateBitCast(S, getShadowTy(&I));
2123 setShadow(&I, S);
2124 setOriginForNaryOp(I);
2125 }
2126
2127 // \brief Instrument multiply-add intrinsic.
2128 void handleVectorPmaddIntrinsic(IntrinsicInst &I,
2129 unsigned EltSizeInBits = 0) {
2130 bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2131 Type *ResTy = isX86_MMX ? getMMXVectorTy(EltSizeInBits * 2) : I.getType();
2132 IRBuilder<> IRB(&I);
2133 Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2134 S = IRB.CreateBitCast(S, ResTy);
2135 S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
2136 ResTy);
2137 S = IRB.CreateBitCast(S, getShadowTy(&I));
2138 setShadow(&I, S);
2139 setOriginForNaryOp(I);
2140 }
2141
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00002142 void visitIntrinsicInst(IntrinsicInst &I) {
2143 switch (I.getIntrinsicID()) {
2144 case llvm::Intrinsic::bswap:
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +00002145 handleBswap(I);
2146 break;
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002147 case llvm::Intrinsic::x86_avx512_cvtsd2usi64:
2148 case llvm::Intrinsic::x86_avx512_cvtsd2usi:
2149 case llvm::Intrinsic::x86_avx512_cvtss2usi64:
2150 case llvm::Intrinsic::x86_avx512_cvtss2usi:
2151 case llvm::Intrinsic::x86_avx512_cvttss2usi64:
2152 case llvm::Intrinsic::x86_avx512_cvttss2usi:
2153 case llvm::Intrinsic::x86_avx512_cvttsd2usi64:
2154 case llvm::Intrinsic::x86_avx512_cvttsd2usi:
2155 case llvm::Intrinsic::x86_avx512_cvtusi2sd:
2156 case llvm::Intrinsic::x86_avx512_cvtusi2ss:
2157 case llvm::Intrinsic::x86_avx512_cvtusi642sd:
2158 case llvm::Intrinsic::x86_avx512_cvtusi642ss:
2159 case llvm::Intrinsic::x86_sse2_cvtsd2si64:
2160 case llvm::Intrinsic::x86_sse2_cvtsd2si:
2161 case llvm::Intrinsic::x86_sse2_cvtsd2ss:
2162 case llvm::Intrinsic::x86_sse2_cvtsi2sd:
2163 case llvm::Intrinsic::x86_sse2_cvtsi642sd:
2164 case llvm::Intrinsic::x86_sse2_cvtss2sd:
2165 case llvm::Intrinsic::x86_sse2_cvttsd2si64:
2166 case llvm::Intrinsic::x86_sse2_cvttsd2si:
2167 case llvm::Intrinsic::x86_sse_cvtsi2ss:
2168 case llvm::Intrinsic::x86_sse_cvtsi642ss:
2169 case llvm::Intrinsic::x86_sse_cvtss2si64:
2170 case llvm::Intrinsic::x86_sse_cvtss2si:
2171 case llvm::Intrinsic::x86_sse_cvttss2si64:
2172 case llvm::Intrinsic::x86_sse_cvttss2si:
2173 handleVectorConvertIntrinsic(I, 1);
2174 break;
2175 case llvm::Intrinsic::x86_sse2_cvtdq2pd:
2176 case llvm::Intrinsic::x86_sse2_cvtps2pd:
2177 case llvm::Intrinsic::x86_sse_cvtps2pi:
2178 case llvm::Intrinsic::x86_sse_cvttps2pi:
2179 handleVectorConvertIntrinsic(I, 2);
2180 break;
Evgeniy Stepanov77be5322014-03-03 13:47:42 +00002181 case llvm::Intrinsic::x86_avx512_psll_dq:
2182 case llvm::Intrinsic::x86_avx512_psrl_dq:
2183 case llvm::Intrinsic::x86_avx2_psll_w:
2184 case llvm::Intrinsic::x86_avx2_psll_d:
2185 case llvm::Intrinsic::x86_avx2_psll_q:
2186 case llvm::Intrinsic::x86_avx2_pslli_w:
2187 case llvm::Intrinsic::x86_avx2_pslli_d:
2188 case llvm::Intrinsic::x86_avx2_pslli_q:
2189 case llvm::Intrinsic::x86_avx2_psll_dq:
2190 case llvm::Intrinsic::x86_avx2_psrl_w:
2191 case llvm::Intrinsic::x86_avx2_psrl_d:
2192 case llvm::Intrinsic::x86_avx2_psrl_q:
2193 case llvm::Intrinsic::x86_avx2_psra_w:
2194 case llvm::Intrinsic::x86_avx2_psra_d:
2195 case llvm::Intrinsic::x86_avx2_psrli_w:
2196 case llvm::Intrinsic::x86_avx2_psrli_d:
2197 case llvm::Intrinsic::x86_avx2_psrli_q:
2198 case llvm::Intrinsic::x86_avx2_psrai_w:
2199 case llvm::Intrinsic::x86_avx2_psrai_d:
2200 case llvm::Intrinsic::x86_avx2_psrl_dq:
2201 case llvm::Intrinsic::x86_sse2_psll_w:
2202 case llvm::Intrinsic::x86_sse2_psll_d:
2203 case llvm::Intrinsic::x86_sse2_psll_q:
2204 case llvm::Intrinsic::x86_sse2_pslli_w:
2205 case llvm::Intrinsic::x86_sse2_pslli_d:
2206 case llvm::Intrinsic::x86_sse2_pslli_q:
2207 case llvm::Intrinsic::x86_sse2_psll_dq:
2208 case llvm::Intrinsic::x86_sse2_psrl_w:
2209 case llvm::Intrinsic::x86_sse2_psrl_d:
2210 case llvm::Intrinsic::x86_sse2_psrl_q:
2211 case llvm::Intrinsic::x86_sse2_psra_w:
2212 case llvm::Intrinsic::x86_sse2_psra_d:
2213 case llvm::Intrinsic::x86_sse2_psrli_w:
2214 case llvm::Intrinsic::x86_sse2_psrli_d:
2215 case llvm::Intrinsic::x86_sse2_psrli_q:
2216 case llvm::Intrinsic::x86_sse2_psrai_w:
2217 case llvm::Intrinsic::x86_sse2_psrai_d:
2218 case llvm::Intrinsic::x86_sse2_psrl_dq:
2219 case llvm::Intrinsic::x86_mmx_psll_w:
2220 case llvm::Intrinsic::x86_mmx_psll_d:
2221 case llvm::Intrinsic::x86_mmx_psll_q:
2222 case llvm::Intrinsic::x86_mmx_pslli_w:
2223 case llvm::Intrinsic::x86_mmx_pslli_d:
2224 case llvm::Intrinsic::x86_mmx_pslli_q:
2225 case llvm::Intrinsic::x86_mmx_psrl_w:
2226 case llvm::Intrinsic::x86_mmx_psrl_d:
2227 case llvm::Intrinsic::x86_mmx_psrl_q:
2228 case llvm::Intrinsic::x86_mmx_psra_w:
2229 case llvm::Intrinsic::x86_mmx_psra_d:
2230 case llvm::Intrinsic::x86_mmx_psrli_w:
2231 case llvm::Intrinsic::x86_mmx_psrli_d:
2232 case llvm::Intrinsic::x86_mmx_psrli_q:
2233 case llvm::Intrinsic::x86_mmx_psrai_w:
2234 case llvm::Intrinsic::x86_mmx_psrai_d:
2235 handleVectorShiftIntrinsic(I, /* Variable */ false);
2236 break;
2237 case llvm::Intrinsic::x86_avx2_psllv_d:
2238 case llvm::Intrinsic::x86_avx2_psllv_d_256:
2239 case llvm::Intrinsic::x86_avx2_psllv_q:
2240 case llvm::Intrinsic::x86_avx2_psllv_q_256:
2241 case llvm::Intrinsic::x86_avx2_psrlv_d:
2242 case llvm::Intrinsic::x86_avx2_psrlv_d_256:
2243 case llvm::Intrinsic::x86_avx2_psrlv_q:
2244 case llvm::Intrinsic::x86_avx2_psrlv_q_256:
2245 case llvm::Intrinsic::x86_avx2_psrav_d:
2246 case llvm::Intrinsic::x86_avx2_psrav_d_256:
2247 handleVectorShiftIntrinsic(I, /* Variable */ true);
2248 break;
2249
2250 // Byte shifts are not implemented.
2251 // case llvm::Intrinsic::x86_avx512_psll_dq_bs:
2252 // case llvm::Intrinsic::x86_avx512_psrl_dq_bs:
2253 // case llvm::Intrinsic::x86_avx2_psll_dq_bs:
2254 // case llvm::Intrinsic::x86_avx2_psrl_dq_bs:
2255 // case llvm::Intrinsic::x86_sse2_psll_dq_bs:
2256 // case llvm::Intrinsic::x86_sse2_psrl_dq_bs:
2257
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002258 case llvm::Intrinsic::x86_sse2_packsswb_128:
2259 case llvm::Intrinsic::x86_sse2_packssdw_128:
2260 case llvm::Intrinsic::x86_sse2_packuswb_128:
2261 case llvm::Intrinsic::x86_sse41_packusdw:
2262 case llvm::Intrinsic::x86_avx2_packsswb:
2263 case llvm::Intrinsic::x86_avx2_packssdw:
2264 case llvm::Intrinsic::x86_avx2_packuswb:
2265 case llvm::Intrinsic::x86_avx2_packusdw:
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002266 handleVectorPackIntrinsic(I);
2267 break;
2268
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002269 case llvm::Intrinsic::x86_mmx_packsswb:
2270 case llvm::Intrinsic::x86_mmx_packuswb:
2271 handleVectorPackIntrinsic(I, 16);
2272 break;
2273
2274 case llvm::Intrinsic::x86_mmx_packssdw:
2275 handleVectorPackIntrinsic(I, 32);
2276 break;
2277
Evgeniy Stepanov4ea16472014-06-18 12:02:29 +00002278 case llvm::Intrinsic::x86_mmx_psad_bw:
2279 case llvm::Intrinsic::x86_sse2_psad_bw:
2280 case llvm::Intrinsic::x86_avx2_psad_bw:
2281 handleVectorSadIntrinsic(I);
2282 break;
2283
2284 case llvm::Intrinsic::x86_sse2_pmadd_wd:
2285 case llvm::Intrinsic::x86_avx2_pmadd_wd:
2286 case llvm::Intrinsic::x86_ssse3_pmadd_ub_sw_128:
2287 case llvm::Intrinsic::x86_avx2_pmadd_ub_sw:
2288 handleVectorPmaddIntrinsic(I);
2289 break;
2290
2291 case llvm::Intrinsic::x86_ssse3_pmadd_ub_sw:
2292 handleVectorPmaddIntrinsic(I, 8);
2293 break;
2294
2295 case llvm::Intrinsic::x86_mmx_pmadd_wd:
2296 handleVectorPmaddIntrinsic(I, 16);
2297 break;
2298
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00002299 default:
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00002300 if (!handleUnknownIntrinsic(I))
2301 visitInstruction(I);
Evgeniy Stepanov88b8dce2012-12-17 16:30:05 +00002302 break;
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00002303 }
2304 }
2305
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002306 void visitCallSite(CallSite CS) {
2307 Instruction &I = *CS.getInstruction();
2308 assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
2309 if (CS.isCall()) {
Evgeniy Stepanov7ad7e832012-11-29 14:32:03 +00002310 CallInst *Call = cast<CallInst>(&I);
2311
2312 // For inline asm, do the usual thing: check argument shadow and mark all
2313 // outputs as clean. Note that any side effects of the inline asm that are
2314 // not immediately visible in its constraints are not handled.
2315 if (Call->isInlineAsm()) {
2316 visitInstruction(I);
2317 return;
2318 }
2319
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00002320 assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
Evgeniy Stepanov383b61e2012-12-07 09:08:32 +00002321
2322 // We are going to insert code that relies on the fact that the callee
2323 // will become a non-readonly function after it is instrumented by us. To
2324 // prevent this code from being optimized out, mark that function
2325 // non-readonly in advance.
2326 if (Function *Func = Call->getCalledFunction()) {
2327 // Clear out readonly/readnone attributes.
2328 AttrBuilder B;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002329 B.addAttribute(Attribute::ReadOnly)
2330 .addAttribute(Attribute::ReadNone);
Bill Wendling430fa9b2013-01-23 00:45:55 +00002331 Func->removeAttributes(AttributeSet::FunctionIndex,
2332 AttributeSet::get(Func->getContext(),
2333 AttributeSet::FunctionIndex,
2334 B));
Evgeniy Stepanov383b61e2012-12-07 09:08:32 +00002335 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002336 }
2337 IRBuilder<> IRB(&I);
Evgeniy Stepanov37b86452013-09-19 15:22:35 +00002338
2339 if (MS.WrapIndirectCalls && !CS.getCalledFunction())
Evgeniy Stepanov585813e2013-11-14 12:29:04 +00002340 IndirectCallList.push_back(CS);
Evgeniy Stepanov37b86452013-09-19 15:22:35 +00002341
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002342 unsigned ArgOffset = 0;
2343 DEBUG(dbgs() << " CallSite: " << I << "\n");
2344 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
2345 ArgIt != End; ++ArgIt) {
2346 Value *A = *ArgIt;
2347 unsigned i = ArgIt - CS.arg_begin();
2348 if (!A->getType()->isSized()) {
2349 DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
2350 continue;
2351 }
2352 unsigned Size = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00002353 Value *Store = nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002354 // Compute the Shadow for arg even if it is ByVal, because
2355 // in that case getShadow() will copy the actual arg shadow to
2356 // __msan_param_tls.
2357 Value *ArgShadow = getShadow(A);
2358 Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
2359 DEBUG(dbgs() << " Arg#" << i << ": " << *A <<
2360 " Shadow: " << *ArgShadow << "\n");
Evgeniy Stepanovc8227aa2014-07-17 09:10:37 +00002361 bool ArgIsInitialized = false;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002362 if (CS.paramHasAttr(i + 1, Attribute::ByVal)) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002363 assert(A->getType()->isPointerTy() &&
2364 "ByVal argument is not a pointer!");
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002365 Size = MS.DL->getTypeAllocSize(A->getType()->getPointerElementType());
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +00002366 if (ArgOffset + Size > kParamTLSSize) break;
Evgeniy Stepanove08633e2014-10-17 23:29:44 +00002367 unsigned ParamAlignment = CS.getParamAlignment(i + 1);
2368 unsigned Alignment = std::min(ParamAlignment, kShadowTLSAlignment);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002369 Store = IRB.CreateMemCpy(ArgShadowBase,
2370 getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
2371 Size, Alignment);
2372 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002373 Size = MS.DL->getTypeAllocSize(A->getType());
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +00002374 if (ArgOffset + Size > kParamTLSSize) break;
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00002375 Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
2376 kShadowTLSAlignment);
Evgeniy Stepanovc8227aa2014-07-17 09:10:37 +00002377 Constant *Cst = dyn_cast<Constant>(ArgShadow);
2378 if (Cst && Cst->isNullValue()) ArgIsInitialized = true;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002379 }
Evgeniy Stepanovc8227aa2014-07-17 09:10:37 +00002380 if (MS.TrackOrigins && !ArgIsInitialized)
Evgeniy Stepanov49175b22012-12-14 13:43:11 +00002381 IRB.CreateStore(getOrigin(A),
2382 getOriginPtrForArgument(A, IRB, ArgOffset));
Edwin Vane82f80d42013-01-29 17:42:24 +00002383 (void)Store;
Craig Toppere73658d2014-04-28 04:05:08 +00002384 assert(Size != 0 && Store != nullptr);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002385 DEBUG(dbgs() << " Param:" << *Store << "\n");
David Majnemerf3cadce2014-10-20 06:13:33 +00002386 ArgOffset += RoundUpToAlignment(Size, 8);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002387 }
2388 DEBUG(dbgs() << " done with call args\n");
2389
2390 FunctionType *FT =
Evgeniy Stepanov37b86452013-09-19 15:22:35 +00002391 cast<FunctionType>(CS.getCalledValue()->getType()->getContainedType(0));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002392 if (FT->isVarArg()) {
2393 VAHelper->visitCallSite(CS, IRB);
2394 }
2395
2396 // Now, get the shadow for the RetVal.
2397 if (!I.getType()->isSized()) return;
2398 IRBuilder<> IRBBefore(&I);
Alp Tokercb402912014-01-24 17:20:08 +00002399 // Until we have full dynamic coverage, make sure the retval shadow is 0.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002400 Value *Base = getShadowPtrForRetval(&I, IRBBefore);
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00002401 IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
Craig Topperf40110f2014-04-25 05:29:35 +00002402 Instruction *NextInsn = nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002403 if (CS.isCall()) {
2404 NextInsn = I.getNextNode();
2405 } else {
2406 BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
2407 if (!NormalDest->getSinglePredecessor()) {
2408 // FIXME: this case is tricky, so we are just conservative here.
2409 // Perhaps we need to split the edge between this BB and NormalDest,
2410 // but a naive attempt to use SplitEdge leads to a crash.
2411 setShadow(&I, getCleanShadow(&I));
2412 setOrigin(&I, getCleanOrigin());
2413 return;
2414 }
2415 NextInsn = NormalDest->getFirstInsertionPt();
2416 assert(NextInsn &&
2417 "Could not find insertion point for retval shadow load");
2418 }
2419 IRBuilder<> IRBAfter(NextInsn);
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00002420 Value *RetvalShadow =
2421 IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
2422 kShadowTLSAlignment, "_msret");
2423 setShadow(&I, RetvalShadow);
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00002424 if (MS.TrackOrigins)
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002425 setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
2426 }
2427
2428 void visitReturnInst(ReturnInst &I) {
2429 IRBuilder<> IRB(&I);
Evgeniy Stepanov604293f2013-09-16 13:24:32 +00002430 Value *RetVal = I.getReturnValue();
2431 if (!RetVal) return;
2432 Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
2433 if (CheckReturnValue) {
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002434 insertShadowCheck(RetVal, &I);
Evgeniy Stepanov604293f2013-09-16 13:24:32 +00002435 Value *Shadow = getCleanShadow(RetVal);
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00002436 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
Evgeniy Stepanov604293f2013-09-16 13:24:32 +00002437 } else {
2438 Value *Shadow = getShadow(RetVal);
2439 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
2440 // FIXME: make it conditional if ClStoreCleanOrigin==0
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00002441 if (MS.TrackOrigins)
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002442 IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
2443 }
2444 }
2445
2446 void visitPHINode(PHINode &I) {
2447 IRBuilder<> IRB(&I);
Evgeniy Stepanovd948a5f2014-07-07 13:28:31 +00002448 if (!PropagateShadow) {
2449 setShadow(&I, getCleanShadow(&I));
2450 return;
2451 }
2452
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002453 ShadowPHINodes.push_back(&I);
2454 setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
2455 "_msphi_s"));
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00002456 if (MS.TrackOrigins)
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002457 setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
2458 "_msphi_o"));
2459 }
2460
2461 void visitAllocaInst(AllocaInst &I) {
2462 setShadow(&I, getCleanShadow(&I));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002463 IRBuilder<> IRB(I.getNextNode());
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002464 uint64_t Size = MS.DL->getTypeAllocSize(I.getAllocatedType());
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +00002465 if (PoisonStack && ClPoisonStackWithCall) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002466 IRB.CreateCall2(MS.MsanPoisonStackFn,
2467 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
2468 ConstantInt::get(MS.IntptrTy, Size));
2469 } else {
2470 Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +00002471 Value *PoisonValue = IRB.getInt8(PoisonStack ? ClPoisonStackPattern : 0);
2472 IRB.CreateMemSet(ShadowBase, PoisonValue, Size, I.getAlignment());
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002473 }
2474
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +00002475 if (PoisonStack && MS.TrackOrigins) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002476 setOrigin(&I, getCleanOrigin());
Alp Tokere69170a2014-06-26 22:52:05 +00002477 SmallString<2048> StackDescriptionStorage;
2478 raw_svector_ostream StackDescription(StackDescriptionStorage);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002479 // We create a string with a description of the stack allocation and
2480 // pass it into __msan_set_alloca_origin.
2481 // It will be printed by the run-time if stack-originated UMR is found.
2482 // The first 4 bytes of the string are set to '----' and will be replaced
2483 // by __msan_va_arg_overflow_size_tls at the first call.
2484 StackDescription << "----" << I.getName() << "@" << F.getName();
2485 Value *Descr =
2486 createPrivateNonConstGlobalForString(*F.getParent(),
2487 StackDescription.str());
Evgeniy Stepanov0435ecd2013-09-13 12:54:49 +00002488
2489 IRB.CreateCall4(MS.MsanSetAllocaOrigin4Fn,
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002490 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
2491 ConstantInt::get(MS.IntptrTy, Size),
Evgeniy Stepanov0435ecd2013-09-13 12:54:49 +00002492 IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()),
2493 IRB.CreatePointerCast(&F, MS.IntptrTy));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002494 }
2495 }
2496
2497 void visitSelectInst(SelectInst& I) {
2498 IRBuilder<> IRB(&I);
Evgeniy Stepanov566f5912013-09-03 10:04:11 +00002499 // a = select b, c, d
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002500 Value *B = I.getCondition();
2501 Value *C = I.getTrueValue();
2502 Value *D = I.getFalseValue();
2503 Value *Sb = getShadow(B);
2504 Value *Sc = getShadow(C);
2505 Value *Sd = getShadow(D);
2506
2507 // Result shadow if condition shadow is 0.
2508 Value *Sa0 = IRB.CreateSelect(B, Sc, Sd);
2509 Value *Sa1;
Evgeniy Stepanove95d37c2013-09-03 13:05:29 +00002510 if (I.getType()->isAggregateType()) {
2511 // To avoid "sign extending" i1 to an arbitrary aggregate type, we just do
2512 // an extra "select". This results in much more compact IR.
2513 // Sa = select Sb, poisoned, (select b, Sc, Sd)
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002514 Sa1 = getPoisonedShadow(getShadowTy(I.getType()));
Evgeniy Stepanove95d37c2013-09-03 13:05:29 +00002515 } else {
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002516 // Sa = select Sb, [ (c^d) | Sc | Sd ], [ b ? Sc : Sd ]
2517 // If Sb (condition is poisoned), look for bits in c and d that are equal
2518 // and both unpoisoned.
2519 // If !Sb (condition is unpoisoned), simply pick one of Sc and Sd.
2520
2521 // Cast arguments to shadow-compatible type.
2522 C = CreateAppToShadowCast(IRB, C);
2523 D = CreateAppToShadowCast(IRB, D);
2524
2525 // Result shadow if condition shadow is 1.
2526 Sa1 = IRB.CreateOr(IRB.CreateXor(C, D), IRB.CreateOr(Sc, Sd));
Evgeniy Stepanove95d37c2013-09-03 13:05:29 +00002527 }
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002528 Value *Sa = IRB.CreateSelect(Sb, Sa1, Sa0, "_msprop_select");
2529 setShadow(&I, Sa);
Evgeniy Stepanovec837122012-12-25 14:56:21 +00002530 if (MS.TrackOrigins) {
2531 // Origins are always i32, so any vector conditions must be flattened.
2532 // FIXME: consider tracking vector origins for app vectors?
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002533 if (B->getType()->isVectorTy()) {
2534 Type *FlatTy = getShadowTyNoVec(B->getType());
2535 B = IRB.CreateICmpNE(IRB.CreateBitCast(B, FlatTy),
Evgeniy Stepanovcb5bdff2013-11-21 12:00:24 +00002536 ConstantInt::getNullValue(FlatTy));
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002537 Sb = IRB.CreateICmpNE(IRB.CreateBitCast(Sb, FlatTy),
Evgeniy Stepanovcb5bdff2013-11-21 12:00:24 +00002538 ConstantInt::getNullValue(FlatTy));
Evgeniy Stepanovec837122012-12-25 14:56:21 +00002539 }
Evgeniy Stepanovcb5bdff2013-11-21 12:00:24 +00002540 // a = select b, c, d
2541 // Oa = Sb ? Ob : (b ? Oc : Od)
2542 setOrigin(&I, IRB.CreateSelect(
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002543 Sb, getOrigin(I.getCondition()),
2544 IRB.CreateSelect(B, getOrigin(C), getOrigin(D))));
Evgeniy Stepanovec837122012-12-25 14:56:21 +00002545 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002546 }
2547
2548 void visitLandingPadInst(LandingPadInst &I) {
2549 // Do nothing.
2550 // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
2551 setShadow(&I, getCleanShadow(&I));
2552 setOrigin(&I, getCleanOrigin());
2553 }
2554
2555 void visitGetElementPtrInst(GetElementPtrInst &I) {
2556 handleShadowOr(I);
2557 }
2558
2559 void visitExtractValueInst(ExtractValueInst &I) {
2560 IRBuilder<> IRB(&I);
2561 Value *Agg = I.getAggregateOperand();
2562 DEBUG(dbgs() << "ExtractValue: " << I << "\n");
2563 Value *AggShadow = getShadow(Agg);
2564 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
2565 Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
2566 DEBUG(dbgs() << " ResShadow: " << *ResShadow << "\n");
2567 setShadow(&I, ResShadow);
Evgeniy Stepanov560e08932013-11-11 13:37:10 +00002568 setOriginForNaryOp(I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002569 }
2570
2571 void visitInsertValueInst(InsertValueInst &I) {
2572 IRBuilder<> IRB(&I);
2573 DEBUG(dbgs() << "InsertValue: " << I << "\n");
2574 Value *AggShadow = getShadow(I.getAggregateOperand());
2575 Value *InsShadow = getShadow(I.getInsertedValueOperand());
2576 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
2577 DEBUG(dbgs() << " InsShadow: " << *InsShadow << "\n");
2578 Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
2579 DEBUG(dbgs() << " Res: " << *Res << "\n");
2580 setShadow(&I, Res);
Evgeniy Stepanov560e08932013-11-11 13:37:10 +00002581 setOriginForNaryOp(I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002582 }
2583
2584 void dumpInst(Instruction &I) {
2585 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
2586 errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
2587 } else {
2588 errs() << "ZZZ " << I.getOpcodeName() << "\n";
2589 }
2590 errs() << "QQQ " << I << "\n";
2591 }
2592
2593 void visitResumeInst(ResumeInst &I) {
2594 DEBUG(dbgs() << "Resume: " << I << "\n");
2595 // Nothing to do here.
2596 }
2597
2598 void visitInstruction(Instruction &I) {
2599 // Everything else: stop propagating and check for poisoned shadow.
2600 if (ClDumpStrictInstructions)
2601 dumpInst(I);
2602 DEBUG(dbgs() << "DEFAULT: " << I << "\n");
2603 for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002604 insertShadowCheck(I.getOperand(i), &I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002605 setShadow(&I, getCleanShadow(&I));
2606 setOrigin(&I, getCleanOrigin());
2607 }
2608};
2609
2610/// \brief AMD64-specific implementation of VarArgHelper.
2611struct VarArgAMD64Helper : public VarArgHelper {
2612 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
2613 // See a comment in visitCallSite for more details.
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +00002614 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002615 static const unsigned AMD64FpEndOffset = 176;
2616
2617 Function &F;
2618 MemorySanitizer &MS;
2619 MemorySanitizerVisitor &MSV;
2620 Value *VAArgTLSCopy;
2621 Value *VAArgOverflowSize;
2622
2623 SmallVector<CallInst*, 16> VAStartInstrumentationList;
2624
2625 VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
2626 MemorySanitizerVisitor &MSV)
Craig Topperf40110f2014-04-25 05:29:35 +00002627 : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(nullptr),
2628 VAArgOverflowSize(nullptr) {}
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002629
2630 enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
2631
2632 ArgKind classifyArgument(Value* arg) {
2633 // A very rough approximation of X86_64 argument classification rules.
2634 Type *T = arg->getType();
2635 if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
2636 return AK_FloatingPoint;
2637 if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
2638 return AK_GeneralPurpose;
2639 if (T->isPointerTy())
2640 return AK_GeneralPurpose;
2641 return AK_Memory;
2642 }
2643
2644 // For VarArg functions, store the argument shadow in an ABI-specific format
2645 // that corresponds to va_list layout.
2646 // We do this because Clang lowers va_arg in the frontend, and this pass
2647 // only sees the low level code that deals with va_list internals.
2648 // A much easier alternative (provided that Clang emits va_arg instructions)
2649 // would have been to associate each live instance of va_list with a copy of
2650 // MSanParamTLS, and extract shadow on va_arg() call in the argument list
2651 // order.
Craig Topper3e4c6972014-03-05 09:10:37 +00002652 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002653 unsigned GpOffset = 0;
2654 unsigned FpOffset = AMD64GpEndOffset;
2655 unsigned OverflowOffset = AMD64FpEndOffset;
2656 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
2657 ArgIt != End; ++ArgIt) {
2658 Value *A = *ArgIt;
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00002659 unsigned ArgNo = CS.getArgumentNo(ArgIt);
2660 bool IsByVal = CS.paramHasAttr(ArgNo + 1, Attribute::ByVal);
2661 if (IsByVal) {
2662 // ByVal arguments always go to the overflow area.
2663 assert(A->getType()->isPointerTy());
2664 Type *RealTy = A->getType()->getPointerElementType();
2665 uint64_t ArgSize = MS.DL->getTypeAllocSize(RealTy);
2666 Value *Base = getShadowPtrForVAArgument(RealTy, IRB, OverflowOffset);
David Majnemerf3cadce2014-10-20 06:13:33 +00002667 OverflowOffset += RoundUpToAlignment(ArgSize, 8);
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00002668 IRB.CreateMemCpy(Base, MSV.getShadowPtr(A, IRB.getInt8Ty(), IRB),
2669 ArgSize, kShadowTLSAlignment);
2670 } else {
2671 ArgKind AK = classifyArgument(A);
2672 if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
2673 AK = AK_Memory;
2674 if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
2675 AK = AK_Memory;
2676 Value *Base;
2677 switch (AK) {
2678 case AK_GeneralPurpose:
2679 Base = getShadowPtrForVAArgument(A->getType(), IRB, GpOffset);
2680 GpOffset += 8;
2681 break;
2682 case AK_FloatingPoint:
2683 Base = getShadowPtrForVAArgument(A->getType(), IRB, FpOffset);
2684 FpOffset += 16;
2685 break;
2686 case AK_Memory:
2687 uint64_t ArgSize = MS.DL->getTypeAllocSize(A->getType());
2688 Base = getShadowPtrForVAArgument(A->getType(), IRB, OverflowOffset);
David Majnemerf3cadce2014-10-20 06:13:33 +00002689 OverflowOffset += RoundUpToAlignment(ArgSize, 8);
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00002690 }
2691 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002692 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002693 }
2694 Constant *OverflowSize =
2695 ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
2696 IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
2697 }
2698
2699 /// \brief Compute the shadow address for a given va_arg.
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00002700 Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002701 int ArgOffset) {
2702 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
2703 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00002704 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002705 "_msarg");
2706 }
2707
Craig Topper3e4c6972014-03-05 09:10:37 +00002708 void visitVAStartInst(VAStartInst &I) override {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002709 IRBuilder<> IRB(&I);
2710 VAStartInstrumentationList.push_back(&I);
2711 Value *VAListTag = I.getArgOperand(0);
2712 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2713
2714 // Unpoison the whole __va_list_tag.
2715 // FIXME: magic ABI constants.
2716 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
Peter Collingbournef7d65c42013-01-10 22:36:33 +00002717 /* size */24, /* alignment */8, false);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002718 }
2719
Craig Topper3e4c6972014-03-05 09:10:37 +00002720 void visitVACopyInst(VACopyInst &I) override {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002721 IRBuilder<> IRB(&I);
2722 Value *VAListTag = I.getArgOperand(0);
2723 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2724
2725 // Unpoison the whole __va_list_tag.
2726 // FIXME: magic ABI constants.
2727 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
Peter Collingbournef7d65c42013-01-10 22:36:33 +00002728 /* size */24, /* alignment */8, false);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002729 }
2730
Craig Topper3e4c6972014-03-05 09:10:37 +00002731 void finalizeInstrumentation() override {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002732 assert(!VAArgOverflowSize && !VAArgTLSCopy &&
2733 "finalizeInstrumentation called twice");
2734 if (!VAStartInstrumentationList.empty()) {
2735 // If there is a va_start in this function, make a backup copy of
2736 // va_arg_tls somewhere in the function entry block.
2737 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
2738 VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
2739 Value *CopySize =
2740 IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
2741 VAArgOverflowSize);
2742 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
2743 IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
2744 }
2745
2746 // Instrument va_start.
2747 // Copy va_list shadow from the backup copy of the TLS contents.
2748 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
2749 CallInst *OrigInst = VAStartInstrumentationList[i];
2750 IRBuilder<> IRB(OrigInst->getNextNode());
2751 Value *VAListTag = OrigInst->getArgOperand(0);
2752
2753 Value *RegSaveAreaPtrPtr =
2754 IRB.CreateIntToPtr(
2755 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2756 ConstantInt::get(MS.IntptrTy, 16)),
2757 Type::getInt64PtrTy(*MS.C));
2758 Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
2759 Value *RegSaveAreaShadowPtr =
2760 MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
2761 IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy,
2762 AMD64FpEndOffset, 16);
2763
2764 Value *OverflowArgAreaPtrPtr =
2765 IRB.CreateIntToPtr(
2766 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2767 ConstantInt::get(MS.IntptrTy, 8)),
2768 Type::getInt64PtrTy(*MS.C));
2769 Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
2770 Value *OverflowArgAreaShadowPtr =
2771 MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
Evgeniy Stepanovd42863c2013-08-23 12:11:00 +00002772 Value *SrcPtr = IRB.CreateConstGEP1_32(VAArgTLSCopy, AMD64FpEndOffset);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002773 IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
2774 }
2775 }
2776};
2777
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00002778/// \brief A no-op implementation of VarArgHelper.
2779struct VarArgNoOpHelper : public VarArgHelper {
2780 VarArgNoOpHelper(Function &F, MemorySanitizer &MS,
2781 MemorySanitizerVisitor &MSV) {}
2782
Craig Topper3e4c6972014-03-05 09:10:37 +00002783 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {}
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00002784
Craig Topper3e4c6972014-03-05 09:10:37 +00002785 void visitVAStartInst(VAStartInst &I) override {}
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00002786
Craig Topper3e4c6972014-03-05 09:10:37 +00002787 void visitVACopyInst(VACopyInst &I) override {}
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00002788
Craig Topper3e4c6972014-03-05 09:10:37 +00002789 void finalizeInstrumentation() override {}
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00002790};
2791
2792VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002793 MemorySanitizerVisitor &Visitor) {
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00002794 // VarArg handling is only implemented on AMD64. False positives are possible
2795 // on other platforms.
2796 llvm::Triple TargetTriple(Func.getParent()->getTargetTriple());
2797 if (TargetTriple.getArch() == llvm::Triple::x86_64)
2798 return new VarArgAMD64Helper(Func, Msan, Visitor);
2799 else
2800 return new VarArgNoOpHelper(Func, Msan, Visitor);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002801}
2802
2803} // namespace
2804
2805bool MemorySanitizer::runOnFunction(Function &F) {
2806 MemorySanitizerVisitor Visitor(F, *this);
2807
2808 // Clear out readonly/readnone attributes.
2809 AttrBuilder B;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002810 B.addAttribute(Attribute::ReadOnly)
2811 .addAttribute(Attribute::ReadNone);
Bill Wendling430fa9b2013-01-23 00:45:55 +00002812 F.removeAttributes(AttributeSet::FunctionIndex,
2813 AttributeSet::get(F.getContext(),
2814 AttributeSet::FunctionIndex, B));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002815
2816 return Visitor.runOnFunction();
2817}