blob: 64882c284b3ee0e1ddda690db54d610874bd1f7a [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///
13/// Status: early prototype.
14///
15/// The algorithm of the tool is similar to Memcheck
16/// (http://goo.gl/QKbem). We associate a few shadow bits with every
17/// byte of the application memory, poison the shadow of the malloc-ed
18/// or alloca-ed memory, load the shadow bits on every memory read,
19/// propagate the shadow bits through some of the arithmetic
20/// instruction (including MOV), store the shadow bits on every memory
21/// write, report a bug on some other instructions (e.g. JMP) if the
22/// associated shadow is poisoned.
23///
24/// But there are differences too. The first and the major one:
25/// compiler instrumentation instead of binary instrumentation. This
26/// gives us much better register allocation, possible compiler
27/// optimizations and a fast start-up. But this brings the major issue
28/// as well: msan needs to see all program events, including system
29/// calls and reads/writes in system libraries, so we either need to
30/// compile *everything* with msan or use a binary translation
31/// component (e.g. DynamoRIO) to instrument pre-built libraries.
32/// Another difference from Memcheck is that we use 8 shadow bits per
33/// byte of application memory and use a direct shadow mapping. This
34/// greatly simplifies the instrumentation code and avoids races on
35/// shadow updates (Memcheck is single-threaded so races are not a
36/// concern there. Memcheck uses 2 shadow bits per byte with a slow
37/// path storage that uses 8 bits per byte).
38///
39/// The default value of shadow is 0, which means "clean" (not poisoned).
40///
41/// Every module initializer should call __msan_init to ensure that the
42/// shadow memory is ready. On error, __msan_warning is called. Since
43/// parameters and return values may be passed via registers, we have a
44/// specialized thread-local shadow for return values
45/// (__msan_retval_tls) and parameters (__msan_param_tls).
Evgeniy Stepanovd8be0c52012-12-26 10:59:00 +000046///
47/// Origin tracking.
48///
49/// MemorySanitizer can track origins (allocation points) of all uninitialized
50/// values. This behavior is controlled with a flag (msan-track-origins) and is
51/// disabled by default.
52///
53/// Origins are 4-byte values created and interpreted by the runtime library.
54/// They are stored in a second shadow mapping, one 4-byte value for 4 bytes
55/// of application memory. Propagation of origins is basically a bunch of
56/// "select" instructions that pick the origin of a dirty argument, if an
57/// instruction has one.
58///
59/// Every 4 aligned, consecutive bytes of application memory have one origin
60/// value associated with them. If these bytes contain uninitialized data
61/// coming from 2 different allocations, the last store wins. Because of this,
62/// MemorySanitizer reports can show unrelated origins, but this is unlikely in
Alexey Samsonov3efc87e2012-12-28 09:30:44 +000063/// practice.
Evgeniy Stepanovd8be0c52012-12-26 10:59:00 +000064///
65/// Origins are meaningless for fully initialized values, so MemorySanitizer
66/// avoids storing origin to memory when a fully initialized value is stored.
67/// This way it avoids needless overwritting origin of the 4-byte region on
68/// a short (i.e. 1 byte) clean store, and it is also good for performance.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +000069//===----------------------------------------------------------------------===//
70
71#define DEBUG_TYPE "msan"
72
Chandler Carruthed0881b2012-12-03 16:50:05 +000073#include "llvm/Transforms/Instrumentation.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +000074#include "llvm/ADT/DepthFirstIterator.h"
75#include "llvm/ADT/SmallString.h"
76#include "llvm/ADT/SmallVector.h"
77#include "llvm/ADT/ValueMap.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000078#include "llvm/IR/DataLayout.h"
79#include "llvm/IR/Function.h"
80#include "llvm/IR/IRBuilder.h"
81#include "llvm/IR/InlineAsm.h"
82#include "llvm/IR/IntrinsicInst.h"
83#include "llvm/IR/LLVMContext.h"
84#include "llvm/IR/MDBuilder.h"
85#include "llvm/IR/Module.h"
86#include "llvm/IR/Type.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000087#include "llvm/InstVisitor.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +000088#include "llvm/Support/CommandLine.h"
89#include "llvm/Support/Compiler.h"
90#include "llvm/Support/Debug.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +000091#include "llvm/Support/raw_ostream.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +000092#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chandler Carruth1fe21fc2013-01-19 08:03:47 +000093#include "llvm/Transforms/Utils/BlackList.h"
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +000094#include "llvm/Transforms/Utils/Local.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +000095#include "llvm/Transforms/Utils/ModuleUtils.h"
96
97using namespace llvm;
98
99static const uint64_t kShadowMask32 = 1ULL << 31;
100static const uint64_t kShadowMask64 = 1ULL << 46;
101static const uint64_t kOriginOffset32 = 1ULL << 30;
102static const uint64_t kOriginOffset64 = 1ULL << 45;
Evgeniy Stepanov5eb5bf82012-12-26 11:55:09 +0000103static const unsigned kMinOriginAlignment = 4;
104static const unsigned kShadowTLSAlignment = 8;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000105
Evgeniy Stepanovd8be0c52012-12-26 10:59:00 +0000106/// \brief Track origins of uninitialized values.
Alexey Samsonov3efc87e2012-12-28 09:30:44 +0000107///
Evgeniy Stepanovd8be0c52012-12-26 10:59:00 +0000108/// Adds a section to MemorySanitizer report that points to the allocation
109/// (stack or heap) the uninitialized bits came from originally.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000110static cl::opt<bool> ClTrackOrigins("msan-track-origins",
111 cl::desc("Track origins (allocation sites) of poisoned memory"),
112 cl::Hidden, cl::init(false));
113static cl::opt<bool> ClKeepGoing("msan-keep-going",
114 cl::desc("keep going after reporting a UMR"),
115 cl::Hidden, cl::init(false));
116static cl::opt<bool> ClPoisonStack("msan-poison-stack",
117 cl::desc("poison uninitialized stack variables"),
118 cl::Hidden, cl::init(true));
119static cl::opt<bool> ClPoisonStackWithCall("msan-poison-stack-with-call",
120 cl::desc("poison uninitialized stack variables with a call"),
121 cl::Hidden, cl::init(false));
122static cl::opt<int> ClPoisonStackPattern("msan-poison-stack-pattern",
123 cl::desc("poison uninitialized stack variables with the given patter"),
124 cl::Hidden, cl::init(0xff));
125
126static cl::opt<bool> ClHandleICmp("msan-handle-icmp",
127 cl::desc("propagate shadow through ICmpEQ and ICmpNE"),
128 cl::Hidden, cl::init(true));
129
Evgeniy Stepanovfac84032013-01-25 15:31:10 +0000130static cl::opt<bool> ClHandleICmpExact("msan-handle-icmp-exact",
131 cl::desc("exact handling of relational integer ICmp"),
132 cl::Hidden, cl::init(true));
133
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000134static cl::opt<bool> ClStoreCleanOrigin("msan-store-clean-origin",
135 cl::desc("store origin for clean (fully initialized) values"),
136 cl::Hidden, cl::init(false));
137
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000138// This flag controls whether we check the shadow of the address
139// operand of load or store. Such bugs are very rare, since load from
140// a garbage address typically results in SEGV, but still happen
141// (e.g. only lower bits of address are garbage, or the access happens
142// early at program startup where malloc-ed memory is more likely to
143// be zeroed. As of 2012-08-28 this flag adds 20% slowdown.
144static cl::opt<bool> ClCheckAccessAddress("msan-check-access-address",
145 cl::desc("report accesses through a pointer which has poisoned shadow"),
146 cl::Hidden, cl::init(true));
147
148static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions",
149 cl::desc("print out instructions with default strict semantics"),
150 cl::Hidden, cl::init(false));
151
Alexey Samsonov3efc87e2012-12-28 09:30:44 +0000152static cl::opt<std::string> ClBlacklistFile("msan-blacklist",
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000153 cl::desc("File containing the list of functions where MemorySanitizer "
154 "should not report bugs"), cl::Hidden);
155
156namespace {
157
158/// \brief An instrumentation pass implementing detection of uninitialized
159/// reads.
160///
161/// MemorySanitizer: instrument the code in module to find
162/// uninitialized reads.
163class MemorySanitizer : public FunctionPass {
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000164 public:
Alexey Samsonov3efc87e2012-12-28 09:30:44 +0000165 MemorySanitizer(bool TrackOrigins = false,
166 StringRef BlacklistFile = StringRef())
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000167 : FunctionPass(ID),
168 TrackOrigins(TrackOrigins || ClTrackOrigins),
169 TD(0),
Alexey Samsonov3efc87e2012-12-28 09:30:44 +0000170 WarningFn(0),
171 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
172 : BlacklistFile) { }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000173 const char *getPassName() const { return "MemorySanitizer"; }
174 bool runOnFunction(Function &F);
175 bool doInitialization(Module &M);
176 static char ID; // Pass identification, replacement for typeid.
177
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000178 private:
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000179 void initializeCallbacks(Module &M);
180
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000181 /// \brief Track origins (allocation points) of uninitialized values.
182 bool TrackOrigins;
183
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000184 DataLayout *TD;
185 LLVMContext *C;
186 Type *IntptrTy;
187 Type *OriginTy;
188 /// \brief Thread-local shadow storage for function parameters.
189 GlobalVariable *ParamTLS;
190 /// \brief Thread-local origin storage for function parameters.
191 GlobalVariable *ParamOriginTLS;
192 /// \brief Thread-local shadow storage for function return value.
193 GlobalVariable *RetvalTLS;
194 /// \brief Thread-local origin storage for function return value.
195 GlobalVariable *RetvalOriginTLS;
196 /// \brief Thread-local shadow storage for in-register va_arg function
197 /// parameters (x86_64-specific).
198 GlobalVariable *VAArgTLS;
199 /// \brief Thread-local shadow storage for va_arg overflow area
200 /// (x86_64-specific).
201 GlobalVariable *VAArgOverflowSizeTLS;
202 /// \brief Thread-local space used to pass origin value to the UMR reporting
203 /// function.
204 GlobalVariable *OriginTLS;
205
206 /// \brief The run-time callback to print a warning.
207 Value *WarningFn;
208 /// \brief Run-time helper that copies origin info for a memory range.
209 Value *MsanCopyOriginFn;
210 /// \brief Run-time helper that generates a new origin value for a stack
211 /// allocation.
212 Value *MsanSetAllocaOriginFn;
213 /// \brief Run-time helper that poisons stack on function entry.
214 Value *MsanPoisonStackFn;
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +0000215 /// \brief MSan runtime replacements for memmove, memcpy and memset.
216 Value *MemmoveFn, *MemcpyFn, *MemsetFn;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000217
218 /// \brief Address mask used in application-to-shadow address calculation.
219 /// ShadowAddr is computed as ApplicationAddr & ~ShadowMask.
220 uint64_t ShadowMask;
221 /// \brief Offset of the origin shadow from the "normal" shadow.
222 /// OriginAddr is computed as (ShadowAddr + OriginOffset) & ~3ULL
223 uint64_t OriginOffset;
224 /// \brief Branch weights for error reporting.
225 MDNode *ColdCallWeights;
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000226 /// \brief Branch weights for origin store.
227 MDNode *OriginStoreWeights;
Alexey Samsonov3efc87e2012-12-28 09:30:44 +0000228 /// \bried Path to blacklist file.
229 SmallString<64> BlacklistFile;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000230 /// \brief The blacklist.
231 OwningPtr<BlackList> BL;
Evgeniy Stepanov1d2da652012-11-29 12:30:18 +0000232 /// \brief An empty volatile inline asm that prevents callback merge.
233 InlineAsm *EmptyAsm;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000234
Evgeniy Stepanovda0072b2012-11-29 13:12:03 +0000235 friend struct MemorySanitizerVisitor;
236 friend struct VarArgAMD64Helper;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000237};
238} // namespace
239
240char MemorySanitizer::ID = 0;
241INITIALIZE_PASS(MemorySanitizer, "msan",
242 "MemorySanitizer: detects uninitialized reads.",
243 false, false)
244
Alexey Samsonov3efc87e2012-12-28 09:30:44 +0000245FunctionPass *llvm::createMemorySanitizerPass(bool TrackOrigins,
246 StringRef BlacklistFile) {
247 return new MemorySanitizer(TrackOrigins, BlacklistFile);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000248}
249
250/// \brief Create a non-const global initialized with the given string.
251///
252/// Creates a writable global for Str so that we can pass it to the
253/// run-time lib. Runtime uses first 4 bytes of the string to store the
254/// frame ID, so the string needs to be mutable.
255static GlobalVariable *createPrivateNonConstGlobalForString(Module &M,
256 StringRef Str) {
257 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
258 return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false,
259 GlobalValue::PrivateLinkage, StrConst, "");
260}
261
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000262
263/// \brief Insert extern declaration of runtime-provided functions and globals.
264void MemorySanitizer::initializeCallbacks(Module &M) {
265 // Only do this once.
266 if (WarningFn)
267 return;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000268
269 IRBuilder<> IRB(*C);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000270 // Create the callback.
271 // FIXME: this function should have "Cold" calling conv,
272 // which is not yet implemented.
273 StringRef WarningFnName = ClKeepGoing ? "__msan_warning"
274 : "__msan_warning_noreturn";
275 WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy(), NULL);
276
277 MsanCopyOriginFn = M.getOrInsertFunction(
278 "__msan_copy_origin", IRB.getVoidTy(), IRB.getInt8PtrTy(),
279 IRB.getInt8PtrTy(), IntptrTy, NULL);
280 MsanSetAllocaOriginFn = M.getOrInsertFunction(
281 "__msan_set_alloca_origin", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy,
282 IRB.getInt8PtrTy(), NULL);
283 MsanPoisonStackFn = M.getOrInsertFunction(
284 "__msan_poison_stack", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy, NULL);
285 MemmoveFn = M.getOrInsertFunction(
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000286 "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
287 IRB.getInt8PtrTy(), IntptrTy, NULL);
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +0000288 MemcpyFn = M.getOrInsertFunction(
289 "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
290 IntptrTy, NULL);
291 MemsetFn = M.getOrInsertFunction(
292 "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000293 IntptrTy, NULL);
294
295 // Create globals.
296 RetvalTLS = new GlobalVariable(
297 M, ArrayType::get(IRB.getInt64Ty(), 8), false,
298 GlobalVariable::ExternalLinkage, 0, "__msan_retval_tls", 0,
299 GlobalVariable::GeneralDynamicTLSModel);
300 RetvalOriginTLS = new GlobalVariable(
301 M, OriginTy, false, GlobalVariable::ExternalLinkage, 0,
302 "__msan_retval_origin_tls", 0, GlobalVariable::GeneralDynamicTLSModel);
303
304 ParamTLS = new GlobalVariable(
305 M, ArrayType::get(IRB.getInt64Ty(), 1000), false,
306 GlobalVariable::ExternalLinkage, 0, "__msan_param_tls", 0,
307 GlobalVariable::GeneralDynamicTLSModel);
308 ParamOriginTLS = new GlobalVariable(
309 M, ArrayType::get(OriginTy, 1000), false, GlobalVariable::ExternalLinkage,
310 0, "__msan_param_origin_tls", 0, GlobalVariable::GeneralDynamicTLSModel);
311
312 VAArgTLS = new GlobalVariable(
313 M, ArrayType::get(IRB.getInt64Ty(), 1000), false,
314 GlobalVariable::ExternalLinkage, 0, "__msan_va_arg_tls", 0,
315 GlobalVariable::GeneralDynamicTLSModel);
316 VAArgOverflowSizeTLS = new GlobalVariable(
317 M, IRB.getInt64Ty(), false, GlobalVariable::ExternalLinkage, 0,
318 "__msan_va_arg_overflow_size_tls", 0,
319 GlobalVariable::GeneralDynamicTLSModel);
320 OriginTLS = new GlobalVariable(
321 M, IRB.getInt32Ty(), false, GlobalVariable::ExternalLinkage, 0,
322 "__msan_origin_tls", 0, GlobalVariable::GeneralDynamicTLSModel);
Evgeniy Stepanov1d2da652012-11-29 12:30:18 +0000323
324 // We insert an empty inline asm after __msan_report* to avoid callback merge.
325 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
326 StringRef(""), StringRef(""),
327 /*hasSideEffects=*/true);
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000328}
329
330/// \brief Module-level initialization.
331///
332/// inserts a call to __msan_init to the module's constructor list.
333bool MemorySanitizer::doInitialization(Module &M) {
334 TD = getAnalysisIfAvailable<DataLayout>();
335 if (!TD)
336 return false;
Alexey Samsonov3efc87e2012-12-28 09:30:44 +0000337 BL.reset(new BlackList(BlacklistFile));
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000338 C = &(M.getContext());
339 unsigned PtrSize = TD->getPointerSizeInBits(/* AddressSpace */0);
340 switch (PtrSize) {
341 case 64:
342 ShadowMask = kShadowMask64;
343 OriginOffset = kOriginOffset64;
344 break;
345 case 32:
346 ShadowMask = kShadowMask32;
347 OriginOffset = kOriginOffset32;
348 break;
349 default:
350 report_fatal_error("unsupported pointer size");
351 break;
352 }
353
354 IRBuilder<> IRB(*C);
355 IntptrTy = IRB.getIntPtrTy(TD);
356 OriginTy = IRB.getInt32Ty();
357
358 ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000359 OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000);
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000360
361 // Insert a call to __msan_init/__msan_track_origins into the module's CTORs.
362 appendToGlobalCtors(M, cast<Function>(M.getOrInsertFunction(
363 "__msan_init", IRB.getVoidTy(), NULL)), 0);
364
365 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000366 IRB.getInt32(TrackOrigins), "__msan_track_origins");
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000367
Evgeniy Stepanovdcf6bcb2013-01-22 13:26:53 +0000368 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
369 IRB.getInt32(ClKeepGoing), "__msan_keep_going");
370
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000371 return true;
372}
373
374namespace {
375
376/// \brief A helper class that handles instrumentation of VarArg
377/// functions on a particular platform.
378///
379/// Implementations are expected to insert the instrumentation
380/// necessary to propagate argument shadow through VarArg function
381/// calls. Visit* methods are called during an InstVisitor pass over
382/// the function, and should avoid creating new basic blocks. A new
383/// instance of this class is created for each instrumented function.
384struct VarArgHelper {
385 /// \brief Visit a CallSite.
386 virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0;
387
388 /// \brief Visit a va_start call.
389 virtual void visitVAStartInst(VAStartInst &I) = 0;
390
391 /// \brief Visit a va_copy call.
392 virtual void visitVACopyInst(VACopyInst &I) = 0;
393
394 /// \brief Finalize function instrumentation.
395 ///
396 /// This method is called after visiting all interesting (see above)
397 /// instructions in a function.
398 virtual void finalizeInstrumentation() = 0;
Evgeniy Stepanovda0072b2012-11-29 13:12:03 +0000399
400 virtual ~VarArgHelper() {}
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000401};
402
403struct MemorySanitizerVisitor;
404
405VarArgHelper*
406CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
407 MemorySanitizerVisitor &Visitor);
408
409/// This class does all the work for a given function. Store and Load
410/// instructions store and load corresponding shadow and origin
411/// values. Most instructions propagate shadow from arguments to their
412/// return values. Certain instructions (most importantly, BranchInst)
413/// test their argument shadow and print reports (with a runtime call) if it's
414/// non-zero.
415struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
416 Function &F;
417 MemorySanitizer &MS;
418 SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
419 ValueMap<Value*, Value*> ShadowMap, OriginMap;
420 bool InsertChecks;
421 OwningPtr<VarArgHelper> VAHelper;
422
423 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
424 // See a comment in visitCallSite for more details.
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000425 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000426 static const unsigned AMD64FpEndOffset = 176;
427
428 struct ShadowOriginAndInsertPoint {
429 Instruction *Shadow;
430 Instruction *Origin;
431 Instruction *OrigIns;
432 ShadowOriginAndInsertPoint(Instruction *S, Instruction *O, Instruction *I)
433 : Shadow(S), Origin(O), OrigIns(I) { }
434 ShadowOriginAndInsertPoint() : Shadow(0), Origin(0), OrigIns(0) { }
435 };
436 SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000437 SmallVector<Instruction*, 16> StoreList;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000438
439 MemorySanitizerVisitor(Function &F, MemorySanitizer &MS)
440 : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)) {
441 InsertChecks = !MS.BL->isIn(F);
442 DEBUG(if (!InsertChecks)
443 dbgs() << "MemorySanitizer is not inserting checks into '"
444 << F.getName() << "'\n");
445 }
446
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000447 void materializeStores() {
448 for (size_t i = 0, n = StoreList.size(); i < n; i++) {
449 StoreInst& I = *dyn_cast<StoreInst>(StoreList[i]);
450
451 IRBuilder<> IRB(&I);
452 Value *Val = I.getValueOperand();
453 Value *Addr = I.getPointerOperand();
454 Value *Shadow = getShadow(Val);
455 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
456
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000457 StoreInst *NewSI =
458 IRB.CreateAlignedStore(Shadow, ShadowPtr, I.getAlignment());
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000459 DEBUG(dbgs() << " STORE: " << *NewSI << "\n");
NAKAMURA Takumie0b1b462012-12-06 13:38:00 +0000460 (void)NewSI;
Evgeniy Stepanovc4415592013-01-22 12:30:52 +0000461
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000462 if (ClCheckAccessAddress)
463 insertCheck(Addr, &I);
464
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000465 if (MS.TrackOrigins) {
Evgeniy Stepanov5eb5bf82012-12-26 11:55:09 +0000466 unsigned Alignment = std::max(kMinOriginAlignment, I.getAlignment());
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000467 if (ClStoreCleanOrigin || isa<StructType>(Shadow->getType())) {
Evgeniy Stepanov5eb5bf82012-12-26 11:55:09 +0000468 IRB.CreateAlignedStore(getOrigin(Val), getOriginPtr(Addr, IRB),
469 Alignment);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000470 } else {
471 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
472
473 Constant *Cst = dyn_cast_or_null<Constant>(ConvertedShadow);
474 // TODO(eugenis): handle non-zero constant shadow by inserting an
475 // unconditional check (can not simply fail compilation as this could
476 // be in the dead code).
477 if (Cst)
478 continue;
479
480 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
481 getCleanShadow(ConvertedShadow), "_mscmp");
482 Instruction *CheckTerm =
Evgeniy Stepanov49175b22012-12-14 13:43:11 +0000483 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false,
484 MS.OriginStoreWeights);
485 IRBuilder<> IRBNew(CheckTerm);
Evgeniy Stepanov5eb5bf82012-12-26 11:55:09 +0000486 IRBNew.CreateAlignedStore(getOrigin(Val), getOriginPtr(Addr, IRBNew),
487 Alignment);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000488 }
489 }
490 }
491 }
492
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000493 void materializeChecks() {
494 for (size_t i = 0, n = InstrumentationList.size(); i < n; i++) {
495 Instruction *Shadow = InstrumentationList[i].Shadow;
496 Instruction *OrigIns = InstrumentationList[i].OrigIns;
497 IRBuilder<> IRB(OrigIns);
498 DEBUG(dbgs() << " SHAD0 : " << *Shadow << "\n");
499 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
500 DEBUG(dbgs() << " SHAD1 : " << *ConvertedShadow << "\n");
501 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
502 getCleanShadow(ConvertedShadow), "_mscmp");
503 Instruction *CheckTerm =
504 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp),
505 /* Unreachable */ !ClKeepGoing,
506 MS.ColdCallWeights);
507
508 IRB.SetInsertPoint(CheckTerm);
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000509 if (MS.TrackOrigins) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000510 Instruction *Origin = InstrumentationList[i].Origin;
511 IRB.CreateStore(Origin ? (Value*)Origin : (Value*)IRB.getInt32(0),
512 MS.OriginTLS);
513 }
514 CallInst *Call = IRB.CreateCall(MS.WarningFn);
515 Call->setDebugLoc(OrigIns->getDebugLoc());
Evgeniy Stepanov1d2da652012-11-29 12:30:18 +0000516 IRB.CreateCall(MS.EmptyAsm);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000517 DEBUG(dbgs() << " CHECK: " << *Cmp << "\n");
518 }
519 DEBUG(dbgs() << "DONE:\n" << F);
520 }
521
522 /// \brief Add MemorySanitizer instrumentation to a function.
523 bool runOnFunction() {
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000524 MS.initializeCallbacks(*F.getParent());
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000525 if (!MS.TD) return false;
Evgeniy Stepanov4fbc0d082012-12-21 11:18:49 +0000526
527 // In the presence of unreachable blocks, we may see Phi nodes with
528 // incoming nodes from such blocks. Since InstVisitor skips unreachable
529 // blocks, such nodes will not have any shadow value associated with them.
530 // It's easier to remove unreachable blocks than deal with missing shadow.
531 removeUnreachableBlocks(F);
532
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000533 // Iterate all BBs in depth-first order and create shadow instructions
534 // for all instructions (where applicable).
535 // For PHI nodes we create dummy shadow PHIs which will be finalized later.
536 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
537 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
538 BasicBlock *BB = *DI;
539 visit(*BB);
540 }
541
542 // Finalize PHI nodes.
543 for (size_t i = 0, n = ShadowPHINodes.size(); i < n; i++) {
544 PHINode *PN = ShadowPHINodes[i];
545 PHINode *PNS = cast<PHINode>(getShadow(PN));
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000546 PHINode *PNO = MS.TrackOrigins ? cast<PHINode>(getOrigin(PN)) : 0;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000547 size_t NumValues = PN->getNumIncomingValues();
548 for (size_t v = 0; v < NumValues; v++) {
549 PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
550 if (PNO)
551 PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
552 }
553 }
554
555 VAHelper->finalizeInstrumentation();
556
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000557 // Delayed instrumentation of StoreInst.
Evgeniy Stepanov47ac9ba2012-12-06 11:58:59 +0000558 // This may add new checks to be inserted later.
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000559 materializeStores();
560
561 // Insert shadow value checks.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000562 materializeChecks();
563
564 return true;
565 }
566
567 /// \brief Compute the shadow type that corresponds to a given Value.
568 Type *getShadowTy(Value *V) {
569 return getShadowTy(V->getType());
570 }
571
572 /// \brief Compute the shadow type that corresponds to a given Type.
573 Type *getShadowTy(Type *OrigTy) {
574 if (!OrigTy->isSized()) {
575 return 0;
576 }
577 // For integer type, shadow is the same as the original type.
578 // This may return weird-sized types like i1.
579 if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
580 return IT;
Evgeniy Stepanovf19c0862012-12-25 16:04:38 +0000581 if (VectorType *VT = dyn_cast<VectorType>(OrigTy)) {
Evgeniy Stepanovd14e47b2013-01-15 16:44:52 +0000582 uint32_t EltSize = MS.TD->getTypeSizeInBits(VT->getElementType());
Evgeniy Stepanovf19c0862012-12-25 16:04:38 +0000583 return VectorType::get(IntegerType::get(*MS.C, EltSize),
584 VT->getNumElements());
585 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000586 if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
587 SmallVector<Type*, 4> Elements;
588 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
589 Elements.push_back(getShadowTy(ST->getElementType(i)));
590 StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
591 DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
592 return Res;
593 }
Evgeniy Stepanovd14e47b2013-01-15 16:44:52 +0000594 uint32_t TypeSize = MS.TD->getTypeSizeInBits(OrigTy);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000595 return IntegerType::get(*MS.C, TypeSize);
596 }
597
598 /// \brief Flatten a vector type.
599 Type *getShadowTyNoVec(Type *ty) {
600 if (VectorType *vt = dyn_cast<VectorType>(ty))
601 return IntegerType::get(*MS.C, vt->getBitWidth());
602 return ty;
603 }
604
605 /// \brief Convert a shadow value to it's flattened variant.
606 Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
607 Type *Ty = V->getType();
608 Type *NoVecTy = getShadowTyNoVec(Ty);
609 if (Ty == NoVecTy) return V;
610 return IRB.CreateBitCast(V, NoVecTy);
611 }
612
613 /// \brief Compute the shadow address that corresponds to a given application
614 /// address.
615 ///
616 /// Shadow = Addr & ~ShadowMask.
617 Value *getShadowPtr(Value *Addr, Type *ShadowTy,
618 IRBuilder<> &IRB) {
619 Value *ShadowLong =
620 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
621 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
622 return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
623 }
624
625 /// \brief Compute the origin address that corresponds to a given application
626 /// address.
627 ///
628 /// OriginAddr = (ShadowAddr + OriginOffset) & ~3ULL
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000629 Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB) {
630 Value *ShadowLong =
631 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
Evgeniy Stepanov62ba6112012-11-29 13:43:05 +0000632 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000633 Value *Add =
634 IRB.CreateAdd(ShadowLong,
635 ConstantInt::get(MS.IntptrTy, MS.OriginOffset));
Evgeniy Stepanov62ba6112012-11-29 13:43:05 +0000636 Value *SecondAnd =
637 IRB.CreateAnd(Add, ConstantInt::get(MS.IntptrTy, ~3ULL));
638 return IRB.CreateIntToPtr(SecondAnd, PointerType::get(IRB.getInt32Ty(), 0));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000639 }
640
641 /// \brief Compute the shadow address for a given function argument.
642 ///
643 /// Shadow = ParamTLS+ArgOffset.
644 Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
645 int ArgOffset) {
646 Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
647 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
648 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
649 "_msarg");
650 }
651
652 /// \brief Compute the origin address for a given function argument.
653 Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
654 int ArgOffset) {
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000655 if (!MS.TrackOrigins) return 0;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000656 Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
657 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
658 return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
659 "_msarg_o");
660 }
661
662 /// \brief Compute the shadow address for a retval.
663 Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
664 Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy);
665 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
666 "_msret");
667 }
668
669 /// \brief Compute the origin address for a retval.
670 Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
671 // We keep a single origin for the entire retval. Might be too optimistic.
672 return MS.RetvalOriginTLS;
673 }
674
675 /// \brief Set SV to be the shadow value for V.
676 void setShadow(Value *V, Value *SV) {
677 assert(!ShadowMap.count(V) && "Values may only have one shadow");
678 ShadowMap[V] = SV;
679 }
680
681 /// \brief Set Origin to be the origin value for V.
682 void setOrigin(Value *V, Value *Origin) {
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000683 if (!MS.TrackOrigins) return;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000684 assert(!OriginMap.count(V) && "Values may only have one origin");
685 DEBUG(dbgs() << "ORIGIN: " << *V << " ==> " << *Origin << "\n");
686 OriginMap[V] = Origin;
687 }
688
689 /// \brief Create a clean shadow value for a given value.
690 ///
691 /// Clean shadow (all zeroes) means all bits of the value are defined
692 /// (initialized).
693 Value *getCleanShadow(Value *V) {
694 Type *ShadowTy = getShadowTy(V);
695 if (!ShadowTy)
696 return 0;
697 return Constant::getNullValue(ShadowTy);
698 }
699
700 /// \brief Create a dirty shadow of a given shadow type.
701 Constant *getPoisonedShadow(Type *ShadowTy) {
702 assert(ShadowTy);
703 if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
704 return Constant::getAllOnesValue(ShadowTy);
705 StructType *ST = cast<StructType>(ShadowTy);
706 SmallVector<Constant *, 4> Vals;
707 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
708 Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
709 return ConstantStruct::get(ST, Vals);
710 }
711
712 /// \brief Create a clean (zero) origin.
713 Value *getCleanOrigin() {
714 return Constant::getNullValue(MS.OriginTy);
715 }
716
717 /// \brief Get the shadow value for a given Value.
718 ///
719 /// This function either returns the value set earlier with setShadow,
720 /// or extracts if from ParamTLS (for function arguments).
721 Value *getShadow(Value *V) {
722 if (Instruction *I = dyn_cast<Instruction>(V)) {
723 // For instructions the shadow is already stored in the map.
724 Value *Shadow = ShadowMap[V];
725 if (!Shadow) {
726 DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +0000727 (void)I;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000728 assert(Shadow && "No shadow for a value");
729 }
730 return Shadow;
731 }
732 if (UndefValue *U = dyn_cast<UndefValue>(V)) {
733 Value *AllOnes = getPoisonedShadow(getShadowTy(V));
734 DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +0000735 (void)U;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000736 return AllOnes;
737 }
738 if (Argument *A = dyn_cast<Argument>(V)) {
739 // For arguments we compute the shadow on demand and store it in the map.
740 Value **ShadowPtr = &ShadowMap[V];
741 if (*ShadowPtr)
742 return *ShadowPtr;
743 Function *F = A->getParent();
744 IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI());
745 unsigned ArgOffset = 0;
746 for (Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
747 AI != AE; ++AI) {
748 if (!AI->getType()->isSized()) {
749 DEBUG(dbgs() << "Arg is not sized\n");
750 continue;
751 }
752 unsigned Size = AI->hasByValAttr()
753 ? MS.TD->getTypeAllocSize(AI->getType()->getPointerElementType())
754 : MS.TD->getTypeAllocSize(AI->getType());
755 if (A == AI) {
756 Value *Base = getShadowPtrForArgument(AI, EntryIRB, ArgOffset);
757 if (AI->hasByValAttr()) {
758 // ByVal pointer itself has clean shadow. We copy the actual
759 // argument shadow to the underlying memory.
760 Value *Cpy = EntryIRB.CreateMemCpy(
761 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB),
762 Base, Size, AI->getParamAlignment());
763 DEBUG(dbgs() << " ByValCpy: " << *Cpy << "\n");
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +0000764 (void)Cpy;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000765 *ShadowPtr = getCleanShadow(V);
766 } else {
767 *ShadowPtr = EntryIRB.CreateLoad(Base);
768 }
769 DEBUG(dbgs() << " ARG: " << *AI << " ==> " <<
770 **ShadowPtr << "\n");
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000771 if (MS.TrackOrigins) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000772 Value* OriginPtr = getOriginPtrForArgument(AI, EntryIRB, ArgOffset);
773 setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
774 }
775 }
776 ArgOffset += DataLayout::RoundUpAlignment(Size, 8);
777 }
778 assert(*ShadowPtr && "Could not find shadow for an argument");
779 return *ShadowPtr;
780 }
781 // For everything else the shadow is zero.
782 return getCleanShadow(V);
783 }
784
785 /// \brief Get the shadow for i-th argument of the instruction I.
786 Value *getShadow(Instruction *I, int i) {
787 return getShadow(I->getOperand(i));
788 }
789
790 /// \brief Get the origin for a value.
791 Value *getOrigin(Value *V) {
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +0000792 if (!MS.TrackOrigins) return 0;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000793 if (isa<Instruction>(V) || isa<Argument>(V)) {
794 Value *Origin = OriginMap[V];
795 if (!Origin) {
796 DEBUG(dbgs() << "NO ORIGIN: " << *V << "\n");
797 Origin = getCleanOrigin();
798 }
799 return Origin;
800 }
801 return getCleanOrigin();
802 }
803
804 /// \brief Get the origin for i-th argument of the instruction I.
805 Value *getOrigin(Instruction *I, int i) {
806 return getOrigin(I->getOperand(i));
807 }
808
809 /// \brief Remember the place where a shadow check should be inserted.
810 ///
811 /// This location will be later instrumented with a check that will print a
812 /// UMR warning in runtime if the value is not fully defined.
813 void insertCheck(Value *Val, Instruction *OrigIns) {
814 assert(Val);
815 if (!InsertChecks) return;
816 Instruction *Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
817 if (!Shadow) return;
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +0000818#ifndef NDEBUG
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000819 Type *ShadowTy = Shadow->getType();
820 assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
821 "Can only insert checks for integer and vector shadow types");
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +0000822#endif
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000823 Instruction *Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
824 InstrumentationList.push_back(
825 ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
826 }
827
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000828 // ------------------- Visitors.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000829
830 /// \brief Instrument LoadInst
831 ///
832 /// Loads the corresponding shadow and (optionally) origin.
833 /// Optionally, checks that the load address is fully defined.
834 void visitLoadInst(LoadInst &I) {
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +0000835 assert(I.getType()->isSized() && "Load type must have size");
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000836 IRBuilder<> IRB(&I);
837 Type *ShadowTy = getShadowTy(&I);
838 Value *Addr = I.getPointerOperand();
839 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
Evgeniy Stepanoveeb8b7c2012-11-29 14:05:53 +0000840 setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld"));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000841
842 if (ClCheckAccessAddress)
843 insertCheck(I.getPointerOperand(), &I);
844
Evgeniy Stepanov5eb5bf82012-12-26 11:55:09 +0000845 if (MS.TrackOrigins) {
846 unsigned Alignment = std::max(kMinOriginAlignment, I.getAlignment());
847 setOrigin(&I, IRB.CreateAlignedLoad(getOriginPtr(Addr, IRB), Alignment));
848 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000849 }
850
851 /// \brief Instrument StoreInst
852 ///
853 /// Stores the corresponding shadow and (optionally) origin.
854 /// Optionally, checks that the store address is fully defined.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000855 void visitStoreInst(StoreInst &I) {
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000856 StoreList.push_back(&I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000857 }
858
Evgeniy Stepanov30484fc2012-11-29 15:22:06 +0000859 // Vector manipulation.
860 void visitExtractElementInst(ExtractElementInst &I) {
861 insertCheck(I.getOperand(1), &I);
862 IRBuilder<> IRB(&I);
863 setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
864 "_msprop"));
865 setOrigin(&I, getOrigin(&I, 0));
866 }
867
868 void visitInsertElementInst(InsertElementInst &I) {
869 insertCheck(I.getOperand(2), &I);
870 IRBuilder<> IRB(&I);
871 setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
872 I.getOperand(2), "_msprop"));
873 setOriginForNaryOp(I);
874 }
875
876 void visitShuffleVectorInst(ShuffleVectorInst &I) {
877 insertCheck(I.getOperand(2), &I);
878 IRBuilder<> IRB(&I);
879 setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
880 I.getOperand(2), "_msprop"));
881 setOriginForNaryOp(I);
882 }
883
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000884 // Casts.
885 void visitSExtInst(SExtInst &I) {
886 IRBuilder<> IRB(&I);
887 setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
888 setOrigin(&I, getOrigin(&I, 0));
889 }
890
891 void visitZExtInst(ZExtInst &I) {
892 IRBuilder<> IRB(&I);
893 setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
894 setOrigin(&I, getOrigin(&I, 0));
895 }
896
897 void visitTruncInst(TruncInst &I) {
898 IRBuilder<> IRB(&I);
899 setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
900 setOrigin(&I, getOrigin(&I, 0));
901 }
902
903 void visitBitCastInst(BitCastInst &I) {
904 IRBuilder<> IRB(&I);
905 setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
906 setOrigin(&I, getOrigin(&I, 0));
907 }
908
909 void visitPtrToIntInst(PtrToIntInst &I) {
910 IRBuilder<> IRB(&I);
911 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
912 "_msprop_ptrtoint"));
913 setOrigin(&I, getOrigin(&I, 0));
914 }
915
916 void visitIntToPtrInst(IntToPtrInst &I) {
917 IRBuilder<> IRB(&I);
918 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
919 "_msprop_inttoptr"));
920 setOrigin(&I, getOrigin(&I, 0));
921 }
922
923 void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
924 void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
925 void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
926 void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
927 void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
928 void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
929
930 /// \brief Propagate shadow for bitwise AND.
931 ///
932 /// This code is exact, i.e. if, for example, a bit in the left argument
933 /// is defined and 0, then neither the value not definedness of the
934 /// corresponding bit in B don't affect the resulting shadow.
935 void visitAnd(BinaryOperator &I) {
936 IRBuilder<> IRB(&I);
937 // "And" of 0 and a poisoned value results in unpoisoned value.
938 // 1&1 => 1; 0&1 => 0; p&1 => p;
939 // 1&0 => 0; 0&0 => 0; p&0 => 0;
940 // 1&p => p; 0&p => 0; p&p => p;
941 // S = (S1 & S2) | (V1 & S2) | (S1 & V2)
942 Value *S1 = getShadow(&I, 0);
943 Value *S2 = getShadow(&I, 1);
944 Value *V1 = I.getOperand(0);
945 Value *V2 = I.getOperand(1);
946 if (V1->getType() != S1->getType()) {
947 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
948 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
949 }
950 Value *S1S2 = IRB.CreateAnd(S1, S2);
951 Value *V1S2 = IRB.CreateAnd(V1, S2);
952 Value *S1V2 = IRB.CreateAnd(S1, V2);
953 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
954 setOriginForNaryOp(I);
955 }
956
957 void visitOr(BinaryOperator &I) {
958 IRBuilder<> IRB(&I);
959 // "Or" of 1 and a poisoned value results in unpoisoned value.
960 // 1|1 => 1; 0|1 => 1; p|1 => 1;
961 // 1|0 => 1; 0|0 => 0; p|0 => p;
962 // 1|p => 1; 0|p => p; p|p => p;
963 // S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
964 Value *S1 = getShadow(&I, 0);
965 Value *S2 = getShadow(&I, 1);
966 Value *V1 = IRB.CreateNot(I.getOperand(0));
967 Value *V2 = IRB.CreateNot(I.getOperand(1));
968 if (V1->getType() != S1->getType()) {
969 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
970 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
971 }
972 Value *S1S2 = IRB.CreateAnd(S1, S2);
973 Value *V1S2 = IRB.CreateAnd(V1, S2);
974 Value *S1V2 = IRB.CreateAnd(S1, V2);
975 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
976 setOriginForNaryOp(I);
977 }
978
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +0000979 /// \brief Default propagation of shadow and/or origin.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000980 ///
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +0000981 /// This class implements the general case of shadow propagation, used in all
982 /// cases where we don't know and/or don't care about what the operation
983 /// actually does. It converts all input shadow values to a common type
984 /// (extending or truncating as necessary), and bitwise OR's them.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000985 ///
986 /// This is much cheaper than inserting checks (i.e. requiring inputs to be
987 /// fully initialized), and less prone to false positives.
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +0000988 ///
989 /// This class also implements the general case of origin propagation. For a
990 /// Nary operation, result origin is set to the origin of an argument that is
991 /// not entirely initialized. If there is more than one such arguments, the
992 /// rightmost of them is picked. It does not matter which one is picked if all
993 /// arguments are initialized.
994 template <bool CombineShadow>
995 class Combiner {
996 Value *Shadow;
997 Value *Origin;
998 IRBuilder<> &IRB;
999 MemorySanitizerVisitor *MSV;
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +00001000
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001001 public:
1002 Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB) :
1003 Shadow(0), Origin(0), IRB(IRB), MSV(MSV) {}
1004
1005 /// \brief Add a pair of shadow and origin values to the mix.
1006 Combiner &Add(Value *OpShadow, Value *OpOrigin) {
1007 if (CombineShadow) {
1008 assert(OpShadow);
1009 if (!Shadow)
1010 Shadow = OpShadow;
1011 else {
1012 OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
1013 Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
1014 }
1015 }
1016
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001017 if (MSV->MS.TrackOrigins) {
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001018 assert(OpOrigin);
1019 if (!Origin) {
1020 Origin = OpOrigin;
1021 } else {
1022 Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB);
1023 Value *Cond = IRB.CreateICmpNE(FlatShadow,
1024 MSV->getCleanShadow(FlatShadow));
1025 Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
1026 }
1027 }
1028 return *this;
1029 }
1030
1031 /// \brief Add an application value to the mix.
1032 Combiner &Add(Value *V) {
1033 Value *OpShadow = MSV->getShadow(V);
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001034 Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : 0;
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001035 return Add(OpShadow, OpOrigin);
1036 }
1037
1038 /// \brief Set the current combined values as the given instruction's shadow
1039 /// and origin.
1040 void Done(Instruction *I) {
1041 if (CombineShadow) {
1042 assert(Shadow);
1043 Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
1044 MSV->setShadow(I, Shadow);
1045 }
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001046 if (MSV->MS.TrackOrigins) {
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001047 assert(Origin);
1048 MSV->setOrigin(I, Origin);
1049 }
1050 }
1051 };
1052
1053 typedef Combiner<true> ShadowAndOriginCombiner;
1054 typedef Combiner<false> OriginCombiner;
1055
1056 /// \brief Propagate origin for arbitrary operation.
1057 void setOriginForNaryOp(Instruction &I) {
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001058 if (!MS.TrackOrigins) return;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001059 IRBuilder<> IRB(&I);
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001060 OriginCombiner OC(this, IRB);
1061 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1062 OC.Add(OI->get());
1063 OC.Done(&I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001064 }
1065
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001066 size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
Evgeniy Stepanovf19c0862012-12-25 16:04:38 +00001067 assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) &&
1068 "Vector of pointers is not a valid shadow type");
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001069 return Ty->isVectorTy() ?
1070 Ty->getVectorNumElements() * Ty->getScalarSizeInBits() :
1071 Ty->getPrimitiveSizeInBits();
1072 }
1073
1074 /// \brief Cast between two shadow types, extending or truncating as
1075 /// necessary.
1076 Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy) {
1077 Type *srcTy = V->getType();
1078 if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
1079 return IRB.CreateIntCast(V, dstTy, false);
1080 if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
1081 dstTy->getVectorNumElements() == srcTy->getVectorNumElements())
1082 return IRB.CreateIntCast(V, dstTy, false);
1083 size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
1084 size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
1085 Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
1086 Value *V2 =
1087 IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), false);
1088 return IRB.CreateBitCast(V2, dstTy);
1089 // TODO: handle struct types.
1090 }
1091
1092 /// \brief Propagate shadow for arbitrary operation.
1093 void handleShadowOr(Instruction &I) {
1094 IRBuilder<> IRB(&I);
1095 ShadowAndOriginCombiner SC(this, IRB);
1096 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1097 SC.Add(OI->get());
1098 SC.Done(&I);
1099 }
1100
1101 void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
1102 void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
1103 void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
1104 void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
1105 void visitSub(BinaryOperator &I) { handleShadowOr(I); }
1106 void visitXor(BinaryOperator &I) { handleShadowOr(I); }
1107 void visitMul(BinaryOperator &I) { handleShadowOr(I); }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001108
1109 void handleDiv(Instruction &I) {
1110 IRBuilder<> IRB(&I);
1111 // Strict on the second argument.
1112 insertCheck(I.getOperand(1), &I);
1113 setShadow(&I, getShadow(&I, 0));
1114 setOrigin(&I, getOrigin(&I, 0));
1115 }
1116
1117 void visitUDiv(BinaryOperator &I) { handleDiv(I); }
1118 void visitSDiv(BinaryOperator &I) { handleDiv(I); }
1119 void visitFDiv(BinaryOperator &I) { handleDiv(I); }
1120 void visitURem(BinaryOperator &I) { handleDiv(I); }
1121 void visitSRem(BinaryOperator &I) { handleDiv(I); }
1122 void visitFRem(BinaryOperator &I) { handleDiv(I); }
1123
1124 /// \brief Instrument == and != comparisons.
1125 ///
1126 /// Sometimes the comparison result is known even if some of the bits of the
1127 /// arguments are not.
1128 void handleEqualityComparison(ICmpInst &I) {
1129 IRBuilder<> IRB(&I);
1130 Value *A = I.getOperand(0);
1131 Value *B = I.getOperand(1);
1132 Value *Sa = getShadow(A);
1133 Value *Sb = getShadow(B);
Evgeniy Stepanovd14e47b2013-01-15 16:44:52 +00001134
1135 // Get rid of pointers and vectors of pointers.
1136 // For ints (and vectors of ints), types of A and Sa match,
1137 // and this is a no-op.
1138 A = IRB.CreatePointerCast(A, Sa->getType());
1139 B = IRB.CreatePointerCast(B, Sb->getType());
1140
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001141 // A == B <==> (C = A^B) == 0
1142 // A != B <==> (C = A^B) != 0
1143 // Sc = Sa | Sb
1144 Value *C = IRB.CreateXor(A, B);
1145 Value *Sc = IRB.CreateOr(Sa, Sb);
1146 // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
1147 // Result is defined if one of the following is true
1148 // * there is a defined 1 bit in C
1149 // * C is fully defined
1150 // Si = !(C & ~Sc) && Sc
1151 Value *Zero = Constant::getNullValue(Sc->getType());
1152 Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
1153 Value *Si =
1154 IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
1155 IRB.CreateICmpEQ(
1156 IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
1157 Si->setName("_msprop_icmp");
1158 setShadow(&I, Si);
1159 setOriginForNaryOp(I);
1160 }
1161
Evgeniy Stepanovfac84032013-01-25 15:31:10 +00001162 /// \brief Build the lowest possible value of V, taking into account V's
1163 /// uninitialized bits.
1164 Value *getLowestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1165 bool isSigned) {
1166 if (isSigned) {
1167 // Split shadow into sign bit and other bits.
1168 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1169 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1170 // Maximise the undefined shadow bit, minimize other undefined bits.
1171 return
1172 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaOtherBits)), SaSignBit);
1173 } else {
1174 // Minimize undefined bits.
1175 return IRB.CreateAnd(A, IRB.CreateNot(Sa));
1176 }
1177 }
1178
1179 /// \brief Build the highest possible value of V, taking into account V's
1180 /// uninitialized bits.
1181 Value *getHighestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1182 bool isSigned) {
1183 if (isSigned) {
1184 // Split shadow into sign bit and other bits.
1185 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1186 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1187 // Minimise the undefined shadow bit, maximise other undefined bits.
1188 return
1189 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaSignBit)), SaOtherBits);
1190 } else {
1191 // Maximize undefined bits.
1192 return IRB.CreateOr(A, Sa);
1193 }
1194 }
1195
1196 /// \brief Instrument relational comparisons.
1197 ///
1198 /// This function does exact shadow propagation for all relational
1199 /// comparisons of integers, pointers and vectors of those.
1200 /// FIXME: output seems suboptimal when one of the operands is a constant
1201 void handleRelationalComparisonExact(ICmpInst &I) {
1202 IRBuilder<> IRB(&I);
1203 Value *A = I.getOperand(0);
1204 Value *B = I.getOperand(1);
1205 Value *Sa = getShadow(A);
1206 Value *Sb = getShadow(B);
1207
1208 // Get rid of pointers and vectors of pointers.
1209 // For ints (and vectors of ints), types of A and Sa match,
1210 // and this is a no-op.
1211 A = IRB.CreatePointerCast(A, Sa->getType());
1212 B = IRB.CreatePointerCast(B, Sb->getType());
1213
1214 bool IsSigned = I.isSigned();
1215 Value *S1 = IRB.CreateICmp(I.getPredicate(),
1216 getLowestPossibleValue(IRB, A, Sa, IsSigned),
1217 getHighestPossibleValue(IRB, B, Sb, IsSigned));
1218 Value *S2 = IRB.CreateICmp(I.getPredicate(),
1219 getHighestPossibleValue(IRB, A, Sa, IsSigned),
1220 getLowestPossibleValue(IRB, B, Sb, IsSigned));
1221 Value *Si = IRB.CreateXor(S1, S2);
1222 setShadow(&I, Si);
1223 setOriginForNaryOp(I);
1224 }
1225
Evgeniy Stepanov857d9d22012-11-29 14:25:47 +00001226 /// \brief Instrument signed relational comparisons.
1227 ///
1228 /// Handle (x<0) and (x>=0) comparisons (essentially, sign bit tests) by
1229 /// propagating the highest bit of the shadow. Everything else is delegated
1230 /// to handleShadowOr().
1231 void handleSignedRelationalComparison(ICmpInst &I) {
1232 Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1233 Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
1234 Value* op = NULL;
1235 CmpInst::Predicate pre = I.getPredicate();
1236 if (constOp0 && constOp0->isNullValue() &&
1237 (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE)) {
1238 op = I.getOperand(1);
1239 } else if (constOp1 && constOp1->isNullValue() &&
1240 (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) {
1241 op = I.getOperand(0);
1242 }
1243 if (op) {
1244 IRBuilder<> IRB(&I);
1245 Value* Shadow =
1246 IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op), "_msprop_icmpslt");
1247 setShadow(&I, Shadow);
1248 setOrigin(&I, getOrigin(op));
1249 } else {
1250 handleShadowOr(I);
1251 }
1252 }
1253
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001254 void visitICmpInst(ICmpInst &I) {
1255 if (ClHandleICmp && I.isEquality())
1256 handleEqualityComparison(I);
Evgeniy Stepanovfac84032013-01-25 15:31:10 +00001257 else if (ClHandleICmp && ClHandleICmpExact && I.isRelational())
1258 handleRelationalComparisonExact(I);
Evgeniy Stepanov857d9d22012-11-29 14:25:47 +00001259 else if (ClHandleICmp && I.isSigned() && I.isRelational())
1260 handleSignedRelationalComparison(I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001261 else
1262 handleShadowOr(I);
1263 }
1264
1265 void visitFCmpInst(FCmpInst &I) {
1266 handleShadowOr(I);
1267 }
1268
1269 void handleShift(BinaryOperator &I) {
1270 IRBuilder<> IRB(&I);
1271 // If any of the S2 bits are poisoned, the whole thing is poisoned.
1272 // Otherwise perform the same shift on S1.
1273 Value *S1 = getShadow(&I, 0);
1274 Value *S2 = getShadow(&I, 1);
1275 Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
1276 S2->getType());
1277 Value *V2 = I.getOperand(1);
1278 Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
1279 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1280 setOriginForNaryOp(I);
1281 }
1282
1283 void visitShl(BinaryOperator &I) { handleShift(I); }
1284 void visitAShr(BinaryOperator &I) { handleShift(I); }
1285 void visitLShr(BinaryOperator &I) { handleShift(I); }
1286
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001287 /// \brief Instrument llvm.memmove
1288 ///
1289 /// At this point we don't know if llvm.memmove will be inlined or not.
1290 /// If we don't instrument it and it gets inlined,
1291 /// our interceptor will not kick in and we will lose the memmove.
1292 /// If we instrument the call here, but it does not get inlined,
1293 /// we will memove the shadow twice: which is bad in case
1294 /// of overlapping regions. So, we simply lower the intrinsic to a call.
1295 ///
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +00001296 /// Similar situation exists for memcpy and memset.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001297 void visitMemMoveInst(MemMoveInst &I) {
1298 IRBuilder<> IRB(&I);
1299 IRB.CreateCall3(
1300 MS.MemmoveFn,
1301 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1302 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1303 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1304 I.eraseFromParent();
1305 }
1306
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +00001307 // Similar to memmove: avoid copying shadow twice.
1308 // This is somewhat unfortunate as it may slowdown small constant memcpys.
1309 // FIXME: consider doing manual inline for small constant sizes and proper
1310 // alignment.
1311 void visitMemCpyInst(MemCpyInst &I) {
1312 IRBuilder<> IRB(&I);
1313 IRB.CreateCall3(
1314 MS.MemcpyFn,
1315 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1316 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1317 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1318 I.eraseFromParent();
1319 }
1320
1321 // Same as memcpy.
1322 void visitMemSetInst(MemSetInst &I) {
1323 IRBuilder<> IRB(&I);
1324 IRB.CreateCall3(
1325 MS.MemsetFn,
1326 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1327 IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
1328 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1329 I.eraseFromParent();
1330 }
1331
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001332 void visitVAStartInst(VAStartInst &I) {
1333 VAHelper->visitVAStartInst(I);
1334 }
1335
1336 void visitVACopyInst(VACopyInst &I) {
1337 VAHelper->visitVACopyInst(I);
1338 }
1339
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001340 enum IntrinsicKind {
1341 IK_DoesNotAccessMemory,
1342 IK_OnlyReadsMemory,
1343 IK_WritesMemory
1344 };
1345
1346 static IntrinsicKind getIntrinsicKind(Intrinsic::ID iid) {
1347 const int DoesNotAccessMemory = IK_DoesNotAccessMemory;
1348 const int OnlyReadsArgumentPointees = IK_OnlyReadsMemory;
1349 const int OnlyReadsMemory = IK_OnlyReadsMemory;
1350 const int OnlyAccessesArgumentPointees = IK_WritesMemory;
1351 const int UnknownModRefBehavior = IK_WritesMemory;
1352#define GET_INTRINSIC_MODREF_BEHAVIOR
1353#define ModRefBehavior IntrinsicKind
Chandler Carruthdb25c6c2013-01-02 12:09:16 +00001354#include "llvm/IR/Intrinsics.gen"
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001355#undef ModRefBehavior
1356#undef GET_INTRINSIC_MODREF_BEHAVIOR
1357 }
1358
1359 /// \brief Handle vector store-like intrinsics.
1360 ///
1361 /// Instrument intrinsics that look like a simple SIMD store: writes memory,
1362 /// has 1 pointer argument and 1 vector argument, returns void.
1363 bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
1364 IRBuilder<> IRB(&I);
1365 Value* Addr = I.getArgOperand(0);
1366 Value *Shadow = getShadow(&I, 1);
1367 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
1368
1369 // We don't know the pointer alignment (could be unaligned SSE store!).
1370 // Have to assume to worst case.
1371 IRB.CreateAlignedStore(Shadow, ShadowPtr, 1);
1372
1373 if (ClCheckAccessAddress)
1374 insertCheck(Addr, &I);
1375
1376 // FIXME: use ClStoreCleanOrigin
1377 // FIXME: factor out common code from materializeStores
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001378 if (MS.TrackOrigins)
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001379 IRB.CreateStore(getOrigin(&I, 1), getOriginPtr(Addr, IRB));
1380 return true;
1381 }
1382
1383 /// \brief Handle vector load-like intrinsics.
1384 ///
1385 /// Instrument intrinsics that look like a simple SIMD load: reads memory,
1386 /// has 1 pointer argument, returns a vector.
1387 bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
1388 IRBuilder<> IRB(&I);
1389 Value *Addr = I.getArgOperand(0);
1390
1391 Type *ShadowTy = getShadowTy(&I);
1392 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1393 // We don't know the pointer alignment (could be unaligned SSE load!).
1394 // Have to assume to worst case.
1395 setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, 1, "_msld"));
1396
1397 if (ClCheckAccessAddress)
1398 insertCheck(Addr, &I);
1399
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001400 if (MS.TrackOrigins)
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001401 setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB)));
1402 return true;
1403 }
1404
1405 /// \brief Handle (SIMD arithmetic)-like intrinsics.
1406 ///
1407 /// Instrument intrinsics with any number of arguments of the same type,
1408 /// equal to the return type. The type should be simple (no aggregates or
1409 /// pointers; vectors are fine).
1410 /// Caller guarantees that this intrinsic does not access memory.
1411 bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) {
1412 Type *RetTy = I.getType();
1413 if (!(RetTy->isIntOrIntVectorTy() ||
1414 RetTy->isFPOrFPVectorTy() ||
1415 RetTy->isX86_MMXTy()))
1416 return false;
1417
1418 unsigned NumArgOperands = I.getNumArgOperands();
1419
1420 for (unsigned i = 0; i < NumArgOperands; ++i) {
1421 Type *Ty = I.getArgOperand(i)->getType();
1422 if (Ty != RetTy)
1423 return false;
1424 }
1425
1426 IRBuilder<> IRB(&I);
1427 ShadowAndOriginCombiner SC(this, IRB);
1428 for (unsigned i = 0; i < NumArgOperands; ++i)
1429 SC.Add(I.getArgOperand(i));
1430 SC.Done(&I);
1431
1432 return true;
1433 }
1434
1435 /// \brief Heuristically instrument unknown intrinsics.
1436 ///
1437 /// The main purpose of this code is to do something reasonable with all
1438 /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
1439 /// We recognize several classes of intrinsics by their argument types and
1440 /// ModRefBehaviour and apply special intrumentation when we are reasonably
1441 /// sure that we know what the intrinsic does.
1442 ///
1443 /// We special-case intrinsics where this approach fails. See llvm.bswap
1444 /// handling as an example of that.
1445 bool handleUnknownIntrinsic(IntrinsicInst &I) {
1446 unsigned NumArgOperands = I.getNumArgOperands();
1447 if (NumArgOperands == 0)
1448 return false;
1449
1450 Intrinsic::ID iid = I.getIntrinsicID();
1451 IntrinsicKind IK = getIntrinsicKind(iid);
1452 bool OnlyReadsMemory = IK == IK_OnlyReadsMemory;
1453 bool WritesMemory = IK == IK_WritesMemory;
1454 assert(!(OnlyReadsMemory && WritesMemory));
1455
1456 if (NumArgOperands == 2 &&
1457 I.getArgOperand(0)->getType()->isPointerTy() &&
1458 I.getArgOperand(1)->getType()->isVectorTy() &&
1459 I.getType()->isVoidTy() &&
1460 WritesMemory) {
1461 // This looks like a vector store.
1462 return handleVectorStoreIntrinsic(I);
1463 }
1464
1465 if (NumArgOperands == 1 &&
1466 I.getArgOperand(0)->getType()->isPointerTy() &&
1467 I.getType()->isVectorTy() &&
1468 OnlyReadsMemory) {
1469 // This looks like a vector load.
1470 return handleVectorLoadIntrinsic(I);
1471 }
1472
1473 if (!OnlyReadsMemory && !WritesMemory)
1474 if (maybeHandleSimpleNomemIntrinsic(I))
1475 return true;
1476
1477 // FIXME: detect and handle SSE maskstore/maskload
1478 return false;
1479 }
1480
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00001481 void handleBswap(IntrinsicInst &I) {
1482 IRBuilder<> IRB(&I);
1483 Value *Op = I.getArgOperand(0);
1484 Type *OpType = Op->getType();
1485 Function *BswapFunc = Intrinsic::getDeclaration(
1486 F.getParent(), Intrinsic::bswap, ArrayRef<Type*>(&OpType, 1));
1487 setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
1488 setOrigin(&I, getOrigin(Op));
1489 }
1490
1491 void visitIntrinsicInst(IntrinsicInst &I) {
1492 switch (I.getIntrinsicID()) {
1493 case llvm::Intrinsic::bswap:
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +00001494 handleBswap(I);
1495 break;
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00001496 default:
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001497 if (!handleUnknownIntrinsic(I))
1498 visitInstruction(I);
Evgeniy Stepanov88b8dce2012-12-17 16:30:05 +00001499 break;
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00001500 }
1501 }
1502
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001503 void visitCallSite(CallSite CS) {
1504 Instruction &I = *CS.getInstruction();
1505 assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
1506 if (CS.isCall()) {
Evgeniy Stepanov7ad7e832012-11-29 14:32:03 +00001507 CallInst *Call = cast<CallInst>(&I);
1508
1509 // For inline asm, do the usual thing: check argument shadow and mark all
1510 // outputs as clean. Note that any side effects of the inline asm that are
1511 // not immediately visible in its constraints are not handled.
1512 if (Call->isInlineAsm()) {
1513 visitInstruction(I);
1514 return;
1515 }
1516
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001517 // Allow only tail calls with the same types, otherwise
1518 // we may have a false positive: shadow for a non-void RetVal
1519 // will get propagated to a void RetVal.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001520 if (Call->isTailCall() && Call->getType() != Call->getParent()->getType())
1521 Call->setTailCall(false);
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00001522
1523 assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
Evgeniy Stepanov383b61e2012-12-07 09:08:32 +00001524
1525 // We are going to insert code that relies on the fact that the callee
1526 // will become a non-readonly function after it is instrumented by us. To
1527 // prevent this code from being optimized out, mark that function
1528 // non-readonly in advance.
1529 if (Function *Func = Call->getCalledFunction()) {
1530 // Clear out readonly/readnone attributes.
1531 AttrBuilder B;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001532 B.addAttribute(Attribute::ReadOnly)
1533 .addAttribute(Attribute::ReadNone);
Bill Wendling430fa9b2013-01-23 00:45:55 +00001534 Func->removeAttributes(AttributeSet::FunctionIndex,
1535 AttributeSet::get(Func->getContext(),
1536 AttributeSet::FunctionIndex,
1537 B));
Evgeniy Stepanov383b61e2012-12-07 09:08:32 +00001538 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001539 }
1540 IRBuilder<> IRB(&I);
1541 unsigned ArgOffset = 0;
1542 DEBUG(dbgs() << " CallSite: " << I << "\n");
1543 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
1544 ArgIt != End; ++ArgIt) {
1545 Value *A = *ArgIt;
1546 unsigned i = ArgIt - CS.arg_begin();
1547 if (!A->getType()->isSized()) {
1548 DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
1549 continue;
1550 }
1551 unsigned Size = 0;
1552 Value *Store = 0;
1553 // Compute the Shadow for arg even if it is ByVal, because
1554 // in that case getShadow() will copy the actual arg shadow to
1555 // __msan_param_tls.
1556 Value *ArgShadow = getShadow(A);
1557 Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
1558 DEBUG(dbgs() << " Arg#" << i << ": " << *A <<
1559 " Shadow: " << *ArgShadow << "\n");
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001560 if (CS.paramHasAttr(i + 1, Attribute::ByVal)) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001561 assert(A->getType()->isPointerTy() &&
1562 "ByVal argument is not a pointer!");
1563 Size = MS.TD->getTypeAllocSize(A->getType()->getPointerElementType());
1564 unsigned Alignment = CS.getParamAlignment(i + 1);
1565 Store = IRB.CreateMemCpy(ArgShadowBase,
1566 getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
1567 Size, Alignment);
1568 } else {
1569 Size = MS.TD->getTypeAllocSize(A->getType());
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00001570 Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
1571 kShadowTLSAlignment);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001572 }
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001573 if (MS.TrackOrigins)
Evgeniy Stepanov49175b22012-12-14 13:43:11 +00001574 IRB.CreateStore(getOrigin(A),
1575 getOriginPtrForArgument(A, IRB, ArgOffset));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001576 assert(Size != 0 && Store != 0);
1577 DEBUG(dbgs() << " Param:" << *Store << "\n");
1578 ArgOffset += DataLayout::RoundUpAlignment(Size, 8);
1579 }
1580 DEBUG(dbgs() << " done with call args\n");
1581
1582 FunctionType *FT =
1583 cast<FunctionType>(CS.getCalledValue()->getType()-> getContainedType(0));
1584 if (FT->isVarArg()) {
1585 VAHelper->visitCallSite(CS, IRB);
1586 }
1587
1588 // Now, get the shadow for the RetVal.
1589 if (!I.getType()->isSized()) return;
1590 IRBuilder<> IRBBefore(&I);
1591 // Untill we have full dynamic coverage, make sure the retval shadow is 0.
1592 Value *Base = getShadowPtrForRetval(&I, IRBBefore);
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00001593 IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001594 Instruction *NextInsn = 0;
1595 if (CS.isCall()) {
1596 NextInsn = I.getNextNode();
1597 } else {
1598 BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
1599 if (!NormalDest->getSinglePredecessor()) {
1600 // FIXME: this case is tricky, so we are just conservative here.
1601 // Perhaps we need to split the edge between this BB and NormalDest,
1602 // but a naive attempt to use SplitEdge leads to a crash.
1603 setShadow(&I, getCleanShadow(&I));
1604 setOrigin(&I, getCleanOrigin());
1605 return;
1606 }
1607 NextInsn = NormalDest->getFirstInsertionPt();
1608 assert(NextInsn &&
1609 "Could not find insertion point for retval shadow load");
1610 }
1611 IRBuilder<> IRBAfter(NextInsn);
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00001612 Value *RetvalShadow =
1613 IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
1614 kShadowTLSAlignment, "_msret");
1615 setShadow(&I, RetvalShadow);
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001616 if (MS.TrackOrigins)
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001617 setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
1618 }
1619
1620 void visitReturnInst(ReturnInst &I) {
1621 IRBuilder<> IRB(&I);
1622 if (Value *RetVal = I.getReturnValue()) {
1623 // Set the shadow for the RetVal.
1624 Value *Shadow = getShadow(RetVal);
1625 Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
1626 DEBUG(dbgs() << "Return: " << *Shadow << "\n" << *ShadowPtr << "\n");
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00001627 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001628 if (MS.TrackOrigins)
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001629 IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
1630 }
1631 }
1632
1633 void visitPHINode(PHINode &I) {
1634 IRBuilder<> IRB(&I);
1635 ShadowPHINodes.push_back(&I);
1636 setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
1637 "_msphi_s"));
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001638 if (MS.TrackOrigins)
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001639 setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
1640 "_msphi_o"));
1641 }
1642
1643 void visitAllocaInst(AllocaInst &I) {
1644 setShadow(&I, getCleanShadow(&I));
1645 if (!ClPoisonStack) return;
1646 IRBuilder<> IRB(I.getNextNode());
1647 uint64_t Size = MS.TD->getTypeAllocSize(I.getAllocatedType());
1648 if (ClPoisonStackWithCall) {
1649 IRB.CreateCall2(MS.MsanPoisonStackFn,
1650 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
1651 ConstantInt::get(MS.IntptrTy, Size));
1652 } else {
1653 Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
1654 IRB.CreateMemSet(ShadowBase, IRB.getInt8(ClPoisonStackPattern),
1655 Size, I.getAlignment());
1656 }
1657
Evgeniy Stepanovabeae5c2012-12-19 13:55:51 +00001658 if (MS.TrackOrigins) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001659 setOrigin(&I, getCleanOrigin());
1660 SmallString<2048> StackDescriptionStorage;
1661 raw_svector_ostream StackDescription(StackDescriptionStorage);
1662 // We create a string with a description of the stack allocation and
1663 // pass it into __msan_set_alloca_origin.
1664 // It will be printed by the run-time if stack-originated UMR is found.
1665 // The first 4 bytes of the string are set to '----' and will be replaced
1666 // by __msan_va_arg_overflow_size_tls at the first call.
1667 StackDescription << "----" << I.getName() << "@" << F.getName();
1668 Value *Descr =
1669 createPrivateNonConstGlobalForString(*F.getParent(),
1670 StackDescription.str());
1671 IRB.CreateCall3(MS.MsanSetAllocaOriginFn,
1672 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
1673 ConstantInt::get(MS.IntptrTy, Size),
1674 IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()));
1675 }
1676 }
1677
1678 void visitSelectInst(SelectInst& I) {
1679 IRBuilder<> IRB(&I);
1680 setShadow(&I, IRB.CreateSelect(I.getCondition(),
1681 getShadow(I.getTrueValue()), getShadow(I.getFalseValue()),
1682 "_msprop"));
Evgeniy Stepanovec837122012-12-25 14:56:21 +00001683 if (MS.TrackOrigins) {
1684 // Origins are always i32, so any vector conditions must be flattened.
1685 // FIXME: consider tracking vector origins for app vectors?
1686 Value *Cond = I.getCondition();
1687 if (Cond->getType()->isVectorTy()) {
1688 Value *ConvertedShadow = convertToShadowTyNoVec(Cond, IRB);
1689 Cond = IRB.CreateICmpNE(ConvertedShadow,
1690 getCleanShadow(ConvertedShadow), "_mso_select");
1691 }
1692 setOrigin(&I, IRB.CreateSelect(Cond,
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001693 getOrigin(I.getTrueValue()), getOrigin(I.getFalseValue())));
Evgeniy Stepanovec837122012-12-25 14:56:21 +00001694 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001695 }
1696
1697 void visitLandingPadInst(LandingPadInst &I) {
1698 // Do nothing.
1699 // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
1700 setShadow(&I, getCleanShadow(&I));
1701 setOrigin(&I, getCleanOrigin());
1702 }
1703
1704 void visitGetElementPtrInst(GetElementPtrInst &I) {
1705 handleShadowOr(I);
1706 }
1707
1708 void visitExtractValueInst(ExtractValueInst &I) {
1709 IRBuilder<> IRB(&I);
1710 Value *Agg = I.getAggregateOperand();
1711 DEBUG(dbgs() << "ExtractValue: " << I << "\n");
1712 Value *AggShadow = getShadow(Agg);
1713 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
1714 Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
1715 DEBUG(dbgs() << " ResShadow: " << *ResShadow << "\n");
1716 setShadow(&I, ResShadow);
1717 setOrigin(&I, getCleanOrigin());
1718 }
1719
1720 void visitInsertValueInst(InsertValueInst &I) {
1721 IRBuilder<> IRB(&I);
1722 DEBUG(dbgs() << "InsertValue: " << I << "\n");
1723 Value *AggShadow = getShadow(I.getAggregateOperand());
1724 Value *InsShadow = getShadow(I.getInsertedValueOperand());
1725 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
1726 DEBUG(dbgs() << " InsShadow: " << *InsShadow << "\n");
1727 Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
1728 DEBUG(dbgs() << " Res: " << *Res << "\n");
1729 setShadow(&I, Res);
1730 setOrigin(&I, getCleanOrigin());
1731 }
1732
1733 void dumpInst(Instruction &I) {
1734 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
1735 errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
1736 } else {
1737 errs() << "ZZZ " << I.getOpcodeName() << "\n";
1738 }
1739 errs() << "QQQ " << I << "\n";
1740 }
1741
1742 void visitResumeInst(ResumeInst &I) {
1743 DEBUG(dbgs() << "Resume: " << I << "\n");
1744 // Nothing to do here.
1745 }
1746
1747 void visitInstruction(Instruction &I) {
1748 // Everything else: stop propagating and check for poisoned shadow.
1749 if (ClDumpStrictInstructions)
1750 dumpInst(I);
1751 DEBUG(dbgs() << "DEFAULT: " << I << "\n");
1752 for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
1753 insertCheck(I.getOperand(i), &I);
1754 setShadow(&I, getCleanShadow(&I));
1755 setOrigin(&I, getCleanOrigin());
1756 }
1757};
1758
1759/// \brief AMD64-specific implementation of VarArgHelper.
1760struct VarArgAMD64Helper : public VarArgHelper {
1761 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
1762 // See a comment in visitCallSite for more details.
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +00001763 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001764 static const unsigned AMD64FpEndOffset = 176;
1765
1766 Function &F;
1767 MemorySanitizer &MS;
1768 MemorySanitizerVisitor &MSV;
1769 Value *VAArgTLSCopy;
1770 Value *VAArgOverflowSize;
1771
1772 SmallVector<CallInst*, 16> VAStartInstrumentationList;
1773
1774 VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
1775 MemorySanitizerVisitor &MSV)
1776 : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(0), VAArgOverflowSize(0) { }
1777
1778 enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
1779
1780 ArgKind classifyArgument(Value* arg) {
1781 // A very rough approximation of X86_64 argument classification rules.
1782 Type *T = arg->getType();
1783 if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
1784 return AK_FloatingPoint;
1785 if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
1786 return AK_GeneralPurpose;
1787 if (T->isPointerTy())
1788 return AK_GeneralPurpose;
1789 return AK_Memory;
1790 }
1791
1792 // For VarArg functions, store the argument shadow in an ABI-specific format
1793 // that corresponds to va_list layout.
1794 // We do this because Clang lowers va_arg in the frontend, and this pass
1795 // only sees the low level code that deals with va_list internals.
1796 // A much easier alternative (provided that Clang emits va_arg instructions)
1797 // would have been to associate each live instance of va_list with a copy of
1798 // MSanParamTLS, and extract shadow on va_arg() call in the argument list
1799 // order.
1800 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) {
1801 unsigned GpOffset = 0;
1802 unsigned FpOffset = AMD64GpEndOffset;
1803 unsigned OverflowOffset = AMD64FpEndOffset;
1804 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
1805 ArgIt != End; ++ArgIt) {
1806 Value *A = *ArgIt;
1807 ArgKind AK = classifyArgument(A);
1808 if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
1809 AK = AK_Memory;
1810 if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
1811 AK = AK_Memory;
1812 Value *Base;
1813 switch (AK) {
1814 case AK_GeneralPurpose:
1815 Base = getShadowPtrForVAArgument(A, IRB, GpOffset);
1816 GpOffset += 8;
1817 break;
1818 case AK_FloatingPoint:
1819 Base = getShadowPtrForVAArgument(A, IRB, FpOffset);
1820 FpOffset += 16;
1821 break;
1822 case AK_Memory:
1823 uint64_t ArgSize = MS.TD->getTypeAllocSize(A->getType());
1824 Base = getShadowPtrForVAArgument(A, IRB, OverflowOffset);
1825 OverflowOffset += DataLayout::RoundUpAlignment(ArgSize, 8);
1826 }
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00001827 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001828 }
1829 Constant *OverflowSize =
1830 ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
1831 IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
1832 }
1833
1834 /// \brief Compute the shadow address for a given va_arg.
1835 Value *getShadowPtrForVAArgument(Value *A, IRBuilder<> &IRB,
1836 int ArgOffset) {
1837 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
1838 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
1839 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(A), 0),
1840 "_msarg");
1841 }
1842
1843 void visitVAStartInst(VAStartInst &I) {
1844 IRBuilder<> IRB(&I);
1845 VAStartInstrumentationList.push_back(&I);
1846 Value *VAListTag = I.getArgOperand(0);
1847 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
1848
1849 // Unpoison the whole __va_list_tag.
1850 // FIXME: magic ABI constants.
1851 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
Peter Collingbournef7d65c42013-01-10 22:36:33 +00001852 /* size */24, /* alignment */8, false);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001853 }
1854
1855 void visitVACopyInst(VACopyInst &I) {
1856 IRBuilder<> IRB(&I);
1857 Value *VAListTag = I.getArgOperand(0);
1858 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
1859
1860 // Unpoison the whole __va_list_tag.
1861 // FIXME: magic ABI constants.
1862 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
Peter Collingbournef7d65c42013-01-10 22:36:33 +00001863 /* size */24, /* alignment */8, false);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001864 }
1865
1866 void finalizeInstrumentation() {
1867 assert(!VAArgOverflowSize && !VAArgTLSCopy &&
1868 "finalizeInstrumentation called twice");
1869 if (!VAStartInstrumentationList.empty()) {
1870 // If there is a va_start in this function, make a backup copy of
1871 // va_arg_tls somewhere in the function entry block.
1872 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
1873 VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
1874 Value *CopySize =
1875 IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
1876 VAArgOverflowSize);
1877 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
1878 IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
1879 }
1880
1881 // Instrument va_start.
1882 // Copy va_list shadow from the backup copy of the TLS contents.
1883 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
1884 CallInst *OrigInst = VAStartInstrumentationList[i];
1885 IRBuilder<> IRB(OrigInst->getNextNode());
1886 Value *VAListTag = OrigInst->getArgOperand(0);
1887
1888 Value *RegSaveAreaPtrPtr =
1889 IRB.CreateIntToPtr(
1890 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
1891 ConstantInt::get(MS.IntptrTy, 16)),
1892 Type::getInt64PtrTy(*MS.C));
1893 Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
1894 Value *RegSaveAreaShadowPtr =
1895 MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
1896 IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy,
1897 AMD64FpEndOffset, 16);
1898
1899 Value *OverflowArgAreaPtrPtr =
1900 IRB.CreateIntToPtr(
1901 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
1902 ConstantInt::get(MS.IntptrTy, 8)),
1903 Type::getInt64PtrTy(*MS.C));
1904 Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
1905 Value *OverflowArgAreaShadowPtr =
1906 MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
1907 Value *SrcPtr =
1908 getShadowPtrForVAArgument(VAArgTLSCopy, IRB, AMD64FpEndOffset);
1909 IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
1910 }
1911 }
1912};
1913
1914VarArgHelper* CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
1915 MemorySanitizerVisitor &Visitor) {
1916 return new VarArgAMD64Helper(Func, Msan, Visitor);
1917}
1918
1919} // namespace
1920
1921bool MemorySanitizer::runOnFunction(Function &F) {
1922 MemorySanitizerVisitor Visitor(F, *this);
1923
1924 // Clear out readonly/readnone attributes.
1925 AttrBuilder B;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001926 B.addAttribute(Attribute::ReadOnly)
1927 .addAttribute(Attribute::ReadNone);
Bill Wendling430fa9b2013-01-23 00:45:55 +00001928 F.removeAttributes(AttributeSet::FunctionIndex,
1929 AttributeSet::get(F.getContext(),
1930 AttributeSet::FunctionIndex, B));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001931
1932 return Visitor.runOnFunction();
1933}