blob: 12612591de8a9a046e99c0a353241e1bc2e72d3e [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);
David Blaikiea92765c2014-11-14 00:41:42 +0000354 MsanPoisonStackFn =
355 M.getOrInsertFunction("__msan_poison_stack", IRB.getVoidTy(),
356 IRB.getInt8PtrTy(), IntptrTy, nullptr);
Evgeniy Stepanov302964e2014-03-18 13:30:56 +0000357 MsanChainOriginFn = M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000358 "__msan_chain_origin", IRB.getInt32Ty(), IRB.getInt32Ty(), nullptr);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000359 MemmoveFn = M.getOrInsertFunction(
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000360 "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000361 IRB.getInt8PtrTy(), IntptrTy, nullptr);
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +0000362 MemcpyFn = M.getOrInsertFunction(
363 "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000364 IntptrTy, nullptr);
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +0000365 MemsetFn = M.getOrInsertFunction(
366 "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000367 IntptrTy, nullptr);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000368
369 // Create globals.
370 RetvalTLS = new GlobalVariable(
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +0000371 M, ArrayType::get(IRB.getInt64Ty(), kRetvalTLSSize / 8), false,
Craig Topperf40110f2014-04-25 05:29:35 +0000372 GlobalVariable::ExternalLinkage, nullptr, "__msan_retval_tls", nullptr,
Evgeniy Stepanov1e764322013-05-16 09:14:05 +0000373 GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000374 RetvalOriginTLS = new GlobalVariable(
Craig Topperf40110f2014-04-25 05:29:35 +0000375 M, OriginTy, false, GlobalVariable::ExternalLinkage, nullptr,
376 "__msan_retval_origin_tls", nullptr, GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000377
378 ParamTLS = new GlobalVariable(
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +0000379 M, ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), false,
Craig Topperf40110f2014-04-25 05:29:35 +0000380 GlobalVariable::ExternalLinkage, nullptr, "__msan_param_tls", nullptr,
Evgeniy Stepanov1e764322013-05-16 09:14:05 +0000381 GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000382 ParamOriginTLS = new GlobalVariable(
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +0000383 M, ArrayType::get(OriginTy, kParamTLSSize / 4), false,
384 GlobalVariable::ExternalLinkage, nullptr, "__msan_param_origin_tls",
385 nullptr, GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000386
387 VAArgTLS = new GlobalVariable(
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +0000388 M, ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), false,
Craig Topperf40110f2014-04-25 05:29:35 +0000389 GlobalVariable::ExternalLinkage, nullptr, "__msan_va_arg_tls", nullptr,
Evgeniy Stepanov1e764322013-05-16 09:14:05 +0000390 GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000391 VAArgOverflowSizeTLS = new GlobalVariable(
Craig Topperf40110f2014-04-25 05:29:35 +0000392 M, IRB.getInt64Ty(), false, GlobalVariable::ExternalLinkage, nullptr,
393 "__msan_va_arg_overflow_size_tls", nullptr,
Evgeniy Stepanov1e764322013-05-16 09:14:05 +0000394 GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000395 OriginTLS = new GlobalVariable(
Craig Topperf40110f2014-04-25 05:29:35 +0000396 M, IRB.getInt32Ty(), false, GlobalVariable::ExternalLinkage, nullptr,
397 "__msan_origin_tls", nullptr, GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanov1d2da652012-11-29 12:30:18 +0000398
399 // We insert an empty inline asm after __msan_report* to avoid callback merge.
400 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
401 StringRef(""), StringRef(""),
402 /*hasSideEffects=*/true);
Evgeniy Stepanov37b86452013-09-19 15:22:35 +0000403
404 if (WrapIndirectCalls) {
405 AnyFunctionPtrTy =
406 PointerType::getUnqual(FunctionType::get(IRB.getVoidTy(), false));
407 IndirectCallWrapperFn = M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000408 ClWrapIndirectCalls, AnyFunctionPtrTy, AnyFunctionPtrTy, nullptr);
Evgeniy Stepanov37b86452013-09-19 15:22:35 +0000409 }
Evgeniy Stepanov585813e2013-11-14 12:29:04 +0000410
Evgeniy Stepanovc14fc422014-05-07 14:10:51 +0000411 if (WrapIndirectCalls && ClWrapIndirectCallsFast) {
Evgeniy Stepanov585813e2013-11-14 12:29:04 +0000412 MsandrModuleStart = new GlobalVariable(
413 M, IRB.getInt32Ty(), false, GlobalValue::ExternalLinkage,
Craig Topperf40110f2014-04-25 05:29:35 +0000414 nullptr, "__executable_start");
Evgeniy Stepanov585813e2013-11-14 12:29:04 +0000415 MsandrModuleStart->setVisibility(GlobalVariable::HiddenVisibility);
416 MsandrModuleEnd = new GlobalVariable(
417 M, IRB.getInt32Ty(), false, GlobalValue::ExternalLinkage,
Craig Topperf40110f2014-04-25 05:29:35 +0000418 nullptr, "_end");
Evgeniy Stepanov585813e2013-11-14 12:29:04 +0000419 MsandrModuleEnd->setVisibility(GlobalVariable::HiddenVisibility);
420 }
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000421}
422
423/// \brief Module-level initialization.
424///
425/// inserts a call to __msan_init to the module's constructor list.
426bool MemorySanitizer::doInitialization(Module &M) {
Rafael Espindola93512512014-02-25 17:30:31 +0000427 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
428 if (!DLP)
Evgeniy Stepanov119cb2e2014-04-23 12:51:32 +0000429 report_fatal_error("data layout missing");
Rafael Espindola93512512014-02-25 17:30:31 +0000430 DL = &DLP->getDataLayout();
431
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000432 C = &(M.getContext());
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000433 unsigned PtrSize = DL->getPointerSizeInBits(/* AddressSpace */0);
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000434 switch (PtrSize) {
435 case 64:
436 ShadowMask = kShadowMask64;
437 OriginOffset = kOriginOffset64;
438 break;
439 case 32:
440 ShadowMask = kShadowMask32;
441 OriginOffset = kOriginOffset32;
442 break;
443 default:
444 report_fatal_error("unsupported pointer size");
445 break;
446 }
447
448 IRBuilder<> IRB(*C);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000449 IntptrTy = IRB.getIntPtrTy(DL);
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000450 OriginTy = IRB.getInt32Ty();
451
452 ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000453 OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000);
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000454
455 // Insert a call to __msan_init/__msan_track_origins into the module's CTORs.
456 appendToGlobalCtors(M, cast<Function>(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000457 "__msan_init", IRB.getVoidTy(), nullptr)), 0);
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000458
Evgeniy Stepanov888385e2013-05-31 12:04:29 +0000459 if (TrackOrigins)
460 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
461 IRB.getInt32(TrackOrigins), "__msan_track_origins");
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000462
Evgeniy Stepanov888385e2013-05-31 12:04:29 +0000463 if (ClKeepGoing)
464 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
465 IRB.getInt32(ClKeepGoing), "__msan_keep_going");
Evgeniy Stepanovdcf6bcb2013-01-22 13:26:53 +0000466
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000467 return true;
468}
469
470namespace {
471
472/// \brief A helper class that handles instrumentation of VarArg
473/// functions on a particular platform.
474///
475/// Implementations are expected to insert the instrumentation
476/// necessary to propagate argument shadow through VarArg function
477/// calls. Visit* methods are called during an InstVisitor pass over
478/// the function, and should avoid creating new basic blocks. A new
479/// instance of this class is created for each instrumented function.
480struct VarArgHelper {
481 /// \brief Visit a CallSite.
482 virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0;
483
484 /// \brief Visit a va_start call.
485 virtual void visitVAStartInst(VAStartInst &I) = 0;
486
487 /// \brief Visit a va_copy call.
488 virtual void visitVACopyInst(VACopyInst &I) = 0;
489
490 /// \brief Finalize function instrumentation.
491 ///
492 /// This method is called after visiting all interesting (see above)
493 /// instructions in a function.
494 virtual void finalizeInstrumentation() = 0;
Evgeniy Stepanovda0072b2012-11-29 13:12:03 +0000495
496 virtual ~VarArgHelper() {}
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000497};
498
499struct MemorySanitizerVisitor;
500
501VarArgHelper*
502CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
503 MemorySanitizerVisitor &Visitor);
504
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000505unsigned TypeSizeToSizeIndex(unsigned TypeSize) {
506 if (TypeSize <= 8) return 0;
507 return Log2_32_Ceil(TypeSize / 8);
508}
509
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000510/// This class does all the work for a given function. Store and Load
511/// instructions store and load corresponding shadow and origin
512/// values. Most instructions propagate shadow from arguments to their
513/// return values. Certain instructions (most importantly, BranchInst)
514/// test their argument shadow and print reports (with a runtime call) if it's
515/// non-zero.
516struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
517 Function &F;
518 MemorySanitizer &MS;
519 SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
520 ValueMap<Value*, Value*> ShadowMap, OriginMap;
Ahmed Charles56440fd2014-03-06 05:51:42 +0000521 std::unique_ptr<VarArgHelper> VAHelper;
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +0000522
523 // The following flags disable parts of MSan instrumentation based on
524 // blacklist contents and command-line options.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000525 bool InsertChecks;
Evgeniy Stepanov174242c2014-07-03 11:56:30 +0000526 bool PropagateShadow;
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +0000527 bool PoisonStack;
528 bool PoisonUndef;
Evgeniy Stepanov604293f2013-09-16 13:24:32 +0000529 bool CheckReturnValue;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000530
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000531 struct ShadowOriginAndInsertPoint {
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +0000532 Value *Shadow;
533 Value *Origin;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000534 Instruction *OrigIns;
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +0000535 ShadowOriginAndInsertPoint(Value *S, Value *O, Instruction *I)
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000536 : Shadow(S), Origin(O), OrigIns(I) { }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000537 };
538 SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000539 SmallVector<Instruction*, 16> StoreList;
Evgeniy Stepanov585813e2013-11-14 12:29:04 +0000540 SmallVector<CallSite, 16> IndirectCallList;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000541
542 MemorySanitizerVisitor(Function &F, MemorySanitizer &MS)
Evgeniy Stepanov00062b42013-02-28 11:25:14 +0000543 : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)) {
Alexey Samsonov6d8bab82014-06-02 18:08:27 +0000544 bool SanitizeFunction = F.getAttributes().hasAttribute(
545 AttributeSet::FunctionIndex, Attribute::SanitizeMemory);
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +0000546 InsertChecks = SanitizeFunction;
Evgeniy Stepanov174242c2014-07-03 11:56:30 +0000547 PropagateShadow = SanitizeFunction;
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +0000548 PoisonStack = SanitizeFunction && ClPoisonStack;
549 PoisonUndef = SanitizeFunction && ClPoisonUndef;
Evgeniy Stepanov604293f2013-09-16 13:24:32 +0000550 // FIXME: Consider using SpecialCaseList to specify a list of functions that
551 // must always return fully initialized values. For now, we hardcode "main".
552 CheckReturnValue = SanitizeFunction && (F.getName() == "main");
Evgeniy Stepanov00062b42013-02-28 11:25:14 +0000553
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000554 DEBUG(if (!InsertChecks)
Evgeniy Stepanov00062b42013-02-28 11:25:14 +0000555 dbgs() << "MemorySanitizer is not inserting checks into '"
556 << F.getName() << "'\n");
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000557 }
558
Evgeniy Stepanov302964e2014-03-18 13:30:56 +0000559 Value *updateOrigin(Value *V, IRBuilder<> &IRB) {
560 if (MS.TrackOrigins <= 1) return V;
561 return IRB.CreateCall(MS.MsanChainOriginFn, V);
562 }
563
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000564 void storeOrigin(IRBuilder<> &IRB, Value *Addr, Value *Shadow, Value *Origin,
565 unsigned Alignment, bool AsCall) {
566 if (isa<StructType>(Shadow->getType())) {
567 IRB.CreateAlignedStore(updateOrigin(Origin, IRB), getOriginPtr(Addr, IRB),
568 Alignment);
569 } else {
570 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
571 // TODO(eugenis): handle non-zero constant shadow by inserting an
572 // unconditional check (can not simply fail compilation as this could
573 // be in the dead code).
Evgeniy Stepanov7db296e2014-10-23 01:05:46 +0000574 if (!ClCheckConstantShadow)
575 if (isa<Constant>(ConvertedShadow)) return;
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000576 unsigned TypeSizeInBits =
577 MS.DL->getTypeSizeInBits(ConvertedShadow->getType());
578 unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
579 if (AsCall && SizeIndex < kNumberOfAccessSizes) {
580 Value *Fn = MS.MaybeStoreOriginFn[SizeIndex];
581 Value *ConvertedShadow2 = IRB.CreateZExt(
582 ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
583 IRB.CreateCall3(Fn, ConvertedShadow2,
584 IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
Evgeniy Stepanovb163f022014-06-25 14:41:57 +0000585 Origin);
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000586 } else {
587 Value *Cmp = IRB.CreateICmpNE(
588 ConvertedShadow, getCleanShadow(ConvertedShadow), "_mscmp");
589 Instruction *CheckTerm = SplitBlockAndInsertIfThen(
590 Cmp, IRB.GetInsertPoint(), false, MS.OriginStoreWeights);
591 IRBuilder<> IRBNew(CheckTerm);
592 IRBNew.CreateAlignedStore(updateOrigin(Origin, IRBNew),
593 getOriginPtr(Addr, IRBNew), Alignment);
594 }
595 }
596 }
597
598 void materializeStores(bool InstrumentWithCalls) {
Alexey Samsonova02e6642014-05-29 18:40:48 +0000599 for (auto Inst : StoreList) {
600 StoreInst &SI = *dyn_cast<StoreInst>(Inst);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000601
Alexey Samsonova02e6642014-05-29 18:40:48 +0000602 IRBuilder<> IRB(&SI);
603 Value *Val = SI.getValueOperand();
604 Value *Addr = SI.getPointerOperand();
605 Value *Shadow = SI.isAtomic() ? getCleanShadow(Val) : getShadow(Val);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000606 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
607
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000608 StoreInst *NewSI =
Alexey Samsonova02e6642014-05-29 18:40:48 +0000609 IRB.CreateAlignedStore(Shadow, ShadowPtr, SI.getAlignment());
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000610 DEBUG(dbgs() << " STORE: " << *NewSI << "\n");
NAKAMURA Takumie0b1b462012-12-06 13:38:00 +0000611 (void)NewSI;
Evgeniy Stepanovc4415592013-01-22 12:30:52 +0000612
Alexey Samsonova02e6642014-05-29 18:40:48 +0000613 if (ClCheckAccessAddress) insertShadowCheck(Addr, &SI);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000614
Alexey Samsonova02e6642014-05-29 18:40:48 +0000615 if (SI.isAtomic()) SI.setOrdering(addReleaseOrdering(SI.getOrdering()));
Evgeniy Stepanov5522a702013-09-24 11:20:27 +0000616
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000617 if (MS.TrackOrigins) {
Alexey Samsonova02e6642014-05-29 18:40:48 +0000618 unsigned Alignment = std::max(kMinOriginAlignment, SI.getAlignment());
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000619 storeOrigin(IRB, Addr, Shadow, getOrigin(Val), Alignment,
620 InstrumentWithCalls);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000621 }
622 }
623 }
624
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000625 void materializeOneCheck(Instruction *OrigIns, Value *Shadow, Value *Origin,
626 bool AsCall) {
627 IRBuilder<> IRB(OrigIns);
628 DEBUG(dbgs() << " SHAD0 : " << *Shadow << "\n");
629 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
630 DEBUG(dbgs() << " SHAD1 : " << *ConvertedShadow << "\n");
Evgeniy Stepanov7db296e2014-10-23 01:05:46 +0000631 // See the comment in storeOrigin().
632 if (!ClCheckConstantShadow)
633 if (isa<Constant>(ConvertedShadow)) return;
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000634 unsigned TypeSizeInBits =
635 MS.DL->getTypeSizeInBits(ConvertedShadow->getType());
636 unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
637 if (AsCall && SizeIndex < kNumberOfAccessSizes) {
638 Value *Fn = MS.MaybeWarningFn[SizeIndex];
639 Value *ConvertedShadow2 =
640 IRB.CreateZExt(ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
641 IRB.CreateCall2(Fn, ConvertedShadow2, MS.TrackOrigins && Origin
642 ? Origin
643 : (Value *)IRB.getInt32(0));
644 } else {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000645 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
646 getCleanShadow(ConvertedShadow), "_mscmp");
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000647 Instruction *CheckTerm = SplitBlockAndInsertIfThen(
648 Cmp, OrigIns,
649 /* Unreachable */ !ClKeepGoing, MS.ColdCallWeights);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000650
651 IRB.SetInsertPoint(CheckTerm);
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000652 if (MS.TrackOrigins) {
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000653 IRB.CreateStore(Origin ? (Value *)Origin : (Value *)IRB.getInt32(0),
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000654 MS.OriginTLS);
655 }
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000656 IRB.CreateCall(MS.WarningFn);
Evgeniy Stepanov1d2da652012-11-29 12:30:18 +0000657 IRB.CreateCall(MS.EmptyAsm);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000658 DEBUG(dbgs() << " CHECK: " << *Cmp << "\n");
659 }
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000660 }
661
662 void materializeChecks(bool InstrumentWithCalls) {
Alexey Samsonova02e6642014-05-29 18:40:48 +0000663 for (const auto &ShadowData : InstrumentationList) {
664 Instruction *OrigIns = ShadowData.OrigIns;
665 Value *Shadow = ShadowData.Shadow;
666 Value *Origin = ShadowData.Origin;
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000667 materializeOneCheck(OrigIns, Shadow, Origin, InstrumentWithCalls);
668 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000669 DEBUG(dbgs() << "DONE:\n" << F);
670 }
671
Evgeniy Stepanov585813e2013-11-14 12:29:04 +0000672 void materializeIndirectCalls() {
Alexey Samsonova02e6642014-05-29 18:40:48 +0000673 for (auto &CS : IndirectCallList) {
Evgeniy Stepanov585813e2013-11-14 12:29:04 +0000674 Instruction *I = CS.getInstruction();
675 BasicBlock *B = I->getParent();
676 IRBuilder<> IRB(I);
677 Value *Fn0 = CS.getCalledValue();
678 Value *Fn = IRB.CreateBitCast(Fn0, MS.AnyFunctionPtrTy);
679
680 if (ClWrapIndirectCallsFast) {
681 // Check that call target is inside this module limits.
682 Value *Start =
683 IRB.CreateBitCast(MS.MsandrModuleStart, MS.AnyFunctionPtrTy);
684 Value *End = IRB.CreateBitCast(MS.MsandrModuleEnd, MS.AnyFunctionPtrTy);
685
686 Value *NotInThisModule = IRB.CreateOr(IRB.CreateICmpULT(Fn, Start),
687 IRB.CreateICmpUGE(Fn, End));
688
689 PHINode *NewFnPhi =
690 IRB.CreatePHI(Fn0->getType(), 2, "msandr.indirect_target");
691
692 Instruction *CheckTerm = SplitBlockAndInsertIfThen(
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000693 NotInThisModule, NewFnPhi,
Evgeniy Stepanov585813e2013-11-14 12:29:04 +0000694 /* Unreachable */ false, MS.ColdCallWeights);
695
696 IRB.SetInsertPoint(CheckTerm);
697 // Slow path: call wrapper function to possibly transform the call
698 // target.
699 Value *NewFn = IRB.CreateBitCast(
700 IRB.CreateCall(MS.IndirectCallWrapperFn, Fn), Fn0->getType());
701
702 NewFnPhi->addIncoming(Fn0, B);
703 NewFnPhi->addIncoming(NewFn, dyn_cast<Instruction>(NewFn)->getParent());
704 CS.setCalledFunction(NewFnPhi);
705 } else {
706 Value *NewFn = IRB.CreateBitCast(
707 IRB.CreateCall(MS.IndirectCallWrapperFn, Fn), Fn0->getType());
708 CS.setCalledFunction(NewFn);
709 }
710 }
711 }
712
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000713 /// \brief Add MemorySanitizer instrumentation to a function.
714 bool runOnFunction() {
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000715 MS.initializeCallbacks(*F.getParent());
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000716 if (!MS.DL) return false;
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +0000717
718 // In the presence of unreachable blocks, we may see Phi nodes with
719 // incoming nodes from such blocks. Since InstVisitor skips unreachable
720 // blocks, such nodes will not have any shadow value associated with them.
721 // It's easier to remove unreachable blocks than deal with missing shadow.
722 removeUnreachableBlocks(F);
723
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000724 // Iterate all BBs in depth-first order and create shadow instructions
725 // for all instructions (where applicable).
726 // For PHI nodes we create dummy shadow PHIs which will be finalized later.
David Blaikieceec2bd2014-04-11 01:50:01 +0000727 for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000728 visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000729
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000730
731 // Finalize PHI nodes.
Alexey Samsonova02e6642014-05-29 18:40:48 +0000732 for (PHINode *PN : ShadowPHINodes) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000733 PHINode *PNS = cast<PHINode>(getShadow(PN));
Craig Topperf40110f2014-04-25 05:29:35 +0000734 PHINode *PNO = MS.TrackOrigins ? cast<PHINode>(getOrigin(PN)) : nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000735 size_t NumValues = PN->getNumIncomingValues();
736 for (size_t v = 0; v < NumValues; v++) {
737 PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
Evgeniy Stepanov174242c2014-07-03 11:56:30 +0000738 if (PNO) PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000739 }
740 }
741
742 VAHelper->finalizeInstrumentation();
743
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000744 bool InstrumentWithCalls = ClInstrumentationWithCallThreshold >= 0 &&
745 InstrumentationList.size() + StoreList.size() >
746 (unsigned)ClInstrumentationWithCallThreshold;
747
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000748 // Delayed instrumentation of StoreInst.
Evgeniy Stepanov47ac9ba2012-12-06 11:58:59 +0000749 // This may add new checks to be inserted later.
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000750 materializeStores(InstrumentWithCalls);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000751
752 // Insert shadow value checks.
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000753 materializeChecks(InstrumentWithCalls);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000754
Evgeniy Stepanov585813e2013-11-14 12:29:04 +0000755 // Wrap indirect calls.
756 materializeIndirectCalls();
757
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000758 return true;
759 }
760
761 /// \brief Compute the shadow type that corresponds to a given Value.
762 Type *getShadowTy(Value *V) {
763 return getShadowTy(V->getType());
764 }
765
766 /// \brief Compute the shadow type that corresponds to a given Type.
767 Type *getShadowTy(Type *OrigTy) {
768 if (!OrigTy->isSized()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000769 return nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000770 }
771 // For integer type, shadow is the same as the original type.
772 // This may return weird-sized types like i1.
773 if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
774 return IT;
Evgeniy Stepanovf19c0862012-12-25 16:04:38 +0000775 if (VectorType *VT = dyn_cast<VectorType>(OrigTy)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000776 uint32_t EltSize = MS.DL->getTypeSizeInBits(VT->getElementType());
Evgeniy Stepanovf19c0862012-12-25 16:04:38 +0000777 return VectorType::get(IntegerType::get(*MS.C, EltSize),
778 VT->getNumElements());
779 }
Evgeniy Stepanov5997feb2014-07-31 11:02:27 +0000780 if (ArrayType *AT = dyn_cast<ArrayType>(OrigTy)) {
781 return ArrayType::get(getShadowTy(AT->getElementType()),
782 AT->getNumElements());
783 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000784 if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
785 SmallVector<Type*, 4> Elements;
786 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
787 Elements.push_back(getShadowTy(ST->getElementType(i)));
788 StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
789 DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
790 return Res;
791 }
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000792 uint32_t TypeSize = MS.DL->getTypeSizeInBits(OrigTy);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000793 return IntegerType::get(*MS.C, TypeSize);
794 }
795
796 /// \brief Flatten a vector type.
797 Type *getShadowTyNoVec(Type *ty) {
798 if (VectorType *vt = dyn_cast<VectorType>(ty))
799 return IntegerType::get(*MS.C, vt->getBitWidth());
800 return ty;
801 }
802
803 /// \brief Convert a shadow value to it's flattened variant.
804 Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
805 Type *Ty = V->getType();
806 Type *NoVecTy = getShadowTyNoVec(Ty);
807 if (Ty == NoVecTy) return V;
808 return IRB.CreateBitCast(V, NoVecTy);
809 }
810
811 /// \brief Compute the shadow address that corresponds to a given application
812 /// address.
813 ///
814 /// Shadow = Addr & ~ShadowMask.
815 Value *getShadowPtr(Value *Addr, Type *ShadowTy,
816 IRBuilder<> &IRB) {
817 Value *ShadowLong =
818 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
819 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
820 return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
821 }
822
823 /// \brief Compute the origin address that corresponds to a given application
824 /// address.
825 ///
826 /// OriginAddr = (ShadowAddr + OriginOffset) & ~3ULL
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000827 Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB) {
828 Value *ShadowLong =
829 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
Evgeniy Stepanov62ba6112012-11-29 13:43:05 +0000830 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000831 Value *Add =
832 IRB.CreateAdd(ShadowLong,
833 ConstantInt::get(MS.IntptrTy, MS.OriginOffset));
Evgeniy Stepanov62ba6112012-11-29 13:43:05 +0000834 Value *SecondAnd =
835 IRB.CreateAnd(Add, ConstantInt::get(MS.IntptrTy, ~3ULL));
836 return IRB.CreateIntToPtr(SecondAnd, PointerType::get(IRB.getInt32Ty(), 0));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000837 }
838
839 /// \brief Compute the shadow address for a given function argument.
840 ///
841 /// Shadow = ParamTLS+ArgOffset.
842 Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
843 int ArgOffset) {
844 Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
845 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
846 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
847 "_msarg");
848 }
849
850 /// \brief Compute the origin address for a given function argument.
851 Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
852 int ArgOffset) {
Craig Topperf40110f2014-04-25 05:29:35 +0000853 if (!MS.TrackOrigins) return nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000854 Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
855 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
856 return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
857 "_msarg_o");
858 }
859
860 /// \brief Compute the shadow address for a retval.
861 Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
862 Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy);
863 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
864 "_msret");
865 }
866
867 /// \brief Compute the origin address for a retval.
868 Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
869 // We keep a single origin for the entire retval. Might be too optimistic.
870 return MS.RetvalOriginTLS;
871 }
872
873 /// \brief Set SV to be the shadow value for V.
874 void setShadow(Value *V, Value *SV) {
875 assert(!ShadowMap.count(V) && "Values may only have one shadow");
Evgeniy Stepanov174242c2014-07-03 11:56:30 +0000876 ShadowMap[V] = PropagateShadow ? SV : getCleanShadow(V);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000877 }
878
879 /// \brief Set Origin to be the origin value for V.
880 void setOrigin(Value *V, Value *Origin) {
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000881 if (!MS.TrackOrigins) return;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000882 assert(!OriginMap.count(V) && "Values may only have one origin");
883 DEBUG(dbgs() << "ORIGIN: " << *V << " ==> " << *Origin << "\n");
884 OriginMap[V] = Origin;
885 }
886
887 /// \brief Create a clean shadow value for a given value.
888 ///
889 /// Clean shadow (all zeroes) means all bits of the value are defined
890 /// (initialized).
Evgeniy Stepanova9a962c2013-03-21 09:38:26 +0000891 Constant *getCleanShadow(Value *V) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000892 Type *ShadowTy = getShadowTy(V);
893 if (!ShadowTy)
Craig Topperf40110f2014-04-25 05:29:35 +0000894 return nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000895 return Constant::getNullValue(ShadowTy);
896 }
897
898 /// \brief Create a dirty shadow of a given shadow type.
899 Constant *getPoisonedShadow(Type *ShadowTy) {
900 assert(ShadowTy);
901 if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
902 return Constant::getAllOnesValue(ShadowTy);
Evgeniy Stepanov5997feb2014-07-31 11:02:27 +0000903 if (ArrayType *AT = dyn_cast<ArrayType>(ShadowTy)) {
904 SmallVector<Constant *, 4> Vals(AT->getNumElements(),
905 getPoisonedShadow(AT->getElementType()));
906 return ConstantArray::get(AT, Vals);
907 }
908 if (StructType *ST = dyn_cast<StructType>(ShadowTy)) {
909 SmallVector<Constant *, 4> Vals;
910 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
911 Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
912 return ConstantStruct::get(ST, Vals);
913 }
914 llvm_unreachable("Unexpected shadow type");
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000915 }
916
Evgeniy Stepanova9a962c2013-03-21 09:38:26 +0000917 /// \brief Create a dirty shadow for a given value.
918 Constant *getPoisonedShadow(Value *V) {
919 Type *ShadowTy = getShadowTy(V);
920 if (!ShadowTy)
Craig Topperf40110f2014-04-25 05:29:35 +0000921 return nullptr;
Evgeniy Stepanova9a962c2013-03-21 09:38:26 +0000922 return getPoisonedShadow(ShadowTy);
923 }
924
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000925 /// \brief Create a clean (zero) origin.
926 Value *getCleanOrigin() {
927 return Constant::getNullValue(MS.OriginTy);
928 }
929
930 /// \brief Get the shadow value for a given Value.
931 ///
932 /// This function either returns the value set earlier with setShadow,
933 /// or extracts if from ParamTLS (for function arguments).
934 Value *getShadow(Value *V) {
Evgeniy Stepanov174242c2014-07-03 11:56:30 +0000935 if (!PropagateShadow) return getCleanShadow(V);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000936 if (Instruction *I = dyn_cast<Instruction>(V)) {
937 // For instructions the shadow is already stored in the map.
938 Value *Shadow = ShadowMap[V];
939 if (!Shadow) {
940 DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +0000941 (void)I;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000942 assert(Shadow && "No shadow for a value");
943 }
944 return Shadow;
945 }
946 if (UndefValue *U = dyn_cast<UndefValue>(V)) {
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +0000947 Value *AllOnes = PoisonUndef ? getPoisonedShadow(V) : getCleanShadow(V);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000948 DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +0000949 (void)U;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000950 return AllOnes;
951 }
952 if (Argument *A = dyn_cast<Argument>(V)) {
953 // For arguments we compute the shadow on demand and store it in the map.
954 Value **ShadowPtr = &ShadowMap[V];
955 if (*ShadowPtr)
956 return *ShadowPtr;
957 Function *F = A->getParent();
958 IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI());
959 unsigned ArgOffset = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +0000960 for (auto &FArg : F->args()) {
961 if (!FArg.getType()->isSized()) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000962 DEBUG(dbgs() << "Arg is not sized\n");
963 continue;
964 }
Alexey Samsonova02e6642014-05-29 18:40:48 +0000965 unsigned Size = FArg.hasByValAttr()
966 ? MS.DL->getTypeAllocSize(FArg.getType()->getPointerElementType())
967 : MS.DL->getTypeAllocSize(FArg.getType());
968 if (A == &FArg) {
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +0000969 bool Overflow = ArgOffset + Size > kParamTLSSize;
Alexey Samsonova02e6642014-05-29 18:40:48 +0000970 Value *Base = getShadowPtrForArgument(&FArg, EntryIRB, ArgOffset);
971 if (FArg.hasByValAttr()) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000972 // ByVal pointer itself has clean shadow. We copy the actual
973 // argument shadow to the underlying memory.
Evgeniy Stepanovfca01232013-05-28 13:07:43 +0000974 // Figure out maximal valid memcpy alignment.
Alexey Samsonova02e6642014-05-29 18:40:48 +0000975 unsigned ArgAlign = FArg.getParamAlignment();
Evgeniy Stepanovfca01232013-05-28 13:07:43 +0000976 if (ArgAlign == 0) {
977 Type *EltType = A->getType()->getPointerElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000978 ArgAlign = MS.DL->getABITypeAlignment(EltType);
Evgeniy Stepanovfca01232013-05-28 13:07:43 +0000979 }
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +0000980 if (Overflow) {
981 // ParamTLS overflow.
982 EntryIRB.CreateMemSet(
983 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB),
984 Constant::getNullValue(EntryIRB.getInt8Ty()), Size, ArgAlign);
985 } else {
986 unsigned CopyAlign = std::min(ArgAlign, kShadowTLSAlignment);
987 Value *Cpy = EntryIRB.CreateMemCpy(
988 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB), Base, Size,
989 CopyAlign);
990 DEBUG(dbgs() << " ByValCpy: " << *Cpy << "\n");
991 (void)Cpy;
992 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000993 *ShadowPtr = getCleanShadow(V);
994 } else {
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +0000995 if (Overflow) {
996 // ParamTLS overflow.
997 *ShadowPtr = getCleanShadow(V);
998 } else {
999 *ShadowPtr =
1000 EntryIRB.CreateAlignedLoad(Base, kShadowTLSAlignment);
1001 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001002 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001003 DEBUG(dbgs() << " ARG: " << FArg << " ==> " <<
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001004 **ShadowPtr << "\n");
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +00001005 if (MS.TrackOrigins && !Overflow) {
Alexey Samsonova02e6642014-05-29 18:40:48 +00001006 Value *OriginPtr =
1007 getOriginPtrForArgument(&FArg, EntryIRB, ArgOffset);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001008 setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
1009 }
1010 }
David Majnemerf3cadce2014-10-20 06:13:33 +00001011 ArgOffset += RoundUpToAlignment(Size, kShadowTLSAlignment);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001012 }
1013 assert(*ShadowPtr && "Could not find shadow for an argument");
1014 return *ShadowPtr;
1015 }
1016 // For everything else the shadow is zero.
1017 return getCleanShadow(V);
1018 }
1019
1020 /// \brief Get the shadow for i-th argument of the instruction I.
1021 Value *getShadow(Instruction *I, int i) {
1022 return getShadow(I->getOperand(i));
1023 }
1024
1025 /// \brief Get the origin for a value.
1026 Value *getOrigin(Value *V) {
Craig Topperf40110f2014-04-25 05:29:35 +00001027 if (!MS.TrackOrigins) return nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001028 if (isa<Instruction>(V) || isa<Argument>(V)) {
1029 Value *Origin = OriginMap[V];
1030 if (!Origin) {
1031 DEBUG(dbgs() << "NO ORIGIN: " << *V << "\n");
1032 Origin = getCleanOrigin();
1033 }
1034 return Origin;
1035 }
1036 return getCleanOrigin();
1037 }
1038
1039 /// \brief Get the origin for i-th argument of the instruction I.
1040 Value *getOrigin(Instruction *I, int i) {
1041 return getOrigin(I->getOperand(i));
1042 }
1043
1044 /// \brief Remember the place where a shadow check should be inserted.
1045 ///
1046 /// This location will be later instrumented with a check that will print a
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001047 /// UMR warning in runtime if the shadow value is not 0.
1048 void insertShadowCheck(Value *Shadow, Value *Origin, Instruction *OrigIns) {
1049 assert(Shadow);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001050 if (!InsertChecks) return;
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +00001051#ifndef NDEBUG
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001052 Type *ShadowTy = Shadow->getType();
1053 assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
1054 "Can only insert checks for integer and vector shadow types");
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +00001055#endif
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001056 InstrumentationList.push_back(
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001057 ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
1058 }
1059
1060 /// \brief Remember the place where a shadow check should be inserted.
1061 ///
1062 /// This location will be later instrumented with a check that will print a
1063 /// UMR warning in runtime if the value is not fully defined.
1064 void insertShadowCheck(Value *Val, Instruction *OrigIns) {
1065 assert(Val);
Evgeniy Stepanovd337a592014-10-24 23:34:15 +00001066 Value *Shadow, *Origin;
1067 if (ClCheckConstantShadow) {
1068 Shadow = getShadow(Val);
1069 if (!Shadow) return;
1070 Origin = getOrigin(Val);
1071 } else {
1072 Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
1073 if (!Shadow) return;
1074 Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
1075 }
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001076 insertShadowCheck(Shadow, Origin, OrigIns);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001077 }
1078
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001079 AtomicOrdering addReleaseOrdering(AtomicOrdering a) {
1080 switch (a) {
1081 case NotAtomic:
1082 return NotAtomic;
1083 case Unordered:
1084 case Monotonic:
1085 case Release:
1086 return Release;
1087 case Acquire:
1088 case AcquireRelease:
1089 return AcquireRelease;
1090 case SequentiallyConsistent:
1091 return SequentiallyConsistent;
1092 }
Evgeniy Stepanov32be0342013-09-25 08:56:00 +00001093 llvm_unreachable("Unknown ordering");
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001094 }
1095
1096 AtomicOrdering addAcquireOrdering(AtomicOrdering a) {
1097 switch (a) {
1098 case NotAtomic:
1099 return NotAtomic;
1100 case Unordered:
1101 case Monotonic:
1102 case Acquire:
1103 return Acquire;
1104 case Release:
1105 case AcquireRelease:
1106 return AcquireRelease;
1107 case SequentiallyConsistent:
1108 return SequentiallyConsistent;
1109 }
Evgeniy Stepanov32be0342013-09-25 08:56:00 +00001110 llvm_unreachable("Unknown ordering");
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001111 }
1112
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +00001113 // ------------------- Visitors.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001114
1115 /// \brief Instrument LoadInst
1116 ///
1117 /// Loads the corresponding shadow and (optionally) origin.
1118 /// Optionally, checks that the load address is fully defined.
1119 void visitLoadInst(LoadInst &I) {
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +00001120 assert(I.getType()->isSized() && "Load type must have size");
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001121 IRBuilder<> IRB(I.getNextNode());
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001122 Type *ShadowTy = getShadowTy(&I);
1123 Value *Addr = I.getPointerOperand();
Evgeniy Stepanov174242c2014-07-03 11:56:30 +00001124 if (PropagateShadow) {
Evgeniy Stepanov00062b42013-02-28 11:25:14 +00001125 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1126 setShadow(&I,
1127 IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld"));
1128 } else {
1129 setShadow(&I, getCleanShadow(&I));
1130 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001131
1132 if (ClCheckAccessAddress)
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001133 insertShadowCheck(I.getPointerOperand(), &I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001134
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001135 if (I.isAtomic())
1136 I.setOrdering(addAcquireOrdering(I.getOrdering()));
1137
Evgeniy Stepanov5eb5bf82012-12-26 11:55:09 +00001138 if (MS.TrackOrigins) {
Evgeniy Stepanov174242c2014-07-03 11:56:30 +00001139 if (PropagateShadow) {
Evgeniy Stepanov00062b42013-02-28 11:25:14 +00001140 unsigned Alignment = std::max(kMinOriginAlignment, I.getAlignment());
1141 setOrigin(&I,
1142 IRB.CreateAlignedLoad(getOriginPtr(Addr, IRB), Alignment));
1143 } else {
1144 setOrigin(&I, getCleanOrigin());
1145 }
Evgeniy Stepanov5eb5bf82012-12-26 11:55:09 +00001146 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001147 }
1148
1149 /// \brief Instrument StoreInst
1150 ///
1151 /// Stores the corresponding shadow and (optionally) origin.
1152 /// Optionally, checks that the store address is fully defined.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001153 void visitStoreInst(StoreInst &I) {
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +00001154 StoreList.push_back(&I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001155 }
1156
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001157 void handleCASOrRMW(Instruction &I) {
1158 assert(isa<AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I));
1159
1160 IRBuilder<> IRB(&I);
1161 Value *Addr = I.getOperand(0);
1162 Value *ShadowPtr = getShadowPtr(Addr, I.getType(), IRB);
1163
1164 if (ClCheckAccessAddress)
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001165 insertShadowCheck(Addr, &I);
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001166
1167 // Only test the conditional argument of cmpxchg instruction.
1168 // The other argument can potentially be uninitialized, but we can not
1169 // detect this situation reliably without possible false positives.
1170 if (isa<AtomicCmpXchgInst>(I))
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001171 insertShadowCheck(I.getOperand(1), &I);
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001172
1173 IRB.CreateStore(getCleanShadow(&I), ShadowPtr);
1174
1175 setShadow(&I, getCleanShadow(&I));
1176 }
1177
1178 void visitAtomicRMWInst(AtomicRMWInst &I) {
1179 handleCASOrRMW(I);
1180 I.setOrdering(addReleaseOrdering(I.getOrdering()));
1181 }
1182
1183 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
1184 handleCASOrRMW(I);
Tim Northovere94a5182014-03-11 10:48:52 +00001185 I.setSuccessOrdering(addReleaseOrdering(I.getSuccessOrdering()));
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001186 }
1187
Evgeniy Stepanov30484fc2012-11-29 15:22:06 +00001188 // Vector manipulation.
1189 void visitExtractElementInst(ExtractElementInst &I) {
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001190 insertShadowCheck(I.getOperand(1), &I);
Evgeniy Stepanov30484fc2012-11-29 15:22:06 +00001191 IRBuilder<> IRB(&I);
1192 setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
1193 "_msprop"));
1194 setOrigin(&I, getOrigin(&I, 0));
1195 }
1196
1197 void visitInsertElementInst(InsertElementInst &I) {
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001198 insertShadowCheck(I.getOperand(2), &I);
Evgeniy Stepanov30484fc2012-11-29 15:22:06 +00001199 IRBuilder<> IRB(&I);
1200 setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
1201 I.getOperand(2), "_msprop"));
1202 setOriginForNaryOp(I);
1203 }
1204
1205 void visitShuffleVectorInst(ShuffleVectorInst &I) {
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001206 insertShadowCheck(I.getOperand(2), &I);
Evgeniy Stepanov30484fc2012-11-29 15:22:06 +00001207 IRBuilder<> IRB(&I);
1208 setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
1209 I.getOperand(2), "_msprop"));
1210 setOriginForNaryOp(I);
1211 }
1212
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001213 // Casts.
1214 void visitSExtInst(SExtInst &I) {
1215 IRBuilder<> IRB(&I);
1216 setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
1217 setOrigin(&I, getOrigin(&I, 0));
1218 }
1219
1220 void visitZExtInst(ZExtInst &I) {
1221 IRBuilder<> IRB(&I);
1222 setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
1223 setOrigin(&I, getOrigin(&I, 0));
1224 }
1225
1226 void visitTruncInst(TruncInst &I) {
1227 IRBuilder<> IRB(&I);
1228 setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
1229 setOrigin(&I, getOrigin(&I, 0));
1230 }
1231
1232 void visitBitCastInst(BitCastInst &I) {
1233 IRBuilder<> IRB(&I);
1234 setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
1235 setOrigin(&I, getOrigin(&I, 0));
1236 }
1237
1238 void visitPtrToIntInst(PtrToIntInst &I) {
1239 IRBuilder<> IRB(&I);
1240 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1241 "_msprop_ptrtoint"));
1242 setOrigin(&I, getOrigin(&I, 0));
1243 }
1244
1245 void visitIntToPtrInst(IntToPtrInst &I) {
1246 IRBuilder<> IRB(&I);
1247 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1248 "_msprop_inttoptr"));
1249 setOrigin(&I, getOrigin(&I, 0));
1250 }
1251
1252 void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
1253 void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
1254 void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
1255 void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
1256 void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
1257 void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
1258
1259 /// \brief Propagate shadow for bitwise AND.
1260 ///
1261 /// This code is exact, i.e. if, for example, a bit in the left argument
1262 /// is defined and 0, then neither the value not definedness of the
1263 /// corresponding bit in B don't affect the resulting shadow.
1264 void visitAnd(BinaryOperator &I) {
1265 IRBuilder<> IRB(&I);
1266 // "And" of 0 and a poisoned value results in unpoisoned value.
1267 // 1&1 => 1; 0&1 => 0; p&1 => p;
1268 // 1&0 => 0; 0&0 => 0; p&0 => 0;
1269 // 1&p => p; 0&p => 0; p&p => p;
1270 // S = (S1 & S2) | (V1 & S2) | (S1 & V2)
1271 Value *S1 = getShadow(&I, 0);
1272 Value *S2 = getShadow(&I, 1);
1273 Value *V1 = I.getOperand(0);
1274 Value *V2 = I.getOperand(1);
1275 if (V1->getType() != S1->getType()) {
1276 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1277 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1278 }
1279 Value *S1S2 = IRB.CreateAnd(S1, S2);
1280 Value *V1S2 = IRB.CreateAnd(V1, S2);
1281 Value *S1V2 = IRB.CreateAnd(S1, V2);
1282 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1283 setOriginForNaryOp(I);
1284 }
1285
1286 void visitOr(BinaryOperator &I) {
1287 IRBuilder<> IRB(&I);
1288 // "Or" of 1 and a poisoned value results in unpoisoned value.
1289 // 1|1 => 1; 0|1 => 1; p|1 => 1;
1290 // 1|0 => 1; 0|0 => 0; p|0 => p;
1291 // 1|p => 1; 0|p => p; p|p => p;
1292 // S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
1293 Value *S1 = getShadow(&I, 0);
1294 Value *S2 = getShadow(&I, 1);
1295 Value *V1 = IRB.CreateNot(I.getOperand(0));
1296 Value *V2 = IRB.CreateNot(I.getOperand(1));
1297 if (V1->getType() != S1->getType()) {
1298 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1299 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1300 }
1301 Value *S1S2 = IRB.CreateAnd(S1, S2);
1302 Value *V1S2 = IRB.CreateAnd(V1, S2);
1303 Value *S1V2 = IRB.CreateAnd(S1, V2);
1304 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1305 setOriginForNaryOp(I);
1306 }
1307
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001308 /// \brief Default propagation of shadow and/or origin.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001309 ///
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001310 /// This class implements the general case of shadow propagation, used in all
1311 /// cases where we don't know and/or don't care about what the operation
1312 /// actually does. It converts all input shadow values to a common type
1313 /// (extending or truncating as necessary), and bitwise OR's them.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001314 ///
1315 /// This is much cheaper than inserting checks (i.e. requiring inputs to be
1316 /// fully initialized), and less prone to false positives.
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001317 ///
1318 /// This class also implements the general case of origin propagation. For a
1319 /// Nary operation, result origin is set to the origin of an argument that is
1320 /// not entirely initialized. If there is more than one such arguments, the
1321 /// rightmost of them is picked. It does not matter which one is picked if all
1322 /// arguments are initialized.
1323 template <bool CombineShadow>
1324 class Combiner {
1325 Value *Shadow;
1326 Value *Origin;
1327 IRBuilder<> &IRB;
1328 MemorySanitizerVisitor *MSV;
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +00001329
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001330 public:
1331 Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB) :
Craig Topperf40110f2014-04-25 05:29:35 +00001332 Shadow(nullptr), Origin(nullptr), IRB(IRB), MSV(MSV) {}
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001333
1334 /// \brief Add a pair of shadow and origin values to the mix.
1335 Combiner &Add(Value *OpShadow, Value *OpOrigin) {
1336 if (CombineShadow) {
1337 assert(OpShadow);
1338 if (!Shadow)
1339 Shadow = OpShadow;
1340 else {
1341 OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
1342 Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
1343 }
1344 }
1345
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001346 if (MSV->MS.TrackOrigins) {
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001347 assert(OpOrigin);
1348 if (!Origin) {
1349 Origin = OpOrigin;
1350 } else {
Evgeniy Stepanov70d1b0a2014-06-09 14:29:34 +00001351 Constant *ConstOrigin = dyn_cast<Constant>(OpOrigin);
1352 // No point in adding something that might result in 0 origin value.
1353 if (!ConstOrigin || !ConstOrigin->isNullValue()) {
1354 Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB);
1355 Value *Cond =
1356 IRB.CreateICmpNE(FlatShadow, MSV->getCleanShadow(FlatShadow));
1357 Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
1358 }
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001359 }
1360 }
1361 return *this;
1362 }
1363
1364 /// \brief Add an application value to the mix.
1365 Combiner &Add(Value *V) {
1366 Value *OpShadow = MSV->getShadow(V);
Craig Topperf40110f2014-04-25 05:29:35 +00001367 Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : nullptr;
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001368 return Add(OpShadow, OpOrigin);
1369 }
1370
1371 /// \brief Set the current combined values as the given instruction's shadow
1372 /// and origin.
1373 void Done(Instruction *I) {
1374 if (CombineShadow) {
1375 assert(Shadow);
1376 Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
1377 MSV->setShadow(I, Shadow);
1378 }
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001379 if (MSV->MS.TrackOrigins) {
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001380 assert(Origin);
1381 MSV->setOrigin(I, Origin);
1382 }
1383 }
1384 };
1385
1386 typedef Combiner<true> ShadowAndOriginCombiner;
1387 typedef Combiner<false> OriginCombiner;
1388
1389 /// \brief Propagate origin for arbitrary operation.
1390 void setOriginForNaryOp(Instruction &I) {
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001391 if (!MS.TrackOrigins) return;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001392 IRBuilder<> IRB(&I);
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001393 OriginCombiner OC(this, IRB);
1394 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1395 OC.Add(OI->get());
1396 OC.Done(&I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001397 }
1398
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001399 size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
Evgeniy Stepanovf19c0862012-12-25 16:04:38 +00001400 assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) &&
1401 "Vector of pointers is not a valid shadow type");
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001402 return Ty->isVectorTy() ?
1403 Ty->getVectorNumElements() * Ty->getScalarSizeInBits() :
1404 Ty->getPrimitiveSizeInBits();
1405 }
1406
1407 /// \brief Cast between two shadow types, extending or truncating as
1408 /// necessary.
Evgeniy Stepanov21a9c932013-10-17 10:53:50 +00001409 Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy,
1410 bool Signed = false) {
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001411 Type *srcTy = V->getType();
1412 if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
Evgeniy Stepanov21a9c932013-10-17 10:53:50 +00001413 return IRB.CreateIntCast(V, dstTy, Signed);
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001414 if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
1415 dstTy->getVectorNumElements() == srcTy->getVectorNumElements())
Evgeniy Stepanov21a9c932013-10-17 10:53:50 +00001416 return IRB.CreateIntCast(V, dstTy, Signed);
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001417 size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
1418 size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
1419 Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
1420 Value *V2 =
Evgeniy Stepanov21a9c932013-10-17 10:53:50 +00001421 IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), Signed);
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001422 return IRB.CreateBitCast(V2, dstTy);
1423 // TODO: handle struct types.
1424 }
1425
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00001426 /// \brief Cast an application value to the type of its own shadow.
1427 Value *CreateAppToShadowCast(IRBuilder<> &IRB, Value *V) {
1428 Type *ShadowTy = getShadowTy(V);
1429 if (V->getType() == ShadowTy)
1430 return V;
1431 if (V->getType()->isPtrOrPtrVectorTy())
1432 return IRB.CreatePtrToInt(V, ShadowTy);
1433 else
1434 return IRB.CreateBitCast(V, ShadowTy);
1435 }
1436
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001437 /// \brief Propagate shadow for arbitrary operation.
1438 void handleShadowOr(Instruction &I) {
1439 IRBuilder<> IRB(&I);
1440 ShadowAndOriginCombiner SC(this, IRB);
1441 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1442 SC.Add(OI->get());
1443 SC.Done(&I);
1444 }
1445
Evgeniy Stepanovdf187fe2014-06-17 09:23:12 +00001446 // \brief Handle multiplication by constant.
1447 //
1448 // Handle a special case of multiplication by constant that may have one or
1449 // more zeros in the lower bits. This makes corresponding number of lower bits
1450 // of the result zero as well. We model it by shifting the other operand
1451 // shadow left by the required number of bits. Effectively, we transform
1452 // (X * (A * 2**B)) to ((X << B) * A) and instrument (X << B) as (Sx << B).
1453 // We use multiplication by 2**N instead of shift to cover the case of
1454 // multiplication by 0, which may occur in some elements of a vector operand.
1455 void handleMulByConstant(BinaryOperator &I, Constant *ConstArg,
1456 Value *OtherArg) {
1457 Constant *ShadowMul;
1458 Type *Ty = ConstArg->getType();
1459 if (Ty->isVectorTy()) {
1460 unsigned NumElements = Ty->getVectorNumElements();
1461 Type *EltTy = Ty->getSequentialElementType();
1462 SmallVector<Constant *, 16> Elements;
1463 for (unsigned Idx = 0; Idx < NumElements; ++Idx) {
1464 ConstantInt *Elt =
1465 dyn_cast<ConstantInt>(ConstArg->getAggregateElement(Idx));
1466 APInt V = Elt->getValue();
1467 APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
1468 Elements.push_back(ConstantInt::get(EltTy, V2));
1469 }
1470 ShadowMul = ConstantVector::get(Elements);
1471 } else {
1472 ConstantInt *Elt = dyn_cast<ConstantInt>(ConstArg);
1473 APInt V = Elt->getValue();
1474 APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
1475 ShadowMul = ConstantInt::get(Elt->getType(), V2);
1476 }
1477
1478 IRBuilder<> IRB(&I);
1479 setShadow(&I,
1480 IRB.CreateMul(getShadow(OtherArg), ShadowMul, "msprop_mul_cst"));
1481 setOrigin(&I, getOrigin(OtherArg));
1482 }
1483
1484 void visitMul(BinaryOperator &I) {
1485 Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1486 Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
1487 if (constOp0 && !constOp1)
1488 handleMulByConstant(I, constOp0, I.getOperand(1));
1489 else if (constOp1 && !constOp0)
1490 handleMulByConstant(I, constOp1, I.getOperand(0));
1491 else
1492 handleShadowOr(I);
1493 }
1494
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001495 void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
1496 void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
1497 void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
1498 void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
1499 void visitSub(BinaryOperator &I) { handleShadowOr(I); }
1500 void visitXor(BinaryOperator &I) { handleShadowOr(I); }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001501
1502 void handleDiv(Instruction &I) {
1503 IRBuilder<> IRB(&I);
1504 // Strict on the second argument.
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001505 insertShadowCheck(I.getOperand(1), &I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001506 setShadow(&I, getShadow(&I, 0));
1507 setOrigin(&I, getOrigin(&I, 0));
1508 }
1509
1510 void visitUDiv(BinaryOperator &I) { handleDiv(I); }
1511 void visitSDiv(BinaryOperator &I) { handleDiv(I); }
1512 void visitFDiv(BinaryOperator &I) { handleDiv(I); }
1513 void visitURem(BinaryOperator &I) { handleDiv(I); }
1514 void visitSRem(BinaryOperator &I) { handleDiv(I); }
1515 void visitFRem(BinaryOperator &I) { handleDiv(I); }
1516
1517 /// \brief Instrument == and != comparisons.
1518 ///
1519 /// Sometimes the comparison result is known even if some of the bits of the
1520 /// arguments are not.
1521 void handleEqualityComparison(ICmpInst &I) {
1522 IRBuilder<> IRB(&I);
1523 Value *A = I.getOperand(0);
1524 Value *B = I.getOperand(1);
1525 Value *Sa = getShadow(A);
1526 Value *Sb = getShadow(B);
Evgeniy Stepanovd14e47b2013-01-15 16:44:52 +00001527
1528 // Get rid of pointers and vectors of pointers.
1529 // For ints (and vectors of ints), types of A and Sa match,
1530 // and this is a no-op.
1531 A = IRB.CreatePointerCast(A, Sa->getType());
1532 B = IRB.CreatePointerCast(B, Sb->getType());
1533
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001534 // A == B <==> (C = A^B) == 0
1535 // A != B <==> (C = A^B) != 0
1536 // Sc = Sa | Sb
1537 Value *C = IRB.CreateXor(A, B);
1538 Value *Sc = IRB.CreateOr(Sa, Sb);
1539 // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
1540 // Result is defined if one of the following is true
1541 // * there is a defined 1 bit in C
1542 // * C is fully defined
1543 // Si = !(C & ~Sc) && Sc
1544 Value *Zero = Constant::getNullValue(Sc->getType());
1545 Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
1546 Value *Si =
1547 IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
1548 IRB.CreateICmpEQ(
1549 IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
1550 Si->setName("_msprop_icmp");
1551 setShadow(&I, Si);
1552 setOriginForNaryOp(I);
1553 }
1554
Evgeniy Stepanovfac84032013-01-25 15:31:10 +00001555 /// \brief Build the lowest possible value of V, taking into account V's
1556 /// uninitialized bits.
1557 Value *getLowestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1558 bool isSigned) {
1559 if (isSigned) {
1560 // Split shadow into sign bit and other bits.
1561 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1562 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1563 // Maximise the undefined shadow bit, minimize other undefined bits.
1564 return
1565 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaOtherBits)), SaSignBit);
1566 } else {
1567 // Minimize undefined bits.
1568 return IRB.CreateAnd(A, IRB.CreateNot(Sa));
1569 }
1570 }
1571
1572 /// \brief Build the highest possible value of V, taking into account V's
1573 /// uninitialized bits.
1574 Value *getHighestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1575 bool isSigned) {
1576 if (isSigned) {
1577 // Split shadow into sign bit and other bits.
1578 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1579 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1580 // Minimise the undefined shadow bit, maximise other undefined bits.
1581 return
1582 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaSignBit)), SaOtherBits);
1583 } else {
1584 // Maximize undefined bits.
1585 return IRB.CreateOr(A, Sa);
1586 }
1587 }
1588
1589 /// \brief Instrument relational comparisons.
1590 ///
1591 /// This function does exact shadow propagation for all relational
1592 /// comparisons of integers, pointers and vectors of those.
1593 /// FIXME: output seems suboptimal when one of the operands is a constant
1594 void handleRelationalComparisonExact(ICmpInst &I) {
1595 IRBuilder<> IRB(&I);
1596 Value *A = I.getOperand(0);
1597 Value *B = I.getOperand(1);
1598 Value *Sa = getShadow(A);
1599 Value *Sb = getShadow(B);
1600
1601 // Get rid of pointers and vectors of pointers.
1602 // For ints (and vectors of ints), types of A and Sa match,
1603 // and this is a no-op.
1604 A = IRB.CreatePointerCast(A, Sa->getType());
1605 B = IRB.CreatePointerCast(B, Sb->getType());
1606
Evgeniy Stepanov2cb0fa12013-01-25 15:35:29 +00001607 // Let [a0, a1] be the interval of possible values of A, taking into account
1608 // its undefined bits. Let [b0, b1] be the interval of possible values of B.
1609 // Then (A cmp B) is defined iff (a0 cmp b1) == (a1 cmp b0).
Evgeniy Stepanovfac84032013-01-25 15:31:10 +00001610 bool IsSigned = I.isSigned();
1611 Value *S1 = IRB.CreateICmp(I.getPredicate(),
1612 getLowestPossibleValue(IRB, A, Sa, IsSigned),
1613 getHighestPossibleValue(IRB, B, Sb, IsSigned));
1614 Value *S2 = IRB.CreateICmp(I.getPredicate(),
1615 getHighestPossibleValue(IRB, A, Sa, IsSigned),
1616 getLowestPossibleValue(IRB, B, Sb, IsSigned));
1617 Value *Si = IRB.CreateXor(S1, S2);
1618 setShadow(&I, Si);
1619 setOriginForNaryOp(I);
1620 }
1621
Evgeniy Stepanov857d9d22012-11-29 14:25:47 +00001622 /// \brief Instrument signed relational comparisons.
1623 ///
1624 /// Handle (x<0) and (x>=0) comparisons (essentially, sign bit tests) by
1625 /// propagating the highest bit of the shadow. Everything else is delegated
1626 /// to handleShadowOr().
1627 void handleSignedRelationalComparison(ICmpInst &I) {
1628 Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1629 Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
Craig Topperf40110f2014-04-25 05:29:35 +00001630 Value* op = nullptr;
Evgeniy Stepanov857d9d22012-11-29 14:25:47 +00001631 CmpInst::Predicate pre = I.getPredicate();
1632 if (constOp0 && constOp0->isNullValue() &&
1633 (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE)) {
1634 op = I.getOperand(1);
1635 } else if (constOp1 && constOp1->isNullValue() &&
1636 (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) {
1637 op = I.getOperand(0);
1638 }
1639 if (op) {
1640 IRBuilder<> IRB(&I);
1641 Value* Shadow =
1642 IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op), "_msprop_icmpslt");
1643 setShadow(&I, Shadow);
1644 setOrigin(&I, getOrigin(op));
1645 } else {
1646 handleShadowOr(I);
1647 }
1648 }
1649
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001650 void visitICmpInst(ICmpInst &I) {
Evgeniy Stepanov6f85ef32013-01-28 11:42:28 +00001651 if (!ClHandleICmp) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001652 handleShadowOr(I);
Evgeniy Stepanov6f85ef32013-01-28 11:42:28 +00001653 return;
1654 }
1655 if (I.isEquality()) {
1656 handleEqualityComparison(I);
1657 return;
1658 }
1659
1660 assert(I.isRelational());
1661 if (ClHandleICmpExact) {
1662 handleRelationalComparisonExact(I);
1663 return;
1664 }
1665 if (I.isSigned()) {
1666 handleSignedRelationalComparison(I);
1667 return;
1668 }
1669
1670 assert(I.isUnsigned());
1671 if ((isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
1672 handleRelationalComparisonExact(I);
1673 return;
1674 }
1675
1676 handleShadowOr(I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001677 }
1678
1679 void visitFCmpInst(FCmpInst &I) {
1680 handleShadowOr(I);
1681 }
1682
1683 void handleShift(BinaryOperator &I) {
1684 IRBuilder<> IRB(&I);
1685 // If any of the S2 bits are poisoned, the whole thing is poisoned.
1686 // Otherwise perform the same shift on S1.
1687 Value *S1 = getShadow(&I, 0);
1688 Value *S2 = getShadow(&I, 1);
1689 Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
1690 S2->getType());
1691 Value *V2 = I.getOperand(1);
1692 Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
1693 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1694 setOriginForNaryOp(I);
1695 }
1696
1697 void visitShl(BinaryOperator &I) { handleShift(I); }
1698 void visitAShr(BinaryOperator &I) { handleShift(I); }
1699 void visitLShr(BinaryOperator &I) { handleShift(I); }
1700
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001701 /// \brief Instrument llvm.memmove
1702 ///
1703 /// At this point we don't know if llvm.memmove will be inlined or not.
1704 /// If we don't instrument it and it gets inlined,
1705 /// our interceptor will not kick in and we will lose the memmove.
1706 /// If we instrument the call here, but it does not get inlined,
1707 /// we will memove the shadow twice: which is bad in case
1708 /// of overlapping regions. So, we simply lower the intrinsic to a call.
1709 ///
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +00001710 /// Similar situation exists for memcpy and memset.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001711 void visitMemMoveInst(MemMoveInst &I) {
1712 IRBuilder<> IRB(&I);
1713 IRB.CreateCall3(
1714 MS.MemmoveFn,
1715 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1716 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1717 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1718 I.eraseFromParent();
1719 }
1720
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +00001721 // Similar to memmove: avoid copying shadow twice.
1722 // This is somewhat unfortunate as it may slowdown small constant memcpys.
1723 // FIXME: consider doing manual inline for small constant sizes and proper
1724 // alignment.
1725 void visitMemCpyInst(MemCpyInst &I) {
1726 IRBuilder<> IRB(&I);
1727 IRB.CreateCall3(
1728 MS.MemcpyFn,
1729 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1730 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1731 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1732 I.eraseFromParent();
1733 }
1734
1735 // Same as memcpy.
1736 void visitMemSetInst(MemSetInst &I) {
1737 IRBuilder<> IRB(&I);
1738 IRB.CreateCall3(
1739 MS.MemsetFn,
1740 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1741 IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
1742 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1743 I.eraseFromParent();
1744 }
1745
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001746 void visitVAStartInst(VAStartInst &I) {
1747 VAHelper->visitVAStartInst(I);
1748 }
1749
1750 void visitVACopyInst(VACopyInst &I) {
1751 VAHelper->visitVACopyInst(I);
1752 }
1753
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001754 enum IntrinsicKind {
1755 IK_DoesNotAccessMemory,
1756 IK_OnlyReadsMemory,
1757 IK_WritesMemory
1758 };
1759
1760 static IntrinsicKind getIntrinsicKind(Intrinsic::ID iid) {
1761 const int DoesNotAccessMemory = IK_DoesNotAccessMemory;
1762 const int OnlyReadsArgumentPointees = IK_OnlyReadsMemory;
1763 const int OnlyReadsMemory = IK_OnlyReadsMemory;
1764 const int OnlyAccessesArgumentPointees = IK_WritesMemory;
1765 const int UnknownModRefBehavior = IK_WritesMemory;
1766#define GET_INTRINSIC_MODREF_BEHAVIOR
1767#define ModRefBehavior IntrinsicKind
Chandler Carruthdb25c6c2013-01-02 12:09:16 +00001768#include "llvm/IR/Intrinsics.gen"
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001769#undef ModRefBehavior
1770#undef GET_INTRINSIC_MODREF_BEHAVIOR
1771 }
1772
1773 /// \brief Handle vector store-like intrinsics.
1774 ///
1775 /// Instrument intrinsics that look like a simple SIMD store: writes memory,
1776 /// has 1 pointer argument and 1 vector argument, returns void.
1777 bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
1778 IRBuilder<> IRB(&I);
1779 Value* Addr = I.getArgOperand(0);
1780 Value *Shadow = getShadow(&I, 1);
1781 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
1782
1783 // We don't know the pointer alignment (could be unaligned SSE store!).
1784 // Have to assume to worst case.
1785 IRB.CreateAlignedStore(Shadow, ShadowPtr, 1);
1786
1787 if (ClCheckAccessAddress)
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001788 insertShadowCheck(Addr, &I);
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001789
1790 // FIXME: use ClStoreCleanOrigin
1791 // FIXME: factor out common code from materializeStores
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001792 if (MS.TrackOrigins)
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001793 IRB.CreateStore(getOrigin(&I, 1), getOriginPtr(Addr, IRB));
1794 return true;
1795 }
1796
1797 /// \brief Handle vector load-like intrinsics.
1798 ///
1799 /// Instrument intrinsics that look like a simple SIMD load: reads memory,
1800 /// has 1 pointer argument, returns a vector.
1801 bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
1802 IRBuilder<> IRB(&I);
1803 Value *Addr = I.getArgOperand(0);
1804
1805 Type *ShadowTy = getShadowTy(&I);
Evgeniy Stepanov174242c2014-07-03 11:56:30 +00001806 if (PropagateShadow) {
Evgeniy Stepanov00062b42013-02-28 11:25:14 +00001807 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1808 // We don't know the pointer alignment (could be unaligned SSE load!).
1809 // Have to assume to worst case.
1810 setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, 1, "_msld"));
1811 } else {
1812 setShadow(&I, getCleanShadow(&I));
1813 }
1814
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001815 if (ClCheckAccessAddress)
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001816 insertShadowCheck(Addr, &I);
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001817
Evgeniy Stepanov00062b42013-02-28 11:25:14 +00001818 if (MS.TrackOrigins) {
Evgeniy Stepanov174242c2014-07-03 11:56:30 +00001819 if (PropagateShadow)
Evgeniy Stepanov00062b42013-02-28 11:25:14 +00001820 setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB)));
1821 else
1822 setOrigin(&I, getCleanOrigin());
1823 }
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001824 return true;
1825 }
1826
1827 /// \brief Handle (SIMD arithmetic)-like intrinsics.
1828 ///
1829 /// Instrument intrinsics with any number of arguments of the same type,
1830 /// equal to the return type. The type should be simple (no aggregates or
1831 /// pointers; vectors are fine).
1832 /// Caller guarantees that this intrinsic does not access memory.
1833 bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) {
1834 Type *RetTy = I.getType();
1835 if (!(RetTy->isIntOrIntVectorTy() ||
1836 RetTy->isFPOrFPVectorTy() ||
1837 RetTy->isX86_MMXTy()))
1838 return false;
1839
1840 unsigned NumArgOperands = I.getNumArgOperands();
1841
1842 for (unsigned i = 0; i < NumArgOperands; ++i) {
1843 Type *Ty = I.getArgOperand(i)->getType();
1844 if (Ty != RetTy)
1845 return false;
1846 }
1847
1848 IRBuilder<> IRB(&I);
1849 ShadowAndOriginCombiner SC(this, IRB);
1850 for (unsigned i = 0; i < NumArgOperands; ++i)
1851 SC.Add(I.getArgOperand(i));
1852 SC.Done(&I);
1853
1854 return true;
1855 }
1856
1857 /// \brief Heuristically instrument unknown intrinsics.
1858 ///
1859 /// The main purpose of this code is to do something reasonable with all
1860 /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
1861 /// We recognize several classes of intrinsics by their argument types and
1862 /// ModRefBehaviour and apply special intrumentation when we are reasonably
1863 /// sure that we know what the intrinsic does.
1864 ///
1865 /// We special-case intrinsics where this approach fails. See llvm.bswap
1866 /// handling as an example of that.
1867 bool handleUnknownIntrinsic(IntrinsicInst &I) {
1868 unsigned NumArgOperands = I.getNumArgOperands();
1869 if (NumArgOperands == 0)
1870 return false;
1871
1872 Intrinsic::ID iid = I.getIntrinsicID();
1873 IntrinsicKind IK = getIntrinsicKind(iid);
1874 bool OnlyReadsMemory = IK == IK_OnlyReadsMemory;
1875 bool WritesMemory = IK == IK_WritesMemory;
1876 assert(!(OnlyReadsMemory && WritesMemory));
1877
1878 if (NumArgOperands == 2 &&
1879 I.getArgOperand(0)->getType()->isPointerTy() &&
1880 I.getArgOperand(1)->getType()->isVectorTy() &&
1881 I.getType()->isVoidTy() &&
1882 WritesMemory) {
1883 // This looks like a vector store.
1884 return handleVectorStoreIntrinsic(I);
1885 }
1886
1887 if (NumArgOperands == 1 &&
1888 I.getArgOperand(0)->getType()->isPointerTy() &&
1889 I.getType()->isVectorTy() &&
1890 OnlyReadsMemory) {
1891 // This looks like a vector load.
1892 return handleVectorLoadIntrinsic(I);
1893 }
1894
1895 if (!OnlyReadsMemory && !WritesMemory)
1896 if (maybeHandleSimpleNomemIntrinsic(I))
1897 return true;
1898
1899 // FIXME: detect and handle SSE maskstore/maskload
1900 return false;
1901 }
1902
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00001903 void handleBswap(IntrinsicInst &I) {
1904 IRBuilder<> IRB(&I);
1905 Value *Op = I.getArgOperand(0);
1906 Type *OpType = Op->getType();
1907 Function *BswapFunc = Intrinsic::getDeclaration(
Craig Toppere1d12942014-08-27 05:25:25 +00001908 F.getParent(), Intrinsic::bswap, makeArrayRef(&OpType, 1));
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00001909 setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
1910 setOrigin(&I, getOrigin(Op));
1911 }
1912
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001913 // \brief Instrument vector convert instrinsic.
1914 //
1915 // This function instruments intrinsics like cvtsi2ss:
1916 // %Out = int_xxx_cvtyyy(%ConvertOp)
1917 // or
1918 // %Out = int_xxx_cvtyyy(%CopyOp, %ConvertOp)
1919 // Intrinsic converts \p NumUsedElements elements of \p ConvertOp to the same
1920 // number \p Out elements, and (if has 2 arguments) copies the rest of the
1921 // elements from \p CopyOp.
1922 // In most cases conversion involves floating-point value which may trigger a
1923 // hardware exception when not fully initialized. For this reason we require
1924 // \p ConvertOp[0:NumUsedElements] to be fully initialized and trap otherwise.
1925 // We copy the shadow of \p CopyOp[NumUsedElements:] to \p
1926 // Out[NumUsedElements:]. This means that intrinsics without \p CopyOp always
1927 // return a fully initialized value.
1928 void handleVectorConvertIntrinsic(IntrinsicInst &I, int NumUsedElements) {
1929 IRBuilder<> IRB(&I);
1930 Value *CopyOp, *ConvertOp;
1931
1932 switch (I.getNumArgOperands()) {
1933 case 2:
1934 CopyOp = I.getArgOperand(0);
1935 ConvertOp = I.getArgOperand(1);
1936 break;
1937 case 1:
1938 ConvertOp = I.getArgOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +00001939 CopyOp = nullptr;
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001940 break;
1941 default:
1942 llvm_unreachable("Cvt intrinsic with unsupported number of arguments.");
1943 }
1944
1945 // The first *NumUsedElements* elements of ConvertOp are converted to the
1946 // same number of output elements. The rest of the output is copied from
1947 // CopyOp, or (if not available) filled with zeroes.
1948 // Combine shadow for elements of ConvertOp that are used in this operation,
1949 // and insert a check.
1950 // FIXME: consider propagating shadow of ConvertOp, at least in the case of
1951 // int->any conversion.
1952 Value *ConvertShadow = getShadow(ConvertOp);
Craig Topperf40110f2014-04-25 05:29:35 +00001953 Value *AggShadow = nullptr;
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001954 if (ConvertOp->getType()->isVectorTy()) {
1955 AggShadow = IRB.CreateExtractElement(
1956 ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), 0));
1957 for (int i = 1; i < NumUsedElements; ++i) {
1958 Value *MoreShadow = IRB.CreateExtractElement(
1959 ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), i));
1960 AggShadow = IRB.CreateOr(AggShadow, MoreShadow);
1961 }
1962 } else {
1963 AggShadow = ConvertShadow;
1964 }
1965 assert(AggShadow->getType()->isIntegerTy());
1966 insertShadowCheck(AggShadow, getOrigin(ConvertOp), &I);
1967
1968 // Build result shadow by zero-filling parts of CopyOp shadow that come from
1969 // ConvertOp.
1970 if (CopyOp) {
1971 assert(CopyOp->getType() == I.getType());
1972 assert(CopyOp->getType()->isVectorTy());
1973 Value *ResultShadow = getShadow(CopyOp);
1974 Type *EltTy = ResultShadow->getType()->getVectorElementType();
1975 for (int i = 0; i < NumUsedElements; ++i) {
1976 ResultShadow = IRB.CreateInsertElement(
1977 ResultShadow, ConstantInt::getNullValue(EltTy),
1978 ConstantInt::get(IRB.getInt32Ty(), i));
1979 }
1980 setShadow(&I, ResultShadow);
1981 setOrigin(&I, getOrigin(CopyOp));
1982 } else {
1983 setShadow(&I, getCleanShadow(&I));
1984 }
1985 }
1986
Evgeniy Stepanov77be5322014-03-03 13:47:42 +00001987 // Given a scalar or vector, extract lower 64 bits (or less), and return all
1988 // zeroes if it is zero, and all ones otherwise.
1989 Value *Lower64ShadowExtend(IRBuilder<> &IRB, Value *S, Type *T) {
1990 if (S->getType()->isVectorTy())
1991 S = CreateShadowCast(IRB, S, IRB.getInt64Ty(), /* Signed */ true);
1992 assert(S->getType()->getPrimitiveSizeInBits() <= 64);
1993 Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
1994 return CreateShadowCast(IRB, S2, T, /* Signed */ true);
1995 }
1996
1997 Value *VariableShadowExtend(IRBuilder<> &IRB, Value *S) {
1998 Type *T = S->getType();
1999 assert(T->isVectorTy());
2000 Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
2001 return IRB.CreateSExt(S2, T);
2002 }
2003
2004 // \brief Instrument vector shift instrinsic.
2005 //
2006 // This function instruments intrinsics like int_x86_avx2_psll_w.
2007 // Intrinsic shifts %In by %ShiftSize bits.
2008 // %ShiftSize may be a vector. In that case the lower 64 bits determine shift
2009 // size, and the rest is ignored. Behavior is defined even if shift size is
2010 // greater than register (or field) width.
2011 void handleVectorShiftIntrinsic(IntrinsicInst &I, bool Variable) {
2012 assert(I.getNumArgOperands() == 2);
2013 IRBuilder<> IRB(&I);
2014 // If any of the S2 bits are poisoned, the whole thing is poisoned.
2015 // Otherwise perform the same shift on S1.
2016 Value *S1 = getShadow(&I, 0);
2017 Value *S2 = getShadow(&I, 1);
2018 Value *S2Conv = Variable ? VariableShadowExtend(IRB, S2)
2019 : Lower64ShadowExtend(IRB, S2, getShadowTy(&I));
2020 Value *V1 = I.getOperand(0);
2021 Value *V2 = I.getOperand(1);
2022 Value *Shift = IRB.CreateCall2(I.getCalledValue(),
2023 IRB.CreateBitCast(S1, V1->getType()), V2);
2024 Shift = IRB.CreateBitCast(Shift, getShadowTy(&I));
2025 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
2026 setOriginForNaryOp(I);
2027 }
2028
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002029 // \brief Get an X86_MMX-sized vector type.
2030 Type *getMMXVectorTy(unsigned EltSizeInBits) {
2031 const unsigned X86_MMXSizeInBits = 64;
2032 return VectorType::get(IntegerType::get(*MS.C, EltSizeInBits),
2033 X86_MMXSizeInBits / EltSizeInBits);
2034 }
2035
2036 // \brief Returns a signed counterpart for an (un)signed-saturate-and-pack
2037 // intrinsic.
2038 Intrinsic::ID getSignedPackIntrinsic(Intrinsic::ID id) {
2039 switch (id) {
2040 case llvm::Intrinsic::x86_sse2_packsswb_128:
2041 case llvm::Intrinsic::x86_sse2_packuswb_128:
2042 return llvm::Intrinsic::x86_sse2_packsswb_128;
2043
2044 case llvm::Intrinsic::x86_sse2_packssdw_128:
2045 case llvm::Intrinsic::x86_sse41_packusdw:
2046 return llvm::Intrinsic::x86_sse2_packssdw_128;
2047
2048 case llvm::Intrinsic::x86_avx2_packsswb:
2049 case llvm::Intrinsic::x86_avx2_packuswb:
2050 return llvm::Intrinsic::x86_avx2_packsswb;
2051
2052 case llvm::Intrinsic::x86_avx2_packssdw:
2053 case llvm::Intrinsic::x86_avx2_packusdw:
2054 return llvm::Intrinsic::x86_avx2_packssdw;
2055
2056 case llvm::Intrinsic::x86_mmx_packsswb:
2057 case llvm::Intrinsic::x86_mmx_packuswb:
2058 return llvm::Intrinsic::x86_mmx_packsswb;
2059
2060 case llvm::Intrinsic::x86_mmx_packssdw:
2061 return llvm::Intrinsic::x86_mmx_packssdw;
2062 default:
2063 llvm_unreachable("unexpected intrinsic id");
2064 }
2065 }
2066
Evgeniy Stepanov5d972932014-06-17 11:26:00 +00002067 // \brief Instrument vector pack instrinsic.
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002068 //
2069 // This function instruments intrinsics like x86_mmx_packsswb, that
Evgeniy Stepanov5d972932014-06-17 11:26:00 +00002070 // packs elements of 2 input vectors into half as many bits with saturation.
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002071 // Shadow is propagated with the signed variant of the same intrinsic applied
2072 // to sext(Sa != zeroinitializer), sext(Sb != zeroinitializer).
2073 // EltSizeInBits is used only for x86mmx arguments.
2074 void handleVectorPackIntrinsic(IntrinsicInst &I, unsigned EltSizeInBits = 0) {
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002075 assert(I.getNumArgOperands() == 2);
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002076 bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002077 IRBuilder<> IRB(&I);
2078 Value *S1 = getShadow(&I, 0);
2079 Value *S2 = getShadow(&I, 1);
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002080 assert(isX86_MMX || S1->getType()->isVectorTy());
2081
2082 // SExt and ICmpNE below must apply to individual elements of input vectors.
2083 // In case of x86mmx arguments, cast them to appropriate vector types and
2084 // back.
2085 Type *T = isX86_MMX ? getMMXVectorTy(EltSizeInBits) : S1->getType();
2086 if (isX86_MMX) {
2087 S1 = IRB.CreateBitCast(S1, T);
2088 S2 = IRB.CreateBitCast(S2, T);
2089 }
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002090 Value *S1_ext = IRB.CreateSExt(
2091 IRB.CreateICmpNE(S1, llvm::Constant::getNullValue(T)), T);
2092 Value *S2_ext = IRB.CreateSExt(
2093 IRB.CreateICmpNE(S2, llvm::Constant::getNullValue(T)), T);
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002094 if (isX86_MMX) {
2095 Type *X86_MMXTy = Type::getX86_MMXTy(*MS.C);
2096 S1_ext = IRB.CreateBitCast(S1_ext, X86_MMXTy);
2097 S2_ext = IRB.CreateBitCast(S2_ext, X86_MMXTy);
2098 }
2099
2100 Function *ShadowFn = Intrinsic::getDeclaration(
2101 F.getParent(), getSignedPackIntrinsic(I.getIntrinsicID()));
2102
2103 Value *S = IRB.CreateCall2(ShadowFn, S1_ext, S2_ext, "_msprop_vector_pack");
2104 if (isX86_MMX) S = IRB.CreateBitCast(S, getShadowTy(&I));
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002105 setShadow(&I, S);
2106 setOriginForNaryOp(I);
2107 }
2108
Evgeniy Stepanov4ea16472014-06-18 12:02:29 +00002109 // \brief Instrument sum-of-absolute-differencies intrinsic.
2110 void handleVectorSadIntrinsic(IntrinsicInst &I) {
2111 const unsigned SignificantBitsPerResultElement = 16;
2112 bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2113 Type *ResTy = isX86_MMX ? IntegerType::get(*MS.C, 64) : I.getType();
2114 unsigned ZeroBitsPerResultElement =
2115 ResTy->getScalarSizeInBits() - SignificantBitsPerResultElement;
2116
2117 IRBuilder<> IRB(&I);
2118 Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2119 S = IRB.CreateBitCast(S, ResTy);
2120 S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
2121 ResTy);
2122 S = IRB.CreateLShr(S, ZeroBitsPerResultElement);
2123 S = IRB.CreateBitCast(S, getShadowTy(&I));
2124 setShadow(&I, S);
2125 setOriginForNaryOp(I);
2126 }
2127
2128 // \brief Instrument multiply-add intrinsic.
2129 void handleVectorPmaddIntrinsic(IntrinsicInst &I,
2130 unsigned EltSizeInBits = 0) {
2131 bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2132 Type *ResTy = isX86_MMX ? getMMXVectorTy(EltSizeInBits * 2) : I.getType();
2133 IRBuilder<> IRB(&I);
2134 Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2135 S = IRB.CreateBitCast(S, ResTy);
2136 S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
2137 ResTy);
2138 S = IRB.CreateBitCast(S, getShadowTy(&I));
2139 setShadow(&I, S);
2140 setOriginForNaryOp(I);
2141 }
2142
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00002143 void visitIntrinsicInst(IntrinsicInst &I) {
2144 switch (I.getIntrinsicID()) {
2145 case llvm::Intrinsic::bswap:
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +00002146 handleBswap(I);
2147 break;
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002148 case llvm::Intrinsic::x86_avx512_cvtsd2usi64:
2149 case llvm::Intrinsic::x86_avx512_cvtsd2usi:
2150 case llvm::Intrinsic::x86_avx512_cvtss2usi64:
2151 case llvm::Intrinsic::x86_avx512_cvtss2usi:
2152 case llvm::Intrinsic::x86_avx512_cvttss2usi64:
2153 case llvm::Intrinsic::x86_avx512_cvttss2usi:
2154 case llvm::Intrinsic::x86_avx512_cvttsd2usi64:
2155 case llvm::Intrinsic::x86_avx512_cvttsd2usi:
2156 case llvm::Intrinsic::x86_avx512_cvtusi2sd:
2157 case llvm::Intrinsic::x86_avx512_cvtusi2ss:
2158 case llvm::Intrinsic::x86_avx512_cvtusi642sd:
2159 case llvm::Intrinsic::x86_avx512_cvtusi642ss:
2160 case llvm::Intrinsic::x86_sse2_cvtsd2si64:
2161 case llvm::Intrinsic::x86_sse2_cvtsd2si:
2162 case llvm::Intrinsic::x86_sse2_cvtsd2ss:
2163 case llvm::Intrinsic::x86_sse2_cvtsi2sd:
2164 case llvm::Intrinsic::x86_sse2_cvtsi642sd:
2165 case llvm::Intrinsic::x86_sse2_cvtss2sd:
2166 case llvm::Intrinsic::x86_sse2_cvttsd2si64:
2167 case llvm::Intrinsic::x86_sse2_cvttsd2si:
2168 case llvm::Intrinsic::x86_sse_cvtsi2ss:
2169 case llvm::Intrinsic::x86_sse_cvtsi642ss:
2170 case llvm::Intrinsic::x86_sse_cvtss2si64:
2171 case llvm::Intrinsic::x86_sse_cvtss2si:
2172 case llvm::Intrinsic::x86_sse_cvttss2si64:
2173 case llvm::Intrinsic::x86_sse_cvttss2si:
2174 handleVectorConvertIntrinsic(I, 1);
2175 break;
2176 case llvm::Intrinsic::x86_sse2_cvtdq2pd:
2177 case llvm::Intrinsic::x86_sse2_cvtps2pd:
2178 case llvm::Intrinsic::x86_sse_cvtps2pi:
2179 case llvm::Intrinsic::x86_sse_cvttps2pi:
2180 handleVectorConvertIntrinsic(I, 2);
2181 break;
Evgeniy Stepanov77be5322014-03-03 13:47:42 +00002182 case llvm::Intrinsic::x86_avx512_psll_dq:
2183 case llvm::Intrinsic::x86_avx512_psrl_dq:
2184 case llvm::Intrinsic::x86_avx2_psll_w:
2185 case llvm::Intrinsic::x86_avx2_psll_d:
2186 case llvm::Intrinsic::x86_avx2_psll_q:
2187 case llvm::Intrinsic::x86_avx2_pslli_w:
2188 case llvm::Intrinsic::x86_avx2_pslli_d:
2189 case llvm::Intrinsic::x86_avx2_pslli_q:
2190 case llvm::Intrinsic::x86_avx2_psll_dq:
2191 case llvm::Intrinsic::x86_avx2_psrl_w:
2192 case llvm::Intrinsic::x86_avx2_psrl_d:
2193 case llvm::Intrinsic::x86_avx2_psrl_q:
2194 case llvm::Intrinsic::x86_avx2_psra_w:
2195 case llvm::Intrinsic::x86_avx2_psra_d:
2196 case llvm::Intrinsic::x86_avx2_psrli_w:
2197 case llvm::Intrinsic::x86_avx2_psrli_d:
2198 case llvm::Intrinsic::x86_avx2_psrli_q:
2199 case llvm::Intrinsic::x86_avx2_psrai_w:
2200 case llvm::Intrinsic::x86_avx2_psrai_d:
2201 case llvm::Intrinsic::x86_avx2_psrl_dq:
2202 case llvm::Intrinsic::x86_sse2_psll_w:
2203 case llvm::Intrinsic::x86_sse2_psll_d:
2204 case llvm::Intrinsic::x86_sse2_psll_q:
2205 case llvm::Intrinsic::x86_sse2_pslli_w:
2206 case llvm::Intrinsic::x86_sse2_pslli_d:
2207 case llvm::Intrinsic::x86_sse2_pslli_q:
2208 case llvm::Intrinsic::x86_sse2_psll_dq:
2209 case llvm::Intrinsic::x86_sse2_psrl_w:
2210 case llvm::Intrinsic::x86_sse2_psrl_d:
2211 case llvm::Intrinsic::x86_sse2_psrl_q:
2212 case llvm::Intrinsic::x86_sse2_psra_w:
2213 case llvm::Intrinsic::x86_sse2_psra_d:
2214 case llvm::Intrinsic::x86_sse2_psrli_w:
2215 case llvm::Intrinsic::x86_sse2_psrli_d:
2216 case llvm::Intrinsic::x86_sse2_psrli_q:
2217 case llvm::Intrinsic::x86_sse2_psrai_w:
2218 case llvm::Intrinsic::x86_sse2_psrai_d:
2219 case llvm::Intrinsic::x86_sse2_psrl_dq:
2220 case llvm::Intrinsic::x86_mmx_psll_w:
2221 case llvm::Intrinsic::x86_mmx_psll_d:
2222 case llvm::Intrinsic::x86_mmx_psll_q:
2223 case llvm::Intrinsic::x86_mmx_pslli_w:
2224 case llvm::Intrinsic::x86_mmx_pslli_d:
2225 case llvm::Intrinsic::x86_mmx_pslli_q:
2226 case llvm::Intrinsic::x86_mmx_psrl_w:
2227 case llvm::Intrinsic::x86_mmx_psrl_d:
2228 case llvm::Intrinsic::x86_mmx_psrl_q:
2229 case llvm::Intrinsic::x86_mmx_psra_w:
2230 case llvm::Intrinsic::x86_mmx_psra_d:
2231 case llvm::Intrinsic::x86_mmx_psrli_w:
2232 case llvm::Intrinsic::x86_mmx_psrli_d:
2233 case llvm::Intrinsic::x86_mmx_psrli_q:
2234 case llvm::Intrinsic::x86_mmx_psrai_w:
2235 case llvm::Intrinsic::x86_mmx_psrai_d:
2236 handleVectorShiftIntrinsic(I, /* Variable */ false);
2237 break;
2238 case llvm::Intrinsic::x86_avx2_psllv_d:
2239 case llvm::Intrinsic::x86_avx2_psllv_d_256:
2240 case llvm::Intrinsic::x86_avx2_psllv_q:
2241 case llvm::Intrinsic::x86_avx2_psllv_q_256:
2242 case llvm::Intrinsic::x86_avx2_psrlv_d:
2243 case llvm::Intrinsic::x86_avx2_psrlv_d_256:
2244 case llvm::Intrinsic::x86_avx2_psrlv_q:
2245 case llvm::Intrinsic::x86_avx2_psrlv_q_256:
2246 case llvm::Intrinsic::x86_avx2_psrav_d:
2247 case llvm::Intrinsic::x86_avx2_psrav_d_256:
2248 handleVectorShiftIntrinsic(I, /* Variable */ true);
2249 break;
2250
2251 // Byte shifts are not implemented.
2252 // case llvm::Intrinsic::x86_avx512_psll_dq_bs:
2253 // case llvm::Intrinsic::x86_avx512_psrl_dq_bs:
2254 // case llvm::Intrinsic::x86_avx2_psll_dq_bs:
2255 // case llvm::Intrinsic::x86_avx2_psrl_dq_bs:
2256 // case llvm::Intrinsic::x86_sse2_psll_dq_bs:
2257 // case llvm::Intrinsic::x86_sse2_psrl_dq_bs:
2258
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002259 case llvm::Intrinsic::x86_sse2_packsswb_128:
2260 case llvm::Intrinsic::x86_sse2_packssdw_128:
2261 case llvm::Intrinsic::x86_sse2_packuswb_128:
2262 case llvm::Intrinsic::x86_sse41_packusdw:
2263 case llvm::Intrinsic::x86_avx2_packsswb:
2264 case llvm::Intrinsic::x86_avx2_packssdw:
2265 case llvm::Intrinsic::x86_avx2_packuswb:
2266 case llvm::Intrinsic::x86_avx2_packusdw:
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002267 handleVectorPackIntrinsic(I);
2268 break;
2269
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002270 case llvm::Intrinsic::x86_mmx_packsswb:
2271 case llvm::Intrinsic::x86_mmx_packuswb:
2272 handleVectorPackIntrinsic(I, 16);
2273 break;
2274
2275 case llvm::Intrinsic::x86_mmx_packssdw:
2276 handleVectorPackIntrinsic(I, 32);
2277 break;
2278
Evgeniy Stepanov4ea16472014-06-18 12:02:29 +00002279 case llvm::Intrinsic::x86_mmx_psad_bw:
2280 case llvm::Intrinsic::x86_sse2_psad_bw:
2281 case llvm::Intrinsic::x86_avx2_psad_bw:
2282 handleVectorSadIntrinsic(I);
2283 break;
2284
2285 case llvm::Intrinsic::x86_sse2_pmadd_wd:
2286 case llvm::Intrinsic::x86_avx2_pmadd_wd:
2287 case llvm::Intrinsic::x86_ssse3_pmadd_ub_sw_128:
2288 case llvm::Intrinsic::x86_avx2_pmadd_ub_sw:
2289 handleVectorPmaddIntrinsic(I);
2290 break;
2291
2292 case llvm::Intrinsic::x86_ssse3_pmadd_ub_sw:
2293 handleVectorPmaddIntrinsic(I, 8);
2294 break;
2295
2296 case llvm::Intrinsic::x86_mmx_pmadd_wd:
2297 handleVectorPmaddIntrinsic(I, 16);
2298 break;
2299
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00002300 default:
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00002301 if (!handleUnknownIntrinsic(I))
2302 visitInstruction(I);
Evgeniy Stepanov88b8dce2012-12-17 16:30:05 +00002303 break;
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00002304 }
2305 }
2306
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002307 void visitCallSite(CallSite CS) {
2308 Instruction &I = *CS.getInstruction();
2309 assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
2310 if (CS.isCall()) {
Evgeniy Stepanov7ad7e832012-11-29 14:32:03 +00002311 CallInst *Call = cast<CallInst>(&I);
2312
2313 // For inline asm, do the usual thing: check argument shadow and mark all
2314 // outputs as clean. Note that any side effects of the inline asm that are
2315 // not immediately visible in its constraints are not handled.
2316 if (Call->isInlineAsm()) {
2317 visitInstruction(I);
2318 return;
2319 }
2320
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00002321 assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
Evgeniy Stepanov383b61e2012-12-07 09:08:32 +00002322
2323 // We are going to insert code that relies on the fact that the callee
2324 // will become a non-readonly function after it is instrumented by us. To
2325 // prevent this code from being optimized out, mark that function
2326 // non-readonly in advance.
2327 if (Function *Func = Call->getCalledFunction()) {
2328 // Clear out readonly/readnone attributes.
2329 AttrBuilder B;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002330 B.addAttribute(Attribute::ReadOnly)
2331 .addAttribute(Attribute::ReadNone);
Bill Wendling430fa9b2013-01-23 00:45:55 +00002332 Func->removeAttributes(AttributeSet::FunctionIndex,
2333 AttributeSet::get(Func->getContext(),
2334 AttributeSet::FunctionIndex,
2335 B));
Evgeniy Stepanov383b61e2012-12-07 09:08:32 +00002336 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002337 }
2338 IRBuilder<> IRB(&I);
Evgeniy Stepanov37b86452013-09-19 15:22:35 +00002339
2340 if (MS.WrapIndirectCalls && !CS.getCalledFunction())
Evgeniy Stepanov585813e2013-11-14 12:29:04 +00002341 IndirectCallList.push_back(CS);
Evgeniy Stepanov37b86452013-09-19 15:22:35 +00002342
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002343 unsigned ArgOffset = 0;
2344 DEBUG(dbgs() << " CallSite: " << I << "\n");
2345 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
2346 ArgIt != End; ++ArgIt) {
2347 Value *A = *ArgIt;
2348 unsigned i = ArgIt - CS.arg_begin();
2349 if (!A->getType()->isSized()) {
2350 DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
2351 continue;
2352 }
2353 unsigned Size = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00002354 Value *Store = nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002355 // Compute the Shadow for arg even if it is ByVal, because
2356 // in that case getShadow() will copy the actual arg shadow to
2357 // __msan_param_tls.
2358 Value *ArgShadow = getShadow(A);
2359 Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
2360 DEBUG(dbgs() << " Arg#" << i << ": " << *A <<
2361 " Shadow: " << *ArgShadow << "\n");
Evgeniy Stepanovc8227aa2014-07-17 09:10:37 +00002362 bool ArgIsInitialized = false;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002363 if (CS.paramHasAttr(i + 1, Attribute::ByVal)) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002364 assert(A->getType()->isPointerTy() &&
2365 "ByVal argument is not a pointer!");
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002366 Size = MS.DL->getTypeAllocSize(A->getType()->getPointerElementType());
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +00002367 if (ArgOffset + Size > kParamTLSSize) break;
Evgeniy Stepanove08633e2014-10-17 23:29:44 +00002368 unsigned ParamAlignment = CS.getParamAlignment(i + 1);
2369 unsigned Alignment = std::min(ParamAlignment, kShadowTLSAlignment);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002370 Store = IRB.CreateMemCpy(ArgShadowBase,
2371 getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
2372 Size, Alignment);
2373 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002374 Size = MS.DL->getTypeAllocSize(A->getType());
Evgeniy Stepanov35eb2652014-10-22 00:12:40 +00002375 if (ArgOffset + Size > kParamTLSSize) break;
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00002376 Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
2377 kShadowTLSAlignment);
Evgeniy Stepanovc8227aa2014-07-17 09:10:37 +00002378 Constant *Cst = dyn_cast<Constant>(ArgShadow);
2379 if (Cst && Cst->isNullValue()) ArgIsInitialized = true;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002380 }
Evgeniy Stepanovc8227aa2014-07-17 09:10:37 +00002381 if (MS.TrackOrigins && !ArgIsInitialized)
Evgeniy Stepanov49175b22012-12-14 13:43:11 +00002382 IRB.CreateStore(getOrigin(A),
2383 getOriginPtrForArgument(A, IRB, ArgOffset));
Edwin Vane82f80d42013-01-29 17:42:24 +00002384 (void)Store;
Craig Toppere73658d2014-04-28 04:05:08 +00002385 assert(Size != 0 && Store != nullptr);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002386 DEBUG(dbgs() << " Param:" << *Store << "\n");
David Majnemerf3cadce2014-10-20 06:13:33 +00002387 ArgOffset += RoundUpToAlignment(Size, 8);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002388 }
2389 DEBUG(dbgs() << " done with call args\n");
2390
2391 FunctionType *FT =
Evgeniy Stepanov37b86452013-09-19 15:22:35 +00002392 cast<FunctionType>(CS.getCalledValue()->getType()->getContainedType(0));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002393 if (FT->isVarArg()) {
2394 VAHelper->visitCallSite(CS, IRB);
2395 }
2396
2397 // Now, get the shadow for the RetVal.
2398 if (!I.getType()->isSized()) return;
2399 IRBuilder<> IRBBefore(&I);
Alp Tokercb402912014-01-24 17:20:08 +00002400 // Until we have full dynamic coverage, make sure the retval shadow is 0.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002401 Value *Base = getShadowPtrForRetval(&I, IRBBefore);
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00002402 IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
Craig Topperf40110f2014-04-25 05:29:35 +00002403 Instruction *NextInsn = nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002404 if (CS.isCall()) {
2405 NextInsn = I.getNextNode();
2406 } else {
2407 BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
2408 if (!NormalDest->getSinglePredecessor()) {
2409 // FIXME: this case is tricky, so we are just conservative here.
2410 // Perhaps we need to split the edge between this BB and NormalDest,
2411 // but a naive attempt to use SplitEdge leads to a crash.
2412 setShadow(&I, getCleanShadow(&I));
2413 setOrigin(&I, getCleanOrigin());
2414 return;
2415 }
2416 NextInsn = NormalDest->getFirstInsertionPt();
2417 assert(NextInsn &&
2418 "Could not find insertion point for retval shadow load");
2419 }
2420 IRBuilder<> IRBAfter(NextInsn);
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00002421 Value *RetvalShadow =
2422 IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
2423 kShadowTLSAlignment, "_msret");
2424 setShadow(&I, RetvalShadow);
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00002425 if (MS.TrackOrigins)
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002426 setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
2427 }
2428
2429 void visitReturnInst(ReturnInst &I) {
2430 IRBuilder<> IRB(&I);
Evgeniy Stepanov604293f2013-09-16 13:24:32 +00002431 Value *RetVal = I.getReturnValue();
2432 if (!RetVal) return;
2433 Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
2434 if (CheckReturnValue) {
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002435 insertShadowCheck(RetVal, &I);
Evgeniy Stepanov604293f2013-09-16 13:24:32 +00002436 Value *Shadow = getCleanShadow(RetVal);
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00002437 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
Evgeniy Stepanov604293f2013-09-16 13:24:32 +00002438 } else {
2439 Value *Shadow = getShadow(RetVal);
2440 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
2441 // FIXME: make it conditional if ClStoreCleanOrigin==0
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00002442 if (MS.TrackOrigins)
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002443 IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
2444 }
2445 }
2446
2447 void visitPHINode(PHINode &I) {
2448 IRBuilder<> IRB(&I);
Evgeniy Stepanovd948a5f2014-07-07 13:28:31 +00002449 if (!PropagateShadow) {
2450 setShadow(&I, getCleanShadow(&I));
2451 return;
2452 }
2453
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002454 ShadowPHINodes.push_back(&I);
2455 setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
2456 "_msphi_s"));
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00002457 if (MS.TrackOrigins)
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002458 setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
2459 "_msphi_o"));
2460 }
2461
2462 void visitAllocaInst(AllocaInst &I) {
2463 setShadow(&I, getCleanShadow(&I));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002464 IRBuilder<> IRB(I.getNextNode());
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002465 uint64_t Size = MS.DL->getTypeAllocSize(I.getAllocatedType());
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +00002466 if (PoisonStack && ClPoisonStackWithCall) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002467 IRB.CreateCall2(MS.MsanPoisonStackFn,
2468 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
2469 ConstantInt::get(MS.IntptrTy, Size));
2470 } else {
2471 Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +00002472 Value *PoisonValue = IRB.getInt8(PoisonStack ? ClPoisonStackPattern : 0);
2473 IRB.CreateMemSet(ShadowBase, PoisonValue, Size, I.getAlignment());
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002474 }
2475
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +00002476 if (PoisonStack && MS.TrackOrigins) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002477 setOrigin(&I, getCleanOrigin());
Alp Tokere69170a2014-06-26 22:52:05 +00002478 SmallString<2048> StackDescriptionStorage;
2479 raw_svector_ostream StackDescription(StackDescriptionStorage);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002480 // We create a string with a description of the stack allocation and
2481 // pass it into __msan_set_alloca_origin.
2482 // It will be printed by the run-time if stack-originated UMR is found.
2483 // The first 4 bytes of the string are set to '----' and will be replaced
2484 // by __msan_va_arg_overflow_size_tls at the first call.
2485 StackDescription << "----" << I.getName() << "@" << F.getName();
2486 Value *Descr =
2487 createPrivateNonConstGlobalForString(*F.getParent(),
2488 StackDescription.str());
Evgeniy Stepanov0435ecd2013-09-13 12:54:49 +00002489
2490 IRB.CreateCall4(MS.MsanSetAllocaOrigin4Fn,
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002491 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
2492 ConstantInt::get(MS.IntptrTy, Size),
Evgeniy Stepanov0435ecd2013-09-13 12:54:49 +00002493 IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()),
2494 IRB.CreatePointerCast(&F, MS.IntptrTy));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002495 }
2496 }
2497
2498 void visitSelectInst(SelectInst& I) {
2499 IRBuilder<> IRB(&I);
Evgeniy Stepanov566f5912013-09-03 10:04:11 +00002500 // a = select b, c, d
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002501 Value *B = I.getCondition();
2502 Value *C = I.getTrueValue();
2503 Value *D = I.getFalseValue();
2504 Value *Sb = getShadow(B);
2505 Value *Sc = getShadow(C);
2506 Value *Sd = getShadow(D);
2507
2508 // Result shadow if condition shadow is 0.
2509 Value *Sa0 = IRB.CreateSelect(B, Sc, Sd);
2510 Value *Sa1;
Evgeniy Stepanove95d37c2013-09-03 13:05:29 +00002511 if (I.getType()->isAggregateType()) {
2512 // To avoid "sign extending" i1 to an arbitrary aggregate type, we just do
2513 // an extra "select". This results in much more compact IR.
2514 // Sa = select Sb, poisoned, (select b, Sc, Sd)
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002515 Sa1 = getPoisonedShadow(getShadowTy(I.getType()));
Evgeniy Stepanove95d37c2013-09-03 13:05:29 +00002516 } else {
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002517 // Sa = select Sb, [ (c^d) | Sc | Sd ], [ b ? Sc : Sd ]
2518 // If Sb (condition is poisoned), look for bits in c and d that are equal
2519 // and both unpoisoned.
2520 // If !Sb (condition is unpoisoned), simply pick one of Sc and Sd.
2521
2522 // Cast arguments to shadow-compatible type.
2523 C = CreateAppToShadowCast(IRB, C);
2524 D = CreateAppToShadowCast(IRB, D);
2525
2526 // Result shadow if condition shadow is 1.
2527 Sa1 = IRB.CreateOr(IRB.CreateXor(C, D), IRB.CreateOr(Sc, Sd));
Evgeniy Stepanove95d37c2013-09-03 13:05:29 +00002528 }
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002529 Value *Sa = IRB.CreateSelect(Sb, Sa1, Sa0, "_msprop_select");
2530 setShadow(&I, Sa);
Evgeniy Stepanovec837122012-12-25 14:56:21 +00002531 if (MS.TrackOrigins) {
2532 // Origins are always i32, so any vector conditions must be flattened.
2533 // FIXME: consider tracking vector origins for app vectors?
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002534 if (B->getType()->isVectorTy()) {
2535 Type *FlatTy = getShadowTyNoVec(B->getType());
2536 B = IRB.CreateICmpNE(IRB.CreateBitCast(B, FlatTy),
Evgeniy Stepanovcb5bdff2013-11-21 12:00:24 +00002537 ConstantInt::getNullValue(FlatTy));
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002538 Sb = IRB.CreateICmpNE(IRB.CreateBitCast(Sb, FlatTy),
Evgeniy Stepanovcb5bdff2013-11-21 12:00:24 +00002539 ConstantInt::getNullValue(FlatTy));
Evgeniy Stepanovec837122012-12-25 14:56:21 +00002540 }
Evgeniy Stepanovcb5bdff2013-11-21 12:00:24 +00002541 // a = select b, c, d
2542 // Oa = Sb ? Ob : (b ? Oc : Od)
2543 setOrigin(&I, IRB.CreateSelect(
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002544 Sb, getOrigin(I.getCondition()),
2545 IRB.CreateSelect(B, getOrigin(C), getOrigin(D))));
Evgeniy Stepanovec837122012-12-25 14:56:21 +00002546 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002547 }
2548
2549 void visitLandingPadInst(LandingPadInst &I) {
2550 // Do nothing.
2551 // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
2552 setShadow(&I, getCleanShadow(&I));
2553 setOrigin(&I, getCleanOrigin());
2554 }
2555
2556 void visitGetElementPtrInst(GetElementPtrInst &I) {
2557 handleShadowOr(I);
2558 }
2559
2560 void visitExtractValueInst(ExtractValueInst &I) {
2561 IRBuilder<> IRB(&I);
2562 Value *Agg = I.getAggregateOperand();
2563 DEBUG(dbgs() << "ExtractValue: " << I << "\n");
2564 Value *AggShadow = getShadow(Agg);
2565 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
2566 Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
2567 DEBUG(dbgs() << " ResShadow: " << *ResShadow << "\n");
2568 setShadow(&I, ResShadow);
Evgeniy Stepanov560e08932013-11-11 13:37:10 +00002569 setOriginForNaryOp(I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002570 }
2571
2572 void visitInsertValueInst(InsertValueInst &I) {
2573 IRBuilder<> IRB(&I);
2574 DEBUG(dbgs() << "InsertValue: " << I << "\n");
2575 Value *AggShadow = getShadow(I.getAggregateOperand());
2576 Value *InsShadow = getShadow(I.getInsertedValueOperand());
2577 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
2578 DEBUG(dbgs() << " InsShadow: " << *InsShadow << "\n");
2579 Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
2580 DEBUG(dbgs() << " Res: " << *Res << "\n");
2581 setShadow(&I, Res);
Evgeniy Stepanov560e08932013-11-11 13:37:10 +00002582 setOriginForNaryOp(I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002583 }
2584
2585 void dumpInst(Instruction &I) {
2586 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
2587 errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
2588 } else {
2589 errs() << "ZZZ " << I.getOpcodeName() << "\n";
2590 }
2591 errs() << "QQQ " << I << "\n";
2592 }
2593
2594 void visitResumeInst(ResumeInst &I) {
2595 DEBUG(dbgs() << "Resume: " << I << "\n");
2596 // Nothing to do here.
2597 }
2598
2599 void visitInstruction(Instruction &I) {
2600 // Everything else: stop propagating and check for poisoned shadow.
2601 if (ClDumpStrictInstructions)
2602 dumpInst(I);
2603 DEBUG(dbgs() << "DEFAULT: " << I << "\n");
2604 for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002605 insertShadowCheck(I.getOperand(i), &I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002606 setShadow(&I, getCleanShadow(&I));
2607 setOrigin(&I, getCleanOrigin());
2608 }
2609};
2610
2611/// \brief AMD64-specific implementation of VarArgHelper.
2612struct VarArgAMD64Helper : public VarArgHelper {
2613 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
2614 // See a comment in visitCallSite for more details.
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +00002615 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002616 static const unsigned AMD64FpEndOffset = 176;
2617
2618 Function &F;
2619 MemorySanitizer &MS;
2620 MemorySanitizerVisitor &MSV;
2621 Value *VAArgTLSCopy;
2622 Value *VAArgOverflowSize;
2623
2624 SmallVector<CallInst*, 16> VAStartInstrumentationList;
2625
2626 VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
2627 MemorySanitizerVisitor &MSV)
Craig Topperf40110f2014-04-25 05:29:35 +00002628 : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(nullptr),
2629 VAArgOverflowSize(nullptr) {}
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002630
2631 enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
2632
2633 ArgKind classifyArgument(Value* arg) {
2634 // A very rough approximation of X86_64 argument classification rules.
2635 Type *T = arg->getType();
2636 if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
2637 return AK_FloatingPoint;
2638 if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
2639 return AK_GeneralPurpose;
2640 if (T->isPointerTy())
2641 return AK_GeneralPurpose;
2642 return AK_Memory;
2643 }
2644
2645 // For VarArg functions, store the argument shadow in an ABI-specific format
2646 // that corresponds to va_list layout.
2647 // We do this because Clang lowers va_arg in the frontend, and this pass
2648 // only sees the low level code that deals with va_list internals.
2649 // A much easier alternative (provided that Clang emits va_arg instructions)
2650 // would have been to associate each live instance of va_list with a copy of
2651 // MSanParamTLS, and extract shadow on va_arg() call in the argument list
2652 // order.
Craig Topper3e4c6972014-03-05 09:10:37 +00002653 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002654 unsigned GpOffset = 0;
2655 unsigned FpOffset = AMD64GpEndOffset;
2656 unsigned OverflowOffset = AMD64FpEndOffset;
2657 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
2658 ArgIt != End; ++ArgIt) {
2659 Value *A = *ArgIt;
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00002660 unsigned ArgNo = CS.getArgumentNo(ArgIt);
2661 bool IsByVal = CS.paramHasAttr(ArgNo + 1, Attribute::ByVal);
2662 if (IsByVal) {
2663 // ByVal arguments always go to the overflow area.
2664 assert(A->getType()->isPointerTy());
2665 Type *RealTy = A->getType()->getPointerElementType();
2666 uint64_t ArgSize = MS.DL->getTypeAllocSize(RealTy);
2667 Value *Base = getShadowPtrForVAArgument(RealTy, IRB, OverflowOffset);
David Majnemerf3cadce2014-10-20 06:13:33 +00002668 OverflowOffset += RoundUpToAlignment(ArgSize, 8);
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00002669 IRB.CreateMemCpy(Base, MSV.getShadowPtr(A, IRB.getInt8Ty(), IRB),
2670 ArgSize, kShadowTLSAlignment);
2671 } else {
2672 ArgKind AK = classifyArgument(A);
2673 if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
2674 AK = AK_Memory;
2675 if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
2676 AK = AK_Memory;
2677 Value *Base;
2678 switch (AK) {
2679 case AK_GeneralPurpose:
2680 Base = getShadowPtrForVAArgument(A->getType(), IRB, GpOffset);
2681 GpOffset += 8;
2682 break;
2683 case AK_FloatingPoint:
2684 Base = getShadowPtrForVAArgument(A->getType(), IRB, FpOffset);
2685 FpOffset += 16;
2686 break;
2687 case AK_Memory:
2688 uint64_t ArgSize = MS.DL->getTypeAllocSize(A->getType());
2689 Base = getShadowPtrForVAArgument(A->getType(), IRB, OverflowOffset);
David Majnemerf3cadce2014-10-20 06:13:33 +00002690 OverflowOffset += RoundUpToAlignment(ArgSize, 8);
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00002691 }
2692 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002693 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002694 }
2695 Constant *OverflowSize =
2696 ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
2697 IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
2698 }
2699
2700 /// \brief Compute the shadow address for a given va_arg.
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00002701 Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002702 int ArgOffset) {
2703 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
2704 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00002705 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002706 "_msarg");
2707 }
2708
Craig Topper3e4c6972014-03-05 09:10:37 +00002709 void visitVAStartInst(VAStartInst &I) override {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002710 IRBuilder<> IRB(&I);
2711 VAStartInstrumentationList.push_back(&I);
2712 Value *VAListTag = I.getArgOperand(0);
2713 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2714
2715 // Unpoison the whole __va_list_tag.
2716 // FIXME: magic ABI constants.
2717 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
Peter Collingbournef7d65c42013-01-10 22:36:33 +00002718 /* size */24, /* alignment */8, false);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002719 }
2720
Craig Topper3e4c6972014-03-05 09:10:37 +00002721 void visitVACopyInst(VACopyInst &I) override {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002722 IRBuilder<> IRB(&I);
2723 Value *VAListTag = I.getArgOperand(0);
2724 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2725
2726 // Unpoison the whole __va_list_tag.
2727 // FIXME: magic ABI constants.
2728 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
Peter Collingbournef7d65c42013-01-10 22:36:33 +00002729 /* size */24, /* alignment */8, false);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002730 }
2731
Craig Topper3e4c6972014-03-05 09:10:37 +00002732 void finalizeInstrumentation() override {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002733 assert(!VAArgOverflowSize && !VAArgTLSCopy &&
2734 "finalizeInstrumentation called twice");
2735 if (!VAStartInstrumentationList.empty()) {
2736 // If there is a va_start in this function, make a backup copy of
2737 // va_arg_tls somewhere in the function entry block.
2738 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
2739 VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
2740 Value *CopySize =
2741 IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
2742 VAArgOverflowSize);
2743 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
2744 IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
2745 }
2746
2747 // Instrument va_start.
2748 // Copy va_list shadow from the backup copy of the TLS contents.
2749 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
2750 CallInst *OrigInst = VAStartInstrumentationList[i];
2751 IRBuilder<> IRB(OrigInst->getNextNode());
2752 Value *VAListTag = OrigInst->getArgOperand(0);
2753
2754 Value *RegSaveAreaPtrPtr =
2755 IRB.CreateIntToPtr(
2756 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2757 ConstantInt::get(MS.IntptrTy, 16)),
2758 Type::getInt64PtrTy(*MS.C));
2759 Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
2760 Value *RegSaveAreaShadowPtr =
2761 MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
2762 IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy,
2763 AMD64FpEndOffset, 16);
2764
2765 Value *OverflowArgAreaPtrPtr =
2766 IRB.CreateIntToPtr(
2767 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2768 ConstantInt::get(MS.IntptrTy, 8)),
2769 Type::getInt64PtrTy(*MS.C));
2770 Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
2771 Value *OverflowArgAreaShadowPtr =
2772 MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
Evgeniy Stepanovd42863c2013-08-23 12:11:00 +00002773 Value *SrcPtr = IRB.CreateConstGEP1_32(VAArgTLSCopy, AMD64FpEndOffset);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002774 IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
2775 }
2776 }
2777};
2778
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00002779/// \brief A no-op implementation of VarArgHelper.
2780struct VarArgNoOpHelper : public VarArgHelper {
2781 VarArgNoOpHelper(Function &F, MemorySanitizer &MS,
2782 MemorySanitizerVisitor &MSV) {}
2783
Craig Topper3e4c6972014-03-05 09:10:37 +00002784 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {}
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00002785
Craig Topper3e4c6972014-03-05 09:10:37 +00002786 void visitVAStartInst(VAStartInst &I) override {}
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00002787
Craig Topper3e4c6972014-03-05 09:10:37 +00002788 void visitVACopyInst(VACopyInst &I) override {}
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00002789
Craig Topper3e4c6972014-03-05 09:10:37 +00002790 void finalizeInstrumentation() override {}
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00002791};
2792
2793VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002794 MemorySanitizerVisitor &Visitor) {
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00002795 // VarArg handling is only implemented on AMD64. False positives are possible
2796 // on other platforms.
2797 llvm::Triple TargetTriple(Func.getParent()->getTargetTriple());
2798 if (TargetTriple.getArch() == llvm::Triple::x86_64)
2799 return new VarArgAMD64Helper(Func, Msan, Visitor);
2800 else
2801 return new VarArgNoOpHelper(Func, Msan, Visitor);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002802}
2803
2804} // namespace
2805
2806bool MemorySanitizer::runOnFunction(Function &F) {
2807 MemorySanitizerVisitor Visitor(F, *this);
2808
2809 // Clear out readonly/readnone attributes.
2810 AttrBuilder B;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002811 B.addAttribute(Attribute::ReadOnly)
2812 .addAttribute(Attribute::ReadNone);
Bill Wendling430fa9b2013-01-23 00:45:55 +00002813 F.removeAttributes(AttributeSet::FunctionIndex,
2814 AttributeSet::get(F.getContext(),
2815 AttributeSet::FunctionIndex, B));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002816
2817 return Visitor.runOnFunction();
2818}