blob: e890943c6a8431ca8f3b91d4132ab482c4854c71 [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 Stepanov65120ec2014-04-18 12:17:20 +0000130// Accesses sizes are powers of two: 1, 2, 4, 8.
131static const size_t kNumberOfAccessSizes = 4;
132
Evgeniy Stepanovd8be0c52012-12-26 10:59:00 +0000133/// \brief Track origins of uninitialized values.
Alexey Samsonov3efc87e2012-12-28 09:30:44 +0000134///
Evgeniy Stepanovd8be0c52012-12-26 10:59:00 +0000135/// Adds a section to MemorySanitizer report that points to the allocation
136/// (stack or heap) the uninitialized bits came from originally.
Evgeniy Stepanov302964e2014-03-18 13:30:56 +0000137static cl::opt<int> ClTrackOrigins("msan-track-origins",
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000138 cl::desc("Track origins (allocation sites) of poisoned memory"),
Evgeniy Stepanov302964e2014-03-18 13:30:56 +0000139 cl::Hidden, cl::init(0));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000140static cl::opt<bool> ClKeepGoing("msan-keep-going",
141 cl::desc("keep going after reporting a UMR"),
142 cl::Hidden, cl::init(false));
143static cl::opt<bool> ClPoisonStack("msan-poison-stack",
144 cl::desc("poison uninitialized stack variables"),
145 cl::Hidden, cl::init(true));
146static cl::opt<bool> ClPoisonStackWithCall("msan-poison-stack-with-call",
147 cl::desc("poison uninitialized stack variables with a call"),
148 cl::Hidden, cl::init(false));
149static cl::opt<int> ClPoisonStackPattern("msan-poison-stack-pattern",
150 cl::desc("poison uninitialized stack variables with the given patter"),
151 cl::Hidden, cl::init(0xff));
Evgeniy Stepanova9a962c2013-03-21 09:38:26 +0000152static cl::opt<bool> ClPoisonUndef("msan-poison-undef",
153 cl::desc("poison undef temps"),
154 cl::Hidden, cl::init(true));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000155
156static cl::opt<bool> ClHandleICmp("msan-handle-icmp",
157 cl::desc("propagate shadow through ICmpEQ and ICmpNE"),
158 cl::Hidden, cl::init(true));
159
Evgeniy Stepanovfac84032013-01-25 15:31:10 +0000160static cl::opt<bool> ClHandleICmpExact("msan-handle-icmp-exact",
161 cl::desc("exact handling of relational integer ICmp"),
Evgeniy Stepanov6f85ef32013-01-28 11:42:28 +0000162 cl::Hidden, cl::init(false));
Evgeniy Stepanovfac84032013-01-25 15:31:10 +0000163
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000164// This flag controls whether we check the shadow of the address
165// operand of load or store. Such bugs are very rare, since load from
166// a garbage address typically results in SEGV, but still happen
167// (e.g. only lower bits of address are garbage, or the access happens
168// early at program startup where malloc-ed memory is more likely to
169// be zeroed. As of 2012-08-28 this flag adds 20% slowdown.
170static cl::opt<bool> ClCheckAccessAddress("msan-check-access-address",
171 cl::desc("report accesses through a pointer which has poisoned shadow"),
172 cl::Hidden, cl::init(true));
173
174static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions",
175 cl::desc("print out instructions with default strict semantics"),
176 cl::Hidden, cl::init(false));
177
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000178static cl::opt<int> ClInstrumentationWithCallThreshold(
179 "msan-instrumentation-with-call-threshold",
180 cl::desc(
181 "If the function being instrumented requires more than "
182 "this number of checks and origin stores, use callbacks instead of "
183 "inline checks (-1 means never use callbacks)."),
Evgeniy Stepanov3939f542014-04-21 15:04:05 +0000184 cl::Hidden, cl::init(3500));
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000185
Evgeniy Stepanov37b86452013-09-19 15:22:35 +0000186// Experimental. Wraps all indirect calls in the instrumented code with
187// a call to the given function. This is needed to assist the dynamic
188// helper tool (MSanDR) to regain control on transition between instrumented and
189// non-instrumented code.
190static cl::opt<std::string> ClWrapIndirectCalls("msan-wrap-indirect-calls",
191 cl::desc("Wrap indirect calls with a given function"),
192 cl::Hidden);
193
Evgeniy Stepanov585813e2013-11-14 12:29:04 +0000194static cl::opt<bool> ClWrapIndirectCallsFast("msan-wrap-indirect-calls-fast",
195 cl::desc("Do not wrap indirect calls with target in the same module"),
196 cl::Hidden, cl::init(true));
197
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000198namespace {
199
200/// \brief An instrumentation pass implementing detection of uninitialized
201/// reads.
202///
203/// MemorySanitizer: instrument the code in module to find
204/// uninitialized reads.
205class MemorySanitizer : public FunctionPass {
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000206 public:
Alexey Samsonov6d8bab82014-06-02 18:08:27 +0000207 MemorySanitizer(int TrackOrigins = 0)
Evgeniy Stepanov37b86452013-09-19 15:22:35 +0000208 : FunctionPass(ID),
Evgeniy Stepanov302964e2014-03-18 13:30:56 +0000209 TrackOrigins(std::max(TrackOrigins, (int)ClTrackOrigins)),
Craig Topperf40110f2014-04-25 05:29:35 +0000210 DL(nullptr),
211 WarningFn(nullptr),
Evgeniy Stepanov37b86452013-09-19 15:22:35 +0000212 WrapIndirectCalls(!ClWrapIndirectCalls.empty()) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000213 const char *getPassName() const override { return "MemorySanitizer"; }
214 bool runOnFunction(Function &F) override;
215 bool doInitialization(Module &M) override;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000216 static char ID; // Pass identification, replacement for typeid.
217
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000218 private:
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000219 void initializeCallbacks(Module &M);
220
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000221 /// \brief Track origins (allocation points) of uninitialized values.
Evgeniy Stepanov302964e2014-03-18 13:30:56 +0000222 int TrackOrigins;
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000223
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000224 const DataLayout *DL;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000225 LLVMContext *C;
226 Type *IntptrTy;
227 Type *OriginTy;
228 /// \brief Thread-local shadow storage for function parameters.
229 GlobalVariable *ParamTLS;
230 /// \brief Thread-local origin storage for function parameters.
231 GlobalVariable *ParamOriginTLS;
232 /// \brief Thread-local shadow storage for function return value.
233 GlobalVariable *RetvalTLS;
234 /// \brief Thread-local origin storage for function return value.
235 GlobalVariable *RetvalOriginTLS;
236 /// \brief Thread-local shadow storage for in-register va_arg function
237 /// parameters (x86_64-specific).
238 GlobalVariable *VAArgTLS;
239 /// \brief Thread-local shadow storage for va_arg overflow area
240 /// (x86_64-specific).
241 GlobalVariable *VAArgOverflowSizeTLS;
242 /// \brief Thread-local space used to pass origin value to the UMR reporting
243 /// function.
244 GlobalVariable *OriginTLS;
245
Evgeniy Stepanov585813e2013-11-14 12:29:04 +0000246 GlobalVariable *MsandrModuleStart;
247 GlobalVariable *MsandrModuleEnd;
248
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000249 /// \brief The run-time callback to print a warning.
250 Value *WarningFn;
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000251 // These arrays are indexed by log2(AccessSize).
252 Value *MaybeWarningFn[kNumberOfAccessSizes];
253 Value *MaybeStoreOriginFn[kNumberOfAccessSizes];
254
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000255 /// \brief Run-time helper that generates a new origin value for a stack
256 /// allocation.
Evgeniy Stepanov0435ecd2013-09-13 12:54:49 +0000257 Value *MsanSetAllocaOrigin4Fn;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000258 /// \brief Run-time helper that poisons stack on function entry.
259 Value *MsanPoisonStackFn;
Evgeniy Stepanov302964e2014-03-18 13:30:56 +0000260 /// \brief Run-time helper that records a store (or any event) of an
261 /// uninitialized value and returns an updated origin id encoding this info.
262 Value *MsanChainOriginFn;
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +0000263 /// \brief MSan runtime replacements for memmove, memcpy and memset.
264 Value *MemmoveFn, *MemcpyFn, *MemsetFn;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000265
266 /// \brief Address mask used in application-to-shadow address calculation.
267 /// ShadowAddr is computed as ApplicationAddr & ~ShadowMask.
268 uint64_t ShadowMask;
269 /// \brief Offset of the origin shadow from the "normal" shadow.
270 /// OriginAddr is computed as (ShadowAddr + OriginOffset) & ~3ULL
271 uint64_t OriginOffset;
272 /// \brief Branch weights for error reporting.
273 MDNode *ColdCallWeights;
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000274 /// \brief Branch weights for origin store.
275 MDNode *OriginStoreWeights;
Evgeniy Stepanov1d2da652012-11-29 12:30:18 +0000276 /// \brief An empty volatile inline asm that prevents callback merge.
277 InlineAsm *EmptyAsm;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000278
Evgeniy Stepanov37b86452013-09-19 15:22:35 +0000279 bool WrapIndirectCalls;
280 /// \brief Run-time wrapper for indirect calls.
281 Value *IndirectCallWrapperFn;
282 // Argument and return type of IndirectCallWrapperFn: void (*f)(void).
283 Type *AnyFunctionPtrTy;
284
Evgeniy Stepanovda0072b2012-11-29 13:12:03 +0000285 friend struct MemorySanitizerVisitor;
286 friend struct VarArgAMD64Helper;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000287};
288} // namespace
289
290char MemorySanitizer::ID = 0;
291INITIALIZE_PASS(MemorySanitizer, "msan",
292 "MemorySanitizer: detects uninitialized reads.",
293 false, false)
294
Alexey Samsonov6d8bab82014-06-02 18:08:27 +0000295FunctionPass *llvm::createMemorySanitizerPass(int TrackOrigins) {
296 return new MemorySanitizer(TrackOrigins);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000297}
298
299/// \brief Create a non-const global initialized with the given string.
300///
301/// Creates a writable global for Str so that we can pass it to the
302/// run-time lib. Runtime uses first 4 bytes of the string to store the
303/// frame ID, so the string needs to be mutable.
304static GlobalVariable *createPrivateNonConstGlobalForString(Module &M,
305 StringRef Str) {
306 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
307 return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false,
308 GlobalValue::PrivateLinkage, StrConst, "");
309}
310
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000311
312/// \brief Insert extern declaration of runtime-provided functions and globals.
313void MemorySanitizer::initializeCallbacks(Module &M) {
314 // Only do this once.
315 if (WarningFn)
316 return;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000317
318 IRBuilder<> IRB(*C);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000319 // Create the callback.
320 // FIXME: this function should have "Cold" calling conv,
321 // which is not yet implemented.
322 StringRef WarningFnName = ClKeepGoing ? "__msan_warning"
323 : "__msan_warning_noreturn";
324 WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy(), NULL);
325
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000326 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
327 AccessSizeIndex++) {
328 unsigned AccessSize = 1 << AccessSizeIndex;
329 std::string FunctionName = "__msan_maybe_warning_" + itostr(AccessSize);
330 MaybeWarningFn[AccessSizeIndex] = M.getOrInsertFunction(
331 FunctionName, IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8),
332 IRB.getInt32Ty(), NULL);
333
334 FunctionName = "__msan_maybe_store_origin_" + itostr(AccessSize);
335 MaybeStoreOriginFn[AccessSizeIndex] = M.getOrInsertFunction(
336 FunctionName, IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8),
337 IRB.getInt8PtrTy(), IRB.getInt32Ty(), NULL);
338 }
339
Evgeniy Stepanov0435ecd2013-09-13 12:54:49 +0000340 MsanSetAllocaOrigin4Fn = M.getOrInsertFunction(
341 "__msan_set_alloca_origin4", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy,
342 IRB.getInt8PtrTy(), IntptrTy, NULL);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000343 MsanPoisonStackFn = M.getOrInsertFunction(
344 "__msan_poison_stack", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy, NULL);
Evgeniy Stepanov302964e2014-03-18 13:30:56 +0000345 MsanChainOriginFn = M.getOrInsertFunction(
346 "__msan_chain_origin", IRB.getInt32Ty(), IRB.getInt32Ty(), NULL);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000347 MemmoveFn = M.getOrInsertFunction(
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000348 "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
349 IRB.getInt8PtrTy(), IntptrTy, NULL);
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +0000350 MemcpyFn = M.getOrInsertFunction(
351 "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
352 IntptrTy, NULL);
353 MemsetFn = M.getOrInsertFunction(
354 "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000355 IntptrTy, NULL);
356
357 // Create globals.
358 RetvalTLS = new GlobalVariable(
359 M, ArrayType::get(IRB.getInt64Ty(), 8), false,
Craig Topperf40110f2014-04-25 05:29:35 +0000360 GlobalVariable::ExternalLinkage, nullptr, "__msan_retval_tls", nullptr,
Evgeniy Stepanov1e764322013-05-16 09:14:05 +0000361 GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000362 RetvalOriginTLS = new GlobalVariable(
Craig Topperf40110f2014-04-25 05:29:35 +0000363 M, OriginTy, false, GlobalVariable::ExternalLinkage, nullptr,
364 "__msan_retval_origin_tls", nullptr, GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000365
366 ParamTLS = new GlobalVariable(
367 M, ArrayType::get(IRB.getInt64Ty(), 1000), false,
Craig Topperf40110f2014-04-25 05:29:35 +0000368 GlobalVariable::ExternalLinkage, nullptr, "__msan_param_tls", nullptr,
Evgeniy Stepanov1e764322013-05-16 09:14:05 +0000369 GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000370 ParamOriginTLS = new GlobalVariable(
371 M, ArrayType::get(OriginTy, 1000), false, GlobalVariable::ExternalLinkage,
Craig Topperf40110f2014-04-25 05:29:35 +0000372 nullptr, "__msan_param_origin_tls", nullptr,
373 GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000374
375 VAArgTLS = new GlobalVariable(
376 M, ArrayType::get(IRB.getInt64Ty(), 1000), false,
Craig Topperf40110f2014-04-25 05:29:35 +0000377 GlobalVariable::ExternalLinkage, nullptr, "__msan_va_arg_tls", nullptr,
Evgeniy Stepanov1e764322013-05-16 09:14:05 +0000378 GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000379 VAArgOverflowSizeTLS = new GlobalVariable(
Craig Topperf40110f2014-04-25 05:29:35 +0000380 M, IRB.getInt64Ty(), false, GlobalVariable::ExternalLinkage, nullptr,
381 "__msan_va_arg_overflow_size_tls", nullptr,
Evgeniy Stepanov1e764322013-05-16 09:14:05 +0000382 GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000383 OriginTLS = new GlobalVariable(
Craig Topperf40110f2014-04-25 05:29:35 +0000384 M, IRB.getInt32Ty(), false, GlobalVariable::ExternalLinkage, nullptr,
385 "__msan_origin_tls", nullptr, GlobalVariable::InitialExecTLSModel);
Evgeniy Stepanov1d2da652012-11-29 12:30:18 +0000386
387 // We insert an empty inline asm after __msan_report* to avoid callback merge.
388 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
389 StringRef(""), StringRef(""),
390 /*hasSideEffects=*/true);
Evgeniy Stepanov37b86452013-09-19 15:22:35 +0000391
392 if (WrapIndirectCalls) {
393 AnyFunctionPtrTy =
394 PointerType::getUnqual(FunctionType::get(IRB.getVoidTy(), false));
395 IndirectCallWrapperFn = M.getOrInsertFunction(
396 ClWrapIndirectCalls, AnyFunctionPtrTy, AnyFunctionPtrTy, NULL);
397 }
Evgeniy Stepanov585813e2013-11-14 12:29:04 +0000398
Evgeniy Stepanovc14fc422014-05-07 14:10:51 +0000399 if (WrapIndirectCalls && ClWrapIndirectCallsFast) {
Evgeniy Stepanov585813e2013-11-14 12:29:04 +0000400 MsandrModuleStart = new GlobalVariable(
401 M, IRB.getInt32Ty(), false, GlobalValue::ExternalLinkage,
Craig Topperf40110f2014-04-25 05:29:35 +0000402 nullptr, "__executable_start");
Evgeniy Stepanov585813e2013-11-14 12:29:04 +0000403 MsandrModuleStart->setVisibility(GlobalVariable::HiddenVisibility);
404 MsandrModuleEnd = new GlobalVariable(
405 M, IRB.getInt32Ty(), false, GlobalValue::ExternalLinkage,
Craig Topperf40110f2014-04-25 05:29:35 +0000406 nullptr, "_end");
Evgeniy Stepanov585813e2013-11-14 12:29:04 +0000407 MsandrModuleEnd->setVisibility(GlobalVariable::HiddenVisibility);
408 }
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000409}
410
411/// \brief Module-level initialization.
412///
413/// inserts a call to __msan_init to the module's constructor list.
414bool MemorySanitizer::doInitialization(Module &M) {
Rafael Espindola93512512014-02-25 17:30:31 +0000415 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
416 if (!DLP)
Evgeniy Stepanov119cb2e2014-04-23 12:51:32 +0000417 report_fatal_error("data layout missing");
Rafael Espindola93512512014-02-25 17:30:31 +0000418 DL = &DLP->getDataLayout();
419
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000420 C = &(M.getContext());
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000421 unsigned PtrSize = DL->getPointerSizeInBits(/* AddressSpace */0);
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000422 switch (PtrSize) {
423 case 64:
424 ShadowMask = kShadowMask64;
425 OriginOffset = kOriginOffset64;
426 break;
427 case 32:
428 ShadowMask = kShadowMask32;
429 OriginOffset = kOriginOffset32;
430 break;
431 default:
432 report_fatal_error("unsupported pointer size");
433 break;
434 }
435
436 IRBuilder<> IRB(*C);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000437 IntptrTy = IRB.getIntPtrTy(DL);
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000438 OriginTy = IRB.getInt32Ty();
439
440 ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000441 OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000);
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000442
443 // Insert a call to __msan_init/__msan_track_origins into the module's CTORs.
444 appendToGlobalCtors(M, cast<Function>(M.getOrInsertFunction(
445 "__msan_init", IRB.getVoidTy(), NULL)), 0);
446
Evgeniy Stepanov888385e2013-05-31 12:04:29 +0000447 if (TrackOrigins)
448 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
449 IRB.getInt32(TrackOrigins), "__msan_track_origins");
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000450
Evgeniy Stepanov888385e2013-05-31 12:04:29 +0000451 if (ClKeepGoing)
452 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
453 IRB.getInt32(ClKeepGoing), "__msan_keep_going");
Evgeniy Stepanovdcf6bcb2013-01-22 13:26:53 +0000454
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000455 return true;
456}
457
458namespace {
459
460/// \brief A helper class that handles instrumentation of VarArg
461/// functions on a particular platform.
462///
463/// Implementations are expected to insert the instrumentation
464/// necessary to propagate argument shadow through VarArg function
465/// calls. Visit* methods are called during an InstVisitor pass over
466/// the function, and should avoid creating new basic blocks. A new
467/// instance of this class is created for each instrumented function.
468struct VarArgHelper {
469 /// \brief Visit a CallSite.
470 virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0;
471
472 /// \brief Visit a va_start call.
473 virtual void visitVAStartInst(VAStartInst &I) = 0;
474
475 /// \brief Visit a va_copy call.
476 virtual void visitVACopyInst(VACopyInst &I) = 0;
477
478 /// \brief Finalize function instrumentation.
479 ///
480 /// This method is called after visiting all interesting (see above)
481 /// instructions in a function.
482 virtual void finalizeInstrumentation() = 0;
Evgeniy Stepanovda0072b2012-11-29 13:12:03 +0000483
484 virtual ~VarArgHelper() {}
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000485};
486
487struct MemorySanitizerVisitor;
488
489VarArgHelper*
490CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
491 MemorySanitizerVisitor &Visitor);
492
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000493unsigned TypeSizeToSizeIndex(unsigned TypeSize) {
494 if (TypeSize <= 8) return 0;
495 return Log2_32_Ceil(TypeSize / 8);
496}
497
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000498/// This class does all the work for a given function. Store and Load
499/// instructions store and load corresponding shadow and origin
500/// values. Most instructions propagate shadow from arguments to their
501/// return values. Certain instructions (most importantly, BranchInst)
502/// test their argument shadow and print reports (with a runtime call) if it's
503/// non-zero.
504struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
505 Function &F;
506 MemorySanitizer &MS;
507 SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
508 ValueMap<Value*, Value*> ShadowMap, OriginMap;
Ahmed Charles56440fd2014-03-06 05:51:42 +0000509 std::unique_ptr<VarArgHelper> VAHelper;
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +0000510
511 // The following flags disable parts of MSan instrumentation based on
512 // blacklist contents and command-line options.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000513 bool InsertChecks;
Evgeniy Stepanov00062b42013-02-28 11:25:14 +0000514 bool LoadShadow;
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +0000515 bool PoisonStack;
516 bool PoisonUndef;
Evgeniy Stepanov604293f2013-09-16 13:24:32 +0000517 bool CheckReturnValue;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000518
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000519 struct ShadowOriginAndInsertPoint {
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +0000520 Value *Shadow;
521 Value *Origin;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000522 Instruction *OrigIns;
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +0000523 ShadowOriginAndInsertPoint(Value *S, Value *O, Instruction *I)
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000524 : Shadow(S), Origin(O), OrigIns(I) { }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000525 };
526 SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000527 SmallVector<Instruction*, 16> StoreList;
Evgeniy Stepanov585813e2013-11-14 12:29:04 +0000528 SmallVector<CallSite, 16> IndirectCallList;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000529
530 MemorySanitizerVisitor(Function &F, MemorySanitizer &MS)
Evgeniy Stepanov00062b42013-02-28 11:25:14 +0000531 : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)) {
Alexey Samsonov6d8bab82014-06-02 18:08:27 +0000532 bool SanitizeFunction = F.getAttributes().hasAttribute(
533 AttributeSet::FunctionIndex, Attribute::SanitizeMemory);
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +0000534 InsertChecks = SanitizeFunction;
535 LoadShadow = SanitizeFunction;
536 PoisonStack = SanitizeFunction && ClPoisonStack;
537 PoisonUndef = SanitizeFunction && ClPoisonUndef;
Evgeniy Stepanov604293f2013-09-16 13:24:32 +0000538 // FIXME: Consider using SpecialCaseList to specify a list of functions that
539 // must always return fully initialized values. For now, we hardcode "main".
540 CheckReturnValue = SanitizeFunction && (F.getName() == "main");
Evgeniy Stepanov00062b42013-02-28 11:25:14 +0000541
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000542 DEBUG(if (!InsertChecks)
Evgeniy Stepanov00062b42013-02-28 11:25:14 +0000543 dbgs() << "MemorySanitizer is not inserting checks into '"
544 << F.getName() << "'\n");
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000545 }
546
Evgeniy Stepanov302964e2014-03-18 13:30:56 +0000547 Value *updateOrigin(Value *V, IRBuilder<> &IRB) {
548 if (MS.TrackOrigins <= 1) return V;
549 return IRB.CreateCall(MS.MsanChainOriginFn, V);
550 }
551
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000552 void storeOrigin(IRBuilder<> &IRB, Value *Addr, Value *Shadow, Value *Origin,
553 unsigned Alignment, bool AsCall) {
554 if (isa<StructType>(Shadow->getType())) {
555 IRB.CreateAlignedStore(updateOrigin(Origin, IRB), getOriginPtr(Addr, IRB),
556 Alignment);
557 } else {
558 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
559 // TODO(eugenis): handle non-zero constant shadow by inserting an
560 // unconditional check (can not simply fail compilation as this could
561 // be in the dead code).
562 if (isa<Constant>(ConvertedShadow)) return;
563 unsigned TypeSizeInBits =
564 MS.DL->getTypeSizeInBits(ConvertedShadow->getType());
565 unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
566 if (AsCall && SizeIndex < kNumberOfAccessSizes) {
567 Value *Fn = MS.MaybeStoreOriginFn[SizeIndex];
568 Value *ConvertedShadow2 = IRB.CreateZExt(
569 ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
570 IRB.CreateCall3(Fn, ConvertedShadow2,
571 IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
572 updateOrigin(Origin, IRB));
573 } else {
574 Value *Cmp = IRB.CreateICmpNE(
575 ConvertedShadow, getCleanShadow(ConvertedShadow), "_mscmp");
576 Instruction *CheckTerm = SplitBlockAndInsertIfThen(
577 Cmp, IRB.GetInsertPoint(), false, MS.OriginStoreWeights);
578 IRBuilder<> IRBNew(CheckTerm);
579 IRBNew.CreateAlignedStore(updateOrigin(Origin, IRBNew),
580 getOriginPtr(Addr, IRBNew), Alignment);
581 }
582 }
583 }
584
585 void materializeStores(bool InstrumentWithCalls) {
Alexey Samsonova02e6642014-05-29 18:40:48 +0000586 for (auto Inst : StoreList) {
587 StoreInst &SI = *dyn_cast<StoreInst>(Inst);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000588
Alexey Samsonova02e6642014-05-29 18:40:48 +0000589 IRBuilder<> IRB(&SI);
590 Value *Val = SI.getValueOperand();
591 Value *Addr = SI.getPointerOperand();
592 Value *Shadow = SI.isAtomic() ? getCleanShadow(Val) : getShadow(Val);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000593 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
594
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000595 StoreInst *NewSI =
Alexey Samsonova02e6642014-05-29 18:40:48 +0000596 IRB.CreateAlignedStore(Shadow, ShadowPtr, SI.getAlignment());
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000597 DEBUG(dbgs() << " STORE: " << *NewSI << "\n");
NAKAMURA Takumie0b1b462012-12-06 13:38:00 +0000598 (void)NewSI;
Evgeniy Stepanovc4415592013-01-22 12:30:52 +0000599
Alexey Samsonova02e6642014-05-29 18:40:48 +0000600 if (ClCheckAccessAddress) insertShadowCheck(Addr, &SI);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000601
Alexey Samsonova02e6642014-05-29 18:40:48 +0000602 if (SI.isAtomic()) SI.setOrdering(addReleaseOrdering(SI.getOrdering()));
Evgeniy Stepanov5522a702013-09-24 11:20:27 +0000603
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000604 if (MS.TrackOrigins) {
Alexey Samsonova02e6642014-05-29 18:40:48 +0000605 unsigned Alignment = std::max(kMinOriginAlignment, SI.getAlignment());
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000606 storeOrigin(IRB, Addr, Shadow, getOrigin(Val), Alignment,
607 InstrumentWithCalls);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000608 }
609 }
610 }
611
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000612 void materializeOneCheck(Instruction *OrigIns, Value *Shadow, Value *Origin,
613 bool AsCall) {
614 IRBuilder<> IRB(OrigIns);
615 DEBUG(dbgs() << " SHAD0 : " << *Shadow << "\n");
616 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
617 DEBUG(dbgs() << " SHAD1 : " << *ConvertedShadow << "\n");
618 // See the comment in materializeStores().
619 if (isa<Constant>(ConvertedShadow)) return;
620 unsigned TypeSizeInBits =
621 MS.DL->getTypeSizeInBits(ConvertedShadow->getType());
622 unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
623 if (AsCall && SizeIndex < kNumberOfAccessSizes) {
624 Value *Fn = MS.MaybeWarningFn[SizeIndex];
625 Value *ConvertedShadow2 =
626 IRB.CreateZExt(ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
627 IRB.CreateCall2(Fn, ConvertedShadow2, MS.TrackOrigins && Origin
628 ? Origin
629 : (Value *)IRB.getInt32(0));
630 } else {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000631 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
632 getCleanShadow(ConvertedShadow), "_mscmp");
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000633 Instruction *CheckTerm = SplitBlockAndInsertIfThen(
634 Cmp, OrigIns,
635 /* Unreachable */ !ClKeepGoing, MS.ColdCallWeights);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000636
637 IRB.SetInsertPoint(CheckTerm);
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000638 if (MS.TrackOrigins) {
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000639 IRB.CreateStore(Origin ? (Value *)Origin : (Value *)IRB.getInt32(0),
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000640 MS.OriginTLS);
641 }
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000642 IRB.CreateCall(MS.WarningFn);
Evgeniy Stepanov1d2da652012-11-29 12:30:18 +0000643 IRB.CreateCall(MS.EmptyAsm);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000644 DEBUG(dbgs() << " CHECK: " << *Cmp << "\n");
645 }
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000646 }
647
648 void materializeChecks(bool InstrumentWithCalls) {
Alexey Samsonova02e6642014-05-29 18:40:48 +0000649 for (const auto &ShadowData : InstrumentationList) {
650 Instruction *OrigIns = ShadowData.OrigIns;
651 Value *Shadow = ShadowData.Shadow;
652 Value *Origin = ShadowData.Origin;
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000653 materializeOneCheck(OrigIns, Shadow, Origin, InstrumentWithCalls);
654 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000655 DEBUG(dbgs() << "DONE:\n" << F);
656 }
657
Evgeniy Stepanov585813e2013-11-14 12:29:04 +0000658 void materializeIndirectCalls() {
Alexey Samsonova02e6642014-05-29 18:40:48 +0000659 for (auto &CS : IndirectCallList) {
Evgeniy Stepanov585813e2013-11-14 12:29:04 +0000660 Instruction *I = CS.getInstruction();
661 BasicBlock *B = I->getParent();
662 IRBuilder<> IRB(I);
663 Value *Fn0 = CS.getCalledValue();
664 Value *Fn = IRB.CreateBitCast(Fn0, MS.AnyFunctionPtrTy);
665
666 if (ClWrapIndirectCallsFast) {
667 // Check that call target is inside this module limits.
668 Value *Start =
669 IRB.CreateBitCast(MS.MsandrModuleStart, MS.AnyFunctionPtrTy);
670 Value *End = IRB.CreateBitCast(MS.MsandrModuleEnd, MS.AnyFunctionPtrTy);
671
672 Value *NotInThisModule = IRB.CreateOr(IRB.CreateICmpULT(Fn, Start),
673 IRB.CreateICmpUGE(Fn, End));
674
675 PHINode *NewFnPhi =
676 IRB.CreatePHI(Fn0->getType(), 2, "msandr.indirect_target");
677
678 Instruction *CheckTerm = SplitBlockAndInsertIfThen(
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000679 NotInThisModule, NewFnPhi,
Evgeniy Stepanov585813e2013-11-14 12:29:04 +0000680 /* Unreachable */ false, MS.ColdCallWeights);
681
682 IRB.SetInsertPoint(CheckTerm);
683 // Slow path: call wrapper function to possibly transform the call
684 // target.
685 Value *NewFn = IRB.CreateBitCast(
686 IRB.CreateCall(MS.IndirectCallWrapperFn, Fn), Fn0->getType());
687
688 NewFnPhi->addIncoming(Fn0, B);
689 NewFnPhi->addIncoming(NewFn, dyn_cast<Instruction>(NewFn)->getParent());
690 CS.setCalledFunction(NewFnPhi);
691 } else {
692 Value *NewFn = IRB.CreateBitCast(
693 IRB.CreateCall(MS.IndirectCallWrapperFn, Fn), Fn0->getType());
694 CS.setCalledFunction(NewFn);
695 }
696 }
697 }
698
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000699 /// \brief Add MemorySanitizer instrumentation to a function.
700 bool runOnFunction() {
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000701 MS.initializeCallbacks(*F.getParent());
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000702 if (!MS.DL) return false;
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +0000703
704 // In the presence of unreachable blocks, we may see Phi nodes with
705 // incoming nodes from such blocks. Since InstVisitor skips unreachable
706 // blocks, such nodes will not have any shadow value associated with them.
707 // It's easier to remove unreachable blocks than deal with missing shadow.
708 removeUnreachableBlocks(F);
709
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000710 // Iterate all BBs in depth-first order and create shadow instructions
711 // for all instructions (where applicable).
712 // For PHI nodes we create dummy shadow PHIs which will be finalized later.
David Blaikieceec2bd2014-04-11 01:50:01 +0000713 for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000714 visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000715
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000716
717 // Finalize PHI nodes.
Alexey Samsonova02e6642014-05-29 18:40:48 +0000718 for (PHINode *PN : ShadowPHINodes) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000719 PHINode *PNS = cast<PHINode>(getShadow(PN));
Craig Topperf40110f2014-04-25 05:29:35 +0000720 PHINode *PNO = MS.TrackOrigins ? cast<PHINode>(getOrigin(PN)) : nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000721 size_t NumValues = PN->getNumIncomingValues();
722 for (size_t v = 0; v < NumValues; v++) {
723 PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
724 if (PNO)
725 PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
726 }
727 }
728
729 VAHelper->finalizeInstrumentation();
730
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000731 bool InstrumentWithCalls = ClInstrumentationWithCallThreshold >= 0 &&
732 InstrumentationList.size() + StoreList.size() >
733 (unsigned)ClInstrumentationWithCallThreshold;
734
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000735 // Delayed instrumentation of StoreInst.
Evgeniy Stepanov47ac9ba2012-12-06 11:58:59 +0000736 // This may add new checks to be inserted later.
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000737 materializeStores(InstrumentWithCalls);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000738
739 // Insert shadow value checks.
Evgeniy Stepanov65120ec2014-04-18 12:17:20 +0000740 materializeChecks(InstrumentWithCalls);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000741
Evgeniy Stepanov585813e2013-11-14 12:29:04 +0000742 // Wrap indirect calls.
743 materializeIndirectCalls();
744
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000745 return true;
746 }
747
748 /// \brief Compute the shadow type that corresponds to a given Value.
749 Type *getShadowTy(Value *V) {
750 return getShadowTy(V->getType());
751 }
752
753 /// \brief Compute the shadow type that corresponds to a given Type.
754 Type *getShadowTy(Type *OrigTy) {
755 if (!OrigTy->isSized()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000756 return nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000757 }
758 // For integer type, shadow is the same as the original type.
759 // This may return weird-sized types like i1.
760 if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
761 return IT;
Evgeniy Stepanovf19c0862012-12-25 16:04:38 +0000762 if (VectorType *VT = dyn_cast<VectorType>(OrigTy)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000763 uint32_t EltSize = MS.DL->getTypeSizeInBits(VT->getElementType());
Evgeniy Stepanovf19c0862012-12-25 16:04:38 +0000764 return VectorType::get(IntegerType::get(*MS.C, EltSize),
765 VT->getNumElements());
766 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000767 if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
768 SmallVector<Type*, 4> Elements;
769 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
770 Elements.push_back(getShadowTy(ST->getElementType(i)));
771 StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
772 DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
773 return Res;
774 }
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000775 uint32_t TypeSize = MS.DL->getTypeSizeInBits(OrigTy);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000776 return IntegerType::get(*MS.C, TypeSize);
777 }
778
779 /// \brief Flatten a vector type.
780 Type *getShadowTyNoVec(Type *ty) {
781 if (VectorType *vt = dyn_cast<VectorType>(ty))
782 return IntegerType::get(*MS.C, vt->getBitWidth());
783 return ty;
784 }
785
786 /// \brief Convert a shadow value to it's flattened variant.
787 Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
788 Type *Ty = V->getType();
789 Type *NoVecTy = getShadowTyNoVec(Ty);
790 if (Ty == NoVecTy) return V;
791 return IRB.CreateBitCast(V, NoVecTy);
792 }
793
794 /// \brief Compute the shadow address that corresponds to a given application
795 /// address.
796 ///
797 /// Shadow = Addr & ~ShadowMask.
798 Value *getShadowPtr(Value *Addr, Type *ShadowTy,
799 IRBuilder<> &IRB) {
800 Value *ShadowLong =
801 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
802 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
803 return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
804 }
805
806 /// \brief Compute the origin address that corresponds to a given application
807 /// address.
808 ///
809 /// OriginAddr = (ShadowAddr + OriginOffset) & ~3ULL
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000810 Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB) {
811 Value *ShadowLong =
812 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
Evgeniy Stepanov62ba6112012-11-29 13:43:05 +0000813 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000814 Value *Add =
815 IRB.CreateAdd(ShadowLong,
816 ConstantInt::get(MS.IntptrTy, MS.OriginOffset));
Evgeniy Stepanov62ba6112012-11-29 13:43:05 +0000817 Value *SecondAnd =
818 IRB.CreateAnd(Add, ConstantInt::get(MS.IntptrTy, ~3ULL));
819 return IRB.CreateIntToPtr(SecondAnd, PointerType::get(IRB.getInt32Ty(), 0));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000820 }
821
822 /// \brief Compute the shadow address for a given function argument.
823 ///
824 /// Shadow = ParamTLS+ArgOffset.
825 Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
826 int ArgOffset) {
827 Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
828 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
829 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
830 "_msarg");
831 }
832
833 /// \brief Compute the origin address for a given function argument.
834 Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
835 int ArgOffset) {
Craig Topperf40110f2014-04-25 05:29:35 +0000836 if (!MS.TrackOrigins) return nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000837 Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
838 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
839 return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
840 "_msarg_o");
841 }
842
843 /// \brief Compute the shadow address for a retval.
844 Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
845 Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy);
846 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
847 "_msret");
848 }
849
850 /// \brief Compute the origin address for a retval.
851 Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
852 // We keep a single origin for the entire retval. Might be too optimistic.
853 return MS.RetvalOriginTLS;
854 }
855
856 /// \brief Set SV to be the shadow value for V.
857 void setShadow(Value *V, Value *SV) {
858 assert(!ShadowMap.count(V) && "Values may only have one shadow");
859 ShadowMap[V] = SV;
860 }
861
862 /// \brief Set Origin to be the origin value for V.
863 void setOrigin(Value *V, Value *Origin) {
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000864 if (!MS.TrackOrigins) return;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000865 assert(!OriginMap.count(V) && "Values may only have one origin");
866 DEBUG(dbgs() << "ORIGIN: " << *V << " ==> " << *Origin << "\n");
867 OriginMap[V] = Origin;
868 }
869
870 /// \brief Create a clean shadow value for a given value.
871 ///
872 /// Clean shadow (all zeroes) means all bits of the value are defined
873 /// (initialized).
Evgeniy Stepanova9a962c2013-03-21 09:38:26 +0000874 Constant *getCleanShadow(Value *V) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000875 Type *ShadowTy = getShadowTy(V);
876 if (!ShadowTy)
Craig Topperf40110f2014-04-25 05:29:35 +0000877 return nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000878 return Constant::getNullValue(ShadowTy);
879 }
880
881 /// \brief Create a dirty shadow of a given shadow type.
882 Constant *getPoisonedShadow(Type *ShadowTy) {
883 assert(ShadowTy);
884 if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
885 return Constant::getAllOnesValue(ShadowTy);
886 StructType *ST = cast<StructType>(ShadowTy);
887 SmallVector<Constant *, 4> Vals;
888 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
889 Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
890 return ConstantStruct::get(ST, Vals);
891 }
892
Evgeniy Stepanova9a962c2013-03-21 09:38:26 +0000893 /// \brief Create a dirty shadow for a given value.
894 Constant *getPoisonedShadow(Value *V) {
895 Type *ShadowTy = getShadowTy(V);
896 if (!ShadowTy)
Craig Topperf40110f2014-04-25 05:29:35 +0000897 return nullptr;
Evgeniy Stepanova9a962c2013-03-21 09:38:26 +0000898 return getPoisonedShadow(ShadowTy);
899 }
900
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000901 /// \brief Create a clean (zero) origin.
902 Value *getCleanOrigin() {
903 return Constant::getNullValue(MS.OriginTy);
904 }
905
906 /// \brief Get the shadow value for a given Value.
907 ///
908 /// This function either returns the value set earlier with setShadow,
909 /// or extracts if from ParamTLS (for function arguments).
910 Value *getShadow(Value *V) {
911 if (Instruction *I = dyn_cast<Instruction>(V)) {
912 // For instructions the shadow is already stored in the map.
913 Value *Shadow = ShadowMap[V];
914 if (!Shadow) {
915 DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +0000916 (void)I;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000917 assert(Shadow && "No shadow for a value");
918 }
919 return Shadow;
920 }
921 if (UndefValue *U = dyn_cast<UndefValue>(V)) {
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +0000922 Value *AllOnes = PoisonUndef ? getPoisonedShadow(V) : getCleanShadow(V);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000923 DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +0000924 (void)U;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000925 return AllOnes;
926 }
927 if (Argument *A = dyn_cast<Argument>(V)) {
928 // For arguments we compute the shadow on demand and store it in the map.
929 Value **ShadowPtr = &ShadowMap[V];
930 if (*ShadowPtr)
931 return *ShadowPtr;
932 Function *F = A->getParent();
933 IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI());
934 unsigned ArgOffset = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +0000935 for (auto &FArg : F->args()) {
936 if (!FArg.getType()->isSized()) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000937 DEBUG(dbgs() << "Arg is not sized\n");
938 continue;
939 }
Alexey Samsonova02e6642014-05-29 18:40:48 +0000940 unsigned Size = FArg.hasByValAttr()
941 ? MS.DL->getTypeAllocSize(FArg.getType()->getPointerElementType())
942 : MS.DL->getTypeAllocSize(FArg.getType());
943 if (A == &FArg) {
944 Value *Base = getShadowPtrForArgument(&FArg, EntryIRB, ArgOffset);
945 if (FArg.hasByValAttr()) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000946 // ByVal pointer itself has clean shadow. We copy the actual
947 // argument shadow to the underlying memory.
Evgeniy Stepanovfca01232013-05-28 13:07:43 +0000948 // Figure out maximal valid memcpy alignment.
Alexey Samsonova02e6642014-05-29 18:40:48 +0000949 unsigned ArgAlign = FArg.getParamAlignment();
Evgeniy Stepanovfca01232013-05-28 13:07:43 +0000950 if (ArgAlign == 0) {
951 Type *EltType = A->getType()->getPointerElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000952 ArgAlign = MS.DL->getABITypeAlignment(EltType);
Evgeniy Stepanovfca01232013-05-28 13:07:43 +0000953 }
954 unsigned CopyAlign = std::min(ArgAlign, kShadowTLSAlignment);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000955 Value *Cpy = EntryIRB.CreateMemCpy(
Evgeniy Stepanovfca01232013-05-28 13:07:43 +0000956 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB), Base, Size,
957 CopyAlign);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000958 DEBUG(dbgs() << " ByValCpy: " << *Cpy << "\n");
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +0000959 (void)Cpy;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000960 *ShadowPtr = getCleanShadow(V);
961 } else {
Evgeniy Stepanovfca01232013-05-28 13:07:43 +0000962 *ShadowPtr = EntryIRB.CreateAlignedLoad(Base, kShadowTLSAlignment);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000963 }
Alexey Samsonova02e6642014-05-29 18:40:48 +0000964 DEBUG(dbgs() << " ARG: " << FArg << " ==> " <<
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000965 **ShadowPtr << "\n");
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000966 if (MS.TrackOrigins) {
Alexey Samsonova02e6642014-05-29 18:40:48 +0000967 Value *OriginPtr =
968 getOriginPtrForArgument(&FArg, EntryIRB, ArgOffset);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000969 setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
970 }
971 }
Evgeniy Stepanovfca01232013-05-28 13:07:43 +0000972 ArgOffset += DataLayout::RoundUpAlignment(Size, kShadowTLSAlignment);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000973 }
974 assert(*ShadowPtr && "Could not find shadow for an argument");
975 return *ShadowPtr;
976 }
977 // For everything else the shadow is zero.
978 return getCleanShadow(V);
979 }
980
981 /// \brief Get the shadow for i-th argument of the instruction I.
982 Value *getShadow(Instruction *I, int i) {
983 return getShadow(I->getOperand(i));
984 }
985
986 /// \brief Get the origin for a value.
987 Value *getOrigin(Value *V) {
Craig Topperf40110f2014-04-25 05:29:35 +0000988 if (!MS.TrackOrigins) return nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000989 if (isa<Instruction>(V) || isa<Argument>(V)) {
990 Value *Origin = OriginMap[V];
991 if (!Origin) {
992 DEBUG(dbgs() << "NO ORIGIN: " << *V << "\n");
993 Origin = getCleanOrigin();
994 }
995 return Origin;
996 }
997 return getCleanOrigin();
998 }
999
1000 /// \brief Get the origin for i-th argument of the instruction I.
1001 Value *getOrigin(Instruction *I, int i) {
1002 return getOrigin(I->getOperand(i));
1003 }
1004
1005 /// \brief Remember the place where a shadow check should be inserted.
1006 ///
1007 /// This location will be later instrumented with a check that will print a
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001008 /// UMR warning in runtime if the shadow value is not 0.
1009 void insertShadowCheck(Value *Shadow, Value *Origin, Instruction *OrigIns) {
1010 assert(Shadow);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001011 if (!InsertChecks) return;
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +00001012#ifndef NDEBUG
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001013 Type *ShadowTy = Shadow->getType();
1014 assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
1015 "Can only insert checks for integer and vector shadow types");
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +00001016#endif
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001017 InstrumentationList.push_back(
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001018 ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
1019 }
1020
1021 /// \brief Remember the place where a shadow check should be inserted.
1022 ///
1023 /// This location will be later instrumented with a check that will print a
1024 /// UMR warning in runtime if the value is not fully defined.
1025 void insertShadowCheck(Value *Val, Instruction *OrigIns) {
1026 assert(Val);
1027 Instruction *Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
1028 if (!Shadow) return;
1029 Instruction *Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
1030 insertShadowCheck(Shadow, Origin, OrigIns);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001031 }
1032
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001033 AtomicOrdering addReleaseOrdering(AtomicOrdering a) {
1034 switch (a) {
1035 case NotAtomic:
1036 return NotAtomic;
1037 case Unordered:
1038 case Monotonic:
1039 case Release:
1040 return Release;
1041 case Acquire:
1042 case AcquireRelease:
1043 return AcquireRelease;
1044 case SequentiallyConsistent:
1045 return SequentiallyConsistent;
1046 }
Evgeniy Stepanov32be0342013-09-25 08:56:00 +00001047 llvm_unreachable("Unknown ordering");
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001048 }
1049
1050 AtomicOrdering addAcquireOrdering(AtomicOrdering a) {
1051 switch (a) {
1052 case NotAtomic:
1053 return NotAtomic;
1054 case Unordered:
1055 case Monotonic:
1056 case Acquire:
1057 return Acquire;
1058 case Release:
1059 case AcquireRelease:
1060 return AcquireRelease;
1061 case SequentiallyConsistent:
1062 return SequentiallyConsistent;
1063 }
Evgeniy Stepanov32be0342013-09-25 08:56:00 +00001064 llvm_unreachable("Unknown ordering");
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001065 }
1066
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +00001067 // ------------------- Visitors.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001068
1069 /// \brief Instrument LoadInst
1070 ///
1071 /// Loads the corresponding shadow and (optionally) origin.
1072 /// Optionally, checks that the load address is fully defined.
1073 void visitLoadInst(LoadInst &I) {
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +00001074 assert(I.getType()->isSized() && "Load type must have size");
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001075 IRBuilder<> IRB(I.getNextNode());
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001076 Type *ShadowTy = getShadowTy(&I);
1077 Value *Addr = I.getPointerOperand();
Evgeniy Stepanov00062b42013-02-28 11:25:14 +00001078 if (LoadShadow) {
1079 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1080 setShadow(&I,
1081 IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld"));
1082 } else {
1083 setShadow(&I, getCleanShadow(&I));
1084 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001085
1086 if (ClCheckAccessAddress)
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001087 insertShadowCheck(I.getPointerOperand(), &I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001088
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001089 if (I.isAtomic())
1090 I.setOrdering(addAcquireOrdering(I.getOrdering()));
1091
Evgeniy Stepanov5eb5bf82012-12-26 11:55:09 +00001092 if (MS.TrackOrigins) {
Evgeniy Stepanov00062b42013-02-28 11:25:14 +00001093 if (LoadShadow) {
1094 unsigned Alignment = std::max(kMinOriginAlignment, I.getAlignment());
1095 setOrigin(&I,
1096 IRB.CreateAlignedLoad(getOriginPtr(Addr, IRB), Alignment));
1097 } else {
1098 setOrigin(&I, getCleanOrigin());
1099 }
Evgeniy Stepanov5eb5bf82012-12-26 11:55:09 +00001100 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001101 }
1102
1103 /// \brief Instrument StoreInst
1104 ///
1105 /// Stores the corresponding shadow and (optionally) origin.
1106 /// Optionally, checks that the store address is fully defined.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001107 void visitStoreInst(StoreInst &I) {
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +00001108 StoreList.push_back(&I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001109 }
1110
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001111 void handleCASOrRMW(Instruction &I) {
1112 assert(isa<AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I));
1113
1114 IRBuilder<> IRB(&I);
1115 Value *Addr = I.getOperand(0);
1116 Value *ShadowPtr = getShadowPtr(Addr, I.getType(), IRB);
1117
1118 if (ClCheckAccessAddress)
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001119 insertShadowCheck(Addr, &I);
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001120
1121 // Only test the conditional argument of cmpxchg instruction.
1122 // The other argument can potentially be uninitialized, but we can not
1123 // detect this situation reliably without possible false positives.
1124 if (isa<AtomicCmpXchgInst>(I))
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001125 insertShadowCheck(I.getOperand(1), &I);
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001126
1127 IRB.CreateStore(getCleanShadow(&I), ShadowPtr);
1128
1129 setShadow(&I, getCleanShadow(&I));
1130 }
1131
1132 void visitAtomicRMWInst(AtomicRMWInst &I) {
1133 handleCASOrRMW(I);
1134 I.setOrdering(addReleaseOrdering(I.getOrdering()));
1135 }
1136
1137 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
1138 handleCASOrRMW(I);
Tim Northovere94a5182014-03-11 10:48:52 +00001139 I.setSuccessOrdering(addReleaseOrdering(I.getSuccessOrdering()));
Evgeniy Stepanov5522a702013-09-24 11:20:27 +00001140 }
1141
Evgeniy Stepanov30484fc2012-11-29 15:22:06 +00001142 // Vector manipulation.
1143 void visitExtractElementInst(ExtractElementInst &I) {
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001144 insertShadowCheck(I.getOperand(1), &I);
Evgeniy Stepanov30484fc2012-11-29 15:22:06 +00001145 IRBuilder<> IRB(&I);
1146 setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
1147 "_msprop"));
1148 setOrigin(&I, getOrigin(&I, 0));
1149 }
1150
1151 void visitInsertElementInst(InsertElementInst &I) {
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001152 insertShadowCheck(I.getOperand(2), &I);
Evgeniy Stepanov30484fc2012-11-29 15:22:06 +00001153 IRBuilder<> IRB(&I);
1154 setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
1155 I.getOperand(2), "_msprop"));
1156 setOriginForNaryOp(I);
1157 }
1158
1159 void visitShuffleVectorInst(ShuffleVectorInst &I) {
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001160 insertShadowCheck(I.getOperand(2), &I);
Evgeniy Stepanov30484fc2012-11-29 15:22:06 +00001161 IRBuilder<> IRB(&I);
1162 setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
1163 I.getOperand(2), "_msprop"));
1164 setOriginForNaryOp(I);
1165 }
1166
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001167 // Casts.
1168 void visitSExtInst(SExtInst &I) {
1169 IRBuilder<> IRB(&I);
1170 setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
1171 setOrigin(&I, getOrigin(&I, 0));
1172 }
1173
1174 void visitZExtInst(ZExtInst &I) {
1175 IRBuilder<> IRB(&I);
1176 setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
1177 setOrigin(&I, getOrigin(&I, 0));
1178 }
1179
1180 void visitTruncInst(TruncInst &I) {
1181 IRBuilder<> IRB(&I);
1182 setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
1183 setOrigin(&I, getOrigin(&I, 0));
1184 }
1185
1186 void visitBitCastInst(BitCastInst &I) {
1187 IRBuilder<> IRB(&I);
1188 setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
1189 setOrigin(&I, getOrigin(&I, 0));
1190 }
1191
1192 void visitPtrToIntInst(PtrToIntInst &I) {
1193 IRBuilder<> IRB(&I);
1194 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1195 "_msprop_ptrtoint"));
1196 setOrigin(&I, getOrigin(&I, 0));
1197 }
1198
1199 void visitIntToPtrInst(IntToPtrInst &I) {
1200 IRBuilder<> IRB(&I);
1201 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1202 "_msprop_inttoptr"));
1203 setOrigin(&I, getOrigin(&I, 0));
1204 }
1205
1206 void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
1207 void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
1208 void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
1209 void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
1210 void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
1211 void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
1212
1213 /// \brief Propagate shadow for bitwise AND.
1214 ///
1215 /// This code is exact, i.e. if, for example, a bit in the left argument
1216 /// is defined and 0, then neither the value not definedness of the
1217 /// corresponding bit in B don't affect the resulting shadow.
1218 void visitAnd(BinaryOperator &I) {
1219 IRBuilder<> IRB(&I);
1220 // "And" of 0 and a poisoned value results in unpoisoned value.
1221 // 1&1 => 1; 0&1 => 0; p&1 => p;
1222 // 1&0 => 0; 0&0 => 0; p&0 => 0;
1223 // 1&p => p; 0&p => 0; p&p => p;
1224 // S = (S1 & S2) | (V1 & S2) | (S1 & V2)
1225 Value *S1 = getShadow(&I, 0);
1226 Value *S2 = getShadow(&I, 1);
1227 Value *V1 = I.getOperand(0);
1228 Value *V2 = I.getOperand(1);
1229 if (V1->getType() != S1->getType()) {
1230 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1231 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1232 }
1233 Value *S1S2 = IRB.CreateAnd(S1, S2);
1234 Value *V1S2 = IRB.CreateAnd(V1, S2);
1235 Value *S1V2 = IRB.CreateAnd(S1, V2);
1236 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1237 setOriginForNaryOp(I);
1238 }
1239
1240 void visitOr(BinaryOperator &I) {
1241 IRBuilder<> IRB(&I);
1242 // "Or" of 1 and a poisoned value results in unpoisoned value.
1243 // 1|1 => 1; 0|1 => 1; p|1 => 1;
1244 // 1|0 => 1; 0|0 => 0; p|0 => p;
1245 // 1|p => 1; 0|p => p; p|p => p;
1246 // S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
1247 Value *S1 = getShadow(&I, 0);
1248 Value *S2 = getShadow(&I, 1);
1249 Value *V1 = IRB.CreateNot(I.getOperand(0));
1250 Value *V2 = IRB.CreateNot(I.getOperand(1));
1251 if (V1->getType() != S1->getType()) {
1252 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1253 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1254 }
1255 Value *S1S2 = IRB.CreateAnd(S1, S2);
1256 Value *V1S2 = IRB.CreateAnd(V1, S2);
1257 Value *S1V2 = IRB.CreateAnd(S1, V2);
1258 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1259 setOriginForNaryOp(I);
1260 }
1261
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001262 /// \brief Default propagation of shadow and/or origin.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001263 ///
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001264 /// This class implements the general case of shadow propagation, used in all
1265 /// cases where we don't know and/or don't care about what the operation
1266 /// actually does. It converts all input shadow values to a common type
1267 /// (extending or truncating as necessary), and bitwise OR's them.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001268 ///
1269 /// This is much cheaper than inserting checks (i.e. requiring inputs to be
1270 /// fully initialized), and less prone to false positives.
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001271 ///
1272 /// This class also implements the general case of origin propagation. For a
1273 /// Nary operation, result origin is set to the origin of an argument that is
1274 /// not entirely initialized. If there is more than one such arguments, the
1275 /// rightmost of them is picked. It does not matter which one is picked if all
1276 /// arguments are initialized.
1277 template <bool CombineShadow>
1278 class Combiner {
1279 Value *Shadow;
1280 Value *Origin;
1281 IRBuilder<> &IRB;
1282 MemorySanitizerVisitor *MSV;
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +00001283
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001284 public:
1285 Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB) :
Craig Topperf40110f2014-04-25 05:29:35 +00001286 Shadow(nullptr), Origin(nullptr), IRB(IRB), MSV(MSV) {}
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001287
1288 /// \brief Add a pair of shadow and origin values to the mix.
1289 Combiner &Add(Value *OpShadow, Value *OpOrigin) {
1290 if (CombineShadow) {
1291 assert(OpShadow);
1292 if (!Shadow)
1293 Shadow = OpShadow;
1294 else {
1295 OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
1296 Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
1297 }
1298 }
1299
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001300 if (MSV->MS.TrackOrigins) {
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001301 assert(OpOrigin);
1302 if (!Origin) {
1303 Origin = OpOrigin;
1304 } else {
Evgeniy Stepanov70d1b0a2014-06-09 14:29:34 +00001305 Constant *ConstOrigin = dyn_cast<Constant>(OpOrigin);
1306 // No point in adding something that might result in 0 origin value.
1307 if (!ConstOrigin || !ConstOrigin->isNullValue()) {
1308 Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB);
1309 Value *Cond =
1310 IRB.CreateICmpNE(FlatShadow, MSV->getCleanShadow(FlatShadow));
1311 Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
1312 }
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001313 }
1314 }
1315 return *this;
1316 }
1317
1318 /// \brief Add an application value to the mix.
1319 Combiner &Add(Value *V) {
1320 Value *OpShadow = MSV->getShadow(V);
Craig Topperf40110f2014-04-25 05:29:35 +00001321 Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : nullptr;
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001322 return Add(OpShadow, OpOrigin);
1323 }
1324
1325 /// \brief Set the current combined values as the given instruction's shadow
1326 /// and origin.
1327 void Done(Instruction *I) {
1328 if (CombineShadow) {
1329 assert(Shadow);
1330 Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
1331 MSV->setShadow(I, Shadow);
1332 }
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001333 if (MSV->MS.TrackOrigins) {
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001334 assert(Origin);
1335 MSV->setOrigin(I, Origin);
1336 }
1337 }
1338 };
1339
1340 typedef Combiner<true> ShadowAndOriginCombiner;
1341 typedef Combiner<false> OriginCombiner;
1342
1343 /// \brief Propagate origin for arbitrary operation.
1344 void setOriginForNaryOp(Instruction &I) {
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001345 if (!MS.TrackOrigins) return;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001346 IRBuilder<> IRB(&I);
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001347 OriginCombiner OC(this, IRB);
1348 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1349 OC.Add(OI->get());
1350 OC.Done(&I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001351 }
1352
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001353 size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
Evgeniy Stepanovf19c0862012-12-25 16:04:38 +00001354 assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) &&
1355 "Vector of pointers is not a valid shadow type");
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001356 return Ty->isVectorTy() ?
1357 Ty->getVectorNumElements() * Ty->getScalarSizeInBits() :
1358 Ty->getPrimitiveSizeInBits();
1359 }
1360
1361 /// \brief Cast between two shadow types, extending or truncating as
1362 /// necessary.
Evgeniy Stepanov21a9c932013-10-17 10:53:50 +00001363 Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy,
1364 bool Signed = false) {
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001365 Type *srcTy = V->getType();
1366 if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
Evgeniy Stepanov21a9c932013-10-17 10:53:50 +00001367 return IRB.CreateIntCast(V, dstTy, Signed);
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001368 if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
1369 dstTy->getVectorNumElements() == srcTy->getVectorNumElements())
Evgeniy Stepanov21a9c932013-10-17 10:53:50 +00001370 return IRB.CreateIntCast(V, dstTy, Signed);
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001371 size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
1372 size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
1373 Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
1374 Value *V2 =
Evgeniy Stepanov21a9c932013-10-17 10:53:50 +00001375 IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), Signed);
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001376 return IRB.CreateBitCast(V2, dstTy);
1377 // TODO: handle struct types.
1378 }
1379
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00001380 /// \brief Cast an application value to the type of its own shadow.
1381 Value *CreateAppToShadowCast(IRBuilder<> &IRB, Value *V) {
1382 Type *ShadowTy = getShadowTy(V);
1383 if (V->getType() == ShadowTy)
1384 return V;
1385 if (V->getType()->isPtrOrPtrVectorTy())
1386 return IRB.CreatePtrToInt(V, ShadowTy);
1387 else
1388 return IRB.CreateBitCast(V, ShadowTy);
1389 }
1390
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001391 /// \brief Propagate shadow for arbitrary operation.
1392 void handleShadowOr(Instruction &I) {
1393 IRBuilder<> IRB(&I);
1394 ShadowAndOriginCombiner SC(this, IRB);
1395 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1396 SC.Add(OI->get());
1397 SC.Done(&I);
1398 }
1399
1400 void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
1401 void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
1402 void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
1403 void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
1404 void visitSub(BinaryOperator &I) { handleShadowOr(I); }
1405 void visitXor(BinaryOperator &I) { handleShadowOr(I); }
1406 void visitMul(BinaryOperator &I) { handleShadowOr(I); }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001407
1408 void handleDiv(Instruction &I) {
1409 IRBuilder<> IRB(&I);
1410 // Strict on the second argument.
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001411 insertShadowCheck(I.getOperand(1), &I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001412 setShadow(&I, getShadow(&I, 0));
1413 setOrigin(&I, getOrigin(&I, 0));
1414 }
1415
1416 void visitUDiv(BinaryOperator &I) { handleDiv(I); }
1417 void visitSDiv(BinaryOperator &I) { handleDiv(I); }
1418 void visitFDiv(BinaryOperator &I) { handleDiv(I); }
1419 void visitURem(BinaryOperator &I) { handleDiv(I); }
1420 void visitSRem(BinaryOperator &I) { handleDiv(I); }
1421 void visitFRem(BinaryOperator &I) { handleDiv(I); }
1422
1423 /// \brief Instrument == and != comparisons.
1424 ///
1425 /// Sometimes the comparison result is known even if some of the bits of the
1426 /// arguments are not.
1427 void handleEqualityComparison(ICmpInst &I) {
1428 IRBuilder<> IRB(&I);
1429 Value *A = I.getOperand(0);
1430 Value *B = I.getOperand(1);
1431 Value *Sa = getShadow(A);
1432 Value *Sb = getShadow(B);
Evgeniy Stepanovd14e47b2013-01-15 16:44:52 +00001433
1434 // Get rid of pointers and vectors of pointers.
1435 // For ints (and vectors of ints), types of A and Sa match,
1436 // and this is a no-op.
1437 A = IRB.CreatePointerCast(A, Sa->getType());
1438 B = IRB.CreatePointerCast(B, Sb->getType());
1439
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001440 // A == B <==> (C = A^B) == 0
1441 // A != B <==> (C = A^B) != 0
1442 // Sc = Sa | Sb
1443 Value *C = IRB.CreateXor(A, B);
1444 Value *Sc = IRB.CreateOr(Sa, Sb);
1445 // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
1446 // Result is defined if one of the following is true
1447 // * there is a defined 1 bit in C
1448 // * C is fully defined
1449 // Si = !(C & ~Sc) && Sc
1450 Value *Zero = Constant::getNullValue(Sc->getType());
1451 Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
1452 Value *Si =
1453 IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
1454 IRB.CreateICmpEQ(
1455 IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
1456 Si->setName("_msprop_icmp");
1457 setShadow(&I, Si);
1458 setOriginForNaryOp(I);
1459 }
1460
Evgeniy Stepanovfac84032013-01-25 15:31:10 +00001461 /// \brief Build the lowest possible value of V, taking into account V's
1462 /// uninitialized bits.
1463 Value *getLowestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1464 bool isSigned) {
1465 if (isSigned) {
1466 // Split shadow into sign bit and other bits.
1467 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1468 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1469 // Maximise the undefined shadow bit, minimize other undefined bits.
1470 return
1471 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaOtherBits)), SaSignBit);
1472 } else {
1473 // Minimize undefined bits.
1474 return IRB.CreateAnd(A, IRB.CreateNot(Sa));
1475 }
1476 }
1477
1478 /// \brief Build the highest possible value of V, taking into account V's
1479 /// uninitialized bits.
1480 Value *getHighestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1481 bool isSigned) {
1482 if (isSigned) {
1483 // Split shadow into sign bit and other bits.
1484 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1485 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1486 // Minimise the undefined shadow bit, maximise other undefined bits.
1487 return
1488 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaSignBit)), SaOtherBits);
1489 } else {
1490 // Maximize undefined bits.
1491 return IRB.CreateOr(A, Sa);
1492 }
1493 }
1494
1495 /// \brief Instrument relational comparisons.
1496 ///
1497 /// This function does exact shadow propagation for all relational
1498 /// comparisons of integers, pointers and vectors of those.
1499 /// FIXME: output seems suboptimal when one of the operands is a constant
1500 void handleRelationalComparisonExact(ICmpInst &I) {
1501 IRBuilder<> IRB(&I);
1502 Value *A = I.getOperand(0);
1503 Value *B = I.getOperand(1);
1504 Value *Sa = getShadow(A);
1505 Value *Sb = getShadow(B);
1506
1507 // Get rid of pointers and vectors of pointers.
1508 // For ints (and vectors of ints), types of A and Sa match,
1509 // and this is a no-op.
1510 A = IRB.CreatePointerCast(A, Sa->getType());
1511 B = IRB.CreatePointerCast(B, Sb->getType());
1512
Evgeniy Stepanov2cb0fa12013-01-25 15:35:29 +00001513 // Let [a0, a1] be the interval of possible values of A, taking into account
1514 // its undefined bits. Let [b0, b1] be the interval of possible values of B.
1515 // Then (A cmp B) is defined iff (a0 cmp b1) == (a1 cmp b0).
Evgeniy Stepanovfac84032013-01-25 15:31:10 +00001516 bool IsSigned = I.isSigned();
1517 Value *S1 = IRB.CreateICmp(I.getPredicate(),
1518 getLowestPossibleValue(IRB, A, Sa, IsSigned),
1519 getHighestPossibleValue(IRB, B, Sb, IsSigned));
1520 Value *S2 = IRB.CreateICmp(I.getPredicate(),
1521 getHighestPossibleValue(IRB, A, Sa, IsSigned),
1522 getLowestPossibleValue(IRB, B, Sb, IsSigned));
1523 Value *Si = IRB.CreateXor(S1, S2);
1524 setShadow(&I, Si);
1525 setOriginForNaryOp(I);
1526 }
1527
Evgeniy Stepanov857d9d22012-11-29 14:25:47 +00001528 /// \brief Instrument signed relational comparisons.
1529 ///
1530 /// Handle (x<0) and (x>=0) comparisons (essentially, sign bit tests) by
1531 /// propagating the highest bit of the shadow. Everything else is delegated
1532 /// to handleShadowOr().
1533 void handleSignedRelationalComparison(ICmpInst &I) {
1534 Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1535 Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
Craig Topperf40110f2014-04-25 05:29:35 +00001536 Value* op = nullptr;
Evgeniy Stepanov857d9d22012-11-29 14:25:47 +00001537 CmpInst::Predicate pre = I.getPredicate();
1538 if (constOp0 && constOp0->isNullValue() &&
1539 (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE)) {
1540 op = I.getOperand(1);
1541 } else if (constOp1 && constOp1->isNullValue() &&
1542 (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) {
1543 op = I.getOperand(0);
1544 }
1545 if (op) {
1546 IRBuilder<> IRB(&I);
1547 Value* Shadow =
1548 IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op), "_msprop_icmpslt");
1549 setShadow(&I, Shadow);
1550 setOrigin(&I, getOrigin(op));
1551 } else {
1552 handleShadowOr(I);
1553 }
1554 }
1555
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001556 void visitICmpInst(ICmpInst &I) {
Evgeniy Stepanov6f85ef32013-01-28 11:42:28 +00001557 if (!ClHandleICmp) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001558 handleShadowOr(I);
Evgeniy Stepanov6f85ef32013-01-28 11:42:28 +00001559 return;
1560 }
1561 if (I.isEquality()) {
1562 handleEqualityComparison(I);
1563 return;
1564 }
1565
1566 assert(I.isRelational());
1567 if (ClHandleICmpExact) {
1568 handleRelationalComparisonExact(I);
1569 return;
1570 }
1571 if (I.isSigned()) {
1572 handleSignedRelationalComparison(I);
1573 return;
1574 }
1575
1576 assert(I.isUnsigned());
1577 if ((isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
1578 handleRelationalComparisonExact(I);
1579 return;
1580 }
1581
1582 handleShadowOr(I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001583 }
1584
1585 void visitFCmpInst(FCmpInst &I) {
1586 handleShadowOr(I);
1587 }
1588
1589 void handleShift(BinaryOperator &I) {
1590 IRBuilder<> IRB(&I);
1591 // If any of the S2 bits are poisoned, the whole thing is poisoned.
1592 // Otherwise perform the same shift on S1.
1593 Value *S1 = getShadow(&I, 0);
1594 Value *S2 = getShadow(&I, 1);
1595 Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
1596 S2->getType());
1597 Value *V2 = I.getOperand(1);
1598 Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
1599 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1600 setOriginForNaryOp(I);
1601 }
1602
1603 void visitShl(BinaryOperator &I) { handleShift(I); }
1604 void visitAShr(BinaryOperator &I) { handleShift(I); }
1605 void visitLShr(BinaryOperator &I) { handleShift(I); }
1606
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001607 /// \brief Instrument llvm.memmove
1608 ///
1609 /// At this point we don't know if llvm.memmove will be inlined or not.
1610 /// If we don't instrument it and it gets inlined,
1611 /// our interceptor will not kick in and we will lose the memmove.
1612 /// If we instrument the call here, but it does not get inlined,
1613 /// we will memove the shadow twice: which is bad in case
1614 /// of overlapping regions. So, we simply lower the intrinsic to a call.
1615 ///
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +00001616 /// Similar situation exists for memcpy and memset.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001617 void visitMemMoveInst(MemMoveInst &I) {
1618 IRBuilder<> IRB(&I);
1619 IRB.CreateCall3(
1620 MS.MemmoveFn,
1621 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1622 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1623 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1624 I.eraseFromParent();
1625 }
1626
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +00001627 // Similar to memmove: avoid copying shadow twice.
1628 // This is somewhat unfortunate as it may slowdown small constant memcpys.
1629 // FIXME: consider doing manual inline for small constant sizes and proper
1630 // alignment.
1631 void visitMemCpyInst(MemCpyInst &I) {
1632 IRBuilder<> IRB(&I);
1633 IRB.CreateCall3(
1634 MS.MemcpyFn,
1635 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1636 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1637 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1638 I.eraseFromParent();
1639 }
1640
1641 // Same as memcpy.
1642 void visitMemSetInst(MemSetInst &I) {
1643 IRBuilder<> IRB(&I);
1644 IRB.CreateCall3(
1645 MS.MemsetFn,
1646 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1647 IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
1648 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1649 I.eraseFromParent();
1650 }
1651
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001652 void visitVAStartInst(VAStartInst &I) {
1653 VAHelper->visitVAStartInst(I);
1654 }
1655
1656 void visitVACopyInst(VACopyInst &I) {
1657 VAHelper->visitVACopyInst(I);
1658 }
1659
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001660 enum IntrinsicKind {
1661 IK_DoesNotAccessMemory,
1662 IK_OnlyReadsMemory,
1663 IK_WritesMemory
1664 };
1665
1666 static IntrinsicKind getIntrinsicKind(Intrinsic::ID iid) {
1667 const int DoesNotAccessMemory = IK_DoesNotAccessMemory;
1668 const int OnlyReadsArgumentPointees = IK_OnlyReadsMemory;
1669 const int OnlyReadsMemory = IK_OnlyReadsMemory;
1670 const int OnlyAccessesArgumentPointees = IK_WritesMemory;
1671 const int UnknownModRefBehavior = IK_WritesMemory;
1672#define GET_INTRINSIC_MODREF_BEHAVIOR
1673#define ModRefBehavior IntrinsicKind
Chandler Carruthdb25c6c2013-01-02 12:09:16 +00001674#include "llvm/IR/Intrinsics.gen"
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001675#undef ModRefBehavior
1676#undef GET_INTRINSIC_MODREF_BEHAVIOR
1677 }
1678
1679 /// \brief Handle vector store-like intrinsics.
1680 ///
1681 /// Instrument intrinsics that look like a simple SIMD store: writes memory,
1682 /// has 1 pointer argument and 1 vector argument, returns void.
1683 bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
1684 IRBuilder<> IRB(&I);
1685 Value* Addr = I.getArgOperand(0);
1686 Value *Shadow = getShadow(&I, 1);
1687 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
1688
1689 // We don't know the pointer alignment (could be unaligned SSE store!).
1690 // Have to assume to worst case.
1691 IRB.CreateAlignedStore(Shadow, ShadowPtr, 1);
1692
1693 if (ClCheckAccessAddress)
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001694 insertShadowCheck(Addr, &I);
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001695
1696 // FIXME: use ClStoreCleanOrigin
1697 // FIXME: factor out common code from materializeStores
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001698 if (MS.TrackOrigins)
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001699 IRB.CreateStore(getOrigin(&I, 1), getOriginPtr(Addr, IRB));
1700 return true;
1701 }
1702
1703 /// \brief Handle vector load-like intrinsics.
1704 ///
1705 /// Instrument intrinsics that look like a simple SIMD load: reads memory,
1706 /// has 1 pointer argument, returns a vector.
1707 bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
1708 IRBuilder<> IRB(&I);
1709 Value *Addr = I.getArgOperand(0);
1710
1711 Type *ShadowTy = getShadowTy(&I);
Evgeniy Stepanov00062b42013-02-28 11:25:14 +00001712 if (LoadShadow) {
1713 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1714 // We don't know the pointer alignment (could be unaligned SSE load!).
1715 // Have to assume to worst case.
1716 setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, 1, "_msld"));
1717 } else {
1718 setShadow(&I, getCleanShadow(&I));
1719 }
1720
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001721 if (ClCheckAccessAddress)
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001722 insertShadowCheck(Addr, &I);
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001723
Evgeniy Stepanov00062b42013-02-28 11:25:14 +00001724 if (MS.TrackOrigins) {
1725 if (LoadShadow)
1726 setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB)));
1727 else
1728 setOrigin(&I, getCleanOrigin());
1729 }
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001730 return true;
1731 }
1732
1733 /// \brief Handle (SIMD arithmetic)-like intrinsics.
1734 ///
1735 /// Instrument intrinsics with any number of arguments of the same type,
1736 /// equal to the return type. The type should be simple (no aggregates or
1737 /// pointers; vectors are fine).
1738 /// Caller guarantees that this intrinsic does not access memory.
1739 bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) {
1740 Type *RetTy = I.getType();
1741 if (!(RetTy->isIntOrIntVectorTy() ||
1742 RetTy->isFPOrFPVectorTy() ||
1743 RetTy->isX86_MMXTy()))
1744 return false;
1745
1746 unsigned NumArgOperands = I.getNumArgOperands();
1747
1748 for (unsigned i = 0; i < NumArgOperands; ++i) {
1749 Type *Ty = I.getArgOperand(i)->getType();
1750 if (Ty != RetTy)
1751 return false;
1752 }
1753
1754 IRBuilder<> IRB(&I);
1755 ShadowAndOriginCombiner SC(this, IRB);
1756 for (unsigned i = 0; i < NumArgOperands; ++i)
1757 SC.Add(I.getArgOperand(i));
1758 SC.Done(&I);
1759
1760 return true;
1761 }
1762
1763 /// \brief Heuristically instrument unknown intrinsics.
1764 ///
1765 /// The main purpose of this code is to do something reasonable with all
1766 /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
1767 /// We recognize several classes of intrinsics by their argument types and
1768 /// ModRefBehaviour and apply special intrumentation when we are reasonably
1769 /// sure that we know what the intrinsic does.
1770 ///
1771 /// We special-case intrinsics where this approach fails. See llvm.bswap
1772 /// handling as an example of that.
1773 bool handleUnknownIntrinsic(IntrinsicInst &I) {
1774 unsigned NumArgOperands = I.getNumArgOperands();
1775 if (NumArgOperands == 0)
1776 return false;
1777
1778 Intrinsic::ID iid = I.getIntrinsicID();
1779 IntrinsicKind IK = getIntrinsicKind(iid);
1780 bool OnlyReadsMemory = IK == IK_OnlyReadsMemory;
1781 bool WritesMemory = IK == IK_WritesMemory;
1782 assert(!(OnlyReadsMemory && WritesMemory));
1783
1784 if (NumArgOperands == 2 &&
1785 I.getArgOperand(0)->getType()->isPointerTy() &&
1786 I.getArgOperand(1)->getType()->isVectorTy() &&
1787 I.getType()->isVoidTy() &&
1788 WritesMemory) {
1789 // This looks like a vector store.
1790 return handleVectorStoreIntrinsic(I);
1791 }
1792
1793 if (NumArgOperands == 1 &&
1794 I.getArgOperand(0)->getType()->isPointerTy() &&
1795 I.getType()->isVectorTy() &&
1796 OnlyReadsMemory) {
1797 // This looks like a vector load.
1798 return handleVectorLoadIntrinsic(I);
1799 }
1800
1801 if (!OnlyReadsMemory && !WritesMemory)
1802 if (maybeHandleSimpleNomemIntrinsic(I))
1803 return true;
1804
1805 // FIXME: detect and handle SSE maskstore/maskload
1806 return false;
1807 }
1808
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00001809 void handleBswap(IntrinsicInst &I) {
1810 IRBuilder<> IRB(&I);
1811 Value *Op = I.getArgOperand(0);
1812 Type *OpType = Op->getType();
1813 Function *BswapFunc = Intrinsic::getDeclaration(
1814 F.getParent(), Intrinsic::bswap, ArrayRef<Type*>(&OpType, 1));
1815 setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
1816 setOrigin(&I, getOrigin(Op));
1817 }
1818
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001819 // \brief Instrument vector convert instrinsic.
1820 //
1821 // This function instruments intrinsics like cvtsi2ss:
1822 // %Out = int_xxx_cvtyyy(%ConvertOp)
1823 // or
1824 // %Out = int_xxx_cvtyyy(%CopyOp, %ConvertOp)
1825 // Intrinsic converts \p NumUsedElements elements of \p ConvertOp to the same
1826 // number \p Out elements, and (if has 2 arguments) copies the rest of the
1827 // elements from \p CopyOp.
1828 // In most cases conversion involves floating-point value which may trigger a
1829 // hardware exception when not fully initialized. For this reason we require
1830 // \p ConvertOp[0:NumUsedElements] to be fully initialized and trap otherwise.
1831 // We copy the shadow of \p CopyOp[NumUsedElements:] to \p
1832 // Out[NumUsedElements:]. This means that intrinsics without \p CopyOp always
1833 // return a fully initialized value.
1834 void handleVectorConvertIntrinsic(IntrinsicInst &I, int NumUsedElements) {
1835 IRBuilder<> IRB(&I);
1836 Value *CopyOp, *ConvertOp;
1837
1838 switch (I.getNumArgOperands()) {
1839 case 2:
1840 CopyOp = I.getArgOperand(0);
1841 ConvertOp = I.getArgOperand(1);
1842 break;
1843 case 1:
1844 ConvertOp = I.getArgOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +00001845 CopyOp = nullptr;
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001846 break;
1847 default:
1848 llvm_unreachable("Cvt intrinsic with unsupported number of arguments.");
1849 }
1850
1851 // The first *NumUsedElements* elements of ConvertOp are converted to the
1852 // same number of output elements. The rest of the output is copied from
1853 // CopyOp, or (if not available) filled with zeroes.
1854 // Combine shadow for elements of ConvertOp that are used in this operation,
1855 // and insert a check.
1856 // FIXME: consider propagating shadow of ConvertOp, at least in the case of
1857 // int->any conversion.
1858 Value *ConvertShadow = getShadow(ConvertOp);
Craig Topperf40110f2014-04-25 05:29:35 +00001859 Value *AggShadow = nullptr;
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00001860 if (ConvertOp->getType()->isVectorTy()) {
1861 AggShadow = IRB.CreateExtractElement(
1862 ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), 0));
1863 for (int i = 1; i < NumUsedElements; ++i) {
1864 Value *MoreShadow = IRB.CreateExtractElement(
1865 ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), i));
1866 AggShadow = IRB.CreateOr(AggShadow, MoreShadow);
1867 }
1868 } else {
1869 AggShadow = ConvertShadow;
1870 }
1871 assert(AggShadow->getType()->isIntegerTy());
1872 insertShadowCheck(AggShadow, getOrigin(ConvertOp), &I);
1873
1874 // Build result shadow by zero-filling parts of CopyOp shadow that come from
1875 // ConvertOp.
1876 if (CopyOp) {
1877 assert(CopyOp->getType() == I.getType());
1878 assert(CopyOp->getType()->isVectorTy());
1879 Value *ResultShadow = getShadow(CopyOp);
1880 Type *EltTy = ResultShadow->getType()->getVectorElementType();
1881 for (int i = 0; i < NumUsedElements; ++i) {
1882 ResultShadow = IRB.CreateInsertElement(
1883 ResultShadow, ConstantInt::getNullValue(EltTy),
1884 ConstantInt::get(IRB.getInt32Ty(), i));
1885 }
1886 setShadow(&I, ResultShadow);
1887 setOrigin(&I, getOrigin(CopyOp));
1888 } else {
1889 setShadow(&I, getCleanShadow(&I));
1890 }
1891 }
1892
Evgeniy Stepanov77be5322014-03-03 13:47:42 +00001893 // Given a scalar or vector, extract lower 64 bits (or less), and return all
1894 // zeroes if it is zero, and all ones otherwise.
1895 Value *Lower64ShadowExtend(IRBuilder<> &IRB, Value *S, Type *T) {
1896 if (S->getType()->isVectorTy())
1897 S = CreateShadowCast(IRB, S, IRB.getInt64Ty(), /* Signed */ true);
1898 assert(S->getType()->getPrimitiveSizeInBits() <= 64);
1899 Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
1900 return CreateShadowCast(IRB, S2, T, /* Signed */ true);
1901 }
1902
1903 Value *VariableShadowExtend(IRBuilder<> &IRB, Value *S) {
1904 Type *T = S->getType();
1905 assert(T->isVectorTy());
1906 Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
1907 return IRB.CreateSExt(S2, T);
1908 }
1909
1910 // \brief Instrument vector shift instrinsic.
1911 //
1912 // This function instruments intrinsics like int_x86_avx2_psll_w.
1913 // Intrinsic shifts %In by %ShiftSize bits.
1914 // %ShiftSize may be a vector. In that case the lower 64 bits determine shift
1915 // size, and the rest is ignored. Behavior is defined even if shift size is
1916 // greater than register (or field) width.
1917 void handleVectorShiftIntrinsic(IntrinsicInst &I, bool Variable) {
1918 assert(I.getNumArgOperands() == 2);
1919 IRBuilder<> IRB(&I);
1920 // If any of the S2 bits are poisoned, the whole thing is poisoned.
1921 // Otherwise perform the same shift on S1.
1922 Value *S1 = getShadow(&I, 0);
1923 Value *S2 = getShadow(&I, 1);
1924 Value *S2Conv = Variable ? VariableShadowExtend(IRB, S2)
1925 : Lower64ShadowExtend(IRB, S2, getShadowTy(&I));
1926 Value *V1 = I.getOperand(0);
1927 Value *V2 = I.getOperand(1);
1928 Value *Shift = IRB.CreateCall2(I.getCalledValue(),
1929 IRB.CreateBitCast(S1, V1->getType()), V2);
1930 Shift = IRB.CreateBitCast(Shift, getShadowTy(&I));
1931 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1932 setOriginForNaryOp(I);
1933 }
1934
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00001935 // \brief Get an X86_MMX-sized vector type.
1936 Type *getMMXVectorTy(unsigned EltSizeInBits) {
1937 const unsigned X86_MMXSizeInBits = 64;
1938 return VectorType::get(IntegerType::get(*MS.C, EltSizeInBits),
1939 X86_MMXSizeInBits / EltSizeInBits);
1940 }
1941
1942 // \brief Returns a signed counterpart for an (un)signed-saturate-and-pack
1943 // intrinsic.
1944 Intrinsic::ID getSignedPackIntrinsic(Intrinsic::ID id) {
1945 switch (id) {
1946 case llvm::Intrinsic::x86_sse2_packsswb_128:
1947 case llvm::Intrinsic::x86_sse2_packuswb_128:
1948 return llvm::Intrinsic::x86_sse2_packsswb_128;
1949
1950 case llvm::Intrinsic::x86_sse2_packssdw_128:
1951 case llvm::Intrinsic::x86_sse41_packusdw:
1952 return llvm::Intrinsic::x86_sse2_packssdw_128;
1953
1954 case llvm::Intrinsic::x86_avx2_packsswb:
1955 case llvm::Intrinsic::x86_avx2_packuswb:
1956 return llvm::Intrinsic::x86_avx2_packsswb;
1957
1958 case llvm::Intrinsic::x86_avx2_packssdw:
1959 case llvm::Intrinsic::x86_avx2_packusdw:
1960 return llvm::Intrinsic::x86_avx2_packssdw;
1961
1962 case llvm::Intrinsic::x86_mmx_packsswb:
1963 case llvm::Intrinsic::x86_mmx_packuswb:
1964 return llvm::Intrinsic::x86_mmx_packsswb;
1965
1966 case llvm::Intrinsic::x86_mmx_packssdw:
1967 return llvm::Intrinsic::x86_mmx_packssdw;
1968 default:
1969 llvm_unreachable("unexpected intrinsic id");
1970 }
1971 }
1972
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00001973 // \brief Instrument vector shift instrinsic.
1974 //
1975 // This function instruments intrinsics like x86_mmx_packsswb, that
1976 // packs elements of 2 input vectors into half as much bits with saturation.
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00001977 // Shadow is propagated with the signed variant of the same intrinsic applied
1978 // to sext(Sa != zeroinitializer), sext(Sb != zeroinitializer).
1979 // EltSizeInBits is used only for x86mmx arguments.
1980 void handleVectorPackIntrinsic(IntrinsicInst &I, unsigned EltSizeInBits = 0) {
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00001981 assert(I.getNumArgOperands() == 2);
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00001982 bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00001983 IRBuilder<> IRB(&I);
1984 Value *S1 = getShadow(&I, 0);
1985 Value *S2 = getShadow(&I, 1);
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00001986 assert(isX86_MMX || S1->getType()->isVectorTy());
1987
1988 // SExt and ICmpNE below must apply to individual elements of input vectors.
1989 // In case of x86mmx arguments, cast them to appropriate vector types and
1990 // back.
1991 Type *T = isX86_MMX ? getMMXVectorTy(EltSizeInBits) : S1->getType();
1992 if (isX86_MMX) {
1993 S1 = IRB.CreateBitCast(S1, T);
1994 S2 = IRB.CreateBitCast(S2, T);
1995 }
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00001996 Value *S1_ext = IRB.CreateSExt(
1997 IRB.CreateICmpNE(S1, llvm::Constant::getNullValue(T)), T);
1998 Value *S2_ext = IRB.CreateSExt(
1999 IRB.CreateICmpNE(S2, llvm::Constant::getNullValue(T)), T);
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002000 if (isX86_MMX) {
2001 Type *X86_MMXTy = Type::getX86_MMXTy(*MS.C);
2002 S1_ext = IRB.CreateBitCast(S1_ext, X86_MMXTy);
2003 S2_ext = IRB.CreateBitCast(S2_ext, X86_MMXTy);
2004 }
2005
2006 Function *ShadowFn = Intrinsic::getDeclaration(
2007 F.getParent(), getSignedPackIntrinsic(I.getIntrinsicID()));
2008
2009 Value *S = IRB.CreateCall2(ShadowFn, S1_ext, S2_ext, "_msprop_vector_pack");
2010 if (isX86_MMX) S = IRB.CreateBitCast(S, getShadowTy(&I));
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002011 setShadow(&I, S);
2012 setOriginForNaryOp(I);
2013 }
2014
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00002015 void visitIntrinsicInst(IntrinsicInst &I) {
2016 switch (I.getIntrinsicID()) {
2017 case llvm::Intrinsic::bswap:
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +00002018 handleBswap(I);
2019 break;
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002020 case llvm::Intrinsic::x86_avx512_cvtsd2usi64:
2021 case llvm::Intrinsic::x86_avx512_cvtsd2usi:
2022 case llvm::Intrinsic::x86_avx512_cvtss2usi64:
2023 case llvm::Intrinsic::x86_avx512_cvtss2usi:
2024 case llvm::Intrinsic::x86_avx512_cvttss2usi64:
2025 case llvm::Intrinsic::x86_avx512_cvttss2usi:
2026 case llvm::Intrinsic::x86_avx512_cvttsd2usi64:
2027 case llvm::Intrinsic::x86_avx512_cvttsd2usi:
2028 case llvm::Intrinsic::x86_avx512_cvtusi2sd:
2029 case llvm::Intrinsic::x86_avx512_cvtusi2ss:
2030 case llvm::Intrinsic::x86_avx512_cvtusi642sd:
2031 case llvm::Intrinsic::x86_avx512_cvtusi642ss:
2032 case llvm::Intrinsic::x86_sse2_cvtsd2si64:
2033 case llvm::Intrinsic::x86_sse2_cvtsd2si:
2034 case llvm::Intrinsic::x86_sse2_cvtsd2ss:
2035 case llvm::Intrinsic::x86_sse2_cvtsi2sd:
2036 case llvm::Intrinsic::x86_sse2_cvtsi642sd:
2037 case llvm::Intrinsic::x86_sse2_cvtss2sd:
2038 case llvm::Intrinsic::x86_sse2_cvttsd2si64:
2039 case llvm::Intrinsic::x86_sse2_cvttsd2si:
2040 case llvm::Intrinsic::x86_sse_cvtsi2ss:
2041 case llvm::Intrinsic::x86_sse_cvtsi642ss:
2042 case llvm::Intrinsic::x86_sse_cvtss2si64:
2043 case llvm::Intrinsic::x86_sse_cvtss2si:
2044 case llvm::Intrinsic::x86_sse_cvttss2si64:
2045 case llvm::Intrinsic::x86_sse_cvttss2si:
2046 handleVectorConvertIntrinsic(I, 1);
2047 break;
2048 case llvm::Intrinsic::x86_sse2_cvtdq2pd:
2049 case llvm::Intrinsic::x86_sse2_cvtps2pd:
2050 case llvm::Intrinsic::x86_sse_cvtps2pi:
2051 case llvm::Intrinsic::x86_sse_cvttps2pi:
2052 handleVectorConvertIntrinsic(I, 2);
2053 break;
Evgeniy Stepanov77be5322014-03-03 13:47:42 +00002054 case llvm::Intrinsic::x86_avx512_psll_dq:
2055 case llvm::Intrinsic::x86_avx512_psrl_dq:
2056 case llvm::Intrinsic::x86_avx2_psll_w:
2057 case llvm::Intrinsic::x86_avx2_psll_d:
2058 case llvm::Intrinsic::x86_avx2_psll_q:
2059 case llvm::Intrinsic::x86_avx2_pslli_w:
2060 case llvm::Intrinsic::x86_avx2_pslli_d:
2061 case llvm::Intrinsic::x86_avx2_pslli_q:
2062 case llvm::Intrinsic::x86_avx2_psll_dq:
2063 case llvm::Intrinsic::x86_avx2_psrl_w:
2064 case llvm::Intrinsic::x86_avx2_psrl_d:
2065 case llvm::Intrinsic::x86_avx2_psrl_q:
2066 case llvm::Intrinsic::x86_avx2_psra_w:
2067 case llvm::Intrinsic::x86_avx2_psra_d:
2068 case llvm::Intrinsic::x86_avx2_psrli_w:
2069 case llvm::Intrinsic::x86_avx2_psrli_d:
2070 case llvm::Intrinsic::x86_avx2_psrli_q:
2071 case llvm::Intrinsic::x86_avx2_psrai_w:
2072 case llvm::Intrinsic::x86_avx2_psrai_d:
2073 case llvm::Intrinsic::x86_avx2_psrl_dq:
2074 case llvm::Intrinsic::x86_sse2_psll_w:
2075 case llvm::Intrinsic::x86_sse2_psll_d:
2076 case llvm::Intrinsic::x86_sse2_psll_q:
2077 case llvm::Intrinsic::x86_sse2_pslli_w:
2078 case llvm::Intrinsic::x86_sse2_pslli_d:
2079 case llvm::Intrinsic::x86_sse2_pslli_q:
2080 case llvm::Intrinsic::x86_sse2_psll_dq:
2081 case llvm::Intrinsic::x86_sse2_psrl_w:
2082 case llvm::Intrinsic::x86_sse2_psrl_d:
2083 case llvm::Intrinsic::x86_sse2_psrl_q:
2084 case llvm::Intrinsic::x86_sse2_psra_w:
2085 case llvm::Intrinsic::x86_sse2_psra_d:
2086 case llvm::Intrinsic::x86_sse2_psrli_w:
2087 case llvm::Intrinsic::x86_sse2_psrli_d:
2088 case llvm::Intrinsic::x86_sse2_psrli_q:
2089 case llvm::Intrinsic::x86_sse2_psrai_w:
2090 case llvm::Intrinsic::x86_sse2_psrai_d:
2091 case llvm::Intrinsic::x86_sse2_psrl_dq:
2092 case llvm::Intrinsic::x86_mmx_psll_w:
2093 case llvm::Intrinsic::x86_mmx_psll_d:
2094 case llvm::Intrinsic::x86_mmx_psll_q:
2095 case llvm::Intrinsic::x86_mmx_pslli_w:
2096 case llvm::Intrinsic::x86_mmx_pslli_d:
2097 case llvm::Intrinsic::x86_mmx_pslli_q:
2098 case llvm::Intrinsic::x86_mmx_psrl_w:
2099 case llvm::Intrinsic::x86_mmx_psrl_d:
2100 case llvm::Intrinsic::x86_mmx_psrl_q:
2101 case llvm::Intrinsic::x86_mmx_psra_w:
2102 case llvm::Intrinsic::x86_mmx_psra_d:
2103 case llvm::Intrinsic::x86_mmx_psrli_w:
2104 case llvm::Intrinsic::x86_mmx_psrli_d:
2105 case llvm::Intrinsic::x86_mmx_psrli_q:
2106 case llvm::Intrinsic::x86_mmx_psrai_w:
2107 case llvm::Intrinsic::x86_mmx_psrai_d:
2108 handleVectorShiftIntrinsic(I, /* Variable */ false);
2109 break;
2110 case llvm::Intrinsic::x86_avx2_psllv_d:
2111 case llvm::Intrinsic::x86_avx2_psllv_d_256:
2112 case llvm::Intrinsic::x86_avx2_psllv_q:
2113 case llvm::Intrinsic::x86_avx2_psllv_q_256:
2114 case llvm::Intrinsic::x86_avx2_psrlv_d:
2115 case llvm::Intrinsic::x86_avx2_psrlv_d_256:
2116 case llvm::Intrinsic::x86_avx2_psrlv_q:
2117 case llvm::Intrinsic::x86_avx2_psrlv_q_256:
2118 case llvm::Intrinsic::x86_avx2_psrav_d:
2119 case llvm::Intrinsic::x86_avx2_psrav_d_256:
2120 handleVectorShiftIntrinsic(I, /* Variable */ true);
2121 break;
2122
2123 // Byte shifts are not implemented.
2124 // case llvm::Intrinsic::x86_avx512_psll_dq_bs:
2125 // case llvm::Intrinsic::x86_avx512_psrl_dq_bs:
2126 // case llvm::Intrinsic::x86_avx2_psll_dq_bs:
2127 // case llvm::Intrinsic::x86_avx2_psrl_dq_bs:
2128 // case llvm::Intrinsic::x86_sse2_psll_dq_bs:
2129 // case llvm::Intrinsic::x86_sse2_psrl_dq_bs:
2130
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002131 case llvm::Intrinsic::x86_sse2_packsswb_128:
2132 case llvm::Intrinsic::x86_sse2_packssdw_128:
2133 case llvm::Intrinsic::x86_sse2_packuswb_128:
2134 case llvm::Intrinsic::x86_sse41_packusdw:
2135 case llvm::Intrinsic::x86_avx2_packsswb:
2136 case llvm::Intrinsic::x86_avx2_packssdw:
2137 case llvm::Intrinsic::x86_avx2_packuswb:
2138 case llvm::Intrinsic::x86_avx2_packusdw:
Evgeniy Stepanovd425a2b2014-06-02 12:31:44 +00002139 handleVectorPackIntrinsic(I);
2140 break;
2141
Evgeniy Stepanovf7c29a92014-06-09 08:40:16 +00002142 case llvm::Intrinsic::x86_mmx_packsswb:
2143 case llvm::Intrinsic::x86_mmx_packuswb:
2144 handleVectorPackIntrinsic(I, 16);
2145 break;
2146
2147 case llvm::Intrinsic::x86_mmx_packssdw:
2148 handleVectorPackIntrinsic(I, 32);
2149 break;
2150
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00002151 default:
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00002152 if (!handleUnknownIntrinsic(I))
2153 visitInstruction(I);
Evgeniy Stepanov88b8dce2012-12-17 16:30:05 +00002154 break;
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00002155 }
2156 }
2157
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002158 void visitCallSite(CallSite CS) {
2159 Instruction &I = *CS.getInstruction();
2160 assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
2161 if (CS.isCall()) {
Evgeniy Stepanov7ad7e832012-11-29 14:32:03 +00002162 CallInst *Call = cast<CallInst>(&I);
2163
2164 // For inline asm, do the usual thing: check argument shadow and mark all
2165 // outputs as clean. Note that any side effects of the inline asm that are
2166 // not immediately visible in its constraints are not handled.
2167 if (Call->isInlineAsm()) {
2168 visitInstruction(I);
2169 return;
2170 }
2171
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002172 // Allow only tail calls with the same types, otherwise
2173 // we may have a false positive: shadow for a non-void RetVal
2174 // will get propagated to a void RetVal.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002175 if (Call->isTailCall() && Call->getType() != Call->getParent()->getType())
2176 Call->setTailCall(false);
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00002177
2178 assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
Evgeniy Stepanov383b61e2012-12-07 09:08:32 +00002179
2180 // We are going to insert code that relies on the fact that the callee
2181 // will become a non-readonly function after it is instrumented by us. To
2182 // prevent this code from being optimized out, mark that function
2183 // non-readonly in advance.
2184 if (Function *Func = Call->getCalledFunction()) {
2185 // Clear out readonly/readnone attributes.
2186 AttrBuilder B;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002187 B.addAttribute(Attribute::ReadOnly)
2188 .addAttribute(Attribute::ReadNone);
Bill Wendling430fa9b2013-01-23 00:45:55 +00002189 Func->removeAttributes(AttributeSet::FunctionIndex,
2190 AttributeSet::get(Func->getContext(),
2191 AttributeSet::FunctionIndex,
2192 B));
Evgeniy Stepanov383b61e2012-12-07 09:08:32 +00002193 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002194 }
2195 IRBuilder<> IRB(&I);
Evgeniy Stepanov37b86452013-09-19 15:22:35 +00002196
2197 if (MS.WrapIndirectCalls && !CS.getCalledFunction())
Evgeniy Stepanov585813e2013-11-14 12:29:04 +00002198 IndirectCallList.push_back(CS);
Evgeniy Stepanov37b86452013-09-19 15:22:35 +00002199
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002200 unsigned ArgOffset = 0;
2201 DEBUG(dbgs() << " CallSite: " << I << "\n");
2202 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
2203 ArgIt != End; ++ArgIt) {
2204 Value *A = *ArgIt;
2205 unsigned i = ArgIt - CS.arg_begin();
2206 if (!A->getType()->isSized()) {
2207 DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
2208 continue;
2209 }
2210 unsigned Size = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00002211 Value *Store = nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002212 // Compute the Shadow for arg even if it is ByVal, because
2213 // in that case getShadow() will copy the actual arg shadow to
2214 // __msan_param_tls.
2215 Value *ArgShadow = getShadow(A);
2216 Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
2217 DEBUG(dbgs() << " Arg#" << i << ": " << *A <<
2218 " Shadow: " << *ArgShadow << "\n");
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002219 if (CS.paramHasAttr(i + 1, Attribute::ByVal)) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002220 assert(A->getType()->isPointerTy() &&
2221 "ByVal argument is not a pointer!");
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002222 Size = MS.DL->getTypeAllocSize(A->getType()->getPointerElementType());
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002223 unsigned Alignment = CS.getParamAlignment(i + 1);
2224 Store = IRB.CreateMemCpy(ArgShadowBase,
2225 getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
2226 Size, Alignment);
2227 } else {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002228 Size = MS.DL->getTypeAllocSize(A->getType());
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00002229 Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
2230 kShadowTLSAlignment);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002231 }
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00002232 if (MS.TrackOrigins)
Evgeniy Stepanov49175b22012-12-14 13:43:11 +00002233 IRB.CreateStore(getOrigin(A),
2234 getOriginPtrForArgument(A, IRB, ArgOffset));
Edwin Vane82f80d42013-01-29 17:42:24 +00002235 (void)Store;
Craig Toppere73658d2014-04-28 04:05:08 +00002236 assert(Size != 0 && Store != nullptr);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002237 DEBUG(dbgs() << " Param:" << *Store << "\n");
2238 ArgOffset += DataLayout::RoundUpAlignment(Size, 8);
2239 }
2240 DEBUG(dbgs() << " done with call args\n");
2241
2242 FunctionType *FT =
Evgeniy Stepanov37b86452013-09-19 15:22:35 +00002243 cast<FunctionType>(CS.getCalledValue()->getType()->getContainedType(0));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002244 if (FT->isVarArg()) {
2245 VAHelper->visitCallSite(CS, IRB);
2246 }
2247
2248 // Now, get the shadow for the RetVal.
2249 if (!I.getType()->isSized()) return;
2250 IRBuilder<> IRBBefore(&I);
Alp Tokercb402912014-01-24 17:20:08 +00002251 // Until we have full dynamic coverage, make sure the retval shadow is 0.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002252 Value *Base = getShadowPtrForRetval(&I, IRBBefore);
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00002253 IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
Craig Topperf40110f2014-04-25 05:29:35 +00002254 Instruction *NextInsn = nullptr;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002255 if (CS.isCall()) {
2256 NextInsn = I.getNextNode();
2257 } else {
2258 BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
2259 if (!NormalDest->getSinglePredecessor()) {
2260 // FIXME: this case is tricky, so we are just conservative here.
2261 // Perhaps we need to split the edge between this BB and NormalDest,
2262 // but a naive attempt to use SplitEdge leads to a crash.
2263 setShadow(&I, getCleanShadow(&I));
2264 setOrigin(&I, getCleanOrigin());
2265 return;
2266 }
2267 NextInsn = NormalDest->getFirstInsertionPt();
2268 assert(NextInsn &&
2269 "Could not find insertion point for retval shadow load");
2270 }
2271 IRBuilder<> IRBAfter(NextInsn);
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00002272 Value *RetvalShadow =
2273 IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
2274 kShadowTLSAlignment, "_msret");
2275 setShadow(&I, RetvalShadow);
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00002276 if (MS.TrackOrigins)
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002277 setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
2278 }
2279
2280 void visitReturnInst(ReturnInst &I) {
2281 IRBuilder<> IRB(&I);
Evgeniy Stepanov604293f2013-09-16 13:24:32 +00002282 Value *RetVal = I.getReturnValue();
2283 if (!RetVal) return;
2284 Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
2285 if (CheckReturnValue) {
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002286 insertShadowCheck(RetVal, &I);
Evgeniy Stepanov604293f2013-09-16 13:24:32 +00002287 Value *Shadow = getCleanShadow(RetVal);
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00002288 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
Evgeniy Stepanov604293f2013-09-16 13:24:32 +00002289 } else {
2290 Value *Shadow = getShadow(RetVal);
2291 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
2292 // FIXME: make it conditional if ClStoreCleanOrigin==0
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00002293 if (MS.TrackOrigins)
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002294 IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
2295 }
2296 }
2297
2298 void visitPHINode(PHINode &I) {
2299 IRBuilder<> IRB(&I);
2300 ShadowPHINodes.push_back(&I);
2301 setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
2302 "_msphi_s"));
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00002303 if (MS.TrackOrigins)
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002304 setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
2305 "_msphi_o"));
2306 }
2307
2308 void visitAllocaInst(AllocaInst &I) {
2309 setShadow(&I, getCleanShadow(&I));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002310 IRBuilder<> IRB(I.getNextNode());
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002311 uint64_t Size = MS.DL->getTypeAllocSize(I.getAllocatedType());
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +00002312 if (PoisonStack && ClPoisonStackWithCall) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002313 IRB.CreateCall2(MS.MsanPoisonStackFn,
2314 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
2315 ConstantInt::get(MS.IntptrTy, Size));
2316 } else {
2317 Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +00002318 Value *PoisonValue = IRB.getInt8(PoisonStack ? ClPoisonStackPattern : 0);
2319 IRB.CreateMemSet(ShadowBase, PoisonValue, Size, I.getAlignment());
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002320 }
2321
Evgeniy Stepanovdc6d7eb2013-07-03 14:39:14 +00002322 if (PoisonStack && MS.TrackOrigins) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002323 setOrigin(&I, getCleanOrigin());
2324 SmallString<2048> StackDescriptionStorage;
2325 raw_svector_ostream StackDescription(StackDescriptionStorage);
2326 // We create a string with a description of the stack allocation and
2327 // pass it into __msan_set_alloca_origin.
2328 // It will be printed by the run-time if stack-originated UMR is found.
2329 // The first 4 bytes of the string are set to '----' and will be replaced
2330 // by __msan_va_arg_overflow_size_tls at the first call.
2331 StackDescription << "----" << I.getName() << "@" << F.getName();
2332 Value *Descr =
2333 createPrivateNonConstGlobalForString(*F.getParent(),
2334 StackDescription.str());
Evgeniy Stepanov0435ecd2013-09-13 12:54:49 +00002335
2336 IRB.CreateCall4(MS.MsanSetAllocaOrigin4Fn,
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002337 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
2338 ConstantInt::get(MS.IntptrTy, Size),
Evgeniy Stepanov0435ecd2013-09-13 12:54:49 +00002339 IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()),
2340 IRB.CreatePointerCast(&F, MS.IntptrTy));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002341 }
2342 }
2343
2344 void visitSelectInst(SelectInst& I) {
2345 IRBuilder<> IRB(&I);
Evgeniy Stepanov566f5912013-09-03 10:04:11 +00002346 // a = select b, c, d
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002347 Value *B = I.getCondition();
2348 Value *C = I.getTrueValue();
2349 Value *D = I.getFalseValue();
2350 Value *Sb = getShadow(B);
2351 Value *Sc = getShadow(C);
2352 Value *Sd = getShadow(D);
2353
2354 // Result shadow if condition shadow is 0.
2355 Value *Sa0 = IRB.CreateSelect(B, Sc, Sd);
2356 Value *Sa1;
Evgeniy Stepanove95d37c2013-09-03 13:05:29 +00002357 if (I.getType()->isAggregateType()) {
2358 // To avoid "sign extending" i1 to an arbitrary aggregate type, we just do
2359 // an extra "select". This results in much more compact IR.
2360 // Sa = select Sb, poisoned, (select b, Sc, Sd)
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002361 Sa1 = getPoisonedShadow(getShadowTy(I.getType()));
Evgeniy Stepanove95d37c2013-09-03 13:05:29 +00002362 } else {
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002363 // Sa = select Sb, [ (c^d) | Sc | Sd ], [ b ? Sc : Sd ]
2364 // If Sb (condition is poisoned), look for bits in c and d that are equal
2365 // and both unpoisoned.
2366 // If !Sb (condition is unpoisoned), simply pick one of Sc and Sd.
2367
2368 // Cast arguments to shadow-compatible type.
2369 C = CreateAppToShadowCast(IRB, C);
2370 D = CreateAppToShadowCast(IRB, D);
2371
2372 // Result shadow if condition shadow is 1.
2373 Sa1 = IRB.CreateOr(IRB.CreateXor(C, D), IRB.CreateOr(Sc, Sd));
Evgeniy Stepanove95d37c2013-09-03 13:05:29 +00002374 }
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002375 Value *Sa = IRB.CreateSelect(Sb, Sa1, Sa0, "_msprop_select");
2376 setShadow(&I, Sa);
Evgeniy Stepanovec837122012-12-25 14:56:21 +00002377 if (MS.TrackOrigins) {
2378 // Origins are always i32, so any vector conditions must be flattened.
2379 // FIXME: consider tracking vector origins for app vectors?
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002380 if (B->getType()->isVectorTy()) {
2381 Type *FlatTy = getShadowTyNoVec(B->getType());
2382 B = IRB.CreateICmpNE(IRB.CreateBitCast(B, FlatTy),
Evgeniy Stepanovcb5bdff2013-11-21 12:00:24 +00002383 ConstantInt::getNullValue(FlatTy));
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002384 Sb = IRB.CreateICmpNE(IRB.CreateBitCast(Sb, FlatTy),
Evgeniy Stepanovcb5bdff2013-11-21 12:00:24 +00002385 ConstantInt::getNullValue(FlatTy));
Evgeniy Stepanovec837122012-12-25 14:56:21 +00002386 }
Evgeniy Stepanovcb5bdff2013-11-21 12:00:24 +00002387 // a = select b, c, d
2388 // Oa = Sb ? Ob : (b ? Oc : Od)
2389 setOrigin(&I, IRB.CreateSelect(
Evgeniy Stepanovfc742ac2014-03-25 13:08:34 +00002390 Sb, getOrigin(I.getCondition()),
2391 IRB.CreateSelect(B, getOrigin(C), getOrigin(D))));
Evgeniy Stepanovec837122012-12-25 14:56:21 +00002392 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002393 }
2394
2395 void visitLandingPadInst(LandingPadInst &I) {
2396 // Do nothing.
2397 // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
2398 setShadow(&I, getCleanShadow(&I));
2399 setOrigin(&I, getCleanOrigin());
2400 }
2401
2402 void visitGetElementPtrInst(GetElementPtrInst &I) {
2403 handleShadowOr(I);
2404 }
2405
2406 void visitExtractValueInst(ExtractValueInst &I) {
2407 IRBuilder<> IRB(&I);
2408 Value *Agg = I.getAggregateOperand();
2409 DEBUG(dbgs() << "ExtractValue: " << I << "\n");
2410 Value *AggShadow = getShadow(Agg);
2411 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
2412 Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
2413 DEBUG(dbgs() << " ResShadow: " << *ResShadow << "\n");
2414 setShadow(&I, ResShadow);
Evgeniy Stepanov560e08932013-11-11 13:37:10 +00002415 setOriginForNaryOp(I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002416 }
2417
2418 void visitInsertValueInst(InsertValueInst &I) {
2419 IRBuilder<> IRB(&I);
2420 DEBUG(dbgs() << "InsertValue: " << I << "\n");
2421 Value *AggShadow = getShadow(I.getAggregateOperand());
2422 Value *InsShadow = getShadow(I.getInsertedValueOperand());
2423 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
2424 DEBUG(dbgs() << " InsShadow: " << *InsShadow << "\n");
2425 Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
2426 DEBUG(dbgs() << " Res: " << *Res << "\n");
2427 setShadow(&I, Res);
Evgeniy Stepanov560e08932013-11-11 13:37:10 +00002428 setOriginForNaryOp(I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002429 }
2430
2431 void dumpInst(Instruction &I) {
2432 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
2433 errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
2434 } else {
2435 errs() << "ZZZ " << I.getOpcodeName() << "\n";
2436 }
2437 errs() << "QQQ " << I << "\n";
2438 }
2439
2440 void visitResumeInst(ResumeInst &I) {
2441 DEBUG(dbgs() << "Resume: " << I << "\n");
2442 // Nothing to do here.
2443 }
2444
2445 void visitInstruction(Instruction &I) {
2446 // Everything else: stop propagating and check for poisoned shadow.
2447 if (ClDumpStrictInstructions)
2448 dumpInst(I);
2449 DEBUG(dbgs() << "DEFAULT: " << I << "\n");
2450 for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
Evgeniy Stepanovbe83d8f2013-10-14 15:16:25 +00002451 insertShadowCheck(I.getOperand(i), &I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002452 setShadow(&I, getCleanShadow(&I));
2453 setOrigin(&I, getCleanOrigin());
2454 }
2455};
2456
2457/// \brief AMD64-specific implementation of VarArgHelper.
2458struct VarArgAMD64Helper : public VarArgHelper {
2459 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
2460 // See a comment in visitCallSite for more details.
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +00002461 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002462 static const unsigned AMD64FpEndOffset = 176;
2463
2464 Function &F;
2465 MemorySanitizer &MS;
2466 MemorySanitizerVisitor &MSV;
2467 Value *VAArgTLSCopy;
2468 Value *VAArgOverflowSize;
2469
2470 SmallVector<CallInst*, 16> VAStartInstrumentationList;
2471
2472 VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
2473 MemorySanitizerVisitor &MSV)
Craig Topperf40110f2014-04-25 05:29:35 +00002474 : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(nullptr),
2475 VAArgOverflowSize(nullptr) {}
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002476
2477 enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
2478
2479 ArgKind classifyArgument(Value* arg) {
2480 // A very rough approximation of X86_64 argument classification rules.
2481 Type *T = arg->getType();
2482 if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
2483 return AK_FloatingPoint;
2484 if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
2485 return AK_GeneralPurpose;
2486 if (T->isPointerTy())
2487 return AK_GeneralPurpose;
2488 return AK_Memory;
2489 }
2490
2491 // For VarArg functions, store the argument shadow in an ABI-specific format
2492 // that corresponds to va_list layout.
2493 // We do this because Clang lowers va_arg in the frontend, and this pass
2494 // only sees the low level code that deals with va_list internals.
2495 // A much easier alternative (provided that Clang emits va_arg instructions)
2496 // would have been to associate each live instance of va_list with a copy of
2497 // MSanParamTLS, and extract shadow on va_arg() call in the argument list
2498 // order.
Craig Topper3e4c6972014-03-05 09:10:37 +00002499 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002500 unsigned GpOffset = 0;
2501 unsigned FpOffset = AMD64GpEndOffset;
2502 unsigned OverflowOffset = AMD64FpEndOffset;
2503 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
2504 ArgIt != End; ++ArgIt) {
2505 Value *A = *ArgIt;
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00002506 unsigned ArgNo = CS.getArgumentNo(ArgIt);
2507 bool IsByVal = CS.paramHasAttr(ArgNo + 1, Attribute::ByVal);
2508 if (IsByVal) {
2509 // ByVal arguments always go to the overflow area.
2510 assert(A->getType()->isPointerTy());
2511 Type *RealTy = A->getType()->getPointerElementType();
2512 uint64_t ArgSize = MS.DL->getTypeAllocSize(RealTy);
2513 Value *Base = getShadowPtrForVAArgument(RealTy, IRB, OverflowOffset);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002514 OverflowOffset += DataLayout::RoundUpAlignment(ArgSize, 8);
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00002515 IRB.CreateMemCpy(Base, MSV.getShadowPtr(A, IRB.getInt8Ty(), IRB),
2516 ArgSize, kShadowTLSAlignment);
2517 } else {
2518 ArgKind AK = classifyArgument(A);
2519 if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
2520 AK = AK_Memory;
2521 if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
2522 AK = AK_Memory;
2523 Value *Base;
2524 switch (AK) {
2525 case AK_GeneralPurpose:
2526 Base = getShadowPtrForVAArgument(A->getType(), IRB, GpOffset);
2527 GpOffset += 8;
2528 break;
2529 case AK_FloatingPoint:
2530 Base = getShadowPtrForVAArgument(A->getType(), IRB, FpOffset);
2531 FpOffset += 16;
2532 break;
2533 case AK_Memory:
2534 uint64_t ArgSize = MS.DL->getTypeAllocSize(A->getType());
2535 Base = getShadowPtrForVAArgument(A->getType(), IRB, OverflowOffset);
2536 OverflowOffset += DataLayout::RoundUpAlignment(ArgSize, 8);
2537 }
2538 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002539 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002540 }
2541 Constant *OverflowSize =
2542 ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
2543 IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
2544 }
2545
2546 /// \brief Compute the shadow address for a given va_arg.
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00002547 Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002548 int ArgOffset) {
2549 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
2550 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
Evgeniy Stepanov7ab838e2014-03-13 13:17:11 +00002551 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002552 "_msarg");
2553 }
2554
Craig Topper3e4c6972014-03-05 09:10:37 +00002555 void visitVAStartInst(VAStartInst &I) override {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002556 IRBuilder<> IRB(&I);
2557 VAStartInstrumentationList.push_back(&I);
2558 Value *VAListTag = I.getArgOperand(0);
2559 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2560
2561 // Unpoison the whole __va_list_tag.
2562 // FIXME: magic ABI constants.
2563 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
Peter Collingbournef7d65c42013-01-10 22:36:33 +00002564 /* size */24, /* alignment */8, false);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002565 }
2566
Craig Topper3e4c6972014-03-05 09:10:37 +00002567 void visitVACopyInst(VACopyInst &I) override {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002568 IRBuilder<> IRB(&I);
2569 Value *VAListTag = I.getArgOperand(0);
2570 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2571
2572 // Unpoison the whole __va_list_tag.
2573 // FIXME: magic ABI constants.
2574 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
Peter Collingbournef7d65c42013-01-10 22:36:33 +00002575 /* size */24, /* alignment */8, false);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002576 }
2577
Craig Topper3e4c6972014-03-05 09:10:37 +00002578 void finalizeInstrumentation() override {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002579 assert(!VAArgOverflowSize && !VAArgTLSCopy &&
2580 "finalizeInstrumentation called twice");
2581 if (!VAStartInstrumentationList.empty()) {
2582 // If there is a va_start in this function, make a backup copy of
2583 // va_arg_tls somewhere in the function entry block.
2584 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
2585 VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
2586 Value *CopySize =
2587 IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
2588 VAArgOverflowSize);
2589 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
2590 IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
2591 }
2592
2593 // Instrument va_start.
2594 // Copy va_list shadow from the backup copy of the TLS contents.
2595 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
2596 CallInst *OrigInst = VAStartInstrumentationList[i];
2597 IRBuilder<> IRB(OrigInst->getNextNode());
2598 Value *VAListTag = OrigInst->getArgOperand(0);
2599
2600 Value *RegSaveAreaPtrPtr =
2601 IRB.CreateIntToPtr(
2602 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2603 ConstantInt::get(MS.IntptrTy, 16)),
2604 Type::getInt64PtrTy(*MS.C));
2605 Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
2606 Value *RegSaveAreaShadowPtr =
2607 MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
2608 IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy,
2609 AMD64FpEndOffset, 16);
2610
2611 Value *OverflowArgAreaPtrPtr =
2612 IRB.CreateIntToPtr(
2613 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2614 ConstantInt::get(MS.IntptrTy, 8)),
2615 Type::getInt64PtrTy(*MS.C));
2616 Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
2617 Value *OverflowArgAreaShadowPtr =
2618 MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
Evgeniy Stepanovd42863c2013-08-23 12:11:00 +00002619 Value *SrcPtr = IRB.CreateConstGEP1_32(VAArgTLSCopy, AMD64FpEndOffset);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002620 IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
2621 }
2622 }
2623};
2624
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00002625/// \brief A no-op implementation of VarArgHelper.
2626struct VarArgNoOpHelper : public VarArgHelper {
2627 VarArgNoOpHelper(Function &F, MemorySanitizer &MS,
2628 MemorySanitizerVisitor &MSV) {}
2629
Craig Topper3e4c6972014-03-05 09:10:37 +00002630 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {}
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00002631
Craig Topper3e4c6972014-03-05 09:10:37 +00002632 void visitVAStartInst(VAStartInst &I) override {}
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00002633
Craig Topper3e4c6972014-03-05 09:10:37 +00002634 void visitVACopyInst(VACopyInst &I) override {}
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00002635
Craig Topper3e4c6972014-03-05 09:10:37 +00002636 void finalizeInstrumentation() override {}
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00002637};
2638
2639VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002640 MemorySanitizerVisitor &Visitor) {
Evgeniy Stepanovebd7f8e2013-05-21 12:27:47 +00002641 // VarArg handling is only implemented on AMD64. False positives are possible
2642 // on other platforms.
2643 llvm::Triple TargetTriple(Func.getParent()->getTargetTriple());
2644 if (TargetTriple.getArch() == llvm::Triple::x86_64)
2645 return new VarArgAMD64Helper(Func, Msan, Visitor);
2646 else
2647 return new VarArgNoOpHelper(Func, Msan, Visitor);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002648}
2649
2650} // namespace
2651
2652bool MemorySanitizer::runOnFunction(Function &F) {
2653 MemorySanitizerVisitor Visitor(F, *this);
2654
2655 // Clear out readonly/readnone attributes.
2656 AttrBuilder B;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002657 B.addAttribute(Attribute::ReadOnly)
2658 .addAttribute(Attribute::ReadNone);
Bill Wendling430fa9b2013-01-23 00:45:55 +00002659 F.removeAttributes(AttributeSet::FunctionIndex,
2660 AttributeSet::get(F.getContext(),
2661 AttributeSet::FunctionIndex, B));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00002662
2663 return Visitor.runOnFunction();
2664}