blob: ae1c228d71fff9299d69716d81c2f8079d6e46ab [file] [log] [blame]
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001//===-- DataFlowSanitizer.cpp - dynamic data flow analysis ----------------===//
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 DataFlowSanitizer, a generalised dynamic data flow
11/// analysis.
12///
13/// Unlike other Sanitizer tools, this tool is not designed to detect a specific
14/// class of bugs on its own. Instead, it provides a generic dynamic data flow
15/// analysis framework to be used by clients to help detect application-specific
16/// issues within their own code.
17///
18/// The analysis is based on automatic propagation of data flow labels (also
19/// known as taint labels) through a program as it performs computation. Each
20/// byte of application memory is backed by two bytes of shadow memory which
21/// hold the label. On Linux/x86_64, memory is laid out as follows:
22///
23/// +--------------------+ 0x800000000000 (top of memory)
24/// | application memory |
25/// +--------------------+ 0x700000008000 (kAppAddr)
26/// | |
27/// | unused |
28/// | |
29/// +--------------------+ 0x200200000000 (kUnusedAddr)
30/// | union table |
31/// +--------------------+ 0x200000000000 (kUnionTableAddr)
32/// | shadow memory |
33/// +--------------------+ 0x000000010000 (kShadowAddr)
34/// | reserved by kernel |
35/// +--------------------+ 0x000000000000
36///
37/// To derive a shadow memory address from an application memory address,
38/// bits 44-46 are cleared to bring the address into the range
39/// [0x000000008000,0x100000000000). Then the address is shifted left by 1 to
40/// account for the double byte representation of shadow labels and move the
41/// address into the shadow memory range. See the function
42/// DataFlowSanitizer::getShadowAddress below.
43///
44/// For more information, please refer to the design document:
45/// http://clang.llvm.org/docs/DataFlowSanitizerDesign.html
46
47#include "llvm/Transforms/Instrumentation.h"
48#include "llvm/ADT/DenseMap.h"
49#include "llvm/ADT/DenseSet.h"
50#include "llvm/ADT/DepthFirstIterator.h"
Peter Collingbourne28a10af2013-08-27 22:09:06 +000051#include "llvm/ADT/StringExtras.h"
Peter Collingbourne0826e602014-12-05 21:22:32 +000052#include "llvm/ADT/Triple.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000053#include "llvm/Analysis/ValueTracking.h"
Peter Collingbourne705a1ae2014-07-15 04:41:17 +000054#include "llvm/IR/Dominators.h"
David Blaikiec6c6c7b2014-10-07 22:59:46 +000055#include "llvm/IR/DebugInfo.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000056#include "llvm/IR/IRBuilder.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000057#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000058#include "llvm/IR/InstVisitor.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000059#include "llvm/IR/LLVMContext.h"
60#include "llvm/IR/MDBuilder.h"
61#include "llvm/IR/Type.h"
62#include "llvm/IR/Value.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000063#include "llvm/Pass.h"
64#include "llvm/Support/CommandLine.h"
Alexey Samsonovb7dd3292014-07-09 19:40:08 +000065#include "llvm/Support/SpecialCaseList.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000066#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Peter Collingbourneae66d572013-08-09 21:42:53 +000067#include "llvm/Transforms/Utils/Local.h"
Peter Collingbourne9947c492014-07-15 22:13:19 +000068#include <algorithm>
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000069#include <iterator>
Peter Collingbourne9947c492014-07-15 22:13:19 +000070#include <set>
71#include <utility>
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000072
73using namespace llvm;
74
75// The -dfsan-preserve-alignment flag controls whether this pass assumes that
76// alignment requirements provided by the input IR are correct. For example,
77// if the input IR contains a load with alignment 8, this flag will cause
78// the shadow load to have alignment 16. This flag is disabled by default as
79// we have unfortunately encountered too much code (including Clang itself;
80// see PR14291) which performs misaligned access.
81static cl::opt<bool> ClPreserveAlignment(
82 "dfsan-preserve-alignment",
83 cl::desc("respect alignment requirements provided by input IR"), cl::Hidden,
84 cl::init(false));
85
Alexey Samsonovb9b80272015-02-04 17:39:48 +000086// The ABI list files control how shadow parameters are passed. The pass treats
Peter Collingbourne68162e72013-08-14 18:54:12 +000087// every function labelled "uninstrumented" in the ABI list file as conforming
88// to the "native" (i.e. unsanitized) ABI. Unless the ABI list contains
89// additional annotations for those functions, a call to one of those functions
90// will produce a warning message, as the labelling behaviour of the function is
91// unknown. The other supported annotations are "functional" and "discard",
92// which are described below under DataFlowSanitizer::WrapperKind.
Alexey Samsonovb9b80272015-02-04 17:39:48 +000093static cl::list<std::string> ClABIListFiles(
Peter Collingbourne68162e72013-08-14 18:54:12 +000094 "dfsan-abilist",
95 cl::desc("File listing native ABI functions and how the pass treats them"),
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000096 cl::Hidden);
97
Peter Collingbourne68162e72013-08-14 18:54:12 +000098// Controls whether the pass uses IA_Args or IA_TLS as the ABI for instrumented
99// functions (see DataFlowSanitizer::InstrumentedABI below).
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000100static cl::opt<bool> ClArgsABI(
101 "dfsan-args-abi",
102 cl::desc("Use the argument ABI rather than the TLS ABI"),
103 cl::Hidden);
104
Peter Collingbourne0be79e12013-11-21 23:20:54 +0000105// Controls whether the pass includes or ignores the labels of pointers in load
106// instructions.
107static cl::opt<bool> ClCombinePointerLabelsOnLoad(
108 "dfsan-combine-pointer-labels-on-load",
109 cl::desc("Combine the label of the pointer with the label of the data when "
110 "loading from memory."),
111 cl::Hidden, cl::init(true));
112
113// Controls whether the pass includes or ignores the labels of pointers in
114// stores instructions.
115static cl::opt<bool> ClCombinePointerLabelsOnStore(
116 "dfsan-combine-pointer-labels-on-store",
117 cl::desc("Combine the label of the pointer with the label of the data when "
118 "storing in memory."),
119 cl::Hidden, cl::init(false));
120
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000121static cl::opt<bool> ClDebugNonzeroLabels(
122 "dfsan-debug-nonzero-labels",
123 cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, "
124 "load or return with a nonzero label"),
125 cl::Hidden);
126
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000127namespace {
128
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000129StringRef GetGlobalTypeString(const GlobalValue &G) {
130 // Types of GlobalVariables are always pointer types.
131 Type *GType = G.getType()->getElementType();
132 // For now we support blacklisting struct types only.
133 if (StructType *SGType = dyn_cast<StructType>(GType)) {
134 if (!SGType->isLiteral())
135 return SGType->getName();
136 }
137 return "<unknown type>";
138}
139
140class DFSanABIList {
141 std::unique_ptr<SpecialCaseList> SCL;
142
143 public:
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000144 DFSanABIList() {}
145
146 void set(std::unique_ptr<SpecialCaseList> List) { SCL = std::move(List); }
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000147
148 /// Returns whether either this function or its source file are listed in the
149 /// given category.
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000150 bool isIn(const Function &F, StringRef Category) const {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000151 return isIn(*F.getParent(), Category) ||
152 SCL->inSection("fun", F.getName(), Category);
153 }
154
155 /// Returns whether this global alias is listed in the given category.
156 ///
157 /// If GA aliases a function, the alias's name is matched as a function name
158 /// would be. Similarly, aliases of globals are matched like globals.
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000159 bool isIn(const GlobalAlias &GA, StringRef Category) const {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000160 if (isIn(*GA.getParent(), Category))
161 return true;
162
163 if (isa<FunctionType>(GA.getType()->getElementType()))
164 return SCL->inSection("fun", GA.getName(), Category);
165
166 return SCL->inSection("global", GA.getName(), Category) ||
167 SCL->inSection("type", GetGlobalTypeString(GA), Category);
168 }
169
170 /// Returns whether this module is listed in the given category.
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000171 bool isIn(const Module &M, StringRef Category) const {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000172 return SCL->inSection("src", M.getModuleIdentifier(), Category);
173 }
174};
175
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000176class DataFlowSanitizer : public ModulePass {
177 friend struct DFSanFunction;
178 friend class DFSanVisitor;
179
180 enum {
181 ShadowWidth = 16
182 };
183
Peter Collingbourne68162e72013-08-14 18:54:12 +0000184 /// Which ABI should be used for instrumented functions?
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000185 enum InstrumentedABI {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000186 /// Argument and return value labels are passed through additional
187 /// arguments and by modifying the return type.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000188 IA_Args,
Peter Collingbourne68162e72013-08-14 18:54:12 +0000189
190 /// Argument and return value labels are passed through TLS variables
191 /// __dfsan_arg_tls and __dfsan_retval_tls.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000192 IA_TLS
193 };
194
Peter Collingbourne68162e72013-08-14 18:54:12 +0000195 /// How should calls to uninstrumented functions be handled?
196 enum WrapperKind {
197 /// This function is present in an uninstrumented form but we don't know
198 /// how it should be handled. Print a warning and call the function anyway.
199 /// Don't label the return value.
200 WK_Warning,
201
202 /// This function does not write to (user-accessible) memory, and its return
203 /// value is unlabelled.
204 WK_Discard,
205
206 /// This function does not write to (user-accessible) memory, and the label
207 /// of its return value is the union of the label of its arguments.
208 WK_Functional,
209
210 /// Instead of calling the function, a custom wrapper __dfsw_F is called,
211 /// where F is the name of the function. This function may wrap the
212 /// original function or provide its own implementation. This is similar to
213 /// the IA_Args ABI, except that IA_Args uses a struct return type to
214 /// pass the return value shadow in a register, while WK_Custom uses an
215 /// extra pointer argument to return the shadow. This allows the wrapped
216 /// form of the function type to be expressed in C.
217 WK_Custom
218 };
219
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000220 const DataLayout *DL;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000221 Module *Mod;
222 LLVMContext *Ctx;
223 IntegerType *ShadowTy;
224 PointerType *ShadowPtrTy;
225 IntegerType *IntptrTy;
226 ConstantInt *ZeroShadow;
227 ConstantInt *ShadowPtrMask;
228 ConstantInt *ShadowPtrMul;
229 Constant *ArgTLS;
230 Constant *RetvalTLS;
231 void *(*GetArgTLSPtr)();
232 void *(*GetRetvalTLSPtr)();
233 Constant *GetArgTLS;
234 Constant *GetRetvalTLS;
235 FunctionType *DFSanUnionFnTy;
236 FunctionType *DFSanUnionLoadFnTy;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000237 FunctionType *DFSanUnimplementedFnTy;
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000238 FunctionType *DFSanSetLabelFnTy;
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000239 FunctionType *DFSanNonzeroLabelFnTy;
Peter Collingbournea1099842014-11-05 17:21:00 +0000240 FunctionType *DFSanVarargWrapperFnTy;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000241 Constant *DFSanUnionFn;
Peter Collingbournedf240b22014-08-06 00:33:40 +0000242 Constant *DFSanCheckedUnionFn;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000243 Constant *DFSanUnionLoadFn;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000244 Constant *DFSanUnimplementedFn;
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000245 Constant *DFSanSetLabelFn;
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000246 Constant *DFSanNonzeroLabelFn;
Peter Collingbournea1099842014-11-05 17:21:00 +0000247 Constant *DFSanVarargWrapperFn;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000248 MDNode *ColdCallWeights;
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000249 DFSanABIList ABIList;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000250 DenseMap<Value *, Function *> UnwrappedFnMap;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000251 AttributeSet ReadOnlyNoneAttrs;
David Blaikiec6c6c7b2014-10-07 22:59:46 +0000252 DenseMap<const Function *, DISubprogram> FunctionDIs;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000253
254 Value *getShadowAddress(Value *Addr, Instruction *Pos);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000255 bool isInstrumented(const Function *F);
256 bool isInstrumented(const GlobalAlias *GA);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000257 FunctionType *getArgsFunctionType(FunctionType *T);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000258 FunctionType *getTrampolineFunctionType(FunctionType *T);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000259 FunctionType *getCustomFunctionType(FunctionType *T);
260 InstrumentedABI getInstrumentedABI();
261 WrapperKind getWrapperKind(Function *F);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000262 void addGlobalNamePrefix(GlobalValue *GV);
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000263 Function *buildWrapperFunction(Function *F, StringRef NewFName,
264 GlobalValue::LinkageTypes NewFLink,
265 FunctionType *NewFT);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000266 Constant *getOrBuildTrampolineFunction(FunctionType *FT, StringRef FName);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000267
Dmitry Vyukov96a70842013-08-13 16:52:41 +0000268 public:
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000269 DataFlowSanitizer(
270 const std::vector<std::string> &ABIListFiles = std::vector<std::string>(),
271 void *(*getArgTLS)() = nullptr, void *(*getRetValTLS)() = nullptr);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000272 static char ID;
Craig Topper3e4c6972014-03-05 09:10:37 +0000273 bool doInitialization(Module &M) override;
274 bool runOnModule(Module &M) override;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000275};
276
277struct DFSanFunction {
278 DataFlowSanitizer &DFS;
279 Function *F;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000280 DominatorTree DT;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000281 DataFlowSanitizer::InstrumentedABI IA;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000282 bool IsNativeABI;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000283 Value *ArgTLSPtr;
284 Value *RetvalTLSPtr;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000285 AllocaInst *LabelReturnAlloca;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000286 DenseMap<Value *, Value *> ValShadowMap;
287 DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
288 std::vector<std::pair<PHINode *, PHINode *> > PHIFixups;
289 DenseSet<Instruction *> SkipInsts;
Peter Collingbournefab565a2014-08-22 01:18:18 +0000290 std::vector<Value *> NonZeroChecks;
Peter Collingbournedf240b22014-08-06 00:33:40 +0000291 bool AvoidNewBlocks;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000292
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000293 struct CachedCombinedShadow {
294 BasicBlock *Block;
295 Value *Shadow;
296 };
297 DenseMap<std::pair<Value *, Value *>, CachedCombinedShadow>
298 CachedCombinedShadows;
Peter Collingbourne9947c492014-07-15 22:13:19 +0000299 DenseMap<Value *, std::set<Value *>> ShadowElements;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000300
Peter Collingbourne68162e72013-08-14 18:54:12 +0000301 DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
302 : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()),
Craig Topperf40110f2014-04-25 05:29:35 +0000303 IsNativeABI(IsNativeABI), ArgTLSPtr(nullptr), RetvalTLSPtr(nullptr),
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000304 LabelReturnAlloca(nullptr) {
305 DT.recalculate(*F);
Peter Collingbournedf240b22014-08-06 00:33:40 +0000306 // FIXME: Need to track down the register allocator issue which causes poor
307 // performance in pathological cases with large numbers of basic blocks.
308 AvoidNewBlocks = F->size() > 1000;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000309 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000310 Value *getArgTLSPtr();
311 Value *getArgTLS(unsigned Index, Instruction *Pos);
312 Value *getRetvalTLS();
313 Value *getShadow(Value *V);
314 void setShadow(Instruction *I, Value *Shadow);
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000315 Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000316 Value *combineOperandShadows(Instruction *Inst);
317 Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
318 Instruction *Pos);
319 void storeShadow(Value *Addr, uint64_t Size, uint64_t Align, Value *Shadow,
320 Instruction *Pos);
321};
322
323class DFSanVisitor : public InstVisitor<DFSanVisitor> {
Dmitry Vyukov96a70842013-08-13 16:52:41 +0000324 public:
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000325 DFSanFunction &DFSF;
326 DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
327
328 void visitOperandShadowInst(Instruction &I);
329
330 void visitBinaryOperator(BinaryOperator &BO);
331 void visitCastInst(CastInst &CI);
332 void visitCmpInst(CmpInst &CI);
333 void visitGetElementPtrInst(GetElementPtrInst &GEPI);
334 void visitLoadInst(LoadInst &LI);
335 void visitStoreInst(StoreInst &SI);
336 void visitReturnInst(ReturnInst &RI);
337 void visitCallSite(CallSite CS);
338 void visitPHINode(PHINode &PN);
339 void visitExtractElementInst(ExtractElementInst &I);
340 void visitInsertElementInst(InsertElementInst &I);
341 void visitShuffleVectorInst(ShuffleVectorInst &I);
342 void visitExtractValueInst(ExtractValueInst &I);
343 void visitInsertValueInst(InsertValueInst &I);
344 void visitAllocaInst(AllocaInst &I);
345 void visitSelectInst(SelectInst &I);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000346 void visitMemSetInst(MemSetInst &I);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000347 void visitMemTransferInst(MemTransferInst &I);
348};
349
350}
351
352char DataFlowSanitizer::ID;
353INITIALIZE_PASS(DataFlowSanitizer, "dfsan",
354 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
355
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000356ModulePass *
357llvm::createDataFlowSanitizerPass(const std::vector<std::string> &ABIListFiles,
358 void *(*getArgTLS)(),
359 void *(*getRetValTLS)()) {
360 return new DataFlowSanitizer(ABIListFiles, getArgTLS, getRetValTLS);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000361}
362
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000363DataFlowSanitizer::DataFlowSanitizer(
364 const std::vector<std::string> &ABIListFiles, void *(*getArgTLS)(),
365 void *(*getRetValTLS)())
366 : ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS) {
367 std::vector<std::string> AllABIListFiles(std::move(ABIListFiles));
368 AllABIListFiles.insert(AllABIListFiles.end(), ClABIListFiles.begin(),
369 ClABIListFiles.end());
370 ABIList.set(SpecialCaseList::createOrDie(AllABIListFiles));
Peter Collingbourne68162e72013-08-14 18:54:12 +0000371}
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000372
Peter Collingbourne68162e72013-08-14 18:54:12 +0000373FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000374 llvm::SmallVector<Type *, 4> ArgTypes;
375 std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes));
376 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
377 ArgTypes.push_back(ShadowTy);
378 if (T->isVarArg())
379 ArgTypes.push_back(ShadowPtrTy);
380 Type *RetType = T->getReturnType();
381 if (!RetType->isVoidTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000382 RetType = StructType::get(RetType, ShadowTy, (Type *)nullptr);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000383 return FunctionType::get(RetType, ArgTypes, T->isVarArg());
384}
385
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000386FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) {
387 assert(!T->isVarArg());
388 llvm::SmallVector<Type *, 4> ArgTypes;
389 ArgTypes.push_back(T->getPointerTo());
390 std::copy(T->param_begin(), T->param_end(), std::back_inserter(ArgTypes));
391 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
392 ArgTypes.push_back(ShadowTy);
393 Type *RetType = T->getReturnType();
394 if (!RetType->isVoidTy())
395 ArgTypes.push_back(ShadowPtrTy);
396 return FunctionType::get(T->getReturnType(), ArgTypes, false);
397}
398
Peter Collingbourne68162e72013-08-14 18:54:12 +0000399FunctionType *DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000400 llvm::SmallVector<Type *, 4> ArgTypes;
Alexey Samsonov9b7e2b52013-08-28 11:25:12 +0000401 for (FunctionType::param_iterator i = T->param_begin(), e = T->param_end();
402 i != e; ++i) {
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000403 FunctionType *FT;
Alexey Samsonov9b7e2b52013-08-28 11:25:12 +0000404 if (isa<PointerType>(*i) && (FT = dyn_cast<FunctionType>(cast<PointerType>(
405 *i)->getElementType()))) {
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000406 ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo());
407 ArgTypes.push_back(Type::getInt8PtrTy(*Ctx));
408 } else {
409 ArgTypes.push_back(*i);
410 }
411 }
Peter Collingbourne68162e72013-08-14 18:54:12 +0000412 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
413 ArgTypes.push_back(ShadowTy);
Peter Collingbournedd3486e2014-10-30 13:22:57 +0000414 if (T->isVarArg())
415 ArgTypes.push_back(ShadowPtrTy);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000416 Type *RetType = T->getReturnType();
417 if (!RetType->isVoidTy())
418 ArgTypes.push_back(ShadowPtrTy);
Peter Collingbournedd3486e2014-10-30 13:22:57 +0000419 return FunctionType::get(T->getReturnType(), ArgTypes, T->isVarArg());
Peter Collingbourne68162e72013-08-14 18:54:12 +0000420}
421
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000422bool DataFlowSanitizer::doInitialization(Module &M) {
Peter Collingbourne0826e602014-12-05 21:22:32 +0000423 llvm::Triple TargetTriple(M.getTargetTriple());
424 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
425 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
426 TargetTriple.getArch() == llvm::Triple::mips64el;
427
Rafael Espindola93512512014-02-25 17:30:31 +0000428 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
429 if (!DLP)
Evgeniy Stepanov119cb2e2014-04-23 12:51:32 +0000430 report_fatal_error("data layout missing");
Rafael Espindola93512512014-02-25 17:30:31 +0000431 DL = &DLP->getDataLayout();
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000432
433 Mod = &M;
434 Ctx = &M.getContext();
435 ShadowTy = IntegerType::get(*Ctx, ShadowWidth);
436 ShadowPtrTy = PointerType::getUnqual(ShadowTy);
437 IntptrTy = DL->getIntPtrType(*Ctx);
438 ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000439 ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8);
Peter Collingbourne0826e602014-12-05 21:22:32 +0000440 if (IsX86_64)
441 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
442 else if (IsMIPS64)
443 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0xF000000000LL);
444 else
445 report_fatal_error("unsupported triple");
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000446
447 Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy };
448 DFSanUnionFnTy =
449 FunctionType::get(ShadowTy, DFSanUnionArgs, /*isVarArg=*/ false);
450 Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy };
451 DFSanUnionLoadFnTy =
452 FunctionType::get(ShadowTy, DFSanUnionLoadArgs, /*isVarArg=*/ false);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000453 DFSanUnimplementedFnTy = FunctionType::get(
454 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000455 Type *DFSanSetLabelArgs[3] = { ShadowTy, Type::getInt8PtrTy(*Ctx), IntptrTy };
456 DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
457 DFSanSetLabelArgs, /*isVarArg=*/false);
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000458 DFSanNonzeroLabelFnTy = FunctionType::get(
Craig Toppere1d12942014-08-27 05:25:25 +0000459 Type::getVoidTy(*Ctx), None, /*isVarArg=*/false);
Peter Collingbournea1099842014-11-05 17:21:00 +0000460 DFSanVarargWrapperFnTy = FunctionType::get(
461 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000462
463 if (GetArgTLSPtr) {
464 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
Craig Topperf40110f2014-04-25 05:29:35 +0000465 ArgTLS = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000466 GetArgTLS = ConstantExpr::getIntToPtr(
467 ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)),
468 PointerType::getUnqual(
Craig Topperf40110f2014-04-25 05:29:35 +0000469 FunctionType::get(PointerType::getUnqual(ArgTLSTy),
470 (Type *)nullptr)));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000471 }
472 if (GetRetvalTLSPtr) {
Craig Topperf40110f2014-04-25 05:29:35 +0000473 RetvalTLS = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000474 GetRetvalTLS = ConstantExpr::getIntToPtr(
475 ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)),
476 PointerType::getUnqual(
Craig Topperf40110f2014-04-25 05:29:35 +0000477 FunctionType::get(PointerType::getUnqual(ShadowTy),
478 (Type *)nullptr)));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000479 }
480
481 ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
482 return true;
483}
484
Peter Collingbourne59b12622013-08-22 20:08:08 +0000485bool DataFlowSanitizer::isInstrumented(const Function *F) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000486 return !ABIList.isIn(*F, "uninstrumented");
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000487}
488
Peter Collingbourne59b12622013-08-22 20:08:08 +0000489bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000490 return !ABIList.isIn(*GA, "uninstrumented");
Peter Collingbourne59b12622013-08-22 20:08:08 +0000491}
492
Peter Collingbourne68162e72013-08-14 18:54:12 +0000493DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000494 return ClArgsABI ? IA_Args : IA_TLS;
495}
496
Peter Collingbourne68162e72013-08-14 18:54:12 +0000497DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000498 if (ABIList.isIn(*F, "functional"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000499 return WK_Functional;
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000500 if (ABIList.isIn(*F, "discard"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000501 return WK_Discard;
Lorenzo Martignoni40d3dee2014-09-30 12:33:16 +0000502 if (ABIList.isIn(*F, "custom"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000503 return WK_Custom;
504
505 return WK_Warning;
506}
507
Peter Collingbourne59b12622013-08-22 20:08:08 +0000508void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
509 std::string GVName = GV->getName(), Prefix = "dfs$";
510 GV->setName(Prefix + GVName);
511
512 // Try to change the name of the function in module inline asm. We only do
513 // this for specific asm directives, currently only ".symver", to try to avoid
514 // corrupting asm which happens to contain the symbol name as a substring.
515 // Note that the substitution for .symver assumes that the versioned symbol
516 // also has an instrumented name.
517 std::string Asm = GV->getParent()->getModuleInlineAsm();
518 std::string SearchStr = ".symver " + GVName + ",";
519 size_t Pos = Asm.find(SearchStr);
520 if (Pos != std::string::npos) {
521 Asm.replace(Pos, SearchStr.size(),
522 ".symver " + Prefix + GVName + "," + Prefix);
523 GV->getParent()->setModuleInlineAsm(Asm);
524 }
525}
526
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000527Function *
528DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
529 GlobalValue::LinkageTypes NewFLink,
530 FunctionType *NewFT) {
531 FunctionType *FT = F->getFunctionType();
532 Function *NewF = Function::Create(NewFT, NewFLink, NewFName,
533 F->getParent());
534 NewF->copyAttributesFrom(F);
535 NewF->removeAttributes(
536 AttributeSet::ReturnIndex,
537 AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
538 AttributeSet::ReturnIndex));
539
540 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
Peter Collingbournea1099842014-11-05 17:21:00 +0000541 if (F->isVarArg()) {
542 NewF->removeAttributes(
543 AttributeSet::FunctionIndex,
544 AttributeSet().addAttribute(*Ctx, AttributeSet::FunctionIndex,
545 "split-stack"));
546 CallInst::Create(DFSanVarargWrapperFn,
547 IRBuilder<>(BB).CreateGlobalStringPtr(F->getName()), "",
548 BB);
549 new UnreachableInst(*Ctx, BB);
550 } else {
551 std::vector<Value *> Args;
552 unsigned n = FT->getNumParams();
553 for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
554 Args.push_back(&*ai);
555 CallInst *CI = CallInst::Create(F, Args, "", BB);
556 if (FT->getReturnType()->isVoidTy())
557 ReturnInst::Create(*Ctx, BB);
558 else
559 ReturnInst::Create(*Ctx, CI, BB);
560 }
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000561
562 return NewF;
563}
564
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000565Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
566 StringRef FName) {
567 FunctionType *FTT = getTrampolineFunctionType(FT);
568 Constant *C = Mod->getOrInsertFunction(FName, FTT);
569 Function *F = dyn_cast<Function>(C);
570 if (F && F->isDeclaration()) {
571 F->setLinkage(GlobalValue::LinkOnceODRLinkage);
572 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
573 std::vector<Value *> Args;
574 Function::arg_iterator AI = F->arg_begin(); ++AI;
575 for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
576 Args.push_back(&*AI);
577 CallInst *CI =
578 CallInst::Create(&F->getArgumentList().front(), Args, "", BB);
579 ReturnInst *RI;
580 if (FT->getReturnType()->isVoidTy())
581 RI = ReturnInst::Create(*Ctx, BB);
582 else
583 RI = ReturnInst::Create(*Ctx, CI, BB);
584
585 DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
586 Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI;
587 for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N)
588 DFSF.ValShadowMap[ValAI] = ShadowAI;
589 DFSanVisitor(DFSF).visitCallInst(*CI);
590 if (!FT->getReturnType()->isVoidTy())
591 new StoreInst(DFSF.getShadow(RI->getReturnValue()),
592 &F->getArgumentList().back(), RI);
593 }
594
595 return C;
596}
597
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000598bool DataFlowSanitizer::runOnModule(Module &M) {
599 if (!DL)
600 return false;
601
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000602 if (ABIList.isIn(M, "skip"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000603 return false;
604
David Blaikiec6c6c7b2014-10-07 22:59:46 +0000605 FunctionDIs = makeSubprogramMap(M);
606
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000607 if (!GetArgTLSPtr) {
608 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
609 ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
610 if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS))
611 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
612 }
613 if (!GetRetvalTLSPtr) {
614 RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy);
615 if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS))
616 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
617 }
618
619 DFSanUnionFn = Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy);
620 if (Function *F = dyn_cast<Function>(DFSanUnionFn)) {
Peter Collingbournedf240b22014-08-06 00:33:40 +0000621 F->addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
622 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
623 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
624 F->addAttribute(1, Attribute::ZExt);
625 F->addAttribute(2, Attribute::ZExt);
626 }
627 DFSanCheckedUnionFn = Mod->getOrInsertFunction("dfsan_union", DFSanUnionFnTy);
628 if (Function *F = dyn_cast<Function>(DFSanCheckedUnionFn)) {
629 F->addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000630 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadNone);
631 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
632 F->addAttribute(1, Attribute::ZExt);
633 F->addAttribute(2, Attribute::ZExt);
634 }
635 DFSanUnionLoadFn =
636 Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy);
637 if (Function *F = dyn_cast<Function>(DFSanUnionLoadFn)) {
Peter Collingbournedf240b22014-08-06 00:33:40 +0000638 F->addAttribute(AttributeSet::FunctionIndex, Attribute::NoUnwind);
Peter Collingbourne0be79e12013-11-21 23:20:54 +0000639 F->addAttribute(AttributeSet::FunctionIndex, Attribute::ReadOnly);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000640 F->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
641 }
Peter Collingbourne68162e72013-08-14 18:54:12 +0000642 DFSanUnimplementedFn =
643 Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000644 DFSanSetLabelFn =
645 Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy);
646 if (Function *F = dyn_cast<Function>(DFSanSetLabelFn)) {
647 F->addAttribute(1, Attribute::ZExt);
648 }
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000649 DFSanNonzeroLabelFn =
650 Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
Peter Collingbournea1099842014-11-05 17:21:00 +0000651 DFSanVarargWrapperFn = Mod->getOrInsertFunction("__dfsan_vararg_wrapper",
652 DFSanVarargWrapperFnTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000653
654 std::vector<Function *> FnsToInstrument;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000655 llvm::SmallPtrSet<Function *, 2> FnsWithNativeABI;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000656 for (Module::iterator i = M.begin(), e = M.end(); i != e; ++i) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000657 if (!i->isIntrinsic() &&
658 i != DFSanUnionFn &&
Peter Collingbournedf240b22014-08-06 00:33:40 +0000659 i != DFSanCheckedUnionFn &&
Peter Collingbourne68162e72013-08-14 18:54:12 +0000660 i != DFSanUnionLoadFn &&
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000661 i != DFSanUnimplementedFn &&
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000662 i != DFSanSetLabelFn &&
Peter Collingbournea1099842014-11-05 17:21:00 +0000663 i != DFSanNonzeroLabelFn &&
664 i != DFSanVarargWrapperFn)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000665 FnsToInstrument.push_back(&*i);
666 }
667
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000668 // Give function aliases prefixes when necessary, and build wrappers where the
669 // instrumentedness is inconsistent.
Peter Collingbourne59b12622013-08-22 20:08:08 +0000670 for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
671 GlobalAlias *GA = &*i;
672 ++i;
673 // Don't stop on weak. We assume people aren't playing games with the
674 // instrumentedness of overridden weak aliases.
Peter Collingbourne2e28edf2014-07-10 01:30:39 +0000675 if (auto F = dyn_cast<Function>(GA->getBaseObject())) {
Peter Collingbourne59b12622013-08-22 20:08:08 +0000676 bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
677 if (GAInst && FInst) {
678 addGlobalNamePrefix(GA);
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000679 } else if (GAInst != FInst) {
680 // Non-instrumented alias of an instrumented function, or vice versa.
681 // Replace the alias with a native-ABI wrapper of the aliasee. The pass
682 // below will take care of instrumenting it.
683 Function *NewF =
684 buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
Peter Collingbourne2e28edf2014-07-10 01:30:39 +0000685 GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType()));
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000686 NewF->takeName(GA);
687 GA->eraseFromParent();
688 FnsToInstrument.push_back(NewF);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000689 }
690 }
691 }
692
Peter Collingbourne68162e72013-08-14 18:54:12 +0000693 AttrBuilder B;
694 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
695 ReadOnlyNoneAttrs = AttributeSet::get(*Ctx, AttributeSet::FunctionIndex, B);
696
697 // First, change the ABI of every function in the module. ABI-listed
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000698 // functions keep their original ABI and get a wrapper function.
699 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
700 e = FnsToInstrument.end();
701 i != e; ++i) {
702 Function &F = **i;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000703 FunctionType *FT = F.getFunctionType();
Peter Collingbourne68162e72013-08-14 18:54:12 +0000704
Peter Collingbourne59b12622013-08-22 20:08:08 +0000705 bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
706 FT->getReturnType()->isVoidTy());
Peter Collingbourne68162e72013-08-14 18:54:12 +0000707
708 if (isInstrumented(&F)) {
Peter Collingbourne59b12622013-08-22 20:08:08 +0000709 // Instrumented functions get a 'dfs$' prefix. This allows us to more
710 // easily identify cases of mismatching ABIs.
711 if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000712 FunctionType *NewFT = getArgsFunctionType(FT);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000713 Function *NewF = Function::Create(NewFT, F.getLinkage(), "", &M);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000714 NewF->copyAttributesFrom(&F);
715 NewF->removeAttributes(
716 AttributeSet::ReturnIndex,
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000717 AttributeFuncs::typeIncompatible(NewFT->getReturnType(),
Peter Collingbourne68162e72013-08-14 18:54:12 +0000718 AttributeSet::ReturnIndex));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000719 for (Function::arg_iterator FArg = F.arg_begin(),
720 NewFArg = NewF->arg_begin(),
721 FArgEnd = F.arg_end();
722 FArg != FArgEnd; ++FArg, ++NewFArg) {
723 FArg->replaceAllUsesWith(NewFArg);
724 }
725 NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
726
Chandler Carruthcdf47882014-03-09 03:16:01 +0000727 for (Function::user_iterator UI = F.user_begin(), UE = F.user_end();
728 UI != UE;) {
729 BlockAddress *BA = dyn_cast<BlockAddress>(*UI);
730 ++UI;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000731 if (BA) {
732 BA->replaceAllUsesWith(
733 BlockAddress::get(NewF, BA->getBasicBlock()));
734 delete BA;
735 }
736 }
737 F.replaceAllUsesWith(
738 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
739 NewF->takeName(&F);
740 F.eraseFromParent();
741 *i = NewF;
Peter Collingbourne59b12622013-08-22 20:08:08 +0000742 addGlobalNamePrefix(NewF);
743 } else {
744 addGlobalNamePrefix(&F);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000745 }
Peter Collingbourne59b12622013-08-22 20:08:08 +0000746 } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000747 // Build a wrapper function for F. The wrapper simply calls F, and is
748 // added to FnsToInstrument so that any instrumentation according to its
749 // WrapperKind is done in the second pass below.
750 FunctionType *NewFT = getInstrumentedABI() == IA_Args
751 ? getArgsFunctionType(FT)
752 : FT;
Alexey Samsonov6dae24d2013-08-23 07:42:51 +0000753 Function *NewF = buildWrapperFunction(
754 &F, std::string("dfsw$") + std::string(F.getName()),
755 GlobalValue::LinkOnceODRLinkage, NewFT);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000756 if (getInstrumentedABI() == IA_TLS)
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000757 NewF->removeAttributes(AttributeSet::FunctionIndex, ReadOnlyNoneAttrs);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000758
Peter Collingbourne68162e72013-08-14 18:54:12 +0000759 Value *WrappedFnCst =
760 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
761 F.replaceAllUsesWith(WrappedFnCst);
David Blaikiec6c6c7b2014-10-07 22:59:46 +0000762
763 // Patch the pointer to LLVM function in debug info descriptor.
764 auto DI = FunctionDIs.find(&F);
765 if (DI != FunctionDIs.end())
766 DI->second.replaceFunction(&F);
767
Peter Collingbourne68162e72013-08-14 18:54:12 +0000768 UnwrappedFnMap[WrappedFnCst] = &F;
769 *i = NewF;
770
771 if (!F.isDeclaration()) {
772 // This function is probably defining an interposition of an
773 // uninstrumented function and hence needs to keep the original ABI.
774 // But any functions it may call need to use the instrumented ABI, so
775 // we instrument it in a mode which preserves the original ABI.
776 FnsWithNativeABI.insert(&F);
777
778 // This code needs to rebuild the iterators, as they may be invalidated
779 // by the push_back, taking care that the new range does not include
780 // any functions added by this code.
781 size_t N = i - FnsToInstrument.begin(),
782 Count = e - FnsToInstrument.begin();
783 FnsToInstrument.push_back(&F);
784 i = FnsToInstrument.begin() + N;
785 e = FnsToInstrument.begin() + Count;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000786 }
Lorenzo Martignoni40d3dee2014-09-30 12:33:16 +0000787 // Hopefully, nobody will try to indirectly call a vararg
788 // function... yet.
789 } else if (FT->isVarArg()) {
790 UnwrappedFnMap[&F] = &F;
791 *i = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000792 }
793 }
794
795 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
796 e = FnsToInstrument.end();
797 i != e; ++i) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000798 if (!*i || (*i)->isDeclaration())
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000799 continue;
800
Peter Collingbourneae66d572013-08-09 21:42:53 +0000801 removeUnreachableBlocks(**i);
802
Peter Collingbourne68162e72013-08-14 18:54:12 +0000803 DFSanFunction DFSF(*this, *i, FnsWithNativeABI.count(*i));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000804
805 // DFSanVisitor may create new basic blocks, which confuses df_iterator.
806 // Build a copy of the list before iterating over it.
David Blaikieceec2bd2014-04-11 01:50:01 +0000807 llvm::SmallVector<BasicBlock *, 4> BBList(
808 depth_first(&(*i)->getEntryBlock()));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000809
810 for (llvm::SmallVector<BasicBlock *, 4>::iterator i = BBList.begin(),
811 e = BBList.end();
812 i != e; ++i) {
813 Instruction *Inst = &(*i)->front();
814 while (1) {
815 // DFSanVisitor may split the current basic block, changing the current
816 // instruction's next pointer and moving the next instruction to the
817 // tail block from which we should continue.
818 Instruction *Next = Inst->getNextNode();
Peter Collingbournefb3a2b42013-08-12 22:38:39 +0000819 // DFSanVisitor may delete Inst, so keep track of whether it was a
820 // terminator.
821 bool IsTerminator = isa<TerminatorInst>(Inst);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000822 if (!DFSF.SkipInsts.count(Inst))
823 DFSanVisitor(DFSF).visit(Inst);
Peter Collingbournefb3a2b42013-08-12 22:38:39 +0000824 if (IsTerminator)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000825 break;
826 Inst = Next;
827 }
828 }
829
Peter Collingbourne68162e72013-08-14 18:54:12 +0000830 // We will not necessarily be able to compute the shadow for every phi node
831 // until we have visited every block. Therefore, the code that handles phi
832 // nodes adds them to the PHIFixups list so that they can be properly
833 // handled here.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000834 for (std::vector<std::pair<PHINode *, PHINode *> >::iterator
835 i = DFSF.PHIFixups.begin(),
836 e = DFSF.PHIFixups.end();
837 i != e; ++i) {
838 for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
839 ++val) {
840 i->second->setIncomingValue(
841 val, DFSF.getShadow(i->first->getIncomingValue(val)));
842 }
843 }
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000844
845 // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
846 // places (i.e. instructions in basic blocks we haven't even begun visiting
847 // yet). To make our life easier, do this work in a pass after the main
848 // instrumentation.
849 if (ClDebugNonzeroLabels) {
Peter Collingbournefab565a2014-08-22 01:18:18 +0000850 for (Value *V : DFSF.NonZeroChecks) {
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000851 Instruction *Pos;
Peter Collingbournefab565a2014-08-22 01:18:18 +0000852 if (Instruction *I = dyn_cast<Instruction>(V))
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000853 Pos = I->getNextNode();
854 else
855 Pos = DFSF.F->getEntryBlock().begin();
856 while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
857 Pos = Pos->getNextNode();
858 IRBuilder<> IRB(Pos);
Peter Collingbournefab565a2014-08-22 01:18:18 +0000859 Value *Ne = IRB.CreateICmpNE(V, DFSF.DFS.ZeroShadow);
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000860 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000861 Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000862 IRBuilder<> ThenIRB(BI);
863 ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn);
864 }
865 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000866 }
867
868 return false;
869}
870
871Value *DFSanFunction::getArgTLSPtr() {
872 if (ArgTLSPtr)
873 return ArgTLSPtr;
874 if (DFS.ArgTLS)
875 return ArgTLSPtr = DFS.ArgTLS;
876
877 IRBuilder<> IRB(F->getEntryBlock().begin());
878 return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLS);
879}
880
881Value *DFSanFunction::getRetvalTLS() {
882 if (RetvalTLSPtr)
883 return RetvalTLSPtr;
884 if (DFS.RetvalTLS)
885 return RetvalTLSPtr = DFS.RetvalTLS;
886
887 IRBuilder<> IRB(F->getEntryBlock().begin());
888 return RetvalTLSPtr = IRB.CreateCall(DFS.GetRetvalTLS);
889}
890
891Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
892 IRBuilder<> IRB(Pos);
893 return IRB.CreateConstGEP2_64(getArgTLSPtr(), 0, Idx);
894}
895
896Value *DFSanFunction::getShadow(Value *V) {
897 if (!isa<Argument>(V) && !isa<Instruction>(V))
898 return DFS.ZeroShadow;
899 Value *&Shadow = ValShadowMap[V];
900 if (!Shadow) {
901 if (Argument *A = dyn_cast<Argument>(V)) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000902 if (IsNativeABI)
903 return DFS.ZeroShadow;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000904 switch (IA) {
905 case DataFlowSanitizer::IA_TLS: {
906 Value *ArgTLSPtr = getArgTLSPtr();
907 Instruction *ArgTLSPos =
908 DFS.ArgTLS ? &*F->getEntryBlock().begin()
909 : cast<Instruction>(ArgTLSPtr)->getNextNode();
910 IRBuilder<> IRB(ArgTLSPos);
911 Shadow = IRB.CreateLoad(getArgTLS(A->getArgNo(), ArgTLSPos));
912 break;
913 }
914 case DataFlowSanitizer::IA_Args: {
915 unsigned ArgIdx = A->getArgNo() + F->getArgumentList().size() / 2;
916 Function::arg_iterator i = F->arg_begin();
917 while (ArgIdx--)
918 ++i;
919 Shadow = i;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000920 assert(Shadow->getType() == DFS.ShadowTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000921 break;
922 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000923 }
Peter Collingbournefab565a2014-08-22 01:18:18 +0000924 NonZeroChecks.push_back(Shadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000925 } else {
926 Shadow = DFS.ZeroShadow;
927 }
928 }
929 return Shadow;
930}
931
932void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
933 assert(!ValShadowMap.count(I));
934 assert(Shadow->getType() == DFS.ShadowTy);
935 ValShadowMap[I] = Shadow;
936}
937
938Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
939 assert(Addr != RetvalTLS && "Reinstrumenting?");
940 IRBuilder<> IRB(Pos);
941 return IRB.CreateIntToPtr(
942 IRB.CreateMul(
943 IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy), ShadowPtrMask),
944 ShadowPtrMul),
945 ShadowPtrTy);
946}
947
948// Generates IR to compute the union of the two given shadows, inserting it
949// before Pos. Returns the computed union Value.
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000950Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) {
951 if (V1 == DFS.ZeroShadow)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000952 return V2;
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000953 if (V2 == DFS.ZeroShadow)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000954 return V1;
955 if (V1 == V2)
956 return V1;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000957
Peter Collingbourne9947c492014-07-15 22:13:19 +0000958 auto V1Elems = ShadowElements.find(V1);
959 auto V2Elems = ShadowElements.find(V2);
960 if (V1Elems != ShadowElements.end() && V2Elems != ShadowElements.end()) {
961 if (std::includes(V1Elems->second.begin(), V1Elems->second.end(),
962 V2Elems->second.begin(), V2Elems->second.end())) {
963 return V1;
964 } else if (std::includes(V2Elems->second.begin(), V2Elems->second.end(),
965 V1Elems->second.begin(), V1Elems->second.end())) {
966 return V2;
967 }
968 } else if (V1Elems != ShadowElements.end()) {
969 if (V1Elems->second.count(V2))
970 return V1;
971 } else if (V2Elems != ShadowElements.end()) {
972 if (V2Elems->second.count(V1))
973 return V2;
974 }
975
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000976 auto Key = std::make_pair(V1, V2);
977 if (V1 > V2)
978 std::swap(Key.first, Key.second);
979 CachedCombinedShadow &CCS = CachedCombinedShadows[Key];
980 if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent()))
981 return CCS.Shadow;
982
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000983 IRBuilder<> IRB(Pos);
Peter Collingbournedf240b22014-08-06 00:33:40 +0000984 if (AvoidNewBlocks) {
985 CallInst *Call = IRB.CreateCall2(DFS.DFSanCheckedUnionFn, V1, V2);
986 Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
987 Call->addAttribute(1, Attribute::ZExt);
988 Call->addAttribute(2, Attribute::ZExt);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000989
Peter Collingbournedf240b22014-08-06 00:33:40 +0000990 CCS.Block = Pos->getParent();
991 CCS.Shadow = Call;
992 } else {
993 BasicBlock *Head = Pos->getParent();
994 Value *Ne = IRB.CreateICmpNE(V1, V2);
995 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
996 Ne, Pos, /*Unreachable=*/false, DFS.ColdCallWeights, &DT));
997 IRBuilder<> ThenIRB(BI);
998 CallInst *Call = ThenIRB.CreateCall2(DFS.DFSanUnionFn, V1, V2);
999 Call->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
1000 Call->addAttribute(1, Attribute::ZExt);
1001 Call->addAttribute(2, Attribute::ZExt);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001002
Peter Collingbournedf240b22014-08-06 00:33:40 +00001003 BasicBlock *Tail = BI->getSuccessor(0);
1004 PHINode *Phi = PHINode::Create(DFS.ShadowTy, 2, "", Tail->begin());
1005 Phi->addIncoming(Call, Call->getParent());
1006 Phi->addIncoming(V1, Head);
1007
1008 CCS.Block = Tail;
1009 CCS.Shadow = Phi;
1010 }
Peter Collingbourne9947c492014-07-15 22:13:19 +00001011
1012 std::set<Value *> UnionElems;
1013 if (V1Elems != ShadowElements.end()) {
1014 UnionElems = V1Elems->second;
1015 } else {
1016 UnionElems.insert(V1);
1017 }
1018 if (V2Elems != ShadowElements.end()) {
1019 UnionElems.insert(V2Elems->second.begin(), V2Elems->second.end());
1020 } else {
1021 UnionElems.insert(V2);
1022 }
Peter Collingbournedf240b22014-08-06 00:33:40 +00001023 ShadowElements[CCS.Shadow] = std::move(UnionElems);
Peter Collingbourne9947c492014-07-15 22:13:19 +00001024
Peter Collingbournedf240b22014-08-06 00:33:40 +00001025 return CCS.Shadow;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001026}
1027
1028// A convenience function which folds the shadows of each of the operands
1029// of the provided instruction Inst, inserting the IR before Inst. Returns
1030// the computed union Value.
1031Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
1032 if (Inst->getNumOperands() == 0)
1033 return DFS.ZeroShadow;
1034
1035 Value *Shadow = getShadow(Inst->getOperand(0));
1036 for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001037 Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001038 }
1039 return Shadow;
1040}
1041
1042void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
1043 Value *CombinedShadow = DFSF.combineOperandShadows(&I);
1044 DFSF.setShadow(&I, CombinedShadow);
1045}
1046
1047// Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
1048// Addr has alignment Align, and take the union of each of those shadows.
1049Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
1050 Instruction *Pos) {
1051 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1052 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1053 AllocaShadowMap.find(AI);
1054 if (i != AllocaShadowMap.end()) {
1055 IRBuilder<> IRB(Pos);
1056 return IRB.CreateLoad(i->second);
1057 }
1058 }
1059
1060 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1061 SmallVector<Value *, 2> Objs;
1062 GetUnderlyingObjects(Addr, Objs, DFS.DL);
1063 bool AllConstants = true;
1064 for (SmallVector<Value *, 2>::iterator i = Objs.begin(), e = Objs.end();
1065 i != e; ++i) {
1066 if (isa<Function>(*i) || isa<BlockAddress>(*i))
1067 continue;
1068 if (isa<GlobalVariable>(*i) && cast<GlobalVariable>(*i)->isConstant())
1069 continue;
1070
1071 AllConstants = false;
1072 break;
1073 }
1074 if (AllConstants)
1075 return DFS.ZeroShadow;
1076
1077 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1078 switch (Size) {
1079 case 0:
1080 return DFS.ZeroShadow;
1081 case 1: {
1082 LoadInst *LI = new LoadInst(ShadowAddr, "", Pos);
1083 LI->setAlignment(ShadowAlign);
1084 return LI;
1085 }
1086 case 2: {
1087 IRBuilder<> IRB(Pos);
1088 Value *ShadowAddr1 =
1089 IRB.CreateGEP(ShadowAddr, ConstantInt::get(DFS.IntptrTy, 1));
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001090 return combineShadows(IRB.CreateAlignedLoad(ShadowAddr, ShadowAlign),
1091 IRB.CreateAlignedLoad(ShadowAddr1, ShadowAlign), Pos);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001092 }
1093 }
Peter Collingbournedf240b22014-08-06 00:33:40 +00001094 if (!AvoidNewBlocks && Size % (64 / DFS.ShadowWidth) == 0) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001095 // Fast path for the common case where each byte has identical shadow: load
1096 // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
1097 // shadow is non-equal.
1098 BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
1099 IRBuilder<> FallbackIRB(FallbackBB);
1100 CallInst *FallbackCall = FallbackIRB.CreateCall2(
1101 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
1102 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
1103
1104 // Compare each of the shadows stored in the loaded 64 bits to each other,
1105 // by computing (WideShadow rotl ShadowWidth) == WideShadow.
1106 IRBuilder<> IRB(Pos);
1107 Value *WideAddr =
1108 IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
1109 Value *WideShadow = IRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1110 Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
1111 Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
1112 Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
1113 Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
1114 Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
1115
1116 BasicBlock *Head = Pos->getParent();
1117 BasicBlock *Tail = Head->splitBasicBlock(Pos);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001118
1119 if (DomTreeNode *OldNode = DT.getNode(Head)) {
1120 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
1121
1122 DomTreeNode *NewNode = DT.addNewBlock(Tail, Head);
1123 for (auto Child : Children)
1124 DT.changeImmediateDominator(Child, NewNode);
1125 }
1126
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001127 // In the following code LastBr will refer to the previous basic block's
1128 // conditional branch instruction, whose true successor is fixed up to point
1129 // to the next block during the loop below or to the tail after the final
1130 // iteration.
1131 BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
1132 ReplaceInstWithInst(Head->getTerminator(), LastBr);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001133 DT.addNewBlock(FallbackBB, Head);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001134
1135 for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
1136 Ofs += 64 / DFS.ShadowWidth) {
1137 BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001138 DT.addNewBlock(NextBB, LastBr->getParent());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001139 IRBuilder<> NextIRB(NextBB);
1140 WideAddr = NextIRB.CreateGEP(WideAddr, ConstantInt::get(DFS.IntptrTy, 1));
1141 Value *NextWideShadow = NextIRB.CreateAlignedLoad(WideAddr, ShadowAlign);
1142 ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
1143 LastBr->setSuccessor(0, NextBB);
1144 LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
1145 }
1146
1147 LastBr->setSuccessor(0, Tail);
1148 FallbackIRB.CreateBr(Tail);
1149 PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
1150 Shadow->addIncoming(FallbackCall, FallbackBB);
1151 Shadow->addIncoming(TruncShadow, LastBr->getParent());
1152 return Shadow;
1153 }
1154
1155 IRBuilder<> IRB(Pos);
1156 CallInst *FallbackCall = IRB.CreateCall2(
1157 DFS.DFSanUnionLoadFn, ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size));
1158 FallbackCall->addAttribute(AttributeSet::ReturnIndex, Attribute::ZExt);
1159 return FallbackCall;
1160}
1161
1162void DFSanVisitor::visitLoadInst(LoadInst &LI) {
1163 uint64_t Size = DFSF.DFS.DL->getTypeStoreSize(LI.getType());
Peter Collingbourne142fdff2014-08-01 21:18:18 +00001164 if (Size == 0) {
1165 DFSF.setShadow(&LI, DFSF.DFS.ZeroShadow);
1166 return;
1167 }
1168
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001169 uint64_t Align;
1170 if (ClPreserveAlignment) {
1171 Align = LI.getAlignment();
1172 if (Align == 0)
1173 Align = DFSF.DFS.DL->getABITypeAlignment(LI.getType());
1174 } else {
1175 Align = 1;
1176 }
1177 IRBuilder<> IRB(&LI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001178 Value *Shadow = DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
1179 if (ClCombinePointerLabelsOnLoad) {
1180 Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001181 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &LI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001182 }
1183 if (Shadow != DFSF.DFS.ZeroShadow)
Peter Collingbournefab565a2014-08-22 01:18:18 +00001184 DFSF.NonZeroChecks.push_back(Shadow);
Peter Collingbourne444c59e2013-08-15 18:51:12 +00001185
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001186 DFSF.setShadow(&LI, Shadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001187}
1188
1189void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
1190 Value *Shadow, Instruction *Pos) {
1191 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1192 llvm::DenseMap<AllocaInst *, AllocaInst *>::iterator i =
1193 AllocaShadowMap.find(AI);
1194 if (i != AllocaShadowMap.end()) {
1195 IRBuilder<> IRB(Pos);
1196 IRB.CreateStore(Shadow, i->second);
1197 return;
1198 }
1199 }
1200
1201 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1202 IRBuilder<> IRB(Pos);
1203 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1204 if (Shadow == DFS.ZeroShadow) {
1205 IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
1206 Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
1207 Value *ExtShadowAddr =
1208 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
1209 IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
1210 return;
1211 }
1212
1213 const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
1214 uint64_t Offset = 0;
1215 if (Size >= ShadowVecSize) {
1216 VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
1217 Value *ShadowVec = UndefValue::get(ShadowVecTy);
1218 for (unsigned i = 0; i != ShadowVecSize; ++i) {
1219 ShadowVec = IRB.CreateInsertElement(
1220 ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
1221 }
1222 Value *ShadowVecAddr =
1223 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
1224 do {
1225 Value *CurShadowVecAddr = IRB.CreateConstGEP1_32(ShadowVecAddr, Offset);
1226 IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
1227 Size -= ShadowVecSize;
1228 ++Offset;
1229 } while (Size >= ShadowVecSize);
1230 Offset *= ShadowVecSize;
1231 }
1232 while (Size > 0) {
1233 Value *CurShadowAddr = IRB.CreateConstGEP1_32(ShadowAddr, Offset);
1234 IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
1235 --Size;
1236 ++Offset;
1237 }
1238}
1239
1240void DFSanVisitor::visitStoreInst(StoreInst &SI) {
1241 uint64_t Size =
1242 DFSF.DFS.DL->getTypeStoreSize(SI.getValueOperand()->getType());
Peter Collingbourne142fdff2014-08-01 21:18:18 +00001243 if (Size == 0)
1244 return;
1245
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001246 uint64_t Align;
1247 if (ClPreserveAlignment) {
1248 Align = SI.getAlignment();
1249 if (Align == 0)
1250 Align = DFSF.DFS.DL->getABITypeAlignment(SI.getValueOperand()->getType());
1251 } else {
1252 Align = 1;
1253 }
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001254
1255 Value* Shadow = DFSF.getShadow(SI.getValueOperand());
1256 if (ClCombinePointerLabelsOnStore) {
1257 Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001258 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &SI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001259 }
1260 DFSF.storeShadow(SI.getPointerOperand(), Size, Align, Shadow, &SI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001261}
1262
1263void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
1264 visitOperandShadowInst(BO);
1265}
1266
1267void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
1268
1269void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
1270
1271void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
1272 visitOperandShadowInst(GEPI);
1273}
1274
1275void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
1276 visitOperandShadowInst(I);
1277}
1278
1279void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
1280 visitOperandShadowInst(I);
1281}
1282
1283void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
1284 visitOperandShadowInst(I);
1285}
1286
1287void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
1288 visitOperandShadowInst(I);
1289}
1290
1291void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
1292 visitOperandShadowInst(I);
1293}
1294
1295void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
1296 bool AllLoadsStores = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001297 for (User *U : I.users()) {
1298 if (isa<LoadInst>(U))
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001299 continue;
1300
Chandler Carruthcdf47882014-03-09 03:16:01 +00001301 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001302 if (SI->getPointerOperand() == &I)
1303 continue;
1304 }
1305
1306 AllLoadsStores = false;
1307 break;
1308 }
1309 if (AllLoadsStores) {
1310 IRBuilder<> IRB(&I);
1311 DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
1312 }
1313 DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
1314}
1315
1316void DFSanVisitor::visitSelectInst(SelectInst &I) {
1317 Value *CondShadow = DFSF.getShadow(I.getCondition());
1318 Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
1319 Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
1320
1321 if (isa<VectorType>(I.getCondition()->getType())) {
1322 DFSF.setShadow(
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001323 &I,
1324 DFSF.combineShadows(
1325 CondShadow, DFSF.combineShadows(TrueShadow, FalseShadow, &I), &I));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001326 } else {
1327 Value *ShadowSel;
1328 if (TrueShadow == FalseShadow) {
1329 ShadowSel = TrueShadow;
1330 } else {
1331 ShadowSel =
1332 SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
1333 }
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001334 DFSF.setShadow(&I, DFSF.combineShadows(CondShadow, ShadowSel, &I));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001335 }
1336}
1337
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +00001338void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
1339 IRBuilder<> IRB(&I);
1340 Value *ValShadow = DFSF.getShadow(I.getValue());
1341 IRB.CreateCall3(
1342 DFSF.DFS.DFSanSetLabelFn, ValShadow,
1343 IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(*DFSF.DFS.Ctx)),
1344 IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy));
1345}
1346
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001347void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
1348 IRBuilder<> IRB(&I);
1349 Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
1350 Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
1351 Value *LenShadow = IRB.CreateMul(
1352 I.getLength(),
1353 ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
1354 Value *AlignShadow;
1355 if (ClPreserveAlignment) {
1356 AlignShadow = IRB.CreateMul(I.getAlignmentCst(),
1357 ConstantInt::get(I.getAlignmentCst()->getType(),
1358 DFSF.DFS.ShadowWidth / 8));
1359 } else {
1360 AlignShadow = ConstantInt::get(I.getAlignmentCst()->getType(),
1361 DFSF.DFS.ShadowWidth / 8);
1362 }
1363 Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
1364 DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
1365 SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
1366 IRB.CreateCall5(I.getCalledValue(), DestShadow, SrcShadow, LenShadow,
1367 AlignShadow, I.getVolatileCst());
1368}
1369
1370void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
Peter Collingbourne68162e72013-08-14 18:54:12 +00001371 if (!DFSF.IsNativeABI && RI.getReturnValue()) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001372 switch (DFSF.IA) {
1373 case DataFlowSanitizer::IA_TLS: {
1374 Value *S = DFSF.getShadow(RI.getReturnValue());
1375 IRBuilder<> IRB(&RI);
1376 IRB.CreateStore(S, DFSF.getRetvalTLS());
1377 break;
1378 }
1379 case DataFlowSanitizer::IA_Args: {
1380 IRBuilder<> IRB(&RI);
1381 Type *RT = DFSF.F->getFunctionType()->getReturnType();
1382 Value *InsVal =
1383 IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
1384 Value *InsShadow =
1385 IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
1386 RI.setOperand(0, InsShadow);
1387 break;
1388 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001389 }
1390 }
1391}
1392
1393void DFSanVisitor::visitCallSite(CallSite CS) {
1394 Function *F = CS.getCalledFunction();
1395 if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
1396 visitOperandShadowInst(*CS.getInstruction());
1397 return;
1398 }
1399
Peter Collingbournea1099842014-11-05 17:21:00 +00001400 // Calls to this function are synthesized in wrappers, and we shouldn't
1401 // instrument them.
1402 if (F == DFSF.DFS.DFSanVarargWrapperFn)
1403 return;
1404
Lorenzo Martignoni40d3dee2014-09-30 12:33:16 +00001405 assert(!(cast<FunctionType>(
1406 CS.getCalledValue()->getType()->getPointerElementType())->isVarArg() &&
1407 dyn_cast<InvokeInst>(CS.getInstruction())));
1408
Peter Collingbourne68162e72013-08-14 18:54:12 +00001409 IRBuilder<> IRB(CS.getInstruction());
1410
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001411 DenseMap<Value *, Function *>::iterator i =
1412 DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
1413 if (i != DFSF.DFS.UnwrappedFnMap.end()) {
Peter Collingbourne68162e72013-08-14 18:54:12 +00001414 Function *F = i->second;
1415 switch (DFSF.DFS.getWrapperKind(F)) {
1416 case DataFlowSanitizer::WK_Warning: {
1417 CS.setCalledFunction(F);
1418 IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
1419 IRB.CreateGlobalStringPtr(F->getName()));
1420 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1421 return;
1422 }
1423 case DataFlowSanitizer::WK_Discard: {
1424 CS.setCalledFunction(F);
1425 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1426 return;
1427 }
1428 case DataFlowSanitizer::WK_Functional: {
1429 CS.setCalledFunction(F);
1430 visitOperandShadowInst(*CS.getInstruction());
1431 return;
1432 }
1433 case DataFlowSanitizer::WK_Custom: {
1434 // Don't try to handle invokes of custom functions, it's too complicated.
1435 // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
1436 // wrapper.
1437 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
1438 FunctionType *FT = F->getFunctionType();
1439 FunctionType *CustomFT = DFSF.DFS.getCustomFunctionType(FT);
1440 std::string CustomFName = "__dfsw_";
1441 CustomFName += F->getName();
1442 Constant *CustomF =
1443 DFSF.DFS.Mod->getOrInsertFunction(CustomFName, CustomFT);
1444 if (Function *CustomFn = dyn_cast<Function>(CustomF)) {
1445 CustomFn->copyAttributesFrom(F);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001446
Peter Collingbourne68162e72013-08-14 18:54:12 +00001447 // Custom functions returning non-void will write to the return label.
1448 if (!FT->getReturnType()->isVoidTy()) {
1449 CustomFn->removeAttributes(AttributeSet::FunctionIndex,
1450 DFSF.DFS.ReadOnlyNoneAttrs);
1451 }
1452 }
1453
1454 std::vector<Value *> Args;
1455
1456 CallSite::arg_iterator i = CS.arg_begin();
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001457 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n) {
Peter Collingbourne28a10af2013-08-27 22:09:06 +00001458 Type *T = (*i)->getType();
1459 FunctionType *ParamFT;
1460 if (isa<PointerType>(T) &&
1461 (ParamFT = dyn_cast<FunctionType>(
1462 cast<PointerType>(T)->getElementType()))) {
1463 std::string TName = "dfst";
1464 TName += utostr(FT->getNumParams() - n);
1465 TName += "$";
1466 TName += F->getName();
1467 Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
1468 Args.push_back(T);
1469 Args.push_back(
1470 IRB.CreateBitCast(*i, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
1471 } else {
1472 Args.push_back(*i);
1473 }
1474 }
Peter Collingbourne68162e72013-08-14 18:54:12 +00001475
1476 i = CS.arg_begin();
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001477 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
Peter Collingbourne68162e72013-08-14 18:54:12 +00001478 Args.push_back(DFSF.getShadow(*i));
1479
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001480 if (FT->isVarArg()) {
1481 auto LabelVAAlloca =
1482 new AllocaInst(ArrayType::get(DFSF.DFS.ShadowTy,
1483 CS.arg_size() - FT->getNumParams()),
1484 "labelva", DFSF.F->getEntryBlock().begin());
1485
1486 for (unsigned n = 0; i != CS.arg_end(); ++i, ++n) {
1487 auto LabelVAPtr = IRB.CreateStructGEP(LabelVAAlloca, n);
1488 IRB.CreateStore(DFSF.getShadow(*i), LabelVAPtr);
1489 }
1490
1491 Args.push_back(IRB.CreateStructGEP(LabelVAAlloca, 0));
1492 }
1493
Peter Collingbourne68162e72013-08-14 18:54:12 +00001494 if (!FT->getReturnType()->isVoidTy()) {
1495 if (!DFSF.LabelReturnAlloca) {
1496 DFSF.LabelReturnAlloca =
1497 new AllocaInst(DFSF.DFS.ShadowTy, "labelreturn",
1498 DFSF.F->getEntryBlock().begin());
1499 }
1500 Args.push_back(DFSF.LabelReturnAlloca);
1501 }
1502
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001503 for (i = CS.arg_begin() + FT->getNumParams(); i != CS.arg_end(); ++i)
1504 Args.push_back(*i);
1505
Peter Collingbourne68162e72013-08-14 18:54:12 +00001506 CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
1507 CustomCI->setCallingConv(CI->getCallingConv());
1508 CustomCI->setAttributes(CI->getAttributes());
1509
1510 if (!FT->getReturnType()->isVoidTy()) {
1511 LoadInst *LabelLoad = IRB.CreateLoad(DFSF.LabelReturnAlloca);
1512 DFSF.setShadow(CustomCI, LabelLoad);
1513 }
1514
1515 CI->replaceAllUsesWith(CustomCI);
1516 CI->eraseFromParent();
1517 return;
1518 }
1519 break;
1520 }
1521 }
1522 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001523
1524 FunctionType *FT = cast<FunctionType>(
1525 CS.getCalledValue()->getType()->getPointerElementType());
Peter Collingbourne68162e72013-08-14 18:54:12 +00001526 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001527 for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
1528 IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
1529 DFSF.getArgTLS(i, CS.getInstruction()));
1530 }
1531 }
1532
Craig Topperf40110f2014-04-25 05:29:35 +00001533 Instruction *Next = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001534 if (!CS.getType()->isVoidTy()) {
1535 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1536 if (II->getNormalDest()->getSinglePredecessor()) {
1537 Next = II->getNormalDest()->begin();
1538 } else {
1539 BasicBlock *NewBB =
Chandler Carruthd4500562015-01-19 12:36:53 +00001540 SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DT);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001541 Next = NewBB->begin();
1542 }
1543 } else {
1544 Next = CS->getNextNode();
1545 }
1546
Peter Collingbourne68162e72013-08-14 18:54:12 +00001547 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001548 IRBuilder<> NextIRB(Next);
1549 LoadInst *LI = NextIRB.CreateLoad(DFSF.getRetvalTLS());
1550 DFSF.SkipInsts.insert(LI);
1551 DFSF.setShadow(CS.getInstruction(), LI);
Peter Collingbournefab565a2014-08-22 01:18:18 +00001552 DFSF.NonZeroChecks.push_back(LI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001553 }
1554 }
1555
1556 // Do all instrumentation for IA_Args down here to defer tampering with the
1557 // CFG in a way that SplitEdge may be able to detect.
Peter Collingbourne68162e72013-08-14 18:54:12 +00001558 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
1559 FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001560 Value *Func =
1561 IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
1562 std::vector<Value *> Args;
1563
1564 CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1565 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1566 Args.push_back(*i);
1567
1568 i = CS.arg_begin();
1569 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1570 Args.push_back(DFSF.getShadow(*i));
1571
1572 if (FT->isVarArg()) {
1573 unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
1574 ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
1575 AllocaInst *VarArgShadow =
1576 new AllocaInst(VarArgArrayTy, "", DFSF.F->getEntryBlock().begin());
1577 Args.push_back(IRB.CreateConstGEP2_32(VarArgShadow, 0, 0));
1578 for (unsigned n = 0; i != e; ++i, ++n) {
1579 IRB.CreateStore(DFSF.getShadow(*i),
1580 IRB.CreateConstGEP2_32(VarArgShadow, 0, n));
1581 Args.push_back(*i);
1582 }
1583 }
1584
1585 CallSite NewCS;
1586 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1587 NewCS = IRB.CreateInvoke(Func, II->getNormalDest(), II->getUnwindDest(),
1588 Args);
1589 } else {
1590 NewCS = IRB.CreateCall(Func, Args);
1591 }
1592 NewCS.setCallingConv(CS.getCallingConv());
1593 NewCS.setAttributes(CS.getAttributes().removeAttributes(
1594 *DFSF.DFS.Ctx, AttributeSet::ReturnIndex,
1595 AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType(),
1596 AttributeSet::ReturnIndex)));
1597
1598 if (Next) {
1599 ExtractValueInst *ExVal =
1600 ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
1601 DFSF.SkipInsts.insert(ExVal);
1602 ExtractValueInst *ExShadow =
1603 ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
1604 DFSF.SkipInsts.insert(ExShadow);
1605 DFSF.setShadow(ExVal, ExShadow);
Peter Collingbournefab565a2014-08-22 01:18:18 +00001606 DFSF.NonZeroChecks.push_back(ExShadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001607
1608 CS.getInstruction()->replaceAllUsesWith(ExVal);
1609 }
1610
1611 CS.getInstruction()->eraseFromParent();
1612 }
1613}
1614
1615void DFSanVisitor::visitPHINode(PHINode &PN) {
1616 PHINode *ShadowPN =
1617 PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
1618
1619 // Give the shadow phi node valid predecessors to fool SplitEdge into working.
1620 Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
1621 for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1622 ++i) {
1623 ShadowPN->addIncoming(UndefShadow, *i);
1624 }
1625
1626 DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1627 DFSF.setShadow(&PN, ShadowPN);
1628}