blob: a5776a47af7a0bfddd4e2fc6a4e9a3ed13e98624 [file] [log] [blame]
Eugene Zelenkofce43572017-10-21 00:57:46 +00001//===- DataFlowSanitizer.cpp - dynamic data flow analysis -----------------===//
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00006//
7//===----------------------------------------------------------------------===//
Eugene Zelenkofce43572017-10-21 00:57:46 +00008//
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00009/// \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
Eugene Zelenkofce43572017-10-21 00:57:46 +000046//
47//===----------------------------------------------------------------------===//
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000048
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000049#include "llvm/ADT/DenseMap.h"
50#include "llvm/ADT/DenseSet.h"
51#include "llvm/ADT/DepthFirstIterator.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000052#include "llvm/ADT/None.h"
53#include "llvm/ADT/SmallPtrSet.h"
54#include "llvm/ADT/SmallVector.h"
Peter Collingbourne28a10af2013-08-27 22:09:06 +000055#include "llvm/ADT/StringExtras.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000056#include "llvm/ADT/StringRef.h"
Peter Collingbourne0826e602014-12-05 21:22:32 +000057#include "llvm/ADT/Triple.h"
David Blaikie31b98d22018-06-04 21:23:21 +000058#include "llvm/Transforms/Utils/Local.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000059#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000060#include "llvm/IR/Argument.h"
61#include "llvm/IR/Attributes.h"
62#include "llvm/IR/BasicBlock.h"
63#include "llvm/IR/CallSite.h"
64#include "llvm/IR/Constant.h"
65#include "llvm/IR/Constants.h"
66#include "llvm/IR/DataLayout.h"
67#include "llvm/IR/DerivedTypes.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000068#include "llvm/IR/Dominators.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000069#include "llvm/IR/Function.h"
70#include "llvm/IR/GlobalAlias.h"
71#include "llvm/IR/GlobalValue.h"
72#include "llvm/IR/GlobalVariable.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000073#include "llvm/IR/IRBuilder.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000074#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000075#include "llvm/IR/InstVisitor.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000076#include "llvm/IR/InstrTypes.h"
77#include "llvm/IR/Instruction.h"
78#include "llvm/IR/Instructions.h"
79#include "llvm/IR/IntrinsicInst.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000080#include "llvm/IR/LLVMContext.h"
81#include "llvm/IR/MDBuilder.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000082#include "llvm/IR/Module.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000083#include "llvm/IR/Type.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000084#include "llvm/IR/User.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000085#include "llvm/IR/Value.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000086#include "llvm/Pass.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000087#include "llvm/Support/Casting.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000088#include "llvm/Support/CommandLine.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000089#include "llvm/Support/ErrorHandling.h"
Alexey Samsonovb7dd3292014-07-09 19:40:08 +000090#include "llvm/Support/SpecialCaseList.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000091#include "llvm/Transforms/Instrumentation.h"
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000092#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Peter Collingbourne9947c492014-07-15 22:13:19 +000093#include <algorithm>
Eugene Zelenkofce43572017-10-21 00:57:46 +000094#include <cassert>
95#include <cstddef>
96#include <cstdint>
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +000097#include <iterator>
Eugene Zelenkofce43572017-10-21 00:57:46 +000098#include <memory>
Peter Collingbourne9947c492014-07-15 22:13:19 +000099#include <set>
Eugene Zelenkofce43572017-10-21 00:57:46 +0000100#include <string>
Peter Collingbourne9947c492014-07-15 22:13:19 +0000101#include <utility>
Eugene Zelenkofce43572017-10-21 00:57:46 +0000102#include <vector>
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000103
104using namespace llvm;
105
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +0000106// External symbol to be used when generating the shadow address for
107// architectures with multiple VMAs. Instead of using a constant integer
108// the runtime will set the external mask based on the VMA range.
109static const char *const kDFSanExternShadowPtrMask = "__dfsan_shadow_ptr_mask";
Adhemerval Zanella4754e2d2015-08-24 13:48:10 +0000110
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000111// The -dfsan-preserve-alignment flag controls whether this pass assumes that
112// alignment requirements provided by the input IR are correct. For example,
113// if the input IR contains a load with alignment 8, this flag will cause
114// the shadow load to have alignment 16. This flag is disabled by default as
115// we have unfortunately encountered too much code (including Clang itself;
116// see PR14291) which performs misaligned access.
117static cl::opt<bool> ClPreserveAlignment(
118 "dfsan-preserve-alignment",
119 cl::desc("respect alignment requirements provided by input IR"), cl::Hidden,
120 cl::init(false));
121
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000122// The ABI list files control how shadow parameters are passed. The pass treats
Peter Collingbourne68162e72013-08-14 18:54:12 +0000123// every function labelled "uninstrumented" in the ABI list file as conforming
124// to the "native" (i.e. unsanitized) ABI. Unless the ABI list contains
125// additional annotations for those functions, a call to one of those functions
126// will produce a warning message, as the labelling behaviour of the function is
127// unknown. The other supported annotations are "functional" and "discard",
128// which are described below under DataFlowSanitizer::WrapperKind.
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000129static cl::list<std::string> ClABIListFiles(
Peter Collingbourne68162e72013-08-14 18:54:12 +0000130 "dfsan-abilist",
131 cl::desc("File listing native ABI functions and how the pass treats them"),
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000132 cl::Hidden);
133
Peter Collingbourne68162e72013-08-14 18:54:12 +0000134// Controls whether the pass uses IA_Args or IA_TLS as the ABI for instrumented
135// functions (see DataFlowSanitizer::InstrumentedABI below).
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000136static cl::opt<bool> ClArgsABI(
137 "dfsan-args-abi",
138 cl::desc("Use the argument ABI rather than the TLS ABI"),
139 cl::Hidden);
140
Peter Collingbourne0be79e12013-11-21 23:20:54 +0000141// Controls whether the pass includes or ignores the labels of pointers in load
142// instructions.
143static cl::opt<bool> ClCombinePointerLabelsOnLoad(
144 "dfsan-combine-pointer-labels-on-load",
145 cl::desc("Combine the label of the pointer with the label of the data when "
146 "loading from memory."),
147 cl::Hidden, cl::init(true));
148
149// Controls whether the pass includes or ignores the labels of pointers in
150// stores instructions.
151static cl::opt<bool> ClCombinePointerLabelsOnStore(
152 "dfsan-combine-pointer-labels-on-store",
153 cl::desc("Combine the label of the pointer with the label of the data when "
154 "storing in memory."),
155 cl::Hidden, cl::init(false));
156
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000157static cl::opt<bool> ClDebugNonzeroLabels(
158 "dfsan-debug-nonzero-labels",
159 cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, "
160 "load or return with a nonzero label"),
161 cl::Hidden);
162
Eugene Zelenkofce43572017-10-21 00:57:46 +0000163static StringRef GetGlobalTypeString(const GlobalValue &G) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000164 // Types of GlobalVariables are always pointer types.
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000165 Type *GType = G.getValueType();
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000166 // For now we support blacklisting struct types only.
167 if (StructType *SGType = dyn_cast<StructType>(GType)) {
168 if (!SGType->isLiteral())
169 return SGType->getName();
170 }
171 return "<unknown type>";
172}
173
Eugene Zelenkofce43572017-10-21 00:57:46 +0000174namespace {
175
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000176class DFSanABIList {
177 std::unique_ptr<SpecialCaseList> SCL;
178
179 public:
Eugene Zelenkofce43572017-10-21 00:57:46 +0000180 DFSanABIList() = default;
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000181
182 void set(std::unique_ptr<SpecialCaseList> List) { SCL = std::move(List); }
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000183
184 /// Returns whether either this function or its source file are listed in the
185 /// given category.
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000186 bool isIn(const Function &F, StringRef Category) const {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000187 return isIn(*F.getParent(), Category) ||
Vlad Tsyrklevich998b2202017-09-25 22:11:11 +0000188 SCL->inSection("dataflow", "fun", F.getName(), Category);
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000189 }
190
191 /// Returns whether this global alias is listed in the given category.
192 ///
193 /// If GA aliases a function, the alias's name is matched as a function name
194 /// would be. Similarly, aliases of globals are matched like globals.
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000195 bool isIn(const GlobalAlias &GA, StringRef Category) const {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000196 if (isIn(*GA.getParent(), Category))
197 return true;
198
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000199 if (isa<FunctionType>(GA.getValueType()))
Vlad Tsyrklevich998b2202017-09-25 22:11:11 +0000200 return SCL->inSection("dataflow", "fun", GA.getName(), Category);
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000201
Vlad Tsyrklevich998b2202017-09-25 22:11:11 +0000202 return SCL->inSection("dataflow", "global", GA.getName(), Category) ||
203 SCL->inSection("dataflow", "type", GetGlobalTypeString(GA),
204 Category);
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000205 }
206
207 /// Returns whether this module is listed in the given category.
Craig Topper6dc4a8bc2014-08-30 16:48:02 +0000208 bool isIn(const Module &M, StringRef Category) const {
Vlad Tsyrklevich998b2202017-09-25 22:11:11 +0000209 return SCL->inSection("dataflow", "src", M.getModuleIdentifier(), Category);
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000210 }
211};
212
Peter Collingbourne32f54052018-02-22 19:09:07 +0000213/// TransformedFunction is used to express the result of transforming one
214/// function type into another. This struct is immutable. It holds metadata
215/// useful for updating calls of the old function to the new type.
216struct TransformedFunction {
217 TransformedFunction(FunctionType* OriginalType,
218 FunctionType* TransformedType,
219 std::vector<unsigned> ArgumentIndexMapping)
220 : OriginalType(OriginalType),
221 TransformedType(TransformedType),
222 ArgumentIndexMapping(ArgumentIndexMapping) {}
223
224 // Disallow copies.
225 TransformedFunction(const TransformedFunction&) = delete;
226 TransformedFunction& operator=(const TransformedFunction&) = delete;
227
228 // Allow moves.
229 TransformedFunction(TransformedFunction&&) = default;
230 TransformedFunction& operator=(TransformedFunction&&) = default;
231
232 /// Type of the function before the transformation.
Vitaly Buka05090702018-09-29 02:17:12 +0000233 FunctionType *OriginalType;
Peter Collingbourne32f54052018-02-22 19:09:07 +0000234
235 /// Type of the function after the transformation.
Vitaly Buka05090702018-09-29 02:17:12 +0000236 FunctionType *TransformedType;
Peter Collingbourne32f54052018-02-22 19:09:07 +0000237
238 /// Transforming a function may change the position of arguments. This
239 /// member records the mapping from each argument's old position to its new
240 /// position. Argument positions are zero-indexed. If the transformation
241 /// from F to F' made the first argument of F into the third argument of F',
242 /// then ArgumentIndexMapping[0] will equal 2.
Vitaly Buka05090702018-09-29 02:17:12 +0000243 std::vector<unsigned> ArgumentIndexMapping;
Peter Collingbourne32f54052018-02-22 19:09:07 +0000244};
245
246/// Given function attributes from a call site for the original function,
247/// return function attributes appropriate for a call to the transformed
248/// function.
249AttributeList TransformFunctionAttributes(
250 const TransformedFunction& TransformedFunction,
251 LLVMContext& Ctx, AttributeList CallSiteAttrs) {
252
253 // Construct a vector of AttributeSet for each function argument.
254 std::vector<llvm::AttributeSet> ArgumentAttributes(
255 TransformedFunction.TransformedType->getNumParams());
256
257 // Copy attributes from the parameter of the original function to the
258 // transformed version. 'ArgumentIndexMapping' holds the mapping from
259 // old argument position to new.
260 for (unsigned i=0, ie = TransformedFunction.ArgumentIndexMapping.size();
261 i < ie; ++i) {
262 unsigned TransformedIndex = TransformedFunction.ArgumentIndexMapping[i];
263 ArgumentAttributes[TransformedIndex] = CallSiteAttrs.getParamAttributes(i);
264 }
265
266 // Copy annotations on varargs arguments.
267 for (unsigned i = TransformedFunction.OriginalType->getNumParams(),
268 ie = CallSiteAttrs.getNumAttrSets(); i<ie; ++i) {
269 ArgumentAttributes.push_back(CallSiteAttrs.getParamAttributes(i));
270 }
271
272 return AttributeList::get(
273 Ctx,
274 CallSiteAttrs.getFnAttributes(),
275 CallSiteAttrs.getRetAttributes(),
276 llvm::makeArrayRef(ArgumentAttributes));
277}
278
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000279class DataFlowSanitizer : public ModulePass {
280 friend struct DFSanFunction;
281 friend class DFSanVisitor;
282
283 enum {
284 ShadowWidth = 16
285 };
286
Peter Collingbourne68162e72013-08-14 18:54:12 +0000287 /// Which ABI should be used for instrumented functions?
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000288 enum InstrumentedABI {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000289 /// Argument and return value labels are passed through additional
290 /// arguments and by modifying the return type.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000291 IA_Args,
Peter Collingbourne68162e72013-08-14 18:54:12 +0000292
293 /// Argument and return value labels are passed through TLS variables
294 /// __dfsan_arg_tls and __dfsan_retval_tls.
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000295 IA_TLS
296 };
297
Peter Collingbourne68162e72013-08-14 18:54:12 +0000298 /// How should calls to uninstrumented functions be handled?
299 enum WrapperKind {
300 /// This function is present in an uninstrumented form but we don't know
301 /// how it should be handled. Print a warning and call the function anyway.
302 /// Don't label the return value.
303 WK_Warning,
304
305 /// This function does not write to (user-accessible) memory, and its return
306 /// value is unlabelled.
307 WK_Discard,
308
309 /// This function does not write to (user-accessible) memory, and the label
310 /// of its return value is the union of the label of its arguments.
311 WK_Functional,
312
313 /// Instead of calling the function, a custom wrapper __dfsw_F is called,
314 /// where F is the name of the function. This function may wrap the
315 /// original function or provide its own implementation. This is similar to
316 /// the IA_Args ABI, except that IA_Args uses a struct return type to
317 /// pass the return value shadow in a register, while WK_Custom uses an
318 /// extra pointer argument to return the shadow. This allows the wrapped
319 /// form of the function type to be expressed in C.
320 WK_Custom
321 };
322
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000323 Module *Mod;
324 LLVMContext *Ctx;
325 IntegerType *ShadowTy;
326 PointerType *ShadowPtrTy;
327 IntegerType *IntptrTy;
328 ConstantInt *ZeroShadow;
329 ConstantInt *ShadowPtrMask;
330 ConstantInt *ShadowPtrMul;
331 Constant *ArgTLS;
332 Constant *RetvalTLS;
333 void *(*GetArgTLSPtr)();
334 void *(*GetRetvalTLSPtr)();
James Y Knight7976eb52019-02-01 20:43:25 +0000335 FunctionType *GetArgTLSTy;
336 FunctionType *GetRetvalTLSTy;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000337 Constant *GetArgTLS;
338 Constant *GetRetvalTLS;
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +0000339 Constant *ExternalShadowMask;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000340 FunctionType *DFSanUnionFnTy;
341 FunctionType *DFSanUnionLoadFnTy;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000342 FunctionType *DFSanUnimplementedFnTy;
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000343 FunctionType *DFSanSetLabelFnTy;
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000344 FunctionType *DFSanNonzeroLabelFnTy;
Peter Collingbournea1099842014-11-05 17:21:00 +0000345 FunctionType *DFSanVarargWrapperFnTy;
James Y Knight13680222019-02-01 02:28:03 +0000346 FunctionCallee DFSanUnionFn;
347 FunctionCallee DFSanCheckedUnionFn;
348 FunctionCallee DFSanUnionLoadFn;
349 FunctionCallee DFSanUnimplementedFn;
350 FunctionCallee DFSanSetLabelFn;
351 FunctionCallee DFSanNonzeroLabelFn;
352 FunctionCallee DFSanVarargWrapperFn;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000353 MDNode *ColdCallWeights;
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000354 DFSanABIList ABIList;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000355 DenseMap<Value *, Function *> UnwrappedFnMap;
Reid Kleckneree4930b2017-05-02 22:07:37 +0000356 AttrBuilder ReadOnlyNoneAttrs;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000357 bool DFSanRuntimeShadowMask = false;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000358
359 Value *getShadowAddress(Value *Addr, Instruction *Pos);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000360 bool isInstrumented(const Function *F);
361 bool isInstrumented(const GlobalAlias *GA);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000362 FunctionType *getArgsFunctionType(FunctionType *T);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000363 FunctionType *getTrampolineFunctionType(FunctionType *T);
Peter Collingbourne32f54052018-02-22 19:09:07 +0000364 TransformedFunction getCustomFunctionType(FunctionType *T);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000365 InstrumentedABI getInstrumentedABI();
366 WrapperKind getWrapperKind(Function *F);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000367 void addGlobalNamePrefix(GlobalValue *GV);
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000368 Function *buildWrapperFunction(Function *F, StringRef NewFName,
369 GlobalValue::LinkageTypes NewFLink,
370 FunctionType *NewFT);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000371 Constant *getOrBuildTrampolineFunction(FunctionType *FT, StringRef FName);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000372
Eugene Zelenkofce43572017-10-21 00:57:46 +0000373public:
374 static char ID;
375
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000376 DataFlowSanitizer(
377 const std::vector<std::string> &ABIListFiles = std::vector<std::string>(),
378 void *(*getArgTLS)() = nullptr, void *(*getRetValTLS)() = nullptr);
Eugene Zelenkofce43572017-10-21 00:57:46 +0000379
Craig Topper3e4c6972014-03-05 09:10:37 +0000380 bool doInitialization(Module &M) override;
381 bool runOnModule(Module &M) override;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000382};
383
384struct DFSanFunction {
385 DataFlowSanitizer &DFS;
386 Function *F;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000387 DominatorTree DT;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000388 DataFlowSanitizer::InstrumentedABI IA;
Peter Collingbourne68162e72013-08-14 18:54:12 +0000389 bool IsNativeABI;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000390 Value *ArgTLSPtr = nullptr;
391 Value *RetvalTLSPtr = nullptr;
392 AllocaInst *LabelReturnAlloca = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000393 DenseMap<Value *, Value *> ValShadowMap;
394 DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000395 std::vector<std::pair<PHINode *, PHINode *>> PHIFixups;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000396 DenseSet<Instruction *> SkipInsts;
Peter Collingbournefab565a2014-08-22 01:18:18 +0000397 std::vector<Value *> NonZeroChecks;
Peter Collingbournedf240b22014-08-06 00:33:40 +0000398 bool AvoidNewBlocks;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000399
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000400 struct CachedCombinedShadow {
401 BasicBlock *Block;
402 Value *Shadow;
403 };
404 DenseMap<std::pair<Value *, Value *>, CachedCombinedShadow>
405 CachedCombinedShadows;
Peter Collingbourne9947c492014-07-15 22:13:19 +0000406 DenseMap<Value *, std::set<Value *>> ShadowElements;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000407
Peter Collingbourne68162e72013-08-14 18:54:12 +0000408 DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
Eugene Zelenkofce43572017-10-21 00:57:46 +0000409 : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()), IsNativeABI(IsNativeABI) {
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000410 DT.recalculate(*F);
Peter Collingbournedf240b22014-08-06 00:33:40 +0000411 // FIXME: Need to track down the register allocator issue which causes poor
412 // performance in pathological cases with large numbers of basic blocks.
413 AvoidNewBlocks = F->size() > 1000;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +0000414 }
Eugene Zelenkofce43572017-10-21 00:57:46 +0000415
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000416 Value *getArgTLSPtr();
417 Value *getArgTLS(unsigned Index, Instruction *Pos);
418 Value *getRetvalTLS();
419 Value *getShadow(Value *V);
420 void setShadow(Instruction *I, Value *Shadow);
Peter Collingbourne83def1c2014-07-15 04:41:14 +0000421 Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000422 Value *combineOperandShadows(Instruction *Inst);
423 Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
424 Instruction *Pos);
425 void storeShadow(Value *Addr, uint64_t Size, uint64_t Align, Value *Shadow,
426 Instruction *Pos);
427};
428
429class DFSanVisitor : public InstVisitor<DFSanVisitor> {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000430public:
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000431 DFSanFunction &DFSF;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000432
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000433 DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
434
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000435 const DataLayout &getDataLayout() const {
436 return DFSF.F->getParent()->getDataLayout();
437 }
438
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000439 void visitOperandShadowInst(Instruction &I);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000440 void visitBinaryOperator(BinaryOperator &BO);
441 void visitCastInst(CastInst &CI);
442 void visitCmpInst(CmpInst &CI);
443 void visitGetElementPtrInst(GetElementPtrInst &GEPI);
444 void visitLoadInst(LoadInst &LI);
445 void visitStoreInst(StoreInst &SI);
446 void visitReturnInst(ReturnInst &RI);
447 void visitCallSite(CallSite CS);
448 void visitPHINode(PHINode &PN);
449 void visitExtractElementInst(ExtractElementInst &I);
450 void visitInsertElementInst(InsertElementInst &I);
451 void visitShuffleVectorInst(ShuffleVectorInst &I);
452 void visitExtractValueInst(ExtractValueInst &I);
453 void visitInsertValueInst(InsertValueInst &I);
454 void visitAllocaInst(AllocaInst &I);
455 void visitSelectInst(SelectInst &I);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000456 void visitMemSetInst(MemSetInst &I);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000457 void visitMemTransferInst(MemTransferInst &I);
458};
459
Eugene Zelenkofce43572017-10-21 00:57:46 +0000460} // end anonymous namespace
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000461
462char DataFlowSanitizer::ID;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000463
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000464INITIALIZE_PASS(DataFlowSanitizer, "dfsan",
465 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
466
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000467ModulePass *
468llvm::createDataFlowSanitizerPass(const std::vector<std::string> &ABIListFiles,
469 void *(*getArgTLS)(),
470 void *(*getRetValTLS)()) {
471 return new DataFlowSanitizer(ABIListFiles, getArgTLS, getRetValTLS);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000472}
473
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000474DataFlowSanitizer::DataFlowSanitizer(
475 const std::vector<std::string> &ABIListFiles, void *(*getArgTLS)(),
476 void *(*getRetValTLS)())
Eugene Zelenkofce43572017-10-21 00:57:46 +0000477 : ModulePass(ID), GetArgTLSPtr(getArgTLS), GetRetvalTLSPtr(getRetValTLS) {
Alexey Samsonovb9b80272015-02-04 17:39:48 +0000478 std::vector<std::string> AllABIListFiles(std::move(ABIListFiles));
479 AllABIListFiles.insert(AllABIListFiles.end(), ClABIListFiles.begin(),
480 ClABIListFiles.end());
481 ABIList.set(SpecialCaseList::createOrDie(AllABIListFiles));
Peter Collingbourne68162e72013-08-14 18:54:12 +0000482}
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000483
Peter Collingbourne68162e72013-08-14 18:54:12 +0000484FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000485 SmallVector<Type *, 4> ArgTypes(T->param_begin(), T->param_end());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000486 ArgTypes.append(T->getNumParams(), ShadowTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000487 if (T->isVarArg())
488 ArgTypes.push_back(ShadowPtrTy);
489 Type *RetType = T->getReturnType();
490 if (!RetType->isVoidTy())
Serge Gueltone38003f2017-05-09 19:31:13 +0000491 RetType = StructType::get(RetType, ShadowTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000492 return FunctionType::get(RetType, ArgTypes, T->isVarArg());
493}
494
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000495FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) {
496 assert(!T->isVarArg());
Eugene Zelenkofce43572017-10-21 00:57:46 +0000497 SmallVector<Type *, 4> ArgTypes;
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000498 ArgTypes.push_back(T->getPointerTo());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000499 ArgTypes.append(T->param_begin(), T->param_end());
500 ArgTypes.append(T->getNumParams(), ShadowTy);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000501 Type *RetType = T->getReturnType();
502 if (!RetType->isVoidTy())
503 ArgTypes.push_back(ShadowPtrTy);
504 return FunctionType::get(T->getReturnType(), ArgTypes, false);
505}
506
Peter Collingbourne32f54052018-02-22 19:09:07 +0000507TransformedFunction DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000508 SmallVector<Type *, 4> ArgTypes;
Peter Collingbourne32f54052018-02-22 19:09:07 +0000509
510 // Some parameters of the custom function being constructed are
511 // parameters of T. Record the mapping from parameters of T to
512 // parameters of the custom function, so that parameter attributes
513 // at call sites can be updated.
514 std::vector<unsigned> ArgumentIndexMapping;
515 for (unsigned i = 0, ie = T->getNumParams(); i != ie; ++i) {
516 Type* param_type = T->getParamType(i);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000517 FunctionType *FT;
Peter Collingbourne32f54052018-02-22 19:09:07 +0000518 if (isa<PointerType>(param_type) && (FT = dyn_cast<FunctionType>(
519 cast<PointerType>(param_type)->getElementType()))) {
520 ArgumentIndexMapping.push_back(ArgTypes.size());
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000521 ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo());
522 ArgTypes.push_back(Type::getInt8PtrTy(*Ctx));
523 } else {
Peter Collingbourne32f54052018-02-22 19:09:07 +0000524 ArgumentIndexMapping.push_back(ArgTypes.size());
525 ArgTypes.push_back(param_type);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000526 }
527 }
Peter Collingbourne68162e72013-08-14 18:54:12 +0000528 for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
529 ArgTypes.push_back(ShadowTy);
Peter Collingbournedd3486e2014-10-30 13:22:57 +0000530 if (T->isVarArg())
531 ArgTypes.push_back(ShadowPtrTy);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000532 Type *RetType = T->getReturnType();
533 if (!RetType->isVoidTy())
534 ArgTypes.push_back(ShadowPtrTy);
Peter Collingbourne32f54052018-02-22 19:09:07 +0000535 return TransformedFunction(
536 T, FunctionType::get(T->getReturnType(), ArgTypes, T->isVarArg()),
537 ArgumentIndexMapping);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000538}
539
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000540bool DataFlowSanitizer::doInitialization(Module &M) {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000541 Triple TargetTriple(M.getTargetTriple());
542 bool IsX86_64 = TargetTriple.getArch() == Triple::x86_64;
Alexander Richardson85e200e2018-06-25 16:49:20 +0000543 bool IsMIPS64 = TargetTriple.isMIPS64();
Eugene Zelenkofce43572017-10-21 00:57:46 +0000544 bool IsAArch64 = TargetTriple.getArch() == Triple::aarch64 ||
545 TargetTriple.getArch() == Triple::aarch64_be;
Peter Collingbourne0826e602014-12-05 21:22:32 +0000546
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000547 const DataLayout &DL = M.getDataLayout();
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000548
549 Mod = &M;
550 Ctx = &M.getContext();
551 ShadowTy = IntegerType::get(*Ctx, ShadowWidth);
552 ShadowPtrTy = PointerType::getUnqual(ShadowTy);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000553 IntptrTy = DL.getIntPtrType(*Ctx);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000554 ZeroShadow = ConstantInt::getSigned(ShadowTy, 0);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000555 ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidth / 8);
Peter Collingbourne0826e602014-12-05 21:22:32 +0000556 if (IsX86_64)
557 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
558 else if (IsMIPS64)
559 ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0xF000000000LL);
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +0000560 // AArch64 supports multiple VMAs and the shadow mask is set at runtime.
Adhemerval Zanellabfe1eaf2015-07-30 20:49:35 +0000561 else if (IsAArch64)
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +0000562 DFSanRuntimeShadowMask = true;
Peter Collingbourne0826e602014-12-05 21:22:32 +0000563 else
564 report_fatal_error("unsupported triple");
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000565
566 Type *DFSanUnionArgs[2] = { ShadowTy, ShadowTy };
567 DFSanUnionFnTy =
568 FunctionType::get(ShadowTy, DFSanUnionArgs, /*isVarArg=*/ false);
569 Type *DFSanUnionLoadArgs[2] = { ShadowPtrTy, IntptrTy };
570 DFSanUnionLoadFnTy =
571 FunctionType::get(ShadowTy, DFSanUnionLoadArgs, /*isVarArg=*/ false);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000572 DFSanUnimplementedFnTy = FunctionType::get(
573 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000574 Type *DFSanSetLabelArgs[3] = { ShadowTy, Type::getInt8PtrTy(*Ctx), IntptrTy };
575 DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
576 DFSanSetLabelArgs, /*isVarArg=*/false);
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000577 DFSanNonzeroLabelFnTy = FunctionType::get(
Craig Toppere1d12942014-08-27 05:25:25 +0000578 Type::getVoidTy(*Ctx), None, /*isVarArg=*/false);
Peter Collingbournea1099842014-11-05 17:21:00 +0000579 DFSanVarargWrapperFnTy = FunctionType::get(
580 Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000581
582 if (GetArgTLSPtr) {
583 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
Craig Topperf40110f2014-04-25 05:29:35 +0000584 ArgTLS = nullptr;
James Y Knight7976eb52019-02-01 20:43:25 +0000585 GetArgTLSTy = FunctionType::get(PointerType::getUnqual(ArgTLSTy), false);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000586 GetArgTLS = ConstantExpr::getIntToPtr(
587 ConstantInt::get(IntptrTy, uintptr_t(GetArgTLSPtr)),
James Y Knight7976eb52019-02-01 20:43:25 +0000588 PointerType::getUnqual(GetArgTLSTy));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000589 }
590 if (GetRetvalTLSPtr) {
Craig Topperf40110f2014-04-25 05:29:35 +0000591 RetvalTLS = nullptr;
James Y Knight7976eb52019-02-01 20:43:25 +0000592 GetRetvalTLSTy = FunctionType::get(PointerType::getUnqual(ShadowTy), false);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000593 GetRetvalTLS = ConstantExpr::getIntToPtr(
594 ConstantInt::get(IntptrTy, uintptr_t(GetRetvalTLSPtr)),
James Y Knight7976eb52019-02-01 20:43:25 +0000595 PointerType::getUnqual(GetRetvalTLSTy));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000596 }
597
598 ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
599 return true;
600}
601
Peter Collingbourne59b12622013-08-22 20:08:08 +0000602bool DataFlowSanitizer::isInstrumented(const Function *F) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000603 return !ABIList.isIn(*F, "uninstrumented");
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000604}
605
Peter Collingbourne59b12622013-08-22 20:08:08 +0000606bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000607 return !ABIList.isIn(*GA, "uninstrumented");
Peter Collingbourne59b12622013-08-22 20:08:08 +0000608}
609
Peter Collingbourne68162e72013-08-14 18:54:12 +0000610DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000611 return ClArgsABI ? IA_Args : IA_TLS;
612}
613
Peter Collingbourne68162e72013-08-14 18:54:12 +0000614DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000615 if (ABIList.isIn(*F, "functional"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000616 return WK_Functional;
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000617 if (ABIList.isIn(*F, "discard"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000618 return WK_Discard;
Lorenzo Martignoni40d3dee2014-09-30 12:33:16 +0000619 if (ABIList.isIn(*F, "custom"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000620 return WK_Custom;
621
622 return WK_Warning;
623}
624
Peter Collingbourne59b12622013-08-22 20:08:08 +0000625void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
626 std::string GVName = GV->getName(), Prefix = "dfs$";
627 GV->setName(Prefix + GVName);
628
629 // Try to change the name of the function in module inline asm. We only do
630 // this for specific asm directives, currently only ".symver", to try to avoid
631 // corrupting asm which happens to contain the symbol name as a substring.
632 // Note that the substitution for .symver assumes that the versioned symbol
633 // also has an instrumented name.
634 std::string Asm = GV->getParent()->getModuleInlineAsm();
635 std::string SearchStr = ".symver " + GVName + ",";
636 size_t Pos = Asm.find(SearchStr);
637 if (Pos != std::string::npos) {
638 Asm.replace(Pos, SearchStr.size(),
639 ".symver " + Prefix + GVName + "," + Prefix);
640 GV->getParent()->setModuleInlineAsm(Asm);
641 }
642}
643
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000644Function *
645DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
646 GlobalValue::LinkageTypes NewFLink,
647 FunctionType *NewFT) {
648 FunctionType *FT = F->getFunctionType();
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +0000649 Function *NewF = Function::Create(NewFT, NewFLink, F->getAddressSpace(),
650 NewFName, F->getParent());
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000651 NewF->copyAttributesFrom(F);
652 NewF->removeAttributes(
Reid Klecknerb5180542017-03-21 16:57:19 +0000653 AttributeList::ReturnIndex,
Reid Kleckneree4930b2017-05-02 22:07:37 +0000654 AttributeFuncs::typeIncompatible(NewFT->getReturnType()));
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000655
656 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
Peter Collingbournea1099842014-11-05 17:21:00 +0000657 if (F->isVarArg()) {
Reid Kleckneree4930b2017-05-02 22:07:37 +0000658 NewF->removeAttributes(AttributeList::FunctionIndex,
659 AttrBuilder().addAttribute("split-stack"));
Peter Collingbournea1099842014-11-05 17:21:00 +0000660 CallInst::Create(DFSanVarargWrapperFn,
661 IRBuilder<>(BB).CreateGlobalStringPtr(F->getName()), "",
662 BB);
663 new UnreachableInst(*Ctx, BB);
664 } else {
665 std::vector<Value *> Args;
666 unsigned n = FT->getNumParams();
667 for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
668 Args.push_back(&*ai);
669 CallInst *CI = CallInst::Create(F, Args, "", BB);
670 if (FT->getReturnType()->isVoidTy())
671 ReturnInst::Create(*Ctx, BB);
672 else
673 ReturnInst::Create(*Ctx, CI, BB);
674 }
Peter Collingbourne761a4fc2013-08-22 20:08:11 +0000675
676 return NewF;
677}
678
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000679Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
680 StringRef FName) {
681 FunctionType *FTT = getTrampolineFunctionType(FT);
James Y Knight13680222019-02-01 02:28:03 +0000682 FunctionCallee C = Mod->getOrInsertFunction(FName, FTT);
683 Function *F = dyn_cast<Function>(C.getCallee());
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000684 if (F && F->isDeclaration()) {
685 F->setLinkage(GlobalValue::LinkOnceODRLinkage);
686 BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
687 std::vector<Value *> Args;
688 Function::arg_iterator AI = F->arg_begin(); ++AI;
689 for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
690 Args.push_back(&*AI);
James Y Knight7976eb52019-02-01 20:43:25 +0000691 CallInst *CI = CallInst::Create(FT, &*F->arg_begin(), Args, "", BB);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000692 ReturnInst *RI;
693 if (FT->getReturnType()->isVoidTy())
694 RI = ReturnInst::Create(*Ctx, BB);
695 else
696 RI = ReturnInst::Create(*Ctx, CI, BB);
697
698 DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
699 Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI;
700 for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N)
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000701 DFSF.ValShadowMap[&*ValAI] = &*ShadowAI;
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000702 DFSanVisitor(DFSF).visitCallInst(*CI);
703 if (!FT->getReturnType()->isVoidTy())
704 new StoreInst(DFSF.getShadow(RI->getReturnValue()),
Reid Kleckner45707d42017-03-16 22:59:15 +0000705 &*std::prev(F->arg_end()), RI);
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000706 }
707
James Y Knight13680222019-02-01 02:28:03 +0000708 return cast<Constant>(C.getCallee());
Peter Collingbourne28a10af2013-08-27 22:09:06 +0000709}
710
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000711bool DataFlowSanitizer::runOnModule(Module &M) {
Alexey Samsonovb7dd3292014-07-09 19:40:08 +0000712 if (ABIList.isIn(M, "skip"))
Peter Collingbourne68162e72013-08-14 18:54:12 +0000713 return false;
714
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000715 if (!GetArgTLSPtr) {
716 Type *ArgTLSTy = ArrayType::get(ShadowTy, 64);
717 ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
718 if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS))
719 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
720 }
721 if (!GetRetvalTLSPtr) {
722 RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", ShadowTy);
723 if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS))
724 G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
725 }
726
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +0000727 ExternalShadowMask =
728 Mod->getOrInsertGlobal(kDFSanExternShadowPtrMask, IntptrTy);
729
James Y Knight13680222019-02-01 02:28:03 +0000730 {
731 AttributeList AL;
732 AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
733 Attribute::NoUnwind);
734 AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
735 Attribute::ReadNone);
736 AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
737 Attribute::ZExt);
738 AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
739 AL = AL.addParamAttribute(M.getContext(), 1, Attribute::ZExt);
740 DFSanUnionFn =
741 Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy, AL);
Peter Collingbournedf240b22014-08-06 00:33:40 +0000742 }
James Y Knight13680222019-02-01 02:28:03 +0000743
744 {
745 AttributeList AL;
746 AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
747 Attribute::NoUnwind);
748 AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
749 Attribute::ReadNone);
750 AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
751 Attribute::ZExt);
752 AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
753 AL = AL.addParamAttribute(M.getContext(), 1, Attribute::ZExt);
754 DFSanCheckedUnionFn =
755 Mod->getOrInsertFunction("dfsan_union", DFSanUnionFnTy, AL);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000756 }
James Y Knight13680222019-02-01 02:28:03 +0000757 {
758 AttributeList AL;
759 AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
760 Attribute::NoUnwind);
761 AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
762 Attribute::ReadOnly);
763 AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
764 Attribute::ZExt);
765 DFSanUnionLoadFn =
766 Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy, AL);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000767 }
Peter Collingbourne68162e72013-08-14 18:54:12 +0000768 DFSanUnimplementedFn =
769 Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
James Y Knight13680222019-02-01 02:28:03 +0000770 {
771 AttributeList AL;
772 AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
773 DFSanSetLabelFn =
774 Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy, AL);
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +0000775 }
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000776 DFSanNonzeroLabelFn =
777 Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
Peter Collingbournea1099842014-11-05 17:21:00 +0000778 DFSanVarargWrapperFn = Mod->getOrInsertFunction("__dfsan_vararg_wrapper",
779 DFSanVarargWrapperFnTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000780
781 std::vector<Function *> FnsToInstrument;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000782 SmallPtrSet<Function *, 2> FnsWithNativeABI;
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000783 for (Function &i : M) {
784 if (!i.isIntrinsic() &&
James Y Knight13680222019-02-01 02:28:03 +0000785 &i != DFSanUnionFn.getCallee()->stripPointerCasts() &&
786 &i != DFSanCheckedUnionFn.getCallee()->stripPointerCasts() &&
787 &i != DFSanUnionLoadFn.getCallee()->stripPointerCasts() &&
788 &i != DFSanUnimplementedFn.getCallee()->stripPointerCasts() &&
789 &i != DFSanSetLabelFn.getCallee()->stripPointerCasts() &&
790 &i != DFSanNonzeroLabelFn.getCallee()->stripPointerCasts() &&
791 &i != DFSanVarargWrapperFn.getCallee()->stripPointerCasts())
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000792 FnsToInstrument.push_back(&i);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000793 }
794
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000795 // Give function aliases prefixes when necessary, and build wrappers where the
796 // instrumentedness is inconsistent.
Peter Collingbourne59b12622013-08-22 20:08:08 +0000797 for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
798 GlobalAlias *GA = &*i;
799 ++i;
800 // Don't stop on weak. We assume people aren't playing games with the
801 // instrumentedness of overridden weak aliases.
Peter Collingbourne2e28edf2014-07-10 01:30:39 +0000802 if (auto F = dyn_cast<Function>(GA->getBaseObject())) {
Peter Collingbourne59b12622013-08-22 20:08:08 +0000803 bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
804 if (GAInst && FInst) {
805 addGlobalNamePrefix(GA);
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000806 } else if (GAInst != FInst) {
807 // Non-instrumented alias of an instrumented function, or vice versa.
808 // Replace the alias with a native-ABI wrapper of the aliasee. The pass
809 // below will take care of instrumenting it.
810 Function *NewF =
811 buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
Peter Collingbourne2e28edf2014-07-10 01:30:39 +0000812 GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType()));
Peter Collingbourne34f0c312013-08-22 20:08:15 +0000813 NewF->takeName(GA);
814 GA->eraseFromParent();
815 FnsToInstrument.push_back(NewF);
Peter Collingbourne59b12622013-08-22 20:08:08 +0000816 }
817 }
818 }
819
Reid Kleckneree4930b2017-05-02 22:07:37 +0000820 ReadOnlyNoneAttrs.addAttribute(Attribute::ReadOnly)
821 .addAttribute(Attribute::ReadNone);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000822
823 // First, change the ABI of every function in the module. ABI-listed
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000824 // functions keep their original ABI and get a wrapper function.
825 for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
826 e = FnsToInstrument.end();
827 i != e; ++i) {
828 Function &F = **i;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000829 FunctionType *FT = F.getFunctionType();
Peter Collingbourne68162e72013-08-14 18:54:12 +0000830
Peter Collingbourne59b12622013-08-22 20:08:08 +0000831 bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
832 FT->getReturnType()->isVoidTy());
Peter Collingbourne68162e72013-08-14 18:54:12 +0000833
834 if (isInstrumented(&F)) {
Peter Collingbourne59b12622013-08-22 20:08:08 +0000835 // Instrumented functions get a 'dfs$' prefix. This allows us to more
836 // easily identify cases of mismatching ABIs.
837 if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000838 FunctionType *NewFT = getArgsFunctionType(FT);
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +0000839 Function *NewF = Function::Create(NewFT, F.getLinkage(),
840 F.getAddressSpace(), "", &M);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000841 NewF->copyAttributesFrom(&F);
842 NewF->removeAttributes(
Reid Klecknerb5180542017-03-21 16:57:19 +0000843 AttributeList::ReturnIndex,
Reid Kleckneree4930b2017-05-02 22:07:37 +0000844 AttributeFuncs::typeIncompatible(NewFT->getReturnType()));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000845 for (Function::arg_iterator FArg = F.arg_begin(),
846 NewFArg = NewF->arg_begin(),
847 FArgEnd = F.arg_end();
848 FArg != FArgEnd; ++FArg, ++NewFArg) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000849 FArg->replaceAllUsesWith(&*NewFArg);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000850 }
851 NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
852
Chandler Carruthcdf47882014-03-09 03:16:01 +0000853 for (Function::user_iterator UI = F.user_begin(), UE = F.user_end();
854 UI != UE;) {
855 BlockAddress *BA = dyn_cast<BlockAddress>(*UI);
856 ++UI;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000857 if (BA) {
858 BA->replaceAllUsesWith(
859 BlockAddress::get(NewF, BA->getBasicBlock()));
860 delete BA;
861 }
862 }
863 F.replaceAllUsesWith(
864 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
865 NewF->takeName(&F);
866 F.eraseFromParent();
867 *i = NewF;
Peter Collingbourne59b12622013-08-22 20:08:08 +0000868 addGlobalNamePrefix(NewF);
869 } else {
870 addGlobalNamePrefix(&F);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000871 }
Peter Collingbourne59b12622013-08-22 20:08:08 +0000872 } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
Peter Collingbourne68162e72013-08-14 18:54:12 +0000873 // Build a wrapper function for F. The wrapper simply calls F, and is
874 // added to FnsToInstrument so that any instrumentation according to its
875 // WrapperKind is done in the second pass below.
876 FunctionType *NewFT = getInstrumentedABI() == IA_Args
877 ? getArgsFunctionType(FT)
878 : FT;
Peter Collingbourned03bf122018-03-30 18:37:55 +0000879
880 // If the function being wrapped has local linkage, then preserve the
881 // function's linkage in the wrapper function.
882 GlobalValue::LinkageTypes wrapperLinkage =
883 F.hasLocalLinkage()
884 ? F.getLinkage()
885 : GlobalValue::LinkOnceODRLinkage;
886
Alexey Samsonov6dae24d2013-08-23 07:42:51 +0000887 Function *NewF = buildWrapperFunction(
888 &F, std::string("dfsw$") + std::string(F.getName()),
Peter Collingbourned03bf122018-03-30 18:37:55 +0000889 wrapperLinkage, NewFT);
Peter Collingbourne68162e72013-08-14 18:54:12 +0000890 if (getInstrumentedABI() == IA_TLS)
Reid Klecknerb5180542017-03-21 16:57:19 +0000891 NewF->removeAttributes(AttributeList::FunctionIndex, ReadOnlyNoneAttrs);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000892
Peter Collingbourne68162e72013-08-14 18:54:12 +0000893 Value *WrappedFnCst =
894 ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
895 F.replaceAllUsesWith(WrappedFnCst);
David Blaikiec6c6c7b2014-10-07 22:59:46 +0000896
Peter Collingbourne68162e72013-08-14 18:54:12 +0000897 UnwrappedFnMap[WrappedFnCst] = &F;
898 *i = NewF;
899
900 if (!F.isDeclaration()) {
901 // This function is probably defining an interposition of an
902 // uninstrumented function and hence needs to keep the original ABI.
903 // But any functions it may call need to use the instrumented ABI, so
904 // we instrument it in a mode which preserves the original ABI.
905 FnsWithNativeABI.insert(&F);
906
907 // This code needs to rebuild the iterators, as they may be invalidated
908 // by the push_back, taking care that the new range does not include
909 // any functions added by this code.
910 size_t N = i - FnsToInstrument.begin(),
911 Count = e - FnsToInstrument.begin();
912 FnsToInstrument.push_back(&F);
913 i = FnsToInstrument.begin() + N;
914 e = FnsToInstrument.begin() + Count;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000915 }
Lorenzo Martignoni40d3dee2014-09-30 12:33:16 +0000916 // Hopefully, nobody will try to indirectly call a vararg
917 // function... yet.
918 } else if (FT->isVarArg()) {
919 UnwrappedFnMap[&F] = &F;
920 *i = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000921 }
922 }
923
Benjamin Kramer135f7352016-06-26 12:28:59 +0000924 for (Function *i : FnsToInstrument) {
925 if (!i || i->isDeclaration())
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000926 continue;
927
Benjamin Kramer135f7352016-06-26 12:28:59 +0000928 removeUnreachableBlocks(*i);
Peter Collingbourneae66d572013-08-09 21:42:53 +0000929
Benjamin Kramer135f7352016-06-26 12:28:59 +0000930 DFSanFunction DFSF(*this, i, FnsWithNativeABI.count(i));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000931
932 // DFSanVisitor may create new basic blocks, which confuses df_iterator.
933 // Build a copy of the list before iterating over it.
Eugene Zelenkofce43572017-10-21 00:57:46 +0000934 SmallVector<BasicBlock *, 4> BBList(depth_first(&i->getEntryBlock()));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000935
Benjamin Kramer135f7352016-06-26 12:28:59 +0000936 for (BasicBlock *i : BBList) {
937 Instruction *Inst = &i->front();
Eugene Zelenkofce43572017-10-21 00:57:46 +0000938 while (true) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000939 // DFSanVisitor may split the current basic block, changing the current
940 // instruction's next pointer and moving the next instruction to the
941 // tail block from which we should continue.
942 Instruction *Next = Inst->getNextNode();
Peter Collingbournefb3a2b42013-08-12 22:38:39 +0000943 // DFSanVisitor may delete Inst, so keep track of whether it was a
944 // terminator.
Chandler Carruth9ae926b2018-08-26 09:51:22 +0000945 bool IsTerminator = Inst->isTerminator();
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000946 if (!DFSF.SkipInsts.count(Inst))
947 DFSanVisitor(DFSF).visit(Inst);
Peter Collingbournefb3a2b42013-08-12 22:38:39 +0000948 if (IsTerminator)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000949 break;
950 Inst = Next;
951 }
952 }
953
Peter Collingbourne68162e72013-08-14 18:54:12 +0000954 // We will not necessarily be able to compute the shadow for every phi node
955 // until we have visited every block. Therefore, the code that handles phi
956 // nodes adds them to the PHIFixups list so that they can be properly
957 // handled here.
Eugene Zelenkofce43572017-10-21 00:57:46 +0000958 for (std::vector<std::pair<PHINode *, PHINode *>>::iterator
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000959 i = DFSF.PHIFixups.begin(),
960 e = DFSF.PHIFixups.end();
961 i != e; ++i) {
962 for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
963 ++val) {
964 i->second->setIncomingValue(
965 val, DFSF.getShadow(i->first->getIncomingValue(val)));
966 }
967 }
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000968
969 // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
970 // places (i.e. instructions in basic blocks we haven't even begun visiting
971 // yet). To make our life easier, do this work in a pass after the main
972 // instrumentation.
973 if (ClDebugNonzeroLabels) {
Peter Collingbournefab565a2014-08-22 01:18:18 +0000974 for (Value *V : DFSF.NonZeroChecks) {
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000975 Instruction *Pos;
Peter Collingbournefab565a2014-08-22 01:18:18 +0000976 if (Instruction *I = dyn_cast<Instruction>(V))
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000977 Pos = I->getNextNode();
978 else
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000979 Pos = &DFSF.F->getEntryBlock().front();
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000980 while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
981 Pos = Pos->getNextNode();
982 IRBuilder<> IRB(Pos);
Peter Collingbournefab565a2014-08-22 01:18:18 +0000983 Value *Ne = IRB.CreateICmpNE(V, DFSF.DFS.ZeroShadow);
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000984 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000985 Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000986 IRBuilder<> ThenIRB(BI);
David Blaikieff6409d2015-05-18 22:13:54 +0000987 ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn, {});
Peter Collingbourne444c59e2013-08-15 18:51:12 +0000988 }
989 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +0000990 }
991
992 return false;
993}
994
995Value *DFSanFunction::getArgTLSPtr() {
996 if (ArgTLSPtr)
997 return ArgTLSPtr;
998 if (DFS.ArgTLS)
999 return ArgTLSPtr = DFS.ArgTLS;
1000
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001001 IRBuilder<> IRB(&F->getEntryBlock().front());
James Y Knight7976eb52019-02-01 20:43:25 +00001002 return ArgTLSPtr = IRB.CreateCall(DFS.GetArgTLSTy, DFS.GetArgTLS, {});
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001003}
1004
1005Value *DFSanFunction::getRetvalTLS() {
1006 if (RetvalTLSPtr)
1007 return RetvalTLSPtr;
1008 if (DFS.RetvalTLS)
1009 return RetvalTLSPtr = DFS.RetvalTLS;
1010
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001011 IRBuilder<> IRB(&F->getEntryBlock().front());
James Y Knight7976eb52019-02-01 20:43:25 +00001012 return RetvalTLSPtr =
1013 IRB.CreateCall(DFS.GetRetvalTLSTy, DFS.GetRetvalTLS, {});
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001014}
1015
1016Value *DFSanFunction::getArgTLS(unsigned Idx, Instruction *Pos) {
1017 IRBuilder<> IRB(Pos);
James Y Knight77160752019-02-01 20:44:47 +00001018 return IRB.CreateConstGEP2_64(ArrayType::get(DFS.ShadowTy, 64),
1019 getArgTLSPtr(), 0, Idx);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001020}
1021
1022Value *DFSanFunction::getShadow(Value *V) {
1023 if (!isa<Argument>(V) && !isa<Instruction>(V))
1024 return DFS.ZeroShadow;
1025 Value *&Shadow = ValShadowMap[V];
1026 if (!Shadow) {
1027 if (Argument *A = dyn_cast<Argument>(V)) {
Peter Collingbourne68162e72013-08-14 18:54:12 +00001028 if (IsNativeABI)
1029 return DFS.ZeroShadow;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001030 switch (IA) {
1031 case DataFlowSanitizer::IA_TLS: {
1032 Value *ArgTLSPtr = getArgTLSPtr();
1033 Instruction *ArgTLSPos =
1034 DFS.ArgTLS ? &*F->getEntryBlock().begin()
1035 : cast<Instruction>(ArgTLSPtr)->getNextNode();
1036 IRBuilder<> IRB(ArgTLSPos);
James Y Knight14359ef2019-02-01 20:44:24 +00001037 Shadow =
1038 IRB.CreateLoad(DFS.ShadowTy, getArgTLS(A->getArgNo(), ArgTLSPos));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001039 break;
1040 }
1041 case DataFlowSanitizer::IA_Args: {
Reid Kleckner45707d42017-03-16 22:59:15 +00001042 unsigned ArgIdx = A->getArgNo() + F->arg_size() / 2;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001043 Function::arg_iterator i = F->arg_begin();
1044 while (ArgIdx--)
1045 ++i;
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001046 Shadow = &*i;
Peter Collingbourne68162e72013-08-14 18:54:12 +00001047 assert(Shadow->getType() == DFS.ShadowTy);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001048 break;
1049 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001050 }
Peter Collingbournefab565a2014-08-22 01:18:18 +00001051 NonZeroChecks.push_back(Shadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001052 } else {
1053 Shadow = DFS.ZeroShadow;
1054 }
1055 }
1056 return Shadow;
1057}
1058
1059void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
1060 assert(!ValShadowMap.count(I));
1061 assert(Shadow->getType() == DFS.ShadowTy);
1062 ValShadowMap[I] = Shadow;
1063}
1064
1065Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
1066 assert(Addr != RetvalTLS && "Reinstrumenting?");
1067 IRBuilder<> IRB(Pos);
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +00001068 Value *ShadowPtrMaskValue;
1069 if (DFSanRuntimeShadowMask)
1070 ShadowPtrMaskValue = IRB.CreateLoad(IntptrTy, ExternalShadowMask);
1071 else
1072 ShadowPtrMaskValue = ShadowPtrMask;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001073 return IRB.CreateIntToPtr(
1074 IRB.CreateMul(
Adhemerval Zanellad93c0c42015-11-27 12:42:39 +00001075 IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy),
1076 IRB.CreatePtrToInt(ShadowPtrMaskValue, IntptrTy)),
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001077 ShadowPtrMul),
1078 ShadowPtrTy);
1079}
1080
1081// Generates IR to compute the union of the two given shadows, inserting it
1082// before Pos. Returns the computed union Value.
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001083Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) {
1084 if (V1 == DFS.ZeroShadow)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001085 return V2;
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001086 if (V2 == DFS.ZeroShadow)
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001087 return V1;
1088 if (V1 == V2)
1089 return V1;
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001090
Peter Collingbourne9947c492014-07-15 22:13:19 +00001091 auto V1Elems = ShadowElements.find(V1);
1092 auto V2Elems = ShadowElements.find(V2);
1093 if (V1Elems != ShadowElements.end() && V2Elems != ShadowElements.end()) {
1094 if (std::includes(V1Elems->second.begin(), V1Elems->second.end(),
1095 V2Elems->second.begin(), V2Elems->second.end())) {
1096 return V1;
1097 } else if (std::includes(V2Elems->second.begin(), V2Elems->second.end(),
1098 V1Elems->second.begin(), V1Elems->second.end())) {
1099 return V2;
1100 }
1101 } else if (V1Elems != ShadowElements.end()) {
1102 if (V1Elems->second.count(V2))
1103 return V1;
1104 } else if (V2Elems != ShadowElements.end()) {
1105 if (V2Elems->second.count(V1))
1106 return V2;
1107 }
1108
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001109 auto Key = std::make_pair(V1, V2);
1110 if (V1 > V2)
1111 std::swap(Key.first, Key.second);
1112 CachedCombinedShadow &CCS = CachedCombinedShadows[Key];
1113 if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent()))
1114 return CCS.Shadow;
1115
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001116 IRBuilder<> IRB(Pos);
Peter Collingbournedf240b22014-08-06 00:33:40 +00001117 if (AvoidNewBlocks) {
David Blaikieff6409d2015-05-18 22:13:54 +00001118 CallInst *Call = IRB.CreateCall(DFS.DFSanCheckedUnionFn, {V1, V2});
Reid Klecknerb5180542017-03-21 16:57:19 +00001119 Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
Reid Klecknera0b45f42017-05-03 18:17:31 +00001120 Call->addParamAttr(0, Attribute::ZExt);
1121 Call->addParamAttr(1, Attribute::ZExt);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001122
Peter Collingbournedf240b22014-08-06 00:33:40 +00001123 CCS.Block = Pos->getParent();
1124 CCS.Shadow = Call;
1125 } else {
1126 BasicBlock *Head = Pos->getParent();
1127 Value *Ne = IRB.CreateICmpNE(V1, V2);
1128 BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
1129 Ne, Pos, /*Unreachable=*/false, DFS.ColdCallWeights, &DT));
1130 IRBuilder<> ThenIRB(BI);
David Blaikieff6409d2015-05-18 22:13:54 +00001131 CallInst *Call = ThenIRB.CreateCall(DFS.DFSanUnionFn, {V1, V2});
Reid Klecknerb5180542017-03-21 16:57:19 +00001132 Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
Reid Klecknera0b45f42017-05-03 18:17:31 +00001133 Call->addParamAttr(0, Attribute::ZExt);
1134 Call->addParamAttr(1, Attribute::ZExt);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001135
Peter Collingbournedf240b22014-08-06 00:33:40 +00001136 BasicBlock *Tail = BI->getSuccessor(0);
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001137 PHINode *Phi = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
Peter Collingbournedf240b22014-08-06 00:33:40 +00001138 Phi->addIncoming(Call, Call->getParent());
1139 Phi->addIncoming(V1, Head);
1140
1141 CCS.Block = Tail;
1142 CCS.Shadow = Phi;
1143 }
Peter Collingbourne9947c492014-07-15 22:13:19 +00001144
1145 std::set<Value *> UnionElems;
1146 if (V1Elems != ShadowElements.end()) {
1147 UnionElems = V1Elems->second;
1148 } else {
1149 UnionElems.insert(V1);
1150 }
1151 if (V2Elems != ShadowElements.end()) {
1152 UnionElems.insert(V2Elems->second.begin(), V2Elems->second.end());
1153 } else {
1154 UnionElems.insert(V2);
1155 }
Peter Collingbournedf240b22014-08-06 00:33:40 +00001156 ShadowElements[CCS.Shadow] = std::move(UnionElems);
Peter Collingbourne9947c492014-07-15 22:13:19 +00001157
Peter Collingbournedf240b22014-08-06 00:33:40 +00001158 return CCS.Shadow;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001159}
1160
1161// A convenience function which folds the shadows of each of the operands
1162// of the provided instruction Inst, inserting the IR before Inst. Returns
1163// the computed union Value.
1164Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
1165 if (Inst->getNumOperands() == 0)
1166 return DFS.ZeroShadow;
1167
1168 Value *Shadow = getShadow(Inst->getOperand(0));
1169 for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001170 Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001171 }
1172 return Shadow;
1173}
1174
1175void DFSanVisitor::visitOperandShadowInst(Instruction &I) {
1176 Value *CombinedShadow = DFSF.combineOperandShadows(&I);
1177 DFSF.setShadow(&I, CombinedShadow);
1178}
1179
1180// Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
1181// Addr has alignment Align, and take the union of each of those shadows.
1182Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
1183 Instruction *Pos) {
1184 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
Eugene Zelenkofce43572017-10-21 00:57:46 +00001185 const auto i = AllocaShadowMap.find(AI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001186 if (i != AllocaShadowMap.end()) {
1187 IRBuilder<> IRB(Pos);
James Y Knight14359ef2019-02-01 20:44:24 +00001188 return IRB.CreateLoad(DFS.ShadowTy, i->second);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001189 }
1190 }
1191
1192 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +00001193 SmallVector<const Value *, 2> Objs;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001194 GetUnderlyingObjects(Addr, Objs, Pos->getModule()->getDataLayout());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001195 bool AllConstants = true;
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +00001196 for (const Value *Obj : Objs) {
Benjamin Kramer135f7352016-06-26 12:28:59 +00001197 if (isa<Function>(Obj) || isa<BlockAddress>(Obj))
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001198 continue;
Benjamin Kramer135f7352016-06-26 12:28:59 +00001199 if (isa<GlobalVariable>(Obj) && cast<GlobalVariable>(Obj)->isConstant())
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001200 continue;
1201
1202 AllConstants = false;
1203 break;
1204 }
1205 if (AllConstants)
1206 return DFS.ZeroShadow;
1207
1208 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1209 switch (Size) {
1210 case 0:
1211 return DFS.ZeroShadow;
1212 case 1: {
James Y Knight14359ef2019-02-01 20:44:24 +00001213 LoadInst *LI = new LoadInst(DFS.ShadowTy, ShadowAddr, "", Pos);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001214 LI->setAlignment(ShadowAlign);
1215 return LI;
1216 }
1217 case 2: {
1218 IRBuilder<> IRB(Pos);
David Blaikie93c54442015-04-03 19:41:44 +00001219 Value *ShadowAddr1 = IRB.CreateGEP(DFS.ShadowTy, ShadowAddr,
1220 ConstantInt::get(DFS.IntptrTy, 1));
James Y Knight14359ef2019-02-01 20:44:24 +00001221 return combineShadows(
1222 IRB.CreateAlignedLoad(DFS.ShadowTy, ShadowAddr, ShadowAlign),
1223 IRB.CreateAlignedLoad(DFS.ShadowTy, ShadowAddr1, ShadowAlign), Pos);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001224 }
1225 }
Peter Collingbournedf240b22014-08-06 00:33:40 +00001226 if (!AvoidNewBlocks && Size % (64 / DFS.ShadowWidth) == 0) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001227 // Fast path for the common case where each byte has identical shadow: load
1228 // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
1229 // shadow is non-equal.
1230 BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
1231 IRBuilder<> FallbackIRB(FallbackBB);
David Blaikieff6409d2015-05-18 22:13:54 +00001232 CallInst *FallbackCall = FallbackIRB.CreateCall(
1233 DFS.DFSanUnionLoadFn,
1234 {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
Reid Klecknerb5180542017-03-21 16:57:19 +00001235 FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001236
1237 // Compare each of the shadows stored in the loaded 64 bits to each other,
1238 // by computing (WideShadow rotl ShadowWidth) == WideShadow.
1239 IRBuilder<> IRB(Pos);
1240 Value *WideAddr =
1241 IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
James Y Knight14359ef2019-02-01 20:44:24 +00001242 Value *WideShadow =
1243 IRB.CreateAlignedLoad(IRB.getInt64Ty(), WideAddr, ShadowAlign);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001244 Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.ShadowTy);
1245 Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidth);
1246 Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidth);
1247 Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
1248 Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
1249
1250 BasicBlock *Head = Pos->getParent();
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001251 BasicBlock *Tail = Head->splitBasicBlock(Pos->getIterator());
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001252
1253 if (DomTreeNode *OldNode = DT.getNode(Head)) {
1254 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
1255
1256 DomTreeNode *NewNode = DT.addNewBlock(Tail, Head);
1257 for (auto Child : Children)
1258 DT.changeImmediateDominator(Child, NewNode);
1259 }
1260
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001261 // In the following code LastBr will refer to the previous basic block's
1262 // conditional branch instruction, whose true successor is fixed up to point
1263 // to the next block during the loop below or to the tail after the final
1264 // iteration.
1265 BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
1266 ReplaceInstWithInst(Head->getTerminator(), LastBr);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001267 DT.addNewBlock(FallbackBB, Head);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001268
1269 for (uint64_t Ofs = 64 / DFS.ShadowWidth; Ofs != Size;
1270 Ofs += 64 / DFS.ShadowWidth) {
1271 BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
Peter Collingbourne705a1ae2014-07-15 04:41:17 +00001272 DT.addNewBlock(NextBB, LastBr->getParent());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001273 IRBuilder<> NextIRB(NextBB);
David Blaikie93c54442015-04-03 19:41:44 +00001274 WideAddr = NextIRB.CreateGEP(Type::getInt64Ty(*DFS.Ctx), WideAddr,
1275 ConstantInt::get(DFS.IntptrTy, 1));
James Y Knight14359ef2019-02-01 20:44:24 +00001276 Value *NextWideShadow = NextIRB.CreateAlignedLoad(NextIRB.getInt64Ty(),
1277 WideAddr, ShadowAlign);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001278 ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
1279 LastBr->setSuccessor(0, NextBB);
1280 LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
1281 }
1282
1283 LastBr->setSuccessor(0, Tail);
1284 FallbackIRB.CreateBr(Tail);
1285 PHINode *Shadow = PHINode::Create(DFS.ShadowTy, 2, "", &Tail->front());
1286 Shadow->addIncoming(FallbackCall, FallbackBB);
1287 Shadow->addIncoming(TruncShadow, LastBr->getParent());
1288 return Shadow;
1289 }
1290
1291 IRBuilder<> IRB(Pos);
David Blaikieff6409d2015-05-18 22:13:54 +00001292 CallInst *FallbackCall = IRB.CreateCall(
1293 DFS.DFSanUnionLoadFn, {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
Reid Klecknerb5180542017-03-21 16:57:19 +00001294 FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001295 return FallbackCall;
1296}
1297
1298void DFSanVisitor::visitLoadInst(LoadInst &LI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001299 auto &DL = LI.getModule()->getDataLayout();
1300 uint64_t Size = DL.getTypeStoreSize(LI.getType());
Peter Collingbourne142fdff2014-08-01 21:18:18 +00001301 if (Size == 0) {
1302 DFSF.setShadow(&LI, DFSF.DFS.ZeroShadow);
1303 return;
1304 }
1305
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001306 uint64_t Align;
1307 if (ClPreserveAlignment) {
1308 Align = LI.getAlignment();
1309 if (Align == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001310 Align = DL.getABITypeAlignment(LI.getType());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001311 } else {
1312 Align = 1;
1313 }
1314 IRBuilder<> IRB(&LI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001315 Value *Shadow = DFSF.loadShadow(LI.getPointerOperand(), Size, Align, &LI);
1316 if (ClCombinePointerLabelsOnLoad) {
1317 Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001318 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &LI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001319 }
1320 if (Shadow != DFSF.DFS.ZeroShadow)
Peter Collingbournefab565a2014-08-22 01:18:18 +00001321 DFSF.NonZeroChecks.push_back(Shadow);
Peter Collingbourne444c59e2013-08-15 18:51:12 +00001322
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001323 DFSF.setShadow(&LI, Shadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001324}
1325
1326void DFSanFunction::storeShadow(Value *Addr, uint64_t Size, uint64_t Align,
1327 Value *Shadow, Instruction *Pos) {
1328 if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
Eugene Zelenkofce43572017-10-21 00:57:46 +00001329 const auto i = AllocaShadowMap.find(AI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001330 if (i != AllocaShadowMap.end()) {
1331 IRBuilder<> IRB(Pos);
1332 IRB.CreateStore(Shadow, i->second);
1333 return;
1334 }
1335 }
1336
1337 uint64_t ShadowAlign = Align * DFS.ShadowWidth / 8;
1338 IRBuilder<> IRB(Pos);
1339 Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1340 if (Shadow == DFS.ZeroShadow) {
1341 IntegerType *ShadowTy = IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidth);
1342 Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
1343 Value *ExtShadowAddr =
1344 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
1345 IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
1346 return;
1347 }
1348
1349 const unsigned ShadowVecSize = 128 / DFS.ShadowWidth;
1350 uint64_t Offset = 0;
1351 if (Size >= ShadowVecSize) {
1352 VectorType *ShadowVecTy = VectorType::get(DFS.ShadowTy, ShadowVecSize);
1353 Value *ShadowVec = UndefValue::get(ShadowVecTy);
1354 for (unsigned i = 0; i != ShadowVecSize; ++i) {
1355 ShadowVec = IRB.CreateInsertElement(
1356 ShadowVec, Shadow, ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
1357 }
1358 Value *ShadowVecAddr =
1359 IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
1360 do {
David Blaikie95d3e532015-04-03 23:03:54 +00001361 Value *CurShadowVecAddr =
1362 IRB.CreateConstGEP1_32(ShadowVecTy, ShadowVecAddr, Offset);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001363 IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
1364 Size -= ShadowVecSize;
1365 ++Offset;
1366 } while (Size >= ShadowVecSize);
1367 Offset *= ShadowVecSize;
1368 }
1369 while (Size > 0) {
David Blaikie95d3e532015-04-03 23:03:54 +00001370 Value *CurShadowAddr =
1371 IRB.CreateConstGEP1_32(DFS.ShadowTy, ShadowAddr, Offset);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001372 IRB.CreateAlignedStore(Shadow, CurShadowAddr, ShadowAlign);
1373 --Size;
1374 ++Offset;
1375 }
1376}
1377
1378void DFSanVisitor::visitStoreInst(StoreInst &SI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001379 auto &DL = SI.getModule()->getDataLayout();
1380 uint64_t Size = DL.getTypeStoreSize(SI.getValueOperand()->getType());
Peter Collingbourne142fdff2014-08-01 21:18:18 +00001381 if (Size == 0)
1382 return;
1383
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001384 uint64_t Align;
1385 if (ClPreserveAlignment) {
1386 Align = SI.getAlignment();
1387 if (Align == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001388 Align = DL.getABITypeAlignment(SI.getValueOperand()->getType());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001389 } else {
1390 Align = 1;
1391 }
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001392
1393 Value* Shadow = DFSF.getShadow(SI.getValueOperand());
1394 if (ClCombinePointerLabelsOnStore) {
1395 Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001396 Shadow = DFSF.combineShadows(Shadow, PtrShadow, &SI);
Peter Collingbourne0be79e12013-11-21 23:20:54 +00001397 }
1398 DFSF.storeShadow(SI.getPointerOperand(), Size, Align, Shadow, &SI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001399}
1400
1401void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
1402 visitOperandShadowInst(BO);
1403}
1404
1405void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
1406
1407void DFSanVisitor::visitCmpInst(CmpInst &CI) { visitOperandShadowInst(CI); }
1408
1409void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
1410 visitOperandShadowInst(GEPI);
1411}
1412
1413void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
1414 visitOperandShadowInst(I);
1415}
1416
1417void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
1418 visitOperandShadowInst(I);
1419}
1420
1421void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
1422 visitOperandShadowInst(I);
1423}
1424
1425void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
1426 visitOperandShadowInst(I);
1427}
1428
1429void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
1430 visitOperandShadowInst(I);
1431}
1432
1433void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
1434 bool AllLoadsStores = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001435 for (User *U : I.users()) {
1436 if (isa<LoadInst>(U))
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001437 continue;
1438
Chandler Carruthcdf47882014-03-09 03:16:01 +00001439 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001440 if (SI->getPointerOperand() == &I)
1441 continue;
1442 }
1443
1444 AllLoadsStores = false;
1445 break;
1446 }
1447 if (AllLoadsStores) {
1448 IRBuilder<> IRB(&I);
1449 DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.ShadowTy);
1450 }
1451 DFSF.setShadow(&I, DFSF.DFS.ZeroShadow);
1452}
1453
1454void DFSanVisitor::visitSelectInst(SelectInst &I) {
1455 Value *CondShadow = DFSF.getShadow(I.getCondition());
1456 Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
1457 Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
1458
1459 if (isa<VectorType>(I.getCondition()->getType())) {
1460 DFSF.setShadow(
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001461 &I,
1462 DFSF.combineShadows(
1463 CondShadow, DFSF.combineShadows(TrueShadow, FalseShadow, &I), &I));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001464 } else {
1465 Value *ShadowSel;
1466 if (TrueShadow == FalseShadow) {
1467 ShadowSel = TrueShadow;
1468 } else {
1469 ShadowSel =
1470 SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
1471 }
Peter Collingbourne83def1c2014-07-15 04:41:14 +00001472 DFSF.setShadow(&I, DFSF.combineShadows(CondShadow, ShadowSel, &I));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001473 }
1474}
1475
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +00001476void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
1477 IRBuilder<> IRB(&I);
1478 Value *ValShadow = DFSF.getShadow(I.getValue());
David Blaikieff6409d2015-05-18 22:13:54 +00001479 IRB.CreateCall(DFSF.DFS.DFSanSetLabelFn,
1480 {ValShadow, IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(
1481 *DFSF.DFS.Ctx)),
1482 IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy)});
Peter Collingbourne9d31d6f2013-08-14 20:51:38 +00001483}
1484
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001485void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
1486 IRBuilder<> IRB(&I);
1487 Value *DestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
1488 Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
1489 Value *LenShadow = IRB.CreateMul(
1490 I.getLength(),
1491 ConstantInt::get(I.getLength()->getType(), DFSF.DFS.ShadowWidth / 8));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001492 Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
1493 DestShadow = IRB.CreateBitCast(DestShadow, Int8Ptr);
1494 SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
Daniel Neilson1e687242018-01-19 17:13:12 +00001495 auto *MTI = cast<MemTransferInst>(
James Y Knight7976eb52019-02-01 20:43:25 +00001496 IRB.CreateCall(I.getFunctionType(), I.getCalledValue(),
Daniel Neilson1e687242018-01-19 17:13:12 +00001497 {DestShadow, SrcShadow, LenShadow, I.getVolatileCst()}));
Daniel Neilson1e687242018-01-19 17:13:12 +00001498 if (ClPreserveAlignment) {
Daniel Neilson606cf6f2018-02-08 21:28:26 +00001499 MTI->setDestAlignment(I.getDestAlignment() * (DFSF.DFS.ShadowWidth / 8));
1500 MTI->setSourceAlignment(I.getSourceAlignment() * (DFSF.DFS.ShadowWidth / 8));
Daniel Neilson1e687242018-01-19 17:13:12 +00001501 } else {
Daniel Neilson606cf6f2018-02-08 21:28:26 +00001502 MTI->setDestAlignment(DFSF.DFS.ShadowWidth / 8);
1503 MTI->setSourceAlignment(DFSF.DFS.ShadowWidth / 8);
Daniel Neilson1e687242018-01-19 17:13:12 +00001504 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001505}
1506
1507void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
Peter Collingbourne68162e72013-08-14 18:54:12 +00001508 if (!DFSF.IsNativeABI && RI.getReturnValue()) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001509 switch (DFSF.IA) {
1510 case DataFlowSanitizer::IA_TLS: {
1511 Value *S = DFSF.getShadow(RI.getReturnValue());
1512 IRBuilder<> IRB(&RI);
1513 IRB.CreateStore(S, DFSF.getRetvalTLS());
1514 break;
1515 }
1516 case DataFlowSanitizer::IA_Args: {
1517 IRBuilder<> IRB(&RI);
1518 Type *RT = DFSF.F->getFunctionType()->getReturnType();
1519 Value *InsVal =
1520 IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
1521 Value *InsShadow =
1522 IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
1523 RI.setOperand(0, InsShadow);
1524 break;
1525 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001526 }
1527 }
1528}
1529
1530void DFSanVisitor::visitCallSite(CallSite CS) {
1531 Function *F = CS.getCalledFunction();
1532 if ((F && F->isIntrinsic()) || isa<InlineAsm>(CS.getCalledValue())) {
1533 visitOperandShadowInst(*CS.getInstruction());
1534 return;
1535 }
1536
Peter Collingbournea1099842014-11-05 17:21:00 +00001537 // Calls to this function are synthesized in wrappers, and we shouldn't
1538 // instrument them.
James Y Knight13680222019-02-01 02:28:03 +00001539 if (F == DFSF.DFS.DFSanVarargWrapperFn.getCallee()->stripPointerCasts())
Peter Collingbournea1099842014-11-05 17:21:00 +00001540 return;
1541
Peter Collingbourne68162e72013-08-14 18:54:12 +00001542 IRBuilder<> IRB(CS.getInstruction());
1543
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001544 DenseMap<Value *, Function *>::iterator i =
1545 DFSF.DFS.UnwrappedFnMap.find(CS.getCalledValue());
1546 if (i != DFSF.DFS.UnwrappedFnMap.end()) {
Peter Collingbourne68162e72013-08-14 18:54:12 +00001547 Function *F = i->second;
1548 switch (DFSF.DFS.getWrapperKind(F)) {
Eugene Zelenkofce43572017-10-21 00:57:46 +00001549 case DataFlowSanitizer::WK_Warning:
Peter Collingbourne68162e72013-08-14 18:54:12 +00001550 CS.setCalledFunction(F);
1551 IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
1552 IRB.CreateGlobalStringPtr(F->getName()));
1553 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1554 return;
Eugene Zelenkofce43572017-10-21 00:57:46 +00001555 case DataFlowSanitizer::WK_Discard:
Peter Collingbourne68162e72013-08-14 18:54:12 +00001556 CS.setCalledFunction(F);
1557 DFSF.setShadow(CS.getInstruction(), DFSF.DFS.ZeroShadow);
1558 return;
Eugene Zelenkofce43572017-10-21 00:57:46 +00001559 case DataFlowSanitizer::WK_Functional:
Peter Collingbourne68162e72013-08-14 18:54:12 +00001560 CS.setCalledFunction(F);
1561 visitOperandShadowInst(*CS.getInstruction());
1562 return;
Eugene Zelenkofce43572017-10-21 00:57:46 +00001563 case DataFlowSanitizer::WK_Custom:
Peter Collingbourne68162e72013-08-14 18:54:12 +00001564 // Don't try to handle invokes of custom functions, it's too complicated.
1565 // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
1566 // wrapper.
1567 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
1568 FunctionType *FT = F->getFunctionType();
Peter Collingbourne32f54052018-02-22 19:09:07 +00001569 TransformedFunction CustomFn = DFSF.DFS.getCustomFunctionType(FT);
Peter Collingbourne68162e72013-08-14 18:54:12 +00001570 std::string CustomFName = "__dfsw_";
1571 CustomFName += F->getName();
James Y Knight13680222019-02-01 02:28:03 +00001572 FunctionCallee CustomF = DFSF.DFS.Mod->getOrInsertFunction(
Peter Collingbourne32f54052018-02-22 19:09:07 +00001573 CustomFName, CustomFn.TransformedType);
James Y Knight13680222019-02-01 02:28:03 +00001574 if (Function *CustomFn = dyn_cast<Function>(CustomF.getCallee())) {
Peter Collingbourne68162e72013-08-14 18:54:12 +00001575 CustomFn->copyAttributesFrom(F);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001576
Peter Collingbourne68162e72013-08-14 18:54:12 +00001577 // Custom functions returning non-void will write to the return label.
1578 if (!FT->getReturnType()->isVoidTy()) {
Reid Klecknerb5180542017-03-21 16:57:19 +00001579 CustomFn->removeAttributes(AttributeList::FunctionIndex,
Peter Collingbourne68162e72013-08-14 18:54:12 +00001580 DFSF.DFS.ReadOnlyNoneAttrs);
1581 }
1582 }
1583
1584 std::vector<Value *> Args;
1585
1586 CallSite::arg_iterator i = CS.arg_begin();
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001587 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n) {
Peter Collingbourne28a10af2013-08-27 22:09:06 +00001588 Type *T = (*i)->getType();
1589 FunctionType *ParamFT;
1590 if (isa<PointerType>(T) &&
1591 (ParamFT = dyn_cast<FunctionType>(
1592 cast<PointerType>(T)->getElementType()))) {
1593 std::string TName = "dfst";
1594 TName += utostr(FT->getNumParams() - n);
1595 TName += "$";
1596 TName += F->getName();
1597 Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
1598 Args.push_back(T);
1599 Args.push_back(
1600 IRB.CreateBitCast(*i, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
1601 } else {
1602 Args.push_back(*i);
1603 }
1604 }
Peter Collingbourne68162e72013-08-14 18:54:12 +00001605
1606 i = CS.arg_begin();
Simon Dardisb5205c62017-08-17 14:14:25 +00001607 const unsigned ShadowArgStart = Args.size();
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001608 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
Peter Collingbourne68162e72013-08-14 18:54:12 +00001609 Args.push_back(DFSF.getShadow(*i));
1610
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001611 if (FT->isVarArg()) {
David Blaikie1b01e7e2015-04-05 22:44:57 +00001612 auto *LabelVATy = ArrayType::get(DFSF.DFS.ShadowTy,
1613 CS.arg_size() - FT->getNumParams());
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001614 auto *LabelVAAlloca = new AllocaInst(
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001615 LabelVATy, getDataLayout().getAllocaAddrSpace(),
1616 "labelva", &DFSF.F->getEntryBlock().front());
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001617
1618 for (unsigned n = 0; i != CS.arg_end(); ++i, ++n) {
David Blaikie64646022015-04-05 22:41:44 +00001619 auto LabelVAPtr = IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, n);
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001620 IRB.CreateStore(DFSF.getShadow(*i), LabelVAPtr);
1621 }
1622
David Blaikie64646022015-04-05 22:41:44 +00001623 Args.push_back(IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, 0));
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001624 }
1625
Peter Collingbourne68162e72013-08-14 18:54:12 +00001626 if (!FT->getReturnType()->isVoidTy()) {
1627 if (!DFSF.LabelReturnAlloca) {
1628 DFSF.LabelReturnAlloca =
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001629 new AllocaInst(DFSF.DFS.ShadowTy,
1630 getDataLayout().getAllocaAddrSpace(),
1631 "labelreturn", &DFSF.F->getEntryBlock().front());
Peter Collingbourne68162e72013-08-14 18:54:12 +00001632 }
1633 Args.push_back(DFSF.LabelReturnAlloca);
1634 }
1635
Peter Collingbournedd3486e2014-10-30 13:22:57 +00001636 for (i = CS.arg_begin() + FT->getNumParams(); i != CS.arg_end(); ++i)
1637 Args.push_back(*i);
1638
Peter Collingbourne68162e72013-08-14 18:54:12 +00001639 CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
1640 CustomCI->setCallingConv(CI->getCallingConv());
Peter Collingbourne32f54052018-02-22 19:09:07 +00001641 CustomCI->setAttributes(TransformFunctionAttributes(CustomFn,
1642 CI->getContext(), CI->getAttributes()));
Peter Collingbourne68162e72013-08-14 18:54:12 +00001643
Simon Dardisb5205c62017-08-17 14:14:25 +00001644 // Update the parameter attributes of the custom call instruction to
1645 // zero extend the shadow parameters. This is required for targets
1646 // which consider ShadowTy an illegal type.
1647 for (unsigned n = 0; n < FT->getNumParams(); n++) {
1648 const unsigned ArgNo = ShadowArgStart + n;
1649 if (CustomCI->getArgOperand(ArgNo)->getType() == DFSF.DFS.ShadowTy)
1650 CustomCI->addParamAttr(ArgNo, Attribute::ZExt);
1651 }
1652
Peter Collingbourne68162e72013-08-14 18:54:12 +00001653 if (!FT->getReturnType()->isVoidTy()) {
James Y Knight14359ef2019-02-01 20:44:24 +00001654 LoadInst *LabelLoad =
1655 IRB.CreateLoad(DFSF.DFS.ShadowTy, DFSF.LabelReturnAlloca);
Peter Collingbourne68162e72013-08-14 18:54:12 +00001656 DFSF.setShadow(CustomCI, LabelLoad);
1657 }
1658
1659 CI->replaceAllUsesWith(CustomCI);
1660 CI->eraseFromParent();
1661 return;
1662 }
1663 break;
1664 }
Peter Collingbourne68162e72013-08-14 18:54:12 +00001665 }
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001666
1667 FunctionType *FT = cast<FunctionType>(
1668 CS.getCalledValue()->getType()->getPointerElementType());
Peter Collingbourne68162e72013-08-14 18:54:12 +00001669 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001670 for (unsigned i = 0, n = FT->getNumParams(); i != n; ++i) {
1671 IRB.CreateStore(DFSF.getShadow(CS.getArgument(i)),
1672 DFSF.getArgTLS(i, CS.getInstruction()));
1673 }
1674 }
1675
Craig Topperf40110f2014-04-25 05:29:35 +00001676 Instruction *Next = nullptr;
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001677 if (!CS.getType()->isVoidTy()) {
1678 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
1679 if (II->getNormalDest()->getSinglePredecessor()) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001680 Next = &II->getNormalDest()->front();
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001681 } else {
1682 BasicBlock *NewBB =
Chandler Carruthd4500562015-01-19 12:36:53 +00001683 SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DT);
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001684 Next = &NewBB->front();
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001685 }
1686 } else {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001687 assert(CS->getIterator() != CS->getParent()->end());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001688 Next = CS->getNextNode();
1689 }
1690
Peter Collingbourne68162e72013-08-14 18:54:12 +00001691 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001692 IRBuilder<> NextIRB(Next);
James Y Knight14359ef2019-02-01 20:44:24 +00001693 LoadInst *LI = NextIRB.CreateLoad(DFSF.DFS.ShadowTy, DFSF.getRetvalTLS());
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001694 DFSF.SkipInsts.insert(LI);
1695 DFSF.setShadow(CS.getInstruction(), LI);
Peter Collingbournefab565a2014-08-22 01:18:18 +00001696 DFSF.NonZeroChecks.push_back(LI);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001697 }
1698 }
1699
1700 // Do all instrumentation for IA_Args down here to defer tampering with the
1701 // CFG in a way that SplitEdge may be able to detect.
Peter Collingbourne68162e72013-08-14 18:54:12 +00001702 if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
1703 FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001704 Value *Func =
1705 IRB.CreateBitCast(CS.getCalledValue(), PointerType::getUnqual(NewFT));
1706 std::vector<Value *> Args;
1707
1708 CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1709 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1710 Args.push_back(*i);
1711
1712 i = CS.arg_begin();
1713 for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
1714 Args.push_back(DFSF.getShadow(*i));
1715
1716 if (FT->isVarArg()) {
1717 unsigned VarArgSize = CS.arg_size() - FT->getNumParams();
1718 ArrayType *VarArgArrayTy = ArrayType::get(DFSF.DFS.ShadowTy, VarArgSize);
1719 AllocaInst *VarArgShadow =
Matt Arsenault3c1fc762017-04-10 22:27:50 +00001720 new AllocaInst(VarArgArrayTy, getDataLayout().getAllocaAddrSpace(),
1721 "", &DFSF.F->getEntryBlock().front());
David Blaikie4e5d47f42015-04-04 21:07:10 +00001722 Args.push_back(IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, 0));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001723 for (unsigned n = 0; i != e; ++i, ++n) {
David Blaikie4e5d47f42015-04-04 21:07:10 +00001724 IRB.CreateStore(
1725 DFSF.getShadow(*i),
1726 IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, n));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001727 Args.push_back(*i);
1728 }
1729 }
1730
1731 CallSite NewCS;
1732 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
James Y Knightd9e85a02019-02-01 20:43:34 +00001733 NewCS = IRB.CreateInvoke(NewFT, Func, II->getNormalDest(),
1734 II->getUnwindDest(), Args);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001735 } else {
James Y Knight7976eb52019-02-01 20:43:25 +00001736 NewCS = IRB.CreateCall(NewFT, Func, Args);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001737 }
1738 NewCS.setCallingConv(CS.getCallingConv());
1739 NewCS.setAttributes(CS.getAttributes().removeAttributes(
Reid Klecknerb5180542017-03-21 16:57:19 +00001740 *DFSF.DFS.Ctx, AttributeList::ReturnIndex,
Pete Cooper2777d8872015-05-06 23:19:56 +00001741 AttributeFuncs::typeIncompatible(NewCS.getInstruction()->getType())));
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001742
1743 if (Next) {
1744 ExtractValueInst *ExVal =
1745 ExtractValueInst::Create(NewCS.getInstruction(), 0, "", Next);
1746 DFSF.SkipInsts.insert(ExVal);
1747 ExtractValueInst *ExShadow =
1748 ExtractValueInst::Create(NewCS.getInstruction(), 1, "", Next);
1749 DFSF.SkipInsts.insert(ExShadow);
1750 DFSF.setShadow(ExVal, ExShadow);
Peter Collingbournefab565a2014-08-22 01:18:18 +00001751 DFSF.NonZeroChecks.push_back(ExShadow);
Peter Collingbournee5d5b0c2013-08-07 22:47:18 +00001752
1753 CS.getInstruction()->replaceAllUsesWith(ExVal);
1754 }
1755
1756 CS.getInstruction()->eraseFromParent();
1757 }
1758}
1759
1760void DFSanVisitor::visitPHINode(PHINode &PN) {
1761 PHINode *ShadowPN =
1762 PHINode::Create(DFSF.DFS.ShadowTy, PN.getNumIncomingValues(), "", &PN);
1763
1764 // Give the shadow phi node valid predecessors to fool SplitEdge into working.
1765 Value *UndefShadow = UndefValue::get(DFSF.DFS.ShadowTy);
1766 for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
1767 ++i) {
1768 ShadowPN->addIncoming(UndefShadow, *i);
1769 }
1770
1771 DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
1772 DFSF.setShadow(&PN, ShadowPN);
1773}