1 //===- DataFlowSanitizer.cpp - dynamic data flow analysis -----------------===//
2 //
3 // 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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// This file is a part of DataFlowSanitizer, a generalised dynamic data flow
11 /// analysis.
12 ///
13 /// Unlike other Sanitizer tools, this tool is not designed to detect a specific
14 /// class of bugs on its own.  Instead, it provides a generic dynamic data flow
15 /// analysis framework to be used by clients to help detect application-specific
16 /// issues within their own code.
17 ///
18 /// The analysis is based on automatic propagation of data flow labels (also
19 /// known as taint labels) through a program as it performs computation.
20 ///
21 /// There are two possible memory layouts. In the first one, each byte of
22 /// application memory is backed by a shadow memory byte. The shadow byte can
23 /// represent up to 8 labels. To enable this you must specify the
24 /// -dfsan-fast-8-labels flag. On Linux/x86_64, memory is then laid out as
25 /// follows:
26 ///
27 /// +--------------------+ 0x800000000000 (top of memory)
28 /// | application memory |
29 /// +--------------------+ 0x700000008000 (kAppAddr)
30 /// |                    |
31 /// |       unused       |
32 /// |                    |
33 /// +--------------------+ 0x300200000000 (kUnusedAddr)
34 /// |    union table     |
35 /// +--------------------+ 0x300000000000 (kUnionTableAddr)
36 /// |       origin       |
37 /// +--------------------+ 0x200000008000 (kOriginAddr)
38 /// |   shadow memory    |
39 /// +--------------------+ 0x100000008000 (kShadowAddr)
40 /// |       unused       |
41 /// +--------------------+ 0x000000010000
42 /// | reserved by kernel |
43 /// +--------------------+ 0x000000000000
44 ///
45 ///
46 /// In the second memory layout, each byte of application memory is backed by
47 /// two bytes of shadow memory which hold the label. That means we can represent
48 /// either 16 labels (with -dfsan-fast-16-labels flag) or 2^16 labels (on the
49 /// default legacy mode) per byte. On Linux/x86_64, memory is then laid out as
50 /// follows:
51 ///
52 /// +--------------------+ 0x800000000000 (top of memory)
53 /// | application memory |
54 /// +--------------------+ 0x700000008000 (kAppAddr)
55 /// |                    |
56 /// |       unused       |
57 /// |                    |
58 /// +--------------------+ 0x300200000000 (kUnusedAddr)
59 /// |    union table     |
60 /// +--------------------+ 0x300000000000 (kUnionTableAddr)
61 /// |       origin       |
62 /// +--------------------+ 0x200000008000 (kOriginAddr)
63 /// |   shadow memory    |
64 /// +--------------------+ 0x000000010000 (kShadowAddr)
65 /// | reserved by kernel |
66 /// +--------------------+ 0x000000000000
67 ///
68 ///
69 /// To derive a shadow memory address from an application memory address,
70 /// bits 44-46 are cleared to bring the address into the range
71 /// [0x000000008000,0x100000000000).  Then the address is shifted left by 1 to
72 /// account for the double byte representation of shadow labels and move the
73 /// address into the shadow memory range.  See the function
74 /// DataFlowSanitizer::getShadowAddress below.
75 ///
76 /// For more information, please refer to the design document:
77 /// http://clang.llvm.org/docs/DataFlowSanitizerDesign.html
78 //
79 //===----------------------------------------------------------------------===//
80 
81 #include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
82 #include "llvm/ADT/DenseMap.h"
83 #include "llvm/ADT/DenseSet.h"
84 #include "llvm/ADT/DepthFirstIterator.h"
85 #include "llvm/ADT/None.h"
86 #include "llvm/ADT/SmallPtrSet.h"
87 #include "llvm/ADT/SmallVector.h"
88 #include "llvm/ADT/StringExtras.h"
89 #include "llvm/ADT/StringRef.h"
90 #include "llvm/ADT/Triple.h"
91 #include "llvm/ADT/iterator.h"
92 #include "llvm/Analysis/ValueTracking.h"
93 #include "llvm/IR/Argument.h"
94 #include "llvm/IR/Attributes.h"
95 #include "llvm/IR/BasicBlock.h"
96 #include "llvm/IR/Constant.h"
97 #include "llvm/IR/Constants.h"
98 #include "llvm/IR/DataLayout.h"
99 #include "llvm/IR/DerivedTypes.h"
100 #include "llvm/IR/Dominators.h"
101 #include "llvm/IR/Function.h"
102 #include "llvm/IR/GlobalAlias.h"
103 #include "llvm/IR/GlobalValue.h"
104 #include "llvm/IR/GlobalVariable.h"
105 #include "llvm/IR/IRBuilder.h"
106 #include "llvm/IR/InlineAsm.h"
107 #include "llvm/IR/InstVisitor.h"
108 #include "llvm/IR/InstrTypes.h"
109 #include "llvm/IR/Instruction.h"
110 #include "llvm/IR/Instructions.h"
111 #include "llvm/IR/IntrinsicInst.h"
112 #include "llvm/IR/LLVMContext.h"
113 #include "llvm/IR/MDBuilder.h"
114 #include "llvm/IR/Module.h"
115 #include "llvm/IR/PassManager.h"
116 #include "llvm/IR/Type.h"
117 #include "llvm/IR/User.h"
118 #include "llvm/IR/Value.h"
119 #include "llvm/InitializePasses.h"
120 #include "llvm/Pass.h"
121 #include "llvm/Support/Alignment.h"
122 #include "llvm/Support/Casting.h"
123 #include "llvm/Support/CommandLine.h"
124 #include "llvm/Support/ErrorHandling.h"
125 #include "llvm/Support/SpecialCaseList.h"
126 #include "llvm/Support/VirtualFileSystem.h"
127 #include "llvm/Transforms/Instrumentation.h"
128 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
129 #include "llvm/Transforms/Utils/Local.h"
130 #include <algorithm>
131 #include <cassert>
132 #include <cstddef>
133 #include <cstdint>
134 #include <iterator>
135 #include <memory>
136 #include <set>
137 #include <string>
138 #include <utility>
139 #include <vector>
140 
141 using namespace llvm;
142 
143 // This must be consistent with ShadowWidthBits.
144 static const Align ShadowTLSAlignment = Align(2);
145 
146 static const Align MinOriginAlignment = Align(4);
147 
148 // The size of TLS variables. These constants must be kept in sync with the ones
149 // in dfsan.cpp.
150 static const unsigned ArgTLSSize = 800;
151 static const unsigned RetvalTLSSize = 800;
152 
153 // External symbol to be used when generating the shadow address for
154 // architectures with multiple VMAs. Instead of using a constant integer
155 // the runtime will set the external mask based on the VMA range.
156 const char DFSanExternShadowPtrMask[] = "__dfsan_shadow_ptr_mask";
157 
158 // The -dfsan-preserve-alignment flag controls whether this pass assumes that
159 // alignment requirements provided by the input IR are correct.  For example,
160 // if the input IR contains a load with alignment 8, this flag will cause
161 // the shadow load to have alignment 16.  This flag is disabled by default as
162 // we have unfortunately encountered too much code (including Clang itself;
163 // see PR14291) which performs misaligned access.
164 static cl::opt<bool> ClPreserveAlignment(
165     "dfsan-preserve-alignment",
166     cl::desc("respect alignment requirements provided by input IR"), cl::Hidden,
167     cl::init(false));
168 
169 // The ABI list files control how shadow parameters are passed. The pass treats
170 // every function labelled "uninstrumented" in the ABI list file as conforming
171 // to the "native" (i.e. unsanitized) ABI.  Unless the ABI list contains
172 // additional annotations for those functions, a call to one of those functions
173 // will produce a warning message, as the labelling behaviour of the function is
174 // unknown.  The other supported annotations are "functional" and "discard",
175 // which are described below under DataFlowSanitizer::WrapperKind.
176 static cl::list<std::string> ClABIListFiles(
177     "dfsan-abilist",
178     cl::desc("File listing native ABI functions and how the pass treats them"),
179     cl::Hidden);
180 
181 // Controls whether the pass uses IA_Args or IA_TLS as the ABI for instrumented
182 // functions (see DataFlowSanitizer::InstrumentedABI below).
183 static cl::opt<bool>
184     ClArgsABI("dfsan-args-abi",
185               cl::desc("Use the argument ABI rather than the TLS ABI"),
186               cl::Hidden);
187 
188 // Controls whether the pass includes or ignores the labels of pointers in load
189 // instructions.
190 static cl::opt<bool> ClCombinePointerLabelsOnLoad(
191     "dfsan-combine-pointer-labels-on-load",
192     cl::desc("Combine the label of the pointer with the label of the data when "
193              "loading from memory."),
194     cl::Hidden, cl::init(true));
195 
196 // Controls whether the pass includes or ignores the labels of pointers in
197 // stores instructions.
198 static cl::opt<bool> ClCombinePointerLabelsOnStore(
199     "dfsan-combine-pointer-labels-on-store",
200     cl::desc("Combine the label of the pointer with the label of the data when "
201              "storing in memory."),
202     cl::Hidden, cl::init(false));
203 
204 // Controls whether the pass propagates labels of offsets in GEP instructions.
205 static cl::opt<bool> ClCombineOffsetLabelsOnGEP(
206     "dfsan-combine-offset-labels-on-gep",
207     cl::desc(
208         "Combine the label of the offset with the label of the pointer when "
209         "doing pointer arithmetic."),
210     cl::Hidden, cl::init(true));
211 
212 static cl::opt<bool> ClDebugNonzeroLabels(
213     "dfsan-debug-nonzero-labels",
214     cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, "
215              "load or return with a nonzero label"),
216     cl::Hidden);
217 
218 // Experimental feature that inserts callbacks for certain data events.
219 // Currently callbacks are only inserted for loads, stores, memory transfers
220 // (i.e. memcpy and memmove), and comparisons.
221 //
222 // If this flag is set to true, the user must provide definitions for the
223 // following callback functions:
224 //   void __dfsan_load_callback(dfsan_label Label, void* addr);
225 //   void __dfsan_store_callback(dfsan_label Label, void* addr);
226 //   void __dfsan_mem_transfer_callback(dfsan_label *Start, size_t Len);
227 //   void __dfsan_cmp_callback(dfsan_label CombinedLabel);
228 static cl::opt<bool> ClEventCallbacks(
229     "dfsan-event-callbacks",
230     cl::desc("Insert calls to __dfsan_*_callback functions on data events."),
231     cl::Hidden, cl::init(false));
232 
233 // Use a distinct bit for each base label, enabling faster unions with less
234 // instrumentation.  Limits the max number of base labels to 16.
235 static cl::opt<bool> ClFast16Labels(
236     "dfsan-fast-16-labels",
237     cl::desc("Use more efficient instrumentation, limiting the number of "
238              "labels to 16."),
239     cl::Hidden, cl::init(false));
240 
241 // Use a distinct bit for each base label, enabling faster unions with less
242 // instrumentation.  Limits the max number of base labels to 8.
243 static cl::opt<bool> ClFast8Labels(
244     "dfsan-fast-8-labels",
245     cl::desc("Use more efficient instrumentation, limiting the number of "
246              "labels to 8."),
247     cl::Hidden, cl::init(false));
248 
249 // Controls whether the pass tracks the control flow of select instructions.
250 static cl::opt<bool> ClTrackSelectControlFlow(
251     "dfsan-track-select-control-flow",
252     cl::desc("Propagate labels from condition values of select instructions "
253              "to results."),
254     cl::Hidden, cl::init(true));
255 
256 // TODO: This default value follows MSan. DFSan may use a different value.
257 static cl::opt<int> ClInstrumentWithCallThreshold(
258     "dfsan-instrument-with-call-threshold",
259     cl::desc("If the function being instrumented requires more than "
260              "this number of origin stores, use callbacks instead of "
261              "inline checks (-1 means never use callbacks)."),
262     cl::Hidden, cl::init(3500));
263 
264 // Controls how to track origins.
265 // * 0: do not track origins.
266 // * 1: track origins at memory store operations.
267 // * 2: track origins at memory load and store operations.
268 //      TODO: track callsites.
269 static cl::opt<int> ClTrackOrigins("dfsan-track-origins",
270                                    cl::desc("Track origins of labels"),
271                                    cl::Hidden, cl::init(0));
272 
273 static StringRef getGlobalTypeString(const GlobalValue &G) {
274   // Types of GlobalVariables are always pointer types.
275   Type *GType = G.getValueType();
276   // For now we support excluding struct types only.
277   if (StructType *SGType = dyn_cast<StructType>(GType)) {
278     if (!SGType->isLiteral())
279       return SGType->getName();
280   }
281   return "<unknown type>";
282 }
283 
284 namespace {
285 
286 class DFSanABIList {
287   std::unique_ptr<SpecialCaseList> SCL;
288 
289 public:
290   DFSanABIList() = default;
291 
292   void set(std::unique_ptr<SpecialCaseList> List) { SCL = std::move(List); }
293 
294   /// Returns whether either this function or its source file are listed in the
295   /// given category.
296   bool isIn(const Function &F, StringRef Category) const {
297     return isIn(*F.getParent(), Category) ||
298            SCL->inSection("dataflow", "fun", F.getName(), Category);
299   }
300 
301   /// Returns whether this global alias is listed in the given category.
302   ///
303   /// If GA aliases a function, the alias's name is matched as a function name
304   /// would be.  Similarly, aliases of globals are matched like globals.
305   bool isIn(const GlobalAlias &GA, StringRef Category) const {
306     if (isIn(*GA.getParent(), Category))
307       return true;
308 
309     if (isa<FunctionType>(GA.getValueType()))
310       return SCL->inSection("dataflow", "fun", GA.getName(), Category);
311 
312     return SCL->inSection("dataflow", "global", GA.getName(), Category) ||
313            SCL->inSection("dataflow", "type", getGlobalTypeString(GA),
314                           Category);
315   }
316 
317   /// Returns whether this module is listed in the given category.
318   bool isIn(const Module &M, StringRef Category) const {
319     return SCL->inSection("dataflow", "src", M.getModuleIdentifier(), Category);
320   }
321 };
322 
323 /// TransformedFunction is used to express the result of transforming one
324 /// function type into another.  This struct is immutable.  It holds metadata
325 /// useful for updating calls of the old function to the new type.
326 struct TransformedFunction {
327   TransformedFunction(FunctionType *OriginalType, FunctionType *TransformedType,
328                       std::vector<unsigned> ArgumentIndexMapping)
329       : OriginalType(OriginalType), TransformedType(TransformedType),
330         ArgumentIndexMapping(ArgumentIndexMapping) {}
331 
332   // Disallow copies.
333   TransformedFunction(const TransformedFunction &) = delete;
334   TransformedFunction &operator=(const TransformedFunction &) = delete;
335 
336   // Allow moves.
337   TransformedFunction(TransformedFunction &&) = default;
338   TransformedFunction &operator=(TransformedFunction &&) = default;
339 
340   /// Type of the function before the transformation.
341   FunctionType *OriginalType;
342 
343   /// Type of the function after the transformation.
344   FunctionType *TransformedType;
345 
346   /// Transforming a function may change the position of arguments.  This
347   /// member records the mapping from each argument's old position to its new
348   /// position.  Argument positions are zero-indexed.  If the transformation
349   /// from F to F' made the first argument of F into the third argument of F',
350   /// then ArgumentIndexMapping[0] will equal 2.
351   std::vector<unsigned> ArgumentIndexMapping;
352 };
353 
354 /// Given function attributes from a call site for the original function,
355 /// return function attributes appropriate for a call to the transformed
356 /// function.
357 AttributeList
358 transformFunctionAttributes(const TransformedFunction &TransformedFunction,
359                             LLVMContext &Ctx, AttributeList CallSiteAttrs) {
360 
361   // Construct a vector of AttributeSet for each function argument.
362   std::vector<llvm::AttributeSet> ArgumentAttributes(
363       TransformedFunction.TransformedType->getNumParams());
364 
365   // Copy attributes from the parameter of the original function to the
366   // transformed version.  'ArgumentIndexMapping' holds the mapping from
367   // old argument position to new.
368   for (unsigned I = 0, IE = TransformedFunction.ArgumentIndexMapping.size();
369        I < IE; ++I) {
370     unsigned TransformedIndex = TransformedFunction.ArgumentIndexMapping[I];
371     ArgumentAttributes[TransformedIndex] = CallSiteAttrs.getParamAttributes(I);
372   }
373 
374   // Copy annotations on varargs arguments.
375   for (unsigned I = TransformedFunction.OriginalType->getNumParams(),
376                 IE = CallSiteAttrs.getNumAttrSets();
377        I < IE; ++I) {
378     ArgumentAttributes.push_back(CallSiteAttrs.getParamAttributes(I));
379   }
380 
381   return AttributeList::get(Ctx, CallSiteAttrs.getFnAttributes(),
382                             CallSiteAttrs.getRetAttributes(),
383                             llvm::makeArrayRef(ArgumentAttributes));
384 }
385 
386 class DataFlowSanitizer {
387   friend struct DFSanFunction;
388   friend class DFSanVisitor;
389 
390   enum {
391     OriginWidthBits = 32,
392     OriginWidthBytes = OriginWidthBits / 8
393   };
394 
395   /// Which ABI should be used for instrumented functions?
396   enum InstrumentedABI {
397     /// Argument and return value labels are passed through additional
398     /// arguments and by modifying the return type.
399     IA_Args,
400 
401     /// Argument and return value labels are passed through TLS variables
402     /// __dfsan_arg_tls and __dfsan_retval_tls.
403     IA_TLS
404   };
405 
406   /// How should calls to uninstrumented functions be handled?
407   enum WrapperKind {
408     /// This function is present in an uninstrumented form but we don't know
409     /// how it should be handled.  Print a warning and call the function anyway.
410     /// Don't label the return value.
411     WK_Warning,
412 
413     /// This function does not write to (user-accessible) memory, and its return
414     /// value is unlabelled.
415     WK_Discard,
416 
417     /// This function does not write to (user-accessible) memory, and the label
418     /// of its return value is the union of the label of its arguments.
419     WK_Functional,
420 
421     /// Instead of calling the function, a custom wrapper __dfsw_F is called,
422     /// where F is the name of the function.  This function may wrap the
423     /// original function or provide its own implementation.  This is similar to
424     /// the IA_Args ABI, except that IA_Args uses a struct return type to
425     /// pass the return value shadow in a register, while WK_Custom uses an
426     /// extra pointer argument to return the shadow.  This allows the wrapped
427     /// form of the function type to be expressed in C.
428     WK_Custom
429   };
430 
431   unsigned ShadowWidthBits;
432   unsigned ShadowWidthBytes;
433 
434   Module *Mod;
435   LLVMContext *Ctx;
436   Type *Int8Ptr;
437   IntegerType *OriginTy;
438   PointerType *OriginPtrTy;
439   ConstantInt *OriginBase;
440   ConstantInt *ZeroOrigin;
441   /// The shadow type for all primitive types and vector types.
442   IntegerType *PrimitiveShadowTy;
443   PointerType *PrimitiveShadowPtrTy;
444   IntegerType *IntptrTy;
445   ConstantInt *ZeroPrimitiveShadow;
446   ConstantInt *ShadowPtrMask;
447   ConstantInt *ShadowPtrMul;
448   Constant *ArgTLS;
449   ArrayType *ArgOriginTLSTy;
450   Constant *ArgOriginTLS;
451   Constant *RetvalTLS;
452   Constant *RetvalOriginTLS;
453   Constant *ExternalShadowMask;
454   FunctionType *DFSanUnionFnTy;
455   FunctionType *DFSanUnionLoadFnTy;
456   FunctionType *DFSanLoadLabelAndOriginFnTy;
457   FunctionType *DFSanUnimplementedFnTy;
458   FunctionType *DFSanSetLabelFnTy;
459   FunctionType *DFSanNonzeroLabelFnTy;
460   FunctionType *DFSanVarargWrapperFnTy;
461   FunctionType *DFSanCmpCallbackFnTy;
462   FunctionType *DFSanLoadStoreCallbackFnTy;
463   FunctionType *DFSanMemTransferCallbackFnTy;
464   FunctionType *DFSanChainOriginFnTy;
465   FunctionType *DFSanChainOriginIfTaintedFnTy;
466   FunctionType *DFSanMemOriginTransferFnTy;
467   FunctionType *DFSanMaybeStoreOriginFnTy;
468   FunctionCallee DFSanUnionFn;
469   FunctionCallee DFSanCheckedUnionFn;
470   FunctionCallee DFSanUnionLoadFn;
471   FunctionCallee DFSanUnionLoadFastLabelsFn;
472   FunctionCallee DFSanLoadLabelAndOriginFn;
473   FunctionCallee DFSanUnimplementedFn;
474   FunctionCallee DFSanSetLabelFn;
475   FunctionCallee DFSanNonzeroLabelFn;
476   FunctionCallee DFSanVarargWrapperFn;
477   FunctionCallee DFSanLoadCallbackFn;
478   FunctionCallee DFSanStoreCallbackFn;
479   FunctionCallee DFSanMemTransferCallbackFn;
480   FunctionCallee DFSanCmpCallbackFn;
481   FunctionCallee DFSanChainOriginFn;
482   FunctionCallee DFSanChainOriginIfTaintedFn;
483   FunctionCallee DFSanMemOriginTransferFn;
484   FunctionCallee DFSanMaybeStoreOriginFn;
485   SmallPtrSet<Value *, 16> DFSanRuntimeFunctions;
486   MDNode *ColdCallWeights;
487   MDNode *OriginStoreWeights;
488   DFSanABIList ABIList;
489   DenseMap<Value *, Function *> UnwrappedFnMap;
490   AttrBuilder ReadOnlyNoneAttrs;
491   bool DFSanRuntimeShadowMask = false;
492 
493   Value *getShadowOffset(Value *Addr, IRBuilder<> &IRB);
494   Value *getShadowAddress(Value *Addr, Instruction *Pos);
495   Value *getShadowAddress(Value *Addr, Instruction *Pos, Value *ShadowOffset);
496   std::pair<Value *, Value *>
497   getShadowOriginAddress(Value *Addr, Align InstAlignment, Instruction *Pos);
498   bool isInstrumented(const Function *F);
499   bool isInstrumented(const GlobalAlias *GA);
500   FunctionType *getArgsFunctionType(FunctionType *T);
501   FunctionType *getTrampolineFunctionType(FunctionType *T);
502   TransformedFunction getCustomFunctionType(FunctionType *T);
503   InstrumentedABI getInstrumentedABI();
504   WrapperKind getWrapperKind(Function *F);
505   void addGlobalNamePrefix(GlobalValue *GV);
506   Function *buildWrapperFunction(Function *F, StringRef NewFName,
507                                  GlobalValue::LinkageTypes NewFLink,
508                                  FunctionType *NewFT);
509   Constant *getOrBuildTrampolineFunction(FunctionType *FT, StringRef FName);
510   void initializeCallbackFunctions(Module &M);
511   void initializeRuntimeFunctions(Module &M);
512   void injectMetadataGlobals(Module &M);
513 
514   bool init(Module &M);
515 
516   /// Advances \p OriginAddr to point to the next 32-bit origin and then loads
517   /// from it. Returns the origin's loaded value.
518   Value *loadNextOrigin(Instruction *Pos, Align OriginAlign,
519                         Value **OriginAddr);
520 
521   /// Returns whether fast8 or fast16 mode has been specified.
522   bool hasFastLabelsEnabled();
523 
524   /// Returns whether the given load byte size is amenable to inlined
525   /// optimization patterns.
526   bool hasLoadSizeForFastPath(uint64_t Size);
527 
528   /// Returns whether the pass tracks origins. Support only fast16 mode in TLS
529   /// ABI mode.
530   bool shouldTrackOrigins();
531 
532   /// Returns whether the pass tracks labels for struct fields and array
533   /// indices. Support only fast16 mode in TLS ABI mode.
534   bool shouldTrackFieldsAndIndices();
535 
536   /// Returns a zero constant with the shadow type of OrigTy.
537   ///
538   /// getZeroShadow({T1,T2,...}) = {getZeroShadow(T1),getZeroShadow(T2,...}
539   /// getZeroShadow([n x T]) = [n x getZeroShadow(T)]
540   /// getZeroShadow(other type) = i16(0)
541   ///
542   /// Note that a zero shadow is always i16(0) when shouldTrackFieldsAndIndices
543   /// returns false.
544   Constant *getZeroShadow(Type *OrigTy);
545   /// Returns a zero constant with the shadow type of V's type.
546   Constant *getZeroShadow(Value *V);
547 
548   /// Checks if V is a zero shadow.
549   bool isZeroShadow(Value *V);
550 
551   /// Returns the shadow type of OrigTy.
552   ///
553   /// getShadowTy({T1,T2,...}) = {getShadowTy(T1),getShadowTy(T2),...}
554   /// getShadowTy([n x T]) = [n x getShadowTy(T)]
555   /// getShadowTy(other type) = i16
556   ///
557   /// Note that a shadow type is always i16 when shouldTrackFieldsAndIndices
558   /// returns false.
559   Type *getShadowTy(Type *OrigTy);
560   /// Returns the shadow type of of V's type.
561   Type *getShadowTy(Value *V);
562 
563   const uint64_t NumOfElementsInArgOrgTLS = ArgTLSSize / OriginWidthBytes;
564 
565 public:
566   DataFlowSanitizer(const std::vector<std::string> &ABIListFiles);
567 
568   bool runImpl(Module &M);
569 };
570 
571 struct DFSanFunction {
572   DataFlowSanitizer &DFS;
573   Function *F;
574   DominatorTree DT;
575   DataFlowSanitizer::InstrumentedABI IA;
576   bool IsNativeABI;
577   AllocaInst *LabelReturnAlloca = nullptr;
578   AllocaInst *OriginReturnAlloca = nullptr;
579   DenseMap<Value *, Value *> ValShadowMap;
580   DenseMap<Value *, Value *> ValOriginMap;
581   DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
582   DenseMap<AllocaInst *, AllocaInst *> AllocaOriginMap;
583 
584   struct PHIFixupElement {
585     PHINode *Phi;
586     PHINode *ShadowPhi;
587     PHINode *OriginPhi;
588   };
589   std::vector<PHIFixupElement> PHIFixups;
590 
591   DenseSet<Instruction *> SkipInsts;
592   std::vector<Value *> NonZeroChecks;
593   bool AvoidNewBlocks;
594 
595   struct CachedShadow {
596     BasicBlock *Block; // The block where Shadow is defined.
597     Value *Shadow;
598   };
599   /// Maps a value to its latest shadow value in terms of domination tree.
600   DenseMap<std::pair<Value *, Value *>, CachedShadow> CachedShadows;
601   /// Maps a value to its latest collapsed shadow value it was converted to in
602   /// terms of domination tree. When ClDebugNonzeroLabels is on, this cache is
603   /// used at a post process where CFG blocks are split. So it does not cache
604   /// BasicBlock like CachedShadows, but uses domination between values.
605   DenseMap<Value *, Value *> CachedCollapsedShadows;
606   DenseMap<Value *, std::set<Value *>> ShadowElements;
607 
608   DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
609       : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()), IsNativeABI(IsNativeABI) {
610     DT.recalculate(*F);
611     // FIXME: Need to track down the register allocator issue which causes poor
612     // performance in pathological cases with large numbers of basic blocks.
613     AvoidNewBlocks = F->size() > 1000;
614   }
615 
616   /// Computes the shadow address for a given function argument.
617   ///
618   /// Shadow = ArgTLS+ArgOffset.
619   Value *getArgTLS(Type *T, unsigned ArgOffset, IRBuilder<> &IRB);
620 
621   /// Computes the shadow address for a return value.
622   Value *getRetvalTLS(Type *T, IRBuilder<> &IRB);
623 
624   /// Computes the origin address for a given function argument.
625   ///
626   /// Origin = ArgOriginTLS[ArgNo].
627   Value *getArgOriginTLS(unsigned ArgNo, IRBuilder<> &IRB);
628 
629   /// Computes the origin address for a return value.
630   Value *getRetvalOriginTLS();
631 
632   Value *getOrigin(Value *V);
633   void setOrigin(Instruction *I, Value *Origin);
634   /// Generates IR to compute the origin of the last operand with a taint label.
635   Value *combineOperandOrigins(Instruction *Inst);
636   /// Before the instruction Pos, generates IR to compute the last origin with a
637   /// taint label. Labels and origins are from vectors Shadows and Origins
638   /// correspondingly. The generated IR is like
639   ///   Sn-1 != Zero ? On-1: ... S2 != Zero ? O2: S1 != Zero ? O1: O0
640   /// When Zero is nullptr, it uses ZeroPrimitiveShadow. Otherwise it can be
641   /// zeros with other bitwidths.
642   Value *combineOrigins(const std::vector<Value *> &Shadows,
643                         const std::vector<Value *> &Origins, Instruction *Pos,
644                         ConstantInt *Zero = nullptr);
645 
646   Value *getShadow(Value *V);
647   void setShadow(Instruction *I, Value *Shadow);
648   /// Generates IR to compute the union of the two given shadows, inserting it
649   /// before Pos. The combined value is with primitive type.
650   Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
651   /// Combines the shadow values of V1 and V2, then converts the combined value
652   /// with primitive type into a shadow value with the original type T.
653   Value *combineShadowsThenConvert(Type *T, Value *V1, Value *V2,
654                                    Instruction *Pos);
655   Value *combineOperandShadows(Instruction *Inst);
656 
657   /// Generates IR to load shadow and origin corresponding to bytes [\p
658   /// Addr, \p Addr + \p Size), where addr has alignment \p
659   /// InstAlignment, and take the union of each of those shadows. The returned
660   /// shadow always has primitive type.
661   ///
662   /// When tracking loads is enabled, the returned origin is a chain at the
663   /// current stack if the returned shadow is tainted.
664   std::pair<Value *, Value *> loadShadowOrigin(Value *Addr, uint64_t Size,
665                                                Align InstAlignment,
666                                                Instruction *Pos);
667 
668   void storePrimitiveShadowOrigin(Value *Addr, uint64_t Size,
669                                   Align InstAlignment, Value *PrimitiveShadow,
670                                   Value *Origin, Instruction *Pos);
671   /// Applies PrimitiveShadow to all primitive subtypes of T, returning
672   /// the expanded shadow value.
673   ///
674   /// EFP({T1,T2, ...}, PS) = {EFP(T1,PS),EFP(T2,PS),...}
675   /// EFP([n x T], PS) = [n x EFP(T,PS)]
676   /// EFP(other types, PS) = PS
677   Value *expandFromPrimitiveShadow(Type *T, Value *PrimitiveShadow,
678                                    Instruction *Pos);
679   /// Collapses Shadow into a single primitive shadow value, unioning all
680   /// primitive shadow values in the process. Returns the final primitive
681   /// shadow value.
682   ///
683   /// CTP({V1,V2, ...}) = UNION(CFP(V1,PS),CFP(V2,PS),...)
684   /// CTP([V1,V2,...]) = UNION(CFP(V1,PS),CFP(V2,PS),...)
685   /// CTP(other types, PS) = PS
686   Value *collapseToPrimitiveShadow(Value *Shadow, Instruction *Pos);
687 
688   void storeZeroPrimitiveShadow(Value *Addr, uint64_t Size, Align ShadowAlign,
689                                 Instruction *Pos);
690 
691   Align getShadowAlign(Align InstAlignment);
692 
693 private:
694   /// Collapses the shadow with aggregate type into a single primitive shadow
695   /// value.
696   template <class AggregateType>
697   Value *collapseAggregateShadow(AggregateType *AT, Value *Shadow,
698                                  IRBuilder<> &IRB);
699 
700   Value *collapseToPrimitiveShadow(Value *Shadow, IRBuilder<> &IRB);
701 
702   /// Returns the shadow value of an argument A.
703   Value *getShadowForTLSArgument(Argument *A);
704 
705   /// The fast path of loading shadow in legacy mode.
706   Value *loadLegacyShadowFast(Value *ShadowAddr, uint64_t Size,
707                               Align ShadowAlign, Instruction *Pos);
708 
709   /// The fast path of loading shadow in fast-16-label mode.
710   std::pair<Value *, Value *>
711   loadFast16ShadowFast(Value *ShadowAddr, Value *OriginAddr, uint64_t Size,
712                        Align ShadowAlign, Align OriginAlign, Value *FirstOrigin,
713                        Instruction *Pos);
714 
715   Align getOriginAlign(Align InstAlignment);
716 
717   /// Because 4 contiguous bytes share one 4-byte origin, the most accurate load
718   /// is __dfsan_load_label_and_origin. This function returns the union of all
719   /// labels and the origin of the first taint label. However this is an
720   /// additional call with many instructions. To ensure common cases are fast,
721   /// checks if it is possible to load labels and origins without using the
722   /// callback function.
723   ///
724   /// When enabling tracking load instructions, we always use
725   /// __dfsan_load_label_and_origin to reduce code size.
726   bool useCallbackLoadLabelAndOrigin(uint64_t Size, Align InstAlignment);
727 
728   /// Returns a chain at the current stack with previous origin V.
729   Value *updateOrigin(Value *V, IRBuilder<> &IRB);
730 
731   /// Returns a chain at the current stack with previous origin V if Shadow is
732   /// tainted.
733   Value *updateOriginIfTainted(Value *Shadow, Value *Origin, IRBuilder<> &IRB);
734 
735   /// Creates an Intptr = Origin | Origin << 32 if Intptr's size is 64. Returns
736   /// Origin otherwise.
737   Value *originToIntptr(IRBuilder<> &IRB, Value *Origin);
738 
739   /// Stores Origin into the address range [StoreOriginAddr, StoreOriginAddr +
740   /// Size).
741   void paintOrigin(IRBuilder<> &IRB, Value *Origin, Value *StoreOriginAddr,
742                    uint64_t StoreOriginSize, Align Alignment);
743 
744   /// Stores Origin in terms of its Shadow value.
745   /// * Do not write origins for zero shadows because we do not trace origins
746   ///   for untainted sinks.
747   /// * Use __dfsan_maybe_store_origin if there are too many origin store
748   ///   instrumentations.
749   void storeOrigin(Instruction *Pos, Value *Addr, uint64_t Size, Value *Shadow,
750                    Value *Origin, Value *StoreOriginAddr, Align InstAlignment);
751 
752   /// Convert a scalar value to an i1 by comparing with 0.
753   Value *convertToBool(Value *V, IRBuilder<> &IRB, const Twine &Name = "");
754 
755   bool shouldInstrumentWithCall();
756 
757   /// Generates IR to load shadow and origin corresponding to bytes [\p
758   /// Addr, \p Addr + \p Size), where addr has alignment \p
759   /// InstAlignment, and take the union of each of those shadows. The returned
760   /// shadow always has primitive type.
761   std::pair<Value *, Value *>
762   loadShadowOriginSansLoadTracking(Value *Addr, uint64_t Size,
763                                    Align InstAlignment, Instruction *Pos);
764   int NumOriginStores = 0;
765 };
766 
767 class DFSanVisitor : public InstVisitor<DFSanVisitor> {
768 public:
769   DFSanFunction &DFSF;
770 
771   DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
772 
773   const DataLayout &getDataLayout() const {
774     return DFSF.F->getParent()->getDataLayout();
775   }
776 
777   // Combines shadow values and origins for all of I's operands.
778   void visitInstOperands(Instruction &I);
779 
780   void visitUnaryOperator(UnaryOperator &UO);
781   void visitBinaryOperator(BinaryOperator &BO);
782   void visitBitCastInst(BitCastInst &BCI);
783   void visitCastInst(CastInst &CI);
784   void visitCmpInst(CmpInst &CI);
785   void visitGetElementPtrInst(GetElementPtrInst &GEPI);
786   void visitLoadInst(LoadInst &LI);
787   void visitStoreInst(StoreInst &SI);
788   void visitAtomicRMWInst(AtomicRMWInst &I);
789   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I);
790   void visitReturnInst(ReturnInst &RI);
791   void visitCallBase(CallBase &CB);
792   void visitPHINode(PHINode &PN);
793   void visitExtractElementInst(ExtractElementInst &I);
794   void visitInsertElementInst(InsertElementInst &I);
795   void visitShuffleVectorInst(ShuffleVectorInst &I);
796   void visitExtractValueInst(ExtractValueInst &I);
797   void visitInsertValueInst(InsertValueInst &I);
798   void visitAllocaInst(AllocaInst &I);
799   void visitSelectInst(SelectInst &I);
800   void visitMemSetInst(MemSetInst &I);
801   void visitMemTransferInst(MemTransferInst &I);
802 
803 private:
804   void visitCASOrRMW(Align InstAlignment, Instruction &I);
805 
806   // Returns false when this is an invoke of a custom function.
807   bool visitWrappedCallBase(Function &F, CallBase &CB);
808 
809   // Combines origins for all of I's operands.
810   void visitInstOperandOrigins(Instruction &I);
811 
812   void addShadowArguments(Function &F, CallBase &CB, std::vector<Value *> &Args,
813                           IRBuilder<> &IRB);
814 
815   void addOriginArguments(Function &F, CallBase &CB, std::vector<Value *> &Args,
816                           IRBuilder<> &IRB);
817 };
818 
819 } // end anonymous namespace
820 
821 DataFlowSanitizer::DataFlowSanitizer(
822     const std::vector<std::string> &ABIListFiles) {
823   if (ClFast8Labels && ClFast16Labels) {
824     report_fatal_error(
825         "cannot set both -dfsan-fast-8-labels and -dfsan-fast-16-labels");
826   }
827 
828   ShadowWidthBits = ClFast8Labels ? 8 : 16;
829   ShadowWidthBytes = ShadowWidthBits / 8;
830 
831   std::vector<std::string> AllABIListFiles(std::move(ABIListFiles));
832   llvm::append_range(AllABIListFiles, ClABIListFiles);
833   // FIXME: should we propagate vfs::FileSystem to this constructor?
834   ABIList.set(
835       SpecialCaseList::createOrDie(AllABIListFiles, *vfs::getRealFileSystem()));
836 }
837 
838 FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
839   SmallVector<Type *, 4> ArgTypes(T->param_begin(), T->param_end());
840   ArgTypes.append(T->getNumParams(), PrimitiveShadowTy);
841   if (T->isVarArg())
842     ArgTypes.push_back(PrimitiveShadowPtrTy);
843   Type *RetType = T->getReturnType();
844   if (!RetType->isVoidTy())
845     RetType = StructType::get(RetType, PrimitiveShadowTy);
846   return FunctionType::get(RetType, ArgTypes, T->isVarArg());
847 }
848 
849 FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) {
850   assert(!T->isVarArg());
851   SmallVector<Type *, 4> ArgTypes;
852   ArgTypes.push_back(T->getPointerTo());
853   ArgTypes.append(T->param_begin(), T->param_end());
854   ArgTypes.append(T->getNumParams(), PrimitiveShadowTy);
855   Type *RetType = T->getReturnType();
856   if (!RetType->isVoidTy())
857     ArgTypes.push_back(PrimitiveShadowPtrTy);
858 
859   if (shouldTrackOrigins()) {
860     ArgTypes.append(T->getNumParams(), OriginTy);
861     if (!RetType->isVoidTy())
862       ArgTypes.push_back(OriginPtrTy);
863   }
864 
865   return FunctionType::get(T->getReturnType(), ArgTypes, false);
866 }
867 
868 TransformedFunction DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
869   SmallVector<Type *, 4> ArgTypes;
870 
871   // Some parameters of the custom function being constructed are
872   // parameters of T.  Record the mapping from parameters of T to
873   // parameters of the custom function, so that parameter attributes
874   // at call sites can be updated.
875   std::vector<unsigned> ArgumentIndexMapping;
876   for (unsigned I = 0, E = T->getNumParams(); I != E; ++I) {
877     Type *ParamType = T->getParamType(I);
878     FunctionType *FT;
879     if (isa<PointerType>(ParamType) &&
880         (FT = dyn_cast<FunctionType>(ParamType->getPointerElementType()))) {
881       ArgumentIndexMapping.push_back(ArgTypes.size());
882       ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo());
883       ArgTypes.push_back(Type::getInt8PtrTy(*Ctx));
884     } else {
885       ArgumentIndexMapping.push_back(ArgTypes.size());
886       ArgTypes.push_back(ParamType);
887     }
888   }
889   for (unsigned I = 0, E = T->getNumParams(); I != E; ++I)
890     ArgTypes.push_back(PrimitiveShadowTy);
891   if (T->isVarArg())
892     ArgTypes.push_back(PrimitiveShadowPtrTy);
893   Type *RetType = T->getReturnType();
894   if (!RetType->isVoidTy())
895     ArgTypes.push_back(PrimitiveShadowPtrTy);
896 
897   if (shouldTrackOrigins()) {
898     for (unsigned I = 0, E = T->getNumParams(); I != E; ++I)
899       ArgTypes.push_back(OriginTy);
900     if (T->isVarArg())
901       ArgTypes.push_back(OriginPtrTy);
902     if (!RetType->isVoidTy())
903       ArgTypes.push_back(OriginPtrTy);
904   }
905 
906   return TransformedFunction(
907       T, FunctionType::get(T->getReturnType(), ArgTypes, T->isVarArg()),
908       ArgumentIndexMapping);
909 }
910 
911 bool DataFlowSanitizer::isZeroShadow(Value *V) {
912   if (!shouldTrackFieldsAndIndices())
913     return ZeroPrimitiveShadow == V;
914 
915   Type *T = V->getType();
916   if (!isa<ArrayType>(T) && !isa<StructType>(T)) {
917     if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
918       return CI->isZero();
919     return false;
920   }
921 
922   return isa<ConstantAggregateZero>(V);
923 }
924 
925 bool DataFlowSanitizer::hasFastLabelsEnabled() {
926   static const bool HasFastLabelsEnabled = ClFast8Labels || ClFast16Labels;
927   return HasFastLabelsEnabled;
928 }
929 
930 bool DataFlowSanitizer::hasLoadSizeForFastPath(uint64_t Size) {
931   uint64_t ShadowSize = Size * ShadowWidthBytes;
932   return ShadowSize % 8 == 0 || ShadowSize == 4;
933 }
934 
935 bool DataFlowSanitizer::shouldTrackOrigins() {
936   static const bool ShouldTrackOrigins =
937       ClTrackOrigins && getInstrumentedABI() == DataFlowSanitizer::IA_TLS &&
938       hasFastLabelsEnabled();
939   return ShouldTrackOrigins;
940 }
941 
942 bool DataFlowSanitizer::shouldTrackFieldsAndIndices() {
943   return getInstrumentedABI() == DataFlowSanitizer::IA_TLS &&
944          hasFastLabelsEnabled();
945 }
946 
947 Constant *DataFlowSanitizer::getZeroShadow(Type *OrigTy) {
948   if (!shouldTrackFieldsAndIndices())
949     return ZeroPrimitiveShadow;
950 
951   if (!isa<ArrayType>(OrigTy) && !isa<StructType>(OrigTy))
952     return ZeroPrimitiveShadow;
953   Type *ShadowTy = getShadowTy(OrigTy);
954   return ConstantAggregateZero::get(ShadowTy);
955 }
956 
957 Constant *DataFlowSanitizer::getZeroShadow(Value *V) {
958   return getZeroShadow(V->getType());
959 }
960 
961 static Value *expandFromPrimitiveShadowRecursive(
962     Value *Shadow, SmallVector<unsigned, 4> &Indices, Type *SubShadowTy,
963     Value *PrimitiveShadow, IRBuilder<> &IRB) {
964   if (!isa<ArrayType>(SubShadowTy) && !isa<StructType>(SubShadowTy))
965     return IRB.CreateInsertValue(Shadow, PrimitiveShadow, Indices);
966 
967   if (ArrayType *AT = dyn_cast<ArrayType>(SubShadowTy)) {
968     for (unsigned Idx = 0; Idx < AT->getNumElements(); Idx++) {
969       Indices.push_back(Idx);
970       Shadow = expandFromPrimitiveShadowRecursive(
971           Shadow, Indices, AT->getElementType(), PrimitiveShadow, IRB);
972       Indices.pop_back();
973     }
974     return Shadow;
975   }
976 
977   if (StructType *ST = dyn_cast<StructType>(SubShadowTy)) {
978     for (unsigned Idx = 0; Idx < ST->getNumElements(); Idx++) {
979       Indices.push_back(Idx);
980       Shadow = expandFromPrimitiveShadowRecursive(
981           Shadow, Indices, ST->getElementType(Idx), PrimitiveShadow, IRB);
982       Indices.pop_back();
983     }
984     return Shadow;
985   }
986   llvm_unreachable("Unexpected shadow type");
987 }
988 
989 bool DFSanFunction::shouldInstrumentWithCall() {
990   return ClInstrumentWithCallThreshold >= 0 &&
991          NumOriginStores >= ClInstrumentWithCallThreshold;
992 }
993 
994 Value *DFSanFunction::expandFromPrimitiveShadow(Type *T, Value *PrimitiveShadow,
995                                                 Instruction *Pos) {
996   Type *ShadowTy = DFS.getShadowTy(T);
997 
998   if (!isa<ArrayType>(ShadowTy) && !isa<StructType>(ShadowTy))
999     return PrimitiveShadow;
1000 
1001   if (DFS.isZeroShadow(PrimitiveShadow))
1002     return DFS.getZeroShadow(ShadowTy);
1003 
1004   IRBuilder<> IRB(Pos);
1005   SmallVector<unsigned, 4> Indices;
1006   Value *Shadow = UndefValue::get(ShadowTy);
1007   Shadow = expandFromPrimitiveShadowRecursive(Shadow, Indices, ShadowTy,
1008                                               PrimitiveShadow, IRB);
1009 
1010   // Caches the primitive shadow value that built the shadow value.
1011   CachedCollapsedShadows[Shadow] = PrimitiveShadow;
1012   return Shadow;
1013 }
1014 
1015 template <class AggregateType>
1016 Value *DFSanFunction::collapseAggregateShadow(AggregateType *AT, Value *Shadow,
1017                                               IRBuilder<> &IRB) {
1018   if (!AT->getNumElements())
1019     return DFS.ZeroPrimitiveShadow;
1020 
1021   Value *FirstItem = IRB.CreateExtractValue(Shadow, 0);
1022   Value *Aggregator = collapseToPrimitiveShadow(FirstItem, IRB);
1023 
1024   for (unsigned Idx = 1; Idx < AT->getNumElements(); Idx++) {
1025     Value *ShadowItem = IRB.CreateExtractValue(Shadow, Idx);
1026     Value *ShadowInner = collapseToPrimitiveShadow(ShadowItem, IRB);
1027     Aggregator = IRB.CreateOr(Aggregator, ShadowInner);
1028   }
1029   return Aggregator;
1030 }
1031 
1032 Value *DFSanFunction::collapseToPrimitiveShadow(Value *Shadow,
1033                                                 IRBuilder<> &IRB) {
1034   Type *ShadowTy = Shadow->getType();
1035   if (!isa<ArrayType>(ShadowTy) && !isa<StructType>(ShadowTy))
1036     return Shadow;
1037   if (ArrayType *AT = dyn_cast<ArrayType>(ShadowTy))
1038     return collapseAggregateShadow<>(AT, Shadow, IRB);
1039   if (StructType *ST = dyn_cast<StructType>(ShadowTy))
1040     return collapseAggregateShadow<>(ST, Shadow, IRB);
1041   llvm_unreachable("Unexpected shadow type");
1042 }
1043 
1044 Value *DFSanFunction::collapseToPrimitiveShadow(Value *Shadow,
1045                                                 Instruction *Pos) {
1046   Type *ShadowTy = Shadow->getType();
1047   if (!isa<ArrayType>(ShadowTy) && !isa<StructType>(ShadowTy))
1048     return Shadow;
1049 
1050   assert(DFS.shouldTrackFieldsAndIndices());
1051 
1052   // Checks if the cached collapsed shadow value dominates Pos.
1053   Value *&CS = CachedCollapsedShadows[Shadow];
1054   if (CS && DT.dominates(CS, Pos))
1055     return CS;
1056 
1057   IRBuilder<> IRB(Pos);
1058   Value *PrimitiveShadow = collapseToPrimitiveShadow(Shadow, IRB);
1059   // Caches the converted primitive shadow value.
1060   CS = PrimitiveShadow;
1061   return PrimitiveShadow;
1062 }
1063 
1064 Type *DataFlowSanitizer::getShadowTy(Type *OrigTy) {
1065   if (!shouldTrackFieldsAndIndices())
1066     return PrimitiveShadowTy;
1067 
1068   if (!OrigTy->isSized())
1069     return PrimitiveShadowTy;
1070   if (isa<IntegerType>(OrigTy))
1071     return PrimitiveShadowTy;
1072   if (isa<VectorType>(OrigTy))
1073     return PrimitiveShadowTy;
1074   if (ArrayType *AT = dyn_cast<ArrayType>(OrigTy))
1075     return ArrayType::get(getShadowTy(AT->getElementType()),
1076                           AT->getNumElements());
1077   if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
1078     SmallVector<Type *, 4> Elements;
1079     for (unsigned I = 0, N = ST->getNumElements(); I < N; ++I)
1080       Elements.push_back(getShadowTy(ST->getElementType(I)));
1081     return StructType::get(*Ctx, Elements);
1082   }
1083   return PrimitiveShadowTy;
1084 }
1085 
1086 Type *DataFlowSanitizer::getShadowTy(Value *V) {
1087   return getShadowTy(V->getType());
1088 }
1089 
1090 bool DataFlowSanitizer::init(Module &M) {
1091   Triple TargetTriple(M.getTargetTriple());
1092   const DataLayout &DL = M.getDataLayout();
1093 
1094   Mod = &M;
1095   Ctx = &M.getContext();
1096   Int8Ptr = Type::getInt8PtrTy(*Ctx);
1097   OriginTy = IntegerType::get(*Ctx, OriginWidthBits);
1098   OriginPtrTy = PointerType::getUnqual(OriginTy);
1099   PrimitiveShadowTy = IntegerType::get(*Ctx, ShadowWidthBits);
1100   PrimitiveShadowPtrTy = PointerType::getUnqual(PrimitiveShadowTy);
1101   IntptrTy = DL.getIntPtrType(*Ctx);
1102   ZeroPrimitiveShadow = ConstantInt::getSigned(PrimitiveShadowTy, 0);
1103   ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidthBytes);
1104   OriginBase = ConstantInt::get(IntptrTy, 0x200000000000LL);
1105   ZeroOrigin = ConstantInt::getSigned(OriginTy, 0);
1106 
1107   switch (TargetTriple.getArch()) {
1108   case Triple::x86_64:
1109     ShadowPtrMask = ClFast8Labels
1110                         ? ConstantInt::getSigned(IntptrTy, ~0x600000000000LL)
1111                         : ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
1112     break;
1113   case Triple::mips64:
1114   case Triple::mips64el:
1115     ShadowPtrMask = ClFast8Labels
1116                         ? ConstantInt::getSigned(IntptrTy, ~0xE000000000LL)
1117                         : ConstantInt::getSigned(IntptrTy, ~0xF000000000LL);
1118     break;
1119   case Triple::aarch64:
1120   case Triple::aarch64_be:
1121     // AArch64 supports multiple VMAs and the shadow mask is set at runtime.
1122     DFSanRuntimeShadowMask = true;
1123     break;
1124   default:
1125     report_fatal_error("unsupported triple");
1126   }
1127 
1128   Type *DFSanUnionArgs[2] = {PrimitiveShadowTy, PrimitiveShadowTy};
1129   DFSanUnionFnTy =
1130       FunctionType::get(PrimitiveShadowTy, DFSanUnionArgs, /*isVarArg=*/false);
1131   Type *DFSanUnionLoadArgs[2] = {PrimitiveShadowPtrTy, IntptrTy};
1132   DFSanUnionLoadFnTy = FunctionType::get(PrimitiveShadowTy, DFSanUnionLoadArgs,
1133                                          /*isVarArg=*/false);
1134   Type *DFSanLoadLabelAndOriginArgs[2] = {Int8Ptr, IntptrTy};
1135   DFSanLoadLabelAndOriginFnTy =
1136       FunctionType::get(IntegerType::get(*Ctx, 64), DFSanLoadLabelAndOriginArgs,
1137                         /*isVarArg=*/false);
1138   DFSanUnimplementedFnTy = FunctionType::get(
1139       Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
1140   Type *DFSanSetLabelArgs[4] = {PrimitiveShadowTy, OriginTy,
1141                                 Type::getInt8PtrTy(*Ctx), IntptrTy};
1142   DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
1143                                         DFSanSetLabelArgs, /*isVarArg=*/false);
1144   DFSanNonzeroLabelFnTy =
1145       FunctionType::get(Type::getVoidTy(*Ctx), None, /*isVarArg=*/false);
1146   DFSanVarargWrapperFnTy = FunctionType::get(
1147       Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
1148   DFSanCmpCallbackFnTy =
1149       FunctionType::get(Type::getVoidTy(*Ctx), PrimitiveShadowTy,
1150                         /*isVarArg=*/false);
1151   DFSanChainOriginFnTy =
1152       FunctionType::get(OriginTy, OriginTy, /*isVarArg=*/false);
1153   Type *DFSanChainOriginIfTaintedArgs[2] = {PrimitiveShadowTy, OriginTy};
1154   DFSanChainOriginIfTaintedFnTy = FunctionType::get(
1155       OriginTy, DFSanChainOriginIfTaintedArgs, /*isVarArg=*/false);
1156   Type *DFSanMaybeStoreOriginArgs[4] = {IntegerType::get(*Ctx, ShadowWidthBits),
1157                                         Int8Ptr, IntptrTy, OriginTy};
1158   DFSanMaybeStoreOriginFnTy = FunctionType::get(
1159       Type::getVoidTy(*Ctx), DFSanMaybeStoreOriginArgs, /*isVarArg=*/false);
1160   Type *DFSanMemOriginTransferArgs[3] = {Int8Ptr, Int8Ptr, IntptrTy};
1161   DFSanMemOriginTransferFnTy = FunctionType::get(
1162       Type::getVoidTy(*Ctx), DFSanMemOriginTransferArgs, /*isVarArg=*/false);
1163   Type *DFSanLoadStoreCallbackArgs[2] = {PrimitiveShadowTy, Int8Ptr};
1164   DFSanLoadStoreCallbackFnTy =
1165       FunctionType::get(Type::getVoidTy(*Ctx), DFSanLoadStoreCallbackArgs,
1166                         /*isVarArg=*/false);
1167   Type *DFSanMemTransferCallbackArgs[2] = {PrimitiveShadowPtrTy, IntptrTy};
1168   DFSanMemTransferCallbackFnTy =
1169       FunctionType::get(Type::getVoidTy(*Ctx), DFSanMemTransferCallbackArgs,
1170                         /*isVarArg=*/false);
1171 
1172   ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
1173   OriginStoreWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
1174   return true;
1175 }
1176 
1177 bool DataFlowSanitizer::isInstrumented(const Function *F) {
1178   return !ABIList.isIn(*F, "uninstrumented");
1179 }
1180 
1181 bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
1182   return !ABIList.isIn(*GA, "uninstrumented");
1183 }
1184 
1185 DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
1186   return ClArgsABI ? IA_Args : IA_TLS;
1187 }
1188 
1189 DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
1190   if (ABIList.isIn(*F, "functional"))
1191     return WK_Functional;
1192   if (ABIList.isIn(*F, "discard"))
1193     return WK_Discard;
1194   if (ABIList.isIn(*F, "custom"))
1195     return WK_Custom;
1196 
1197   return WK_Warning;
1198 }
1199 
1200 void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
1201   std::string GVName = std::string(GV->getName()), Prefix = "dfs$";
1202   GV->setName(Prefix + GVName);
1203 
1204   // Try to change the name of the function in module inline asm.  We only do
1205   // this for specific asm directives, currently only ".symver", to try to avoid
1206   // corrupting asm which happens to contain the symbol name as a substring.
1207   // Note that the substitution for .symver assumes that the versioned symbol
1208   // also has an instrumented name.
1209   std::string Asm = GV->getParent()->getModuleInlineAsm();
1210   std::string SearchStr = ".symver " + GVName + ",";
1211   size_t Pos = Asm.find(SearchStr);
1212   if (Pos != std::string::npos) {
1213     Asm.replace(Pos, SearchStr.size(),
1214                 ".symver " + Prefix + GVName + "," + Prefix);
1215     GV->getParent()->setModuleInlineAsm(Asm);
1216   }
1217 }
1218 
1219 Function *
1220 DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
1221                                         GlobalValue::LinkageTypes NewFLink,
1222                                         FunctionType *NewFT) {
1223   FunctionType *FT = F->getFunctionType();
1224   Function *NewF = Function::Create(NewFT, NewFLink, F->getAddressSpace(),
1225                                     NewFName, F->getParent());
1226   NewF->copyAttributesFrom(F);
1227   NewF->removeAttributes(
1228       AttributeList::ReturnIndex,
1229       AttributeFuncs::typeIncompatible(NewFT->getReturnType()));
1230 
1231   BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
1232   if (F->isVarArg()) {
1233     NewF->removeAttributes(AttributeList::FunctionIndex,
1234                            AttrBuilder().addAttribute("split-stack"));
1235     CallInst::Create(DFSanVarargWrapperFn,
1236                      IRBuilder<>(BB).CreateGlobalStringPtr(F->getName()), "",
1237                      BB);
1238     new UnreachableInst(*Ctx, BB);
1239   } else {
1240     auto ArgIt = pointer_iterator<Argument *>(NewF->arg_begin());
1241     std::vector<Value *> Args(ArgIt, ArgIt + FT->getNumParams());
1242 
1243     CallInst *CI = CallInst::Create(F, Args, "", BB);
1244     CI->setAttributes(F->getAttributes());
1245     if (FT->getReturnType()->isVoidTy())
1246       ReturnInst::Create(*Ctx, BB);
1247     else
1248       ReturnInst::Create(*Ctx, CI, BB);
1249   }
1250 
1251   return NewF;
1252 }
1253 
1254 Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
1255                                                           StringRef FName) {
1256   FunctionType *FTT = getTrampolineFunctionType(FT);
1257   FunctionCallee C = Mod->getOrInsertFunction(FName, FTT);
1258   Function *F = dyn_cast<Function>(C.getCallee());
1259   if (F && F->isDeclaration()) {
1260     F->setLinkage(GlobalValue::LinkOnceODRLinkage);
1261     BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
1262     std::vector<Value *> Args;
1263     Function::arg_iterator AI = F->arg_begin() + 1;
1264     for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
1265       Args.push_back(&*AI);
1266     CallInst *CI = CallInst::Create(FT, &*F->arg_begin(), Args, "", BB);
1267     Type *RetType = FT->getReturnType();
1268     ReturnInst *RI = RetType->isVoidTy() ? ReturnInst::Create(*Ctx, BB)
1269                                          : ReturnInst::Create(*Ctx, CI, BB);
1270 
1271     // F is called by a wrapped custom function with primitive shadows. So
1272     // its arguments and return value need conversion.
1273     DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
1274     Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI;
1275     ++ValAI;
1276     for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N) {
1277       Value *Shadow =
1278           DFSF.expandFromPrimitiveShadow(ValAI->getType(), &*ShadowAI, CI);
1279       DFSF.ValShadowMap[&*ValAI] = Shadow;
1280     }
1281     Function::arg_iterator RetShadowAI = ShadowAI;
1282     const bool ShouldTrackOrigins = shouldTrackOrigins();
1283     if (ShouldTrackOrigins) {
1284       ValAI = F->arg_begin();
1285       ++ValAI;
1286       Function::arg_iterator OriginAI = ShadowAI;
1287       if (!RetType->isVoidTy())
1288         ++OriginAI;
1289       for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++OriginAI, --N) {
1290         DFSF.ValOriginMap[&*ValAI] = &*OriginAI;
1291       }
1292     }
1293     DFSanVisitor(DFSF).visitCallInst(*CI);
1294     if (!RetType->isVoidTy()) {
1295       Value *PrimitiveShadow = DFSF.collapseToPrimitiveShadow(
1296           DFSF.getShadow(RI->getReturnValue()), RI);
1297       new StoreInst(PrimitiveShadow, &*RetShadowAI, RI);
1298       if (ShouldTrackOrigins) {
1299         Value *Origin = DFSF.getOrigin(RI->getReturnValue());
1300         new StoreInst(Origin, &*std::prev(F->arg_end()), RI);
1301       }
1302     }
1303   }
1304 
1305   return cast<Constant>(C.getCallee());
1306 }
1307 
1308 // Initialize DataFlowSanitizer runtime functions and declare them in the module
1309 void DataFlowSanitizer::initializeRuntimeFunctions(Module &M) {
1310   {
1311     AttributeList AL;
1312     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1313                          Attribute::NoUnwind);
1314     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1315                          Attribute::ReadNone);
1316     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1317                          Attribute::ZExt);
1318     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1319     AL = AL.addParamAttribute(M.getContext(), 1, Attribute::ZExt);
1320     DFSanUnionFn =
1321         Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy, AL);
1322   }
1323   {
1324     AttributeList AL;
1325     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1326                          Attribute::NoUnwind);
1327     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1328                          Attribute::ReadNone);
1329     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1330                          Attribute::ZExt);
1331     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1332     AL = AL.addParamAttribute(M.getContext(), 1, Attribute::ZExt);
1333     DFSanCheckedUnionFn =
1334         Mod->getOrInsertFunction("dfsan_union", DFSanUnionFnTy, AL);
1335   }
1336   {
1337     AttributeList AL;
1338     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1339                          Attribute::NoUnwind);
1340     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1341                          Attribute::ReadOnly);
1342     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1343                          Attribute::ZExt);
1344     DFSanUnionLoadFn =
1345         Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy, AL);
1346   }
1347   {
1348     AttributeList AL;
1349     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1350                          Attribute::NoUnwind);
1351     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1352                          Attribute::ReadOnly);
1353     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1354                          Attribute::ZExt);
1355     DFSanUnionLoadFastLabelsFn = Mod->getOrInsertFunction(
1356         "__dfsan_union_load_fast16labels", DFSanUnionLoadFnTy, AL);
1357   }
1358   {
1359     AttributeList AL;
1360     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1361                          Attribute::NoUnwind);
1362     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1363                          Attribute::ReadOnly);
1364     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1365                          Attribute::ZExt);
1366     DFSanLoadLabelAndOriginFn = Mod->getOrInsertFunction(
1367         "__dfsan_load_label_and_origin", DFSanLoadLabelAndOriginFnTy, AL);
1368   }
1369   DFSanUnimplementedFn =
1370       Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
1371   {
1372     AttributeList AL;
1373     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1374     AL = AL.addParamAttribute(M.getContext(), 1, Attribute::ZExt);
1375     DFSanSetLabelFn =
1376         Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy, AL);
1377   }
1378   DFSanNonzeroLabelFn =
1379       Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
1380   DFSanVarargWrapperFn = Mod->getOrInsertFunction("__dfsan_vararg_wrapper",
1381                                                   DFSanVarargWrapperFnTy);
1382   {
1383     AttributeList AL;
1384     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1385     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1386                          Attribute::ZExt);
1387     DFSanChainOriginFn = Mod->getOrInsertFunction("__dfsan_chain_origin",
1388                                                   DFSanChainOriginFnTy, AL);
1389   }
1390   {
1391     AttributeList AL;
1392     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1393     AL = AL.addParamAttribute(M.getContext(), 1, Attribute::ZExt);
1394     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1395                          Attribute::ZExt);
1396     DFSanChainOriginIfTaintedFn = Mod->getOrInsertFunction(
1397         "__dfsan_chain_origin_if_tainted", DFSanChainOriginIfTaintedFnTy, AL);
1398   }
1399   DFSanMemOriginTransferFn = Mod->getOrInsertFunction(
1400       "__dfsan_mem_origin_transfer", DFSanMemOriginTransferFnTy);
1401 
1402   {
1403     AttributeList AL;
1404     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1405     AL = AL.addParamAttribute(M.getContext(), 3, Attribute::ZExt);
1406     DFSanMaybeStoreOriginFn = Mod->getOrInsertFunction(
1407         "__dfsan_maybe_store_origin", DFSanMaybeStoreOriginFnTy, AL);
1408   }
1409 
1410   DFSanRuntimeFunctions.insert(DFSanUnionFn.getCallee()->stripPointerCasts());
1411   DFSanRuntimeFunctions.insert(
1412       DFSanCheckedUnionFn.getCallee()->stripPointerCasts());
1413   DFSanRuntimeFunctions.insert(
1414       DFSanUnionLoadFn.getCallee()->stripPointerCasts());
1415   DFSanRuntimeFunctions.insert(
1416       DFSanUnionLoadFastLabelsFn.getCallee()->stripPointerCasts());
1417   DFSanRuntimeFunctions.insert(
1418       DFSanLoadLabelAndOriginFn.getCallee()->stripPointerCasts());
1419   DFSanRuntimeFunctions.insert(
1420       DFSanUnimplementedFn.getCallee()->stripPointerCasts());
1421   DFSanRuntimeFunctions.insert(
1422       DFSanSetLabelFn.getCallee()->stripPointerCasts());
1423   DFSanRuntimeFunctions.insert(
1424       DFSanNonzeroLabelFn.getCallee()->stripPointerCasts());
1425   DFSanRuntimeFunctions.insert(
1426       DFSanVarargWrapperFn.getCallee()->stripPointerCasts());
1427   DFSanRuntimeFunctions.insert(
1428       DFSanLoadCallbackFn.getCallee()->stripPointerCasts());
1429   DFSanRuntimeFunctions.insert(
1430       DFSanStoreCallbackFn.getCallee()->stripPointerCasts());
1431   DFSanRuntimeFunctions.insert(
1432       DFSanMemTransferCallbackFn.getCallee()->stripPointerCasts());
1433   DFSanRuntimeFunctions.insert(
1434       DFSanCmpCallbackFn.getCallee()->stripPointerCasts());
1435   DFSanRuntimeFunctions.insert(
1436       DFSanChainOriginFn.getCallee()->stripPointerCasts());
1437   DFSanRuntimeFunctions.insert(
1438       DFSanChainOriginIfTaintedFn.getCallee()->stripPointerCasts());
1439   DFSanRuntimeFunctions.insert(
1440       DFSanMemOriginTransferFn.getCallee()->stripPointerCasts());
1441   DFSanRuntimeFunctions.insert(
1442       DFSanMaybeStoreOriginFn.getCallee()->stripPointerCasts());
1443 }
1444 
1445 // Initializes event callback functions and declare them in the module
1446 void DataFlowSanitizer::initializeCallbackFunctions(Module &M) {
1447   DFSanLoadCallbackFn = Mod->getOrInsertFunction("__dfsan_load_callback",
1448                                                  DFSanLoadStoreCallbackFnTy);
1449   DFSanStoreCallbackFn = Mod->getOrInsertFunction("__dfsan_store_callback",
1450                                                   DFSanLoadStoreCallbackFnTy);
1451   DFSanMemTransferCallbackFn = Mod->getOrInsertFunction(
1452       "__dfsan_mem_transfer_callback", DFSanMemTransferCallbackFnTy);
1453   DFSanCmpCallbackFn =
1454       Mod->getOrInsertFunction("__dfsan_cmp_callback", DFSanCmpCallbackFnTy);
1455 }
1456 
1457 void DataFlowSanitizer::injectMetadataGlobals(Module &M) {
1458   // These variables can be used:
1459   // - by the runtime (to discover what the shadow width was, during
1460   //   compilation)
1461   // - in testing (to avoid hardcoding the shadow width and type but instead
1462   //   extract them by pattern matching)
1463   Type *IntTy = Type::getInt32Ty(*Ctx);
1464   (void)Mod->getOrInsertGlobal("__dfsan_shadow_width_bits", IntTy, [&] {
1465     return new GlobalVariable(
1466         M, IntTy, /*isConstant=*/true, GlobalValue::WeakODRLinkage,
1467         ConstantInt::get(IntTy, ShadowWidthBits), "__dfsan_shadow_width_bits");
1468   });
1469   (void)Mod->getOrInsertGlobal("__dfsan_shadow_width_bytes", IntTy, [&] {
1470     return new GlobalVariable(M, IntTy, /*isConstant=*/true,
1471                               GlobalValue::WeakODRLinkage,
1472                               ConstantInt::get(IntTy, ShadowWidthBytes),
1473                               "__dfsan_shadow_width_bytes");
1474   });
1475 }
1476 
1477 bool DataFlowSanitizer::runImpl(Module &M) {
1478   init(M);
1479 
1480   if (ABIList.isIn(M, "skip"))
1481     return false;
1482 
1483   const unsigned InitialGlobalSize = M.global_size();
1484   const unsigned InitialModuleSize = M.size();
1485 
1486   bool Changed = false;
1487 
1488   auto GetOrInsertGlobal = [this, &Changed](StringRef Name,
1489                                             Type *Ty) -> Constant * {
1490     Constant *C = Mod->getOrInsertGlobal(Name, Ty);
1491     if (GlobalVariable *G = dyn_cast<GlobalVariable>(C)) {
1492       Changed |= G->getThreadLocalMode() != GlobalVariable::InitialExecTLSModel;
1493       G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
1494     }
1495     return C;
1496   };
1497 
1498   // These globals must be kept in sync with the ones in dfsan.cpp.
1499   ArgTLS =
1500       GetOrInsertGlobal("__dfsan_arg_tls",
1501                         ArrayType::get(Type::getInt64Ty(*Ctx), ArgTLSSize / 8));
1502   RetvalTLS = GetOrInsertGlobal(
1503       "__dfsan_retval_tls",
1504       ArrayType::get(Type::getInt64Ty(*Ctx), RetvalTLSSize / 8));
1505   ArgOriginTLSTy = ArrayType::get(OriginTy, NumOfElementsInArgOrgTLS);
1506   ArgOriginTLS = GetOrInsertGlobal("__dfsan_arg_origin_tls", ArgOriginTLSTy);
1507   RetvalOriginTLS = GetOrInsertGlobal("__dfsan_retval_origin_tls", OriginTy);
1508 
1509   (void)Mod->getOrInsertGlobal("__dfsan_track_origins", OriginTy, [&] {
1510     Changed = true;
1511     return new GlobalVariable(
1512         M, OriginTy, true, GlobalValue::WeakODRLinkage,
1513         ConstantInt::getSigned(OriginTy, shouldTrackOrigins()),
1514         "__dfsan_track_origins");
1515   });
1516 
1517   injectMetadataGlobals(M);
1518 
1519   ExternalShadowMask =
1520       Mod->getOrInsertGlobal(DFSanExternShadowPtrMask, IntptrTy);
1521 
1522   initializeCallbackFunctions(M);
1523   initializeRuntimeFunctions(M);
1524 
1525   std::vector<Function *> FnsToInstrument;
1526   SmallPtrSet<Function *, 2> FnsWithNativeABI;
1527   for (Function &F : M)
1528     if (!F.isIntrinsic() && !DFSanRuntimeFunctions.contains(&F))
1529       FnsToInstrument.push_back(&F);
1530 
1531   // Give function aliases prefixes when necessary, and build wrappers where the
1532   // instrumentedness is inconsistent.
1533   for (Module::alias_iterator AI = M.alias_begin(), AE = M.alias_end();
1534        AI != AE;) {
1535     GlobalAlias *GA = &*AI;
1536     ++AI;
1537     // Don't stop on weak.  We assume people aren't playing games with the
1538     // instrumentedness of overridden weak aliases.
1539     auto *F = dyn_cast<Function>(GA->getBaseObject());
1540     if (!F)
1541       continue;
1542 
1543     bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
1544     if (GAInst && FInst) {
1545       addGlobalNamePrefix(GA);
1546     } else if (GAInst != FInst) {
1547       // Non-instrumented alias of an instrumented function, or vice versa.
1548       // Replace the alias with a native-ABI wrapper of the aliasee.  The pass
1549       // below will take care of instrumenting it.
1550       Function *NewF =
1551           buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
1552       GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType()));
1553       NewF->takeName(GA);
1554       GA->eraseFromParent();
1555       FnsToInstrument.push_back(NewF);
1556     }
1557   }
1558 
1559   ReadOnlyNoneAttrs.addAttribute(Attribute::ReadOnly)
1560       .addAttribute(Attribute::ReadNone);
1561 
1562   // First, change the ABI of every function in the module.  ABI-listed
1563   // functions keep their original ABI and get a wrapper function.
1564   for (std::vector<Function *>::iterator FI = FnsToInstrument.begin(),
1565                                          FE = FnsToInstrument.end();
1566        FI != FE; ++FI) {
1567     Function &F = **FI;
1568     FunctionType *FT = F.getFunctionType();
1569 
1570     bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
1571                               FT->getReturnType()->isVoidTy());
1572 
1573     if (isInstrumented(&F)) {
1574       // Instrumented functions get a 'dfs$' prefix.  This allows us to more
1575       // easily identify cases of mismatching ABIs.
1576       if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
1577         FunctionType *NewFT = getArgsFunctionType(FT);
1578         Function *NewF = Function::Create(NewFT, F.getLinkage(),
1579                                           F.getAddressSpace(), "", &M);
1580         NewF->copyAttributesFrom(&F);
1581         NewF->removeAttributes(
1582             AttributeList::ReturnIndex,
1583             AttributeFuncs::typeIncompatible(NewFT->getReturnType()));
1584         for (Function::arg_iterator FArg = F.arg_begin(),
1585                                     NewFArg = NewF->arg_begin(),
1586                                     FArgEnd = F.arg_end();
1587              FArg != FArgEnd; ++FArg, ++NewFArg) {
1588           FArg->replaceAllUsesWith(&*NewFArg);
1589         }
1590         NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
1591 
1592         for (Function::user_iterator UI = F.user_begin(), UE = F.user_end();
1593              UI != UE;) {
1594           BlockAddress *BA = dyn_cast<BlockAddress>(*UI);
1595           ++UI;
1596           if (BA) {
1597             BA->replaceAllUsesWith(
1598                 BlockAddress::get(NewF, BA->getBasicBlock()));
1599             delete BA;
1600           }
1601         }
1602         F.replaceAllUsesWith(
1603             ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
1604         NewF->takeName(&F);
1605         F.eraseFromParent();
1606         *FI = NewF;
1607         addGlobalNamePrefix(NewF);
1608       } else {
1609         addGlobalNamePrefix(&F);
1610       }
1611     } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
1612       // Build a wrapper function for F.  The wrapper simply calls F, and is
1613       // added to FnsToInstrument so that any instrumentation according to its
1614       // WrapperKind is done in the second pass below.
1615       FunctionType *NewFT =
1616           getInstrumentedABI() == IA_Args ? getArgsFunctionType(FT) : FT;
1617 
1618       // If the function being wrapped has local linkage, then preserve the
1619       // function's linkage in the wrapper function.
1620       GlobalValue::LinkageTypes WrapperLinkage =
1621           F.hasLocalLinkage() ? F.getLinkage()
1622                               : GlobalValue::LinkOnceODRLinkage;
1623 
1624       Function *NewF = buildWrapperFunction(
1625           &F,
1626           (shouldTrackOrigins() ? std::string("dfso$") : std::string("dfsw$")) +
1627               std::string(F.getName()),
1628           WrapperLinkage, NewFT);
1629       if (getInstrumentedABI() == IA_TLS)
1630         NewF->removeAttributes(AttributeList::FunctionIndex, ReadOnlyNoneAttrs);
1631 
1632       Value *WrappedFnCst =
1633           ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
1634       F.replaceAllUsesWith(WrappedFnCst);
1635 
1636       UnwrappedFnMap[WrappedFnCst] = &F;
1637       *FI = NewF;
1638 
1639       if (!F.isDeclaration()) {
1640         // This function is probably defining an interposition of an
1641         // uninstrumented function and hence needs to keep the original ABI.
1642         // But any functions it may call need to use the instrumented ABI, so
1643         // we instrument it in a mode which preserves the original ABI.
1644         FnsWithNativeABI.insert(&F);
1645 
1646         // This code needs to rebuild the iterators, as they may be invalidated
1647         // by the push_back, taking care that the new range does not include
1648         // any functions added by this code.
1649         size_t N = FI - FnsToInstrument.begin(),
1650                Count = FE - FnsToInstrument.begin();
1651         FnsToInstrument.push_back(&F);
1652         FI = FnsToInstrument.begin() + N;
1653         FE = FnsToInstrument.begin() + Count;
1654       }
1655       // Hopefully, nobody will try to indirectly call a vararg
1656       // function... yet.
1657     } else if (FT->isVarArg()) {
1658       UnwrappedFnMap[&F] = &F;
1659       *FI = nullptr;
1660     }
1661   }
1662 
1663   for (Function *F : FnsToInstrument) {
1664     if (!F || F->isDeclaration())
1665       continue;
1666 
1667     removeUnreachableBlocks(*F);
1668 
1669     DFSanFunction DFSF(*this, F, FnsWithNativeABI.count(F));
1670 
1671     // DFSanVisitor may create new basic blocks, which confuses df_iterator.
1672     // Build a copy of the list before iterating over it.
1673     SmallVector<BasicBlock *, 4> BBList(depth_first(&F->getEntryBlock()));
1674 
1675     for (BasicBlock *BB : BBList) {
1676       Instruction *Inst = &BB->front();
1677       while (true) {
1678         // DFSanVisitor may split the current basic block, changing the current
1679         // instruction's next pointer and moving the next instruction to the
1680         // tail block from which we should continue.
1681         Instruction *Next = Inst->getNextNode();
1682         // DFSanVisitor may delete Inst, so keep track of whether it was a
1683         // terminator.
1684         bool IsTerminator = Inst->isTerminator();
1685         if (!DFSF.SkipInsts.count(Inst))
1686           DFSanVisitor(DFSF).visit(Inst);
1687         if (IsTerminator)
1688           break;
1689         Inst = Next;
1690       }
1691     }
1692 
1693     // We will not necessarily be able to compute the shadow for every phi node
1694     // until we have visited every block.  Therefore, the code that handles phi
1695     // nodes adds them to the PHIFixups list so that they can be properly
1696     // handled here.
1697     for (DFSanFunction::PHIFixupElement &P : DFSF.PHIFixups) {
1698       for (unsigned Val = 0, N = P.Phi->getNumIncomingValues(); Val != N;
1699            ++Val) {
1700         P.ShadowPhi->setIncomingValue(
1701             Val, DFSF.getShadow(P.Phi->getIncomingValue(Val)));
1702         if (P.OriginPhi)
1703           P.OriginPhi->setIncomingValue(
1704               Val, DFSF.getOrigin(P.Phi->getIncomingValue(Val)));
1705       }
1706     }
1707 
1708     // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
1709     // places (i.e. instructions in basic blocks we haven't even begun visiting
1710     // yet).  To make our life easier, do this work in a pass after the main
1711     // instrumentation.
1712     if (ClDebugNonzeroLabels) {
1713       for (Value *V : DFSF.NonZeroChecks) {
1714         Instruction *Pos;
1715         if (Instruction *I = dyn_cast<Instruction>(V))
1716           Pos = I->getNextNode();
1717         else
1718           Pos = &DFSF.F->getEntryBlock().front();
1719         while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
1720           Pos = Pos->getNextNode();
1721         IRBuilder<> IRB(Pos);
1722         Value *PrimitiveShadow = DFSF.collapseToPrimitiveShadow(V, Pos);
1723         Value *Ne =
1724             IRB.CreateICmpNE(PrimitiveShadow, DFSF.DFS.ZeroPrimitiveShadow);
1725         BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
1726             Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
1727         IRBuilder<> ThenIRB(BI);
1728         ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn, {});
1729       }
1730     }
1731   }
1732 
1733   return Changed || !FnsToInstrument.empty() ||
1734          M.global_size() != InitialGlobalSize || M.size() != InitialModuleSize;
1735 }
1736 
1737 Value *DFSanFunction::getArgTLS(Type *T, unsigned ArgOffset, IRBuilder<> &IRB) {
1738   Value *Base = IRB.CreatePointerCast(DFS.ArgTLS, DFS.IntptrTy);
1739   if (ArgOffset)
1740     Base = IRB.CreateAdd(Base, ConstantInt::get(DFS.IntptrTy, ArgOffset));
1741   return IRB.CreateIntToPtr(Base, PointerType::get(DFS.getShadowTy(T), 0),
1742                             "_dfsarg");
1743 }
1744 
1745 Value *DFSanFunction::getRetvalTLS(Type *T, IRBuilder<> &IRB) {
1746   return IRB.CreatePointerCast(
1747       DFS.RetvalTLS, PointerType::get(DFS.getShadowTy(T), 0), "_dfsret");
1748 }
1749 
1750 Value *DFSanFunction::getRetvalOriginTLS() { return DFS.RetvalOriginTLS; }
1751 
1752 Value *DFSanFunction::getArgOriginTLS(unsigned ArgNo, IRBuilder<> &IRB) {
1753   return IRB.CreateConstGEP2_64(DFS.ArgOriginTLSTy, DFS.ArgOriginTLS, 0, ArgNo,
1754                                 "_dfsarg_o");
1755 }
1756 
1757 Value *DFSanFunction::getOrigin(Value *V) {
1758   assert(DFS.shouldTrackOrigins());
1759   if (!isa<Argument>(V) && !isa<Instruction>(V))
1760     return DFS.ZeroOrigin;
1761   Value *&Origin = ValOriginMap[V];
1762   if (!Origin) {
1763     if (Argument *A = dyn_cast<Argument>(V)) {
1764       if (IsNativeABI)
1765         return DFS.ZeroOrigin;
1766       switch (IA) {
1767       case DataFlowSanitizer::IA_TLS: {
1768         if (A->getArgNo() < DFS.NumOfElementsInArgOrgTLS) {
1769           Instruction *ArgOriginTLSPos = &*F->getEntryBlock().begin();
1770           IRBuilder<> IRB(ArgOriginTLSPos);
1771           Value *ArgOriginPtr = getArgOriginTLS(A->getArgNo(), IRB);
1772           Origin = IRB.CreateLoad(DFS.OriginTy, ArgOriginPtr);
1773         } else {
1774           // Overflow
1775           Origin = DFS.ZeroOrigin;
1776         }
1777         break;
1778       }
1779       case DataFlowSanitizer::IA_Args: {
1780         Origin = DFS.ZeroOrigin;
1781         break;
1782       }
1783       }
1784     } else {
1785       Origin = DFS.ZeroOrigin;
1786     }
1787   }
1788   return Origin;
1789 }
1790 
1791 void DFSanFunction::setOrigin(Instruction *I, Value *Origin) {
1792   if (!DFS.shouldTrackOrigins())
1793     return;
1794   assert(!ValOriginMap.count(I));
1795   assert(Origin->getType() == DFS.OriginTy);
1796   ValOriginMap[I] = Origin;
1797 }
1798 
1799 Value *DFSanFunction::getShadowForTLSArgument(Argument *A) {
1800   unsigned ArgOffset = 0;
1801   const DataLayout &DL = F->getParent()->getDataLayout();
1802   for (auto &FArg : F->args()) {
1803     if (!FArg.getType()->isSized()) {
1804       if (A == &FArg)
1805         break;
1806       continue;
1807     }
1808 
1809     unsigned Size = DL.getTypeAllocSize(DFS.getShadowTy(&FArg));
1810     if (A != &FArg) {
1811       ArgOffset += alignTo(Size, ShadowTLSAlignment);
1812       if (ArgOffset > ArgTLSSize)
1813         break; // ArgTLS overflows, uses a zero shadow.
1814       continue;
1815     }
1816 
1817     if (ArgOffset + Size > ArgTLSSize)
1818       break; // ArgTLS overflows, uses a zero shadow.
1819 
1820     Instruction *ArgTLSPos = &*F->getEntryBlock().begin();
1821     IRBuilder<> IRB(ArgTLSPos);
1822     Value *ArgShadowPtr = getArgTLS(FArg.getType(), ArgOffset, IRB);
1823     return IRB.CreateAlignedLoad(DFS.getShadowTy(&FArg), ArgShadowPtr,
1824                                  ShadowTLSAlignment);
1825   }
1826 
1827   return DFS.getZeroShadow(A);
1828 }
1829 
1830 Value *DFSanFunction::getShadow(Value *V) {
1831   if (!isa<Argument>(V) && !isa<Instruction>(V))
1832     return DFS.getZeroShadow(V);
1833   Value *&Shadow = ValShadowMap[V];
1834   if (!Shadow) {
1835     if (Argument *A = dyn_cast<Argument>(V)) {
1836       if (IsNativeABI)
1837         return DFS.getZeroShadow(V);
1838       switch (IA) {
1839       case DataFlowSanitizer::IA_TLS: {
1840         Shadow = getShadowForTLSArgument(A);
1841         break;
1842       }
1843       case DataFlowSanitizer::IA_Args: {
1844         unsigned ArgIdx = A->getArgNo() + F->arg_size() / 2;
1845         Function::arg_iterator Arg = F->arg_begin();
1846         std::advance(Arg, ArgIdx);
1847         Shadow = &*Arg;
1848         assert(Shadow->getType() == DFS.PrimitiveShadowTy);
1849         break;
1850       }
1851       }
1852       NonZeroChecks.push_back(Shadow);
1853     } else {
1854       Shadow = DFS.getZeroShadow(V);
1855     }
1856   }
1857   return Shadow;
1858 }
1859 
1860 void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
1861   assert(!ValShadowMap.count(I));
1862   assert(DFS.shouldTrackFieldsAndIndices() ||
1863          Shadow->getType() == DFS.PrimitiveShadowTy);
1864   ValShadowMap[I] = Shadow;
1865 }
1866 
1867 Value *DataFlowSanitizer::getShadowOffset(Value *Addr, IRBuilder<> &IRB) {
1868   // Returns Addr & shadow_mask
1869   assert(Addr != RetvalTLS && "Reinstrumenting?");
1870   Value *ShadowPtrMaskValue;
1871   if (DFSanRuntimeShadowMask)
1872     ShadowPtrMaskValue = IRB.CreateLoad(IntptrTy, ExternalShadowMask);
1873   else
1874     ShadowPtrMaskValue = ShadowPtrMask;
1875   return IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy),
1876                        IRB.CreatePtrToInt(ShadowPtrMaskValue, IntptrTy));
1877 }
1878 
1879 std::pair<Value *, Value *>
1880 DataFlowSanitizer::getShadowOriginAddress(Value *Addr, Align InstAlignment,
1881                                           Instruction *Pos) {
1882   // Returns ((Addr & shadow_mask) + origin_base) & ~4UL
1883   IRBuilder<> IRB(Pos);
1884   Value *ShadowOffset = getShadowOffset(Addr, IRB);
1885   Value *ShadowPtr = getShadowAddress(Addr, Pos, ShadowOffset);
1886   Value *OriginPtr = nullptr;
1887   if (shouldTrackOrigins()) {
1888     Value *OriginLong = IRB.CreateAdd(ShadowOffset, OriginBase);
1889     const Align Alignment = llvm::assumeAligned(InstAlignment.value());
1890     // When alignment is >= 4, Addr must be aligned to 4, otherwise it is UB.
1891     // So Mask is unnecessary.
1892     if (Alignment < MinOriginAlignment) {
1893       uint64_t Mask = MinOriginAlignment.value() - 1;
1894       OriginLong = IRB.CreateAnd(OriginLong, ConstantInt::get(IntptrTy, ~Mask));
1895     }
1896     OriginPtr = IRB.CreateIntToPtr(OriginLong, OriginPtrTy);
1897   }
1898   return {ShadowPtr, OriginPtr};
1899 }
1900 
1901 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos,
1902                                            Value *ShadowOffset) {
1903   IRBuilder<> IRB(Pos);
1904 
1905   if (!ShadowPtrMul->isOne())
1906     ShadowOffset = IRB.CreateMul(ShadowOffset, ShadowPtrMul);
1907 
1908   return IRB.CreateIntToPtr(ShadowOffset, PrimitiveShadowPtrTy);
1909 }
1910 
1911 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
1912   // Returns (Addr & shadow_mask) x 2
1913   IRBuilder<> IRB(Pos);
1914   Value *ShadowOffset = getShadowOffset(Addr, IRB);
1915   return getShadowAddress(Addr, Pos, ShadowOffset);
1916 }
1917 
1918 Value *DFSanFunction::combineShadowsThenConvert(Type *T, Value *V1, Value *V2,
1919                                                 Instruction *Pos) {
1920   Value *PrimitiveValue = combineShadows(V1, V2, Pos);
1921   return expandFromPrimitiveShadow(T, PrimitiveValue, Pos);
1922 }
1923 
1924 // Generates IR to compute the union of the two given shadows, inserting it
1925 // before Pos. The combined value is with primitive type.
1926 Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) {
1927   if (DFS.isZeroShadow(V1))
1928     return collapseToPrimitiveShadow(V2, Pos);
1929   if (DFS.isZeroShadow(V2))
1930     return collapseToPrimitiveShadow(V1, Pos);
1931   if (V1 == V2)
1932     return collapseToPrimitiveShadow(V1, Pos);
1933 
1934   auto V1Elems = ShadowElements.find(V1);
1935   auto V2Elems = ShadowElements.find(V2);
1936   if (V1Elems != ShadowElements.end() && V2Elems != ShadowElements.end()) {
1937     if (std::includes(V1Elems->second.begin(), V1Elems->second.end(),
1938                       V2Elems->second.begin(), V2Elems->second.end())) {
1939       return collapseToPrimitiveShadow(V1, Pos);
1940     }
1941     if (std::includes(V2Elems->second.begin(), V2Elems->second.end(),
1942                       V1Elems->second.begin(), V1Elems->second.end())) {
1943       return collapseToPrimitiveShadow(V2, Pos);
1944     }
1945   } else if (V1Elems != ShadowElements.end()) {
1946     if (V1Elems->second.count(V2))
1947       return collapseToPrimitiveShadow(V1, Pos);
1948   } else if (V2Elems != ShadowElements.end()) {
1949     if (V2Elems->second.count(V1))
1950       return collapseToPrimitiveShadow(V2, Pos);
1951   }
1952 
1953   auto Key = std::make_pair(V1, V2);
1954   if (V1 > V2)
1955     std::swap(Key.first, Key.second);
1956   CachedShadow &CCS = CachedShadows[Key];
1957   if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent()))
1958     return CCS.Shadow;
1959 
1960   // Converts inputs shadows to shadows with primitive types.
1961   Value *PV1 = collapseToPrimitiveShadow(V1, Pos);
1962   Value *PV2 = collapseToPrimitiveShadow(V2, Pos);
1963 
1964   IRBuilder<> IRB(Pos);
1965   if (DFS.hasFastLabelsEnabled()) {
1966     CCS.Block = Pos->getParent();
1967     CCS.Shadow = IRB.CreateOr(PV1, PV2);
1968   } else if (AvoidNewBlocks) {
1969     CallInst *Call = IRB.CreateCall(DFS.DFSanCheckedUnionFn, {PV1, PV2});
1970     Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
1971     Call->addParamAttr(0, Attribute::ZExt);
1972     Call->addParamAttr(1, Attribute::ZExt);
1973 
1974     CCS.Block = Pos->getParent();
1975     CCS.Shadow = Call;
1976   } else {
1977     BasicBlock *Head = Pos->getParent();
1978     Value *Ne = IRB.CreateICmpNE(PV1, PV2);
1979     BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
1980         Ne, Pos, /*Unreachable=*/false, DFS.ColdCallWeights, &DT));
1981     IRBuilder<> ThenIRB(BI);
1982     CallInst *Call = ThenIRB.CreateCall(DFS.DFSanUnionFn, {PV1, PV2});
1983     Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
1984     Call->addParamAttr(0, Attribute::ZExt);
1985     Call->addParamAttr(1, Attribute::ZExt);
1986 
1987     BasicBlock *Tail = BI->getSuccessor(0);
1988     PHINode *Phi =
1989         PHINode::Create(DFS.PrimitiveShadowTy, 2, "", &Tail->front());
1990     Phi->addIncoming(Call, Call->getParent());
1991     Phi->addIncoming(PV1, Head);
1992 
1993     CCS.Block = Tail;
1994     CCS.Shadow = Phi;
1995   }
1996 
1997   std::set<Value *> UnionElems;
1998   if (V1Elems != ShadowElements.end()) {
1999     UnionElems = V1Elems->second;
2000   } else {
2001     UnionElems.insert(V1);
2002   }
2003   if (V2Elems != ShadowElements.end()) {
2004     UnionElems.insert(V2Elems->second.begin(), V2Elems->second.end());
2005   } else {
2006     UnionElems.insert(V2);
2007   }
2008   ShadowElements[CCS.Shadow] = std::move(UnionElems);
2009 
2010   return CCS.Shadow;
2011 }
2012 
2013 // A convenience function which folds the shadows of each of the operands
2014 // of the provided instruction Inst, inserting the IR before Inst.  Returns
2015 // the computed union Value.
2016 Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
2017   if (Inst->getNumOperands() == 0)
2018     return DFS.getZeroShadow(Inst);
2019 
2020   Value *Shadow = getShadow(Inst->getOperand(0));
2021   for (unsigned I = 1, N = Inst->getNumOperands(); I < N; ++I)
2022     Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(I)), Inst);
2023 
2024   return expandFromPrimitiveShadow(Inst->getType(), Shadow, Inst);
2025 }
2026 
2027 void DFSanVisitor::visitInstOperands(Instruction &I) {
2028   Value *CombinedShadow = DFSF.combineOperandShadows(&I);
2029   DFSF.setShadow(&I, CombinedShadow);
2030   visitInstOperandOrigins(I);
2031 }
2032 
2033 Value *DFSanFunction::combineOrigins(const std::vector<Value *> &Shadows,
2034                                      const std::vector<Value *> &Origins,
2035                                      Instruction *Pos, ConstantInt *Zero) {
2036   assert(Shadows.size() == Origins.size());
2037   size_t Size = Origins.size();
2038   if (Size == 0)
2039     return DFS.ZeroOrigin;
2040   Value *Origin = nullptr;
2041   if (!Zero)
2042     Zero = DFS.ZeroPrimitiveShadow;
2043   for (size_t I = 0; I != Size; ++I) {
2044     Value *OpOrigin = Origins[I];
2045     Constant *ConstOpOrigin = dyn_cast<Constant>(OpOrigin);
2046     if (ConstOpOrigin && ConstOpOrigin->isNullValue())
2047       continue;
2048     if (!Origin) {
2049       Origin = OpOrigin;
2050       continue;
2051     }
2052     Value *OpShadow = Shadows[I];
2053     Value *PrimitiveShadow = collapseToPrimitiveShadow(OpShadow, Pos);
2054     IRBuilder<> IRB(Pos);
2055     Value *Cond = IRB.CreateICmpNE(PrimitiveShadow, Zero);
2056     Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
2057   }
2058   return Origin ? Origin : DFS.ZeroOrigin;
2059 }
2060 
2061 Value *DFSanFunction::combineOperandOrigins(Instruction *Inst) {
2062   size_t Size = Inst->getNumOperands();
2063   std::vector<Value *> Shadows(Size);
2064   std::vector<Value *> Origins(Size);
2065   for (unsigned I = 0; I != Size; ++I) {
2066     Shadows[I] = getShadow(Inst->getOperand(I));
2067     Origins[I] = getOrigin(Inst->getOperand(I));
2068   }
2069   return combineOrigins(Shadows, Origins, Inst);
2070 }
2071 
2072 void DFSanVisitor::visitInstOperandOrigins(Instruction &I) {
2073   if (!DFSF.DFS.shouldTrackOrigins())
2074     return;
2075   Value *CombinedOrigin = DFSF.combineOperandOrigins(&I);
2076   DFSF.setOrigin(&I, CombinedOrigin);
2077 }
2078 
2079 Align DFSanFunction::getShadowAlign(Align InstAlignment) {
2080   const Align Alignment = ClPreserveAlignment ? InstAlignment : Align(1);
2081   return Align(Alignment.value() * DFS.ShadowWidthBytes);
2082 }
2083 
2084 Align DFSanFunction::getOriginAlign(Align InstAlignment) {
2085   const Align Alignment = llvm::assumeAligned(InstAlignment.value());
2086   return Align(std::max(MinOriginAlignment, Alignment));
2087 }
2088 
2089 bool DFSanFunction::useCallbackLoadLabelAndOrigin(uint64_t Size,
2090                                                   Align InstAlignment) {
2091   // When enabling tracking load instructions, we always use
2092   // __dfsan_load_label_and_origin to reduce code size.
2093   if (ClTrackOrigins == 2)
2094     return true;
2095 
2096   assert(Size != 0);
2097   // * if Size == 1, it is sufficient to load its origin aligned at 4.
2098   // * if Size == 2, we assume most cases Addr % 2 == 0, so it is sufficient to
2099   //   load its origin aligned at 4. If not, although origins may be lost, it
2100   //   should not happen very often.
2101   // * if align >= 4, Addr must be aligned to 4, otherwise it is UB. When
2102   //   Size % 4 == 0, it is more efficient to load origins without callbacks.
2103   // * Otherwise we use __dfsan_load_label_and_origin.
2104   // This should ensure that common cases run efficiently.
2105   if (Size <= 2)
2106     return false;
2107 
2108   const Align Alignment = llvm::assumeAligned(InstAlignment.value());
2109   return Alignment < MinOriginAlignment || !DFS.hasLoadSizeForFastPath(Size);
2110 }
2111 
2112 Value *DataFlowSanitizer::loadNextOrigin(Instruction *Pos, Align OriginAlign,
2113                                          Value **OriginAddr) {
2114   IRBuilder<> IRB(Pos);
2115   *OriginAddr =
2116       IRB.CreateGEP(OriginTy, *OriginAddr, ConstantInt::get(IntptrTy, 1));
2117   return IRB.CreateAlignedLoad(OriginTy, *OriginAddr, OriginAlign);
2118 }
2119 
2120 std::pair<Value *, Value *> DFSanFunction::loadFast16ShadowFast(
2121     Value *ShadowAddr, Value *OriginAddr, uint64_t Size, Align ShadowAlign,
2122     Align OriginAlign, Value *FirstOrigin, Instruction *Pos) {
2123   const bool ShouldTrackOrigins = DFS.shouldTrackOrigins();
2124   const uint64_t ShadowSize = Size * DFS.ShadowWidthBytes;
2125 
2126   assert(Size >= 4 && "Not large enough load size for fast path!");
2127 
2128   // Used for origin tracking.
2129   std::vector<Value *> Shadows;
2130   std::vector<Value *> Origins;
2131 
2132   // Load instructions in LLVM can have arbitrary byte sizes (e.g., 3, 12, 20)
2133   // but this function is only used in a subset of cases that make it possible
2134   // to optimize the instrumentation.
2135   //
2136   // Specifically, when the shadow size in bytes (i.e., loaded bytes x shadow
2137   // per byte) is either:
2138   // - a multiple of 8  (common)
2139   // - equal to 4       (only for load32 in fast-8 mode)
2140   //
2141   // For the second case, we can fit the wide shadow in a 32-bit integer. In all
2142   // other cases, we use a 64-bit integer to hold the wide shadow.
2143   Type *WideShadowTy =
2144       ShadowSize == 4 ? Type::getInt32Ty(*DFS.Ctx) : Type::getInt64Ty(*DFS.Ctx);
2145 
2146   IRBuilder<> IRB(Pos);
2147   Value *WideAddr = IRB.CreateBitCast(ShadowAddr, WideShadowTy->getPointerTo());
2148   Value *CombinedWideShadow =
2149       IRB.CreateAlignedLoad(WideShadowTy, WideAddr, ShadowAlign);
2150 
2151   unsigned WideShadowBitWidth = WideShadowTy->getIntegerBitWidth();
2152   const uint64_t BytesPerWideShadow = WideShadowBitWidth / DFS.ShadowWidthBits;
2153 
2154   auto AppendWideShadowAndOrigin = [&](Value *WideShadow, Value *Origin) {
2155     if (BytesPerWideShadow > 4) {
2156       assert(BytesPerWideShadow == 8);
2157       // The wide shadow relates to two origin pointers: one for the first four
2158       // application bytes, and one for the latest four. We use a left shift to
2159       // get just the shadow bytes that correspond to the first origin pointer,
2160       // and then the entire shadow for the second origin pointer (which will be
2161       // chosen by combineOrigins() iff the least-significant half of the wide
2162       // shadow was empty but the other half was not).
2163       Value *WideShadowLo = IRB.CreateShl(
2164           WideShadow, ConstantInt::get(WideShadowTy, WideShadowBitWidth / 2));
2165       Shadows.push_back(WideShadow);
2166       Origins.push_back(DFS.loadNextOrigin(Pos, OriginAlign, &OriginAddr));
2167 
2168       Shadows.push_back(WideShadowLo);
2169       Origins.push_back(Origin);
2170     } else {
2171       Shadows.push_back(WideShadow);
2172       Origins.push_back(Origin);
2173     }
2174   };
2175 
2176   if (ShouldTrackOrigins)
2177     AppendWideShadowAndOrigin(CombinedWideShadow, FirstOrigin);
2178 
2179   // First OR all the WideShadows (i.e., 64bit or 32bit shadow chunks) linearly;
2180   // then OR individual shadows within the combined WideShadow by binary ORing.
2181   // This is fewer instructions than ORing shadows individually, since it
2182   // needs logN shift/or instructions (N being the bytes of the combined wide
2183   // shadow).
2184   for (uint64_t ByteOfs = BytesPerWideShadow; ByteOfs < Size;
2185        ByteOfs += BytesPerWideShadow) {
2186     WideAddr = IRB.CreateGEP(WideShadowTy, WideAddr,
2187                              ConstantInt::get(DFS.IntptrTy, 1));
2188     Value *NextWideShadow =
2189         IRB.CreateAlignedLoad(WideShadowTy, WideAddr, ShadowAlign);
2190     CombinedWideShadow = IRB.CreateOr(CombinedWideShadow, NextWideShadow);
2191     if (ShouldTrackOrigins) {
2192       Value *NextOrigin = DFS.loadNextOrigin(Pos, OriginAlign, &OriginAddr);
2193       AppendWideShadowAndOrigin(NextWideShadow, NextOrigin);
2194     }
2195   }
2196   for (unsigned Width = WideShadowBitWidth / 2; Width >= DFS.ShadowWidthBits;
2197        Width >>= 1) {
2198     Value *ShrShadow = IRB.CreateLShr(CombinedWideShadow, Width);
2199     CombinedWideShadow = IRB.CreateOr(CombinedWideShadow, ShrShadow);
2200   }
2201   return {IRB.CreateTrunc(CombinedWideShadow, DFS.PrimitiveShadowTy),
2202           ShouldTrackOrigins
2203               ? combineOrigins(Shadows, Origins, Pos,
2204                                ConstantInt::getSigned(IRB.getInt64Ty(), 0))
2205               : DFS.ZeroOrigin};
2206 }
2207 
2208 Value *DFSanFunction::loadLegacyShadowFast(Value *ShadowAddr, uint64_t Size,
2209                                            Align ShadowAlign,
2210                                            Instruction *Pos) {
2211   // Fast path for the common case where each byte has identical shadow: load
2212   // shadow 64 (or 32) bits at a time, fall out to a __dfsan_union_load call if
2213   // any shadow is non-equal.
2214   BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
2215   IRBuilder<> FallbackIRB(FallbackBB);
2216   CallInst *FallbackCall = FallbackIRB.CreateCall(
2217       DFS.DFSanUnionLoadFn, {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
2218   FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
2219 
2220   const uint64_t ShadowSize = Size * DFS.ShadowWidthBytes;
2221   assert(Size >= 4 && "Not large enough load size for fast path!");
2222 
2223   // Same as in loadFast16AShadowsFast. In the case of load32, we can fit the
2224   // wide shadow in a 32-bit integer instead.
2225   Type *WideShadowTy =
2226       ShadowSize == 4 ? Type::getInt32Ty(*DFS.Ctx) : Type::getInt64Ty(*DFS.Ctx);
2227 
2228   // Compare each of the shadows stored in the loaded 64 bits to each other,
2229   // by computing (WideShadow rotl ShadowWidthBits) == WideShadow.
2230   IRBuilder<> IRB(Pos);
2231   unsigned WideShadowBitWidth = WideShadowTy->getIntegerBitWidth();
2232   Value *WideAddr = IRB.CreateBitCast(ShadowAddr, WideShadowTy->getPointerTo());
2233   Value *WideShadow =
2234       IRB.CreateAlignedLoad(WideShadowTy, WideAddr, ShadowAlign);
2235   Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.PrimitiveShadowTy);
2236   Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidthBits);
2237   Value *ShrShadow =
2238       IRB.CreateLShr(WideShadow, WideShadowBitWidth - DFS.ShadowWidthBits);
2239   Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
2240   Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
2241 
2242   BasicBlock *Head = Pos->getParent();
2243   BasicBlock *Tail = Head->splitBasicBlock(Pos->getIterator());
2244 
2245   if (DomTreeNode *OldNode = DT.getNode(Head)) {
2246     std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
2247 
2248     DomTreeNode *NewNode = DT.addNewBlock(Tail, Head);
2249     for (auto *Child : Children)
2250       DT.changeImmediateDominator(Child, NewNode);
2251   }
2252 
2253   // In the following code LastBr will refer to the previous basic block's
2254   // conditional branch instruction, whose true successor is fixed up to point
2255   // to the next block during the loop below or to the tail after the final
2256   // iteration.
2257   BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
2258   ReplaceInstWithInst(Head->getTerminator(), LastBr);
2259   DT.addNewBlock(FallbackBB, Head);
2260 
2261   const uint64_t BytesPerWideShadow = WideShadowBitWidth / DFS.ShadowWidthBits;
2262 
2263   for (uint64_t ByteOfs = BytesPerWideShadow; ByteOfs < Size;
2264        ByteOfs += BytesPerWideShadow) {
2265     BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
2266     DT.addNewBlock(NextBB, LastBr->getParent());
2267     IRBuilder<> NextIRB(NextBB);
2268     WideAddr = NextIRB.CreateGEP(WideShadowTy, WideAddr,
2269                                  ConstantInt::get(DFS.IntptrTy, 1));
2270     Value *NextWideShadow =
2271         NextIRB.CreateAlignedLoad(WideShadowTy, WideAddr, ShadowAlign);
2272     ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
2273     LastBr->setSuccessor(0, NextBB);
2274     LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
2275   }
2276 
2277   LastBr->setSuccessor(0, Tail);
2278   FallbackIRB.CreateBr(Tail);
2279   PHINode *Shadow =
2280       PHINode::Create(DFS.PrimitiveShadowTy, 2, "", &Tail->front());
2281   Shadow->addIncoming(FallbackCall, FallbackBB);
2282   Shadow->addIncoming(TruncShadow, LastBr->getParent());
2283   return Shadow;
2284 }
2285 
2286 std::pair<Value *, Value *> DFSanFunction::loadShadowOriginSansLoadTracking(
2287     Value *Addr, uint64_t Size, Align InstAlignment, Instruction *Pos) {
2288   const bool ShouldTrackOrigins = DFS.shouldTrackOrigins();
2289 
2290   // Non-escaped loads.
2291   if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
2292     const auto SI = AllocaShadowMap.find(AI);
2293     if (SI != AllocaShadowMap.end()) {
2294       IRBuilder<> IRB(Pos);
2295       Value *ShadowLI = IRB.CreateLoad(DFS.PrimitiveShadowTy, SI->second);
2296       const auto OI = AllocaOriginMap.find(AI);
2297       assert(!ShouldTrackOrigins || OI != AllocaOriginMap.end());
2298       return {ShadowLI, ShouldTrackOrigins
2299                             ? IRB.CreateLoad(DFS.OriginTy, OI->second)
2300                             : nullptr};
2301     }
2302   }
2303 
2304   // Load from constant addresses.
2305   SmallVector<const Value *, 2> Objs;
2306   getUnderlyingObjects(Addr, Objs);
2307   bool AllConstants = true;
2308   for (const Value *Obj : Objs) {
2309     if (isa<Function>(Obj) || isa<BlockAddress>(Obj))
2310       continue;
2311     if (isa<GlobalVariable>(Obj) && cast<GlobalVariable>(Obj)->isConstant())
2312       continue;
2313 
2314     AllConstants = false;
2315     break;
2316   }
2317   if (AllConstants)
2318     return {DFS.ZeroPrimitiveShadow,
2319             ShouldTrackOrigins ? DFS.ZeroOrigin : nullptr};
2320 
2321   if (Size == 0)
2322     return {DFS.ZeroPrimitiveShadow,
2323             ShouldTrackOrigins ? DFS.ZeroOrigin : nullptr};
2324 
2325   // Use callback to load if this is not an optimizable case for origin
2326   // tracking.
2327   if (ShouldTrackOrigins &&
2328       useCallbackLoadLabelAndOrigin(Size, InstAlignment)) {
2329     IRBuilder<> IRB(Pos);
2330     CallInst *Call =
2331         IRB.CreateCall(DFS.DFSanLoadLabelAndOriginFn,
2332                        {IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
2333                         ConstantInt::get(DFS.IntptrTy, Size)});
2334     Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
2335     return {IRB.CreateTrunc(IRB.CreateLShr(Call, DFS.OriginWidthBits),
2336                             DFS.PrimitiveShadowTy),
2337             IRB.CreateTrunc(Call, DFS.OriginTy)};
2338   }
2339 
2340   // Other cases that support loading shadows or origins in a fast way.
2341   Value *ShadowAddr, *OriginAddr;
2342   std::tie(ShadowAddr, OriginAddr) =
2343       DFS.getShadowOriginAddress(Addr, InstAlignment, Pos);
2344 
2345   const Align ShadowAlign = getShadowAlign(InstAlignment);
2346   const Align OriginAlign = getOriginAlign(InstAlignment);
2347   Value *Origin = nullptr;
2348   if (ShouldTrackOrigins) {
2349     IRBuilder<> IRB(Pos);
2350     Origin = IRB.CreateAlignedLoad(DFS.OriginTy, OriginAddr, OriginAlign);
2351   }
2352 
2353   // When the byte size is small enough, we can load the shadow directly with
2354   // just a few instructions.
2355   switch (Size) {
2356   case 1: {
2357     LoadInst *LI = new LoadInst(DFS.PrimitiveShadowTy, ShadowAddr, "", Pos);
2358     LI->setAlignment(ShadowAlign);
2359     return {LI, Origin};
2360   }
2361   case 2: {
2362     IRBuilder<> IRB(Pos);
2363     Value *ShadowAddr1 = IRB.CreateGEP(DFS.PrimitiveShadowTy, ShadowAddr,
2364                                        ConstantInt::get(DFS.IntptrTy, 1));
2365     Value *Load =
2366         IRB.CreateAlignedLoad(DFS.PrimitiveShadowTy, ShadowAddr, ShadowAlign);
2367     Value *Load1 =
2368         IRB.CreateAlignedLoad(DFS.PrimitiveShadowTy, ShadowAddr1, ShadowAlign);
2369     return {combineShadows(Load, Load1, Pos), Origin};
2370   }
2371   }
2372   bool HasSizeForFastPath = DFS.hasLoadSizeForFastPath(Size);
2373   bool HasFastLabelsEnabled = DFS.hasFastLabelsEnabled();
2374 
2375   if (HasFastLabelsEnabled && HasSizeForFastPath)
2376     return loadFast16ShadowFast(ShadowAddr, OriginAddr, Size, ShadowAlign,
2377                                 OriginAlign, Origin, Pos);
2378 
2379   if (!AvoidNewBlocks && HasSizeForFastPath)
2380     return {loadLegacyShadowFast(ShadowAddr, Size, ShadowAlign, Pos), Origin};
2381 
2382   IRBuilder<> IRB(Pos);
2383   FunctionCallee &UnionLoadFn = HasFastLabelsEnabled
2384                                     ? DFS.DFSanUnionLoadFastLabelsFn
2385                                     : DFS.DFSanUnionLoadFn;
2386   CallInst *FallbackCall = IRB.CreateCall(
2387       UnionLoadFn, {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
2388   FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
2389   return {FallbackCall, Origin};
2390 }
2391 
2392 std::pair<Value *, Value *> DFSanFunction::loadShadowOrigin(Value *Addr,
2393                                                             uint64_t Size,
2394                                                             Align InstAlignment,
2395                                                             Instruction *Pos) {
2396   Value *PrimitiveShadow, *Origin;
2397   std::tie(PrimitiveShadow, Origin) =
2398       loadShadowOriginSansLoadTracking(Addr, Size, InstAlignment, Pos);
2399   if (DFS.shouldTrackOrigins()) {
2400     if (ClTrackOrigins == 2) {
2401       IRBuilder<> IRB(Pos);
2402       auto *ConstantShadow = dyn_cast<Constant>(PrimitiveShadow);
2403       if (!ConstantShadow || !ConstantShadow->isZeroValue())
2404         Origin = updateOriginIfTainted(PrimitiveShadow, Origin, IRB);
2405     }
2406   }
2407   return {PrimitiveShadow, Origin};
2408 }
2409 
2410 static AtomicOrdering addAcquireOrdering(AtomicOrdering AO) {
2411   switch (AO) {
2412   case AtomicOrdering::NotAtomic:
2413     return AtomicOrdering::NotAtomic;
2414   case AtomicOrdering::Unordered:
2415   case AtomicOrdering::Monotonic:
2416   case AtomicOrdering::Acquire:
2417     return AtomicOrdering::Acquire;
2418   case AtomicOrdering::Release:
2419   case AtomicOrdering::AcquireRelease:
2420     return AtomicOrdering::AcquireRelease;
2421   case AtomicOrdering::SequentiallyConsistent:
2422     return AtomicOrdering::SequentiallyConsistent;
2423   }
2424   llvm_unreachable("Unknown ordering");
2425 }
2426 
2427 void DFSanVisitor::visitLoadInst(LoadInst &LI) {
2428   auto &DL = LI.getModule()->getDataLayout();
2429   uint64_t Size = DL.getTypeStoreSize(LI.getType());
2430   if (Size == 0) {
2431     DFSF.setShadow(&LI, DFSF.DFS.getZeroShadow(&LI));
2432     DFSF.setOrigin(&LI, DFSF.DFS.ZeroOrigin);
2433     return;
2434   }
2435 
2436   // When an application load is atomic, increase atomic ordering between
2437   // atomic application loads and stores to ensure happen-before order; load
2438   // shadow data after application data; store zero shadow data before
2439   // application data. This ensure shadow loads return either labels of the
2440   // initial application data or zeros.
2441   if (LI.isAtomic())
2442     LI.setOrdering(addAcquireOrdering(LI.getOrdering()));
2443 
2444   Instruction *Pos = LI.isAtomic() ? LI.getNextNode() : &LI;
2445   std::vector<Value *> Shadows;
2446   std::vector<Value *> Origins;
2447   Value *PrimitiveShadow, *Origin;
2448   std::tie(PrimitiveShadow, Origin) =
2449       DFSF.loadShadowOrigin(LI.getPointerOperand(), Size, LI.getAlign(), Pos);
2450   const bool ShouldTrackOrigins = DFSF.DFS.shouldTrackOrigins();
2451   if (ShouldTrackOrigins) {
2452     Shadows.push_back(PrimitiveShadow);
2453     Origins.push_back(Origin);
2454   }
2455   if (ClCombinePointerLabelsOnLoad) {
2456     Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
2457     PrimitiveShadow = DFSF.combineShadows(PrimitiveShadow, PtrShadow, Pos);
2458     if (ShouldTrackOrigins) {
2459       Shadows.push_back(PtrShadow);
2460       Origins.push_back(DFSF.getOrigin(LI.getPointerOperand()));
2461     }
2462   }
2463   if (!DFSF.DFS.isZeroShadow(PrimitiveShadow))
2464     DFSF.NonZeroChecks.push_back(PrimitiveShadow);
2465 
2466   Value *Shadow =
2467       DFSF.expandFromPrimitiveShadow(LI.getType(), PrimitiveShadow, Pos);
2468   DFSF.setShadow(&LI, Shadow);
2469 
2470   if (ShouldTrackOrigins) {
2471     DFSF.setOrigin(&LI, DFSF.combineOrigins(Shadows, Origins, Pos));
2472   }
2473 
2474   if (ClEventCallbacks) {
2475     IRBuilder<> IRB(Pos);
2476     Value *Addr8 = IRB.CreateBitCast(LI.getPointerOperand(), DFSF.DFS.Int8Ptr);
2477     IRB.CreateCall(DFSF.DFS.DFSanLoadCallbackFn, {PrimitiveShadow, Addr8});
2478   }
2479 }
2480 
2481 Value *DFSanFunction::updateOriginIfTainted(Value *Shadow, Value *Origin,
2482                                             IRBuilder<> &IRB) {
2483   assert(DFS.shouldTrackOrigins());
2484   auto *CB = IRB.CreateCall(DFS.DFSanChainOriginIfTaintedFn, {Shadow, Origin});
2485   CB->setAttributes(CB->getCalledFunction()->getAttributes());
2486   return CB;
2487 }
2488 
2489 Value *DFSanFunction::updateOrigin(Value *V, IRBuilder<> &IRB) {
2490   if (!DFS.shouldTrackOrigins())
2491     return V;
2492   auto *CB = IRB.CreateCall(DFS.DFSanChainOriginFn, V);
2493   CB->setAttributes(CB->getCalledFunction()->getAttributes());
2494   return CB;
2495 }
2496 
2497 Value *DFSanFunction::originToIntptr(IRBuilder<> &IRB, Value *Origin) {
2498   const unsigned OriginSize = DataFlowSanitizer::OriginWidthBytes;
2499   const DataLayout &DL = F->getParent()->getDataLayout();
2500   unsigned IntptrSize = DL.getTypeStoreSize(DFS.IntptrTy);
2501   if (IntptrSize == OriginSize)
2502     return Origin;
2503   assert(IntptrSize == OriginSize * 2);
2504   Origin = IRB.CreateIntCast(Origin, DFS.IntptrTy, /* isSigned */ false);
2505   return IRB.CreateOr(Origin, IRB.CreateShl(Origin, OriginSize * 8));
2506 }
2507 
2508 void DFSanFunction::paintOrigin(IRBuilder<> &IRB, Value *Origin,
2509                                 Value *StoreOriginAddr,
2510                                 uint64_t StoreOriginSize, Align Alignment) {
2511   const unsigned OriginSize = DataFlowSanitizer::OriginWidthBytes;
2512   const DataLayout &DL = F->getParent()->getDataLayout();
2513   const Align IntptrAlignment = DL.getABITypeAlign(DFS.IntptrTy);
2514   unsigned IntptrSize = DL.getTypeStoreSize(DFS.IntptrTy);
2515   assert(IntptrAlignment >= MinOriginAlignment);
2516   assert(IntptrSize >= OriginSize);
2517 
2518   unsigned Ofs = 0;
2519   Align CurrentAlignment = Alignment;
2520   if (Alignment >= IntptrAlignment && IntptrSize > OriginSize) {
2521     Value *IntptrOrigin = originToIntptr(IRB, Origin);
2522     Value *IntptrStoreOriginPtr = IRB.CreatePointerCast(
2523         StoreOriginAddr, PointerType::get(DFS.IntptrTy, 0));
2524     for (unsigned I = 0; I < StoreOriginSize / IntptrSize; ++I) {
2525       Value *Ptr =
2526           I ? IRB.CreateConstGEP1_32(DFS.IntptrTy, IntptrStoreOriginPtr, I)
2527             : IntptrStoreOriginPtr;
2528       IRB.CreateAlignedStore(IntptrOrigin, Ptr, CurrentAlignment);
2529       Ofs += IntptrSize / OriginSize;
2530       CurrentAlignment = IntptrAlignment;
2531     }
2532   }
2533 
2534   for (unsigned I = Ofs; I < (StoreOriginSize + OriginSize - 1) / OriginSize;
2535        ++I) {
2536     Value *GEP = I ? IRB.CreateConstGEP1_32(DFS.OriginTy, StoreOriginAddr, I)
2537                    : StoreOriginAddr;
2538     IRB.CreateAlignedStore(Origin, GEP, CurrentAlignment);
2539     CurrentAlignment = MinOriginAlignment;
2540   }
2541 }
2542 
2543 Value *DFSanFunction::convertToBool(Value *V, IRBuilder<> &IRB,
2544                                     const Twine &Name) {
2545   Type *VTy = V->getType();
2546   assert(VTy->isIntegerTy());
2547   if (VTy->getIntegerBitWidth() == 1)
2548     // Just converting a bool to a bool, so do nothing.
2549     return V;
2550   return IRB.CreateICmpNE(V, ConstantInt::get(VTy, 0), Name);
2551 }
2552 
2553 void DFSanFunction::storeOrigin(Instruction *Pos, Value *Addr, uint64_t Size,
2554                                 Value *Shadow, Value *Origin,
2555                                 Value *StoreOriginAddr, Align InstAlignment) {
2556   // Do not write origins for zero shadows because we do not trace origins for
2557   // untainted sinks.
2558   const Align OriginAlignment = getOriginAlign(InstAlignment);
2559   Value *CollapsedShadow = collapseToPrimitiveShadow(Shadow, Pos);
2560   IRBuilder<> IRB(Pos);
2561   if (auto *ConstantShadow = dyn_cast<Constant>(CollapsedShadow)) {
2562     if (!ConstantShadow->isZeroValue())
2563       paintOrigin(IRB, updateOrigin(Origin, IRB), StoreOriginAddr, Size,
2564                   OriginAlignment);
2565     return;
2566   }
2567 
2568   if (shouldInstrumentWithCall()) {
2569     auto *CB = IRB.CreateCall(DFS.DFSanMaybeStoreOriginFn,
2570                               {CollapsedShadow,
2571                                IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
2572                                ConstantInt::get(DFS.IntptrTy, Size), Origin});
2573     CB->setAttributes(CB->getCalledFunction()->getAttributes());
2574   } else {
2575     Value *Cmp = convertToBool(CollapsedShadow, IRB, "_dfscmp");
2576     Instruction *CheckTerm = SplitBlockAndInsertIfThen(
2577         Cmp, &*IRB.GetInsertPoint(), false, DFS.OriginStoreWeights, &DT);
2578     IRBuilder<> IRBNew(CheckTerm);
2579     paintOrigin(IRBNew, updateOrigin(Origin, IRBNew), StoreOriginAddr, Size,
2580                 OriginAlignment);
2581     ++NumOriginStores;
2582   }
2583 }
2584 
2585 void DFSanFunction::storeZeroPrimitiveShadow(Value *Addr, uint64_t Size,
2586                                              Align ShadowAlign,
2587                                              Instruction *Pos) {
2588   IRBuilder<> IRB(Pos);
2589   IntegerType *ShadowTy =
2590       IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidthBits);
2591   Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
2592   Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
2593   Value *ExtShadowAddr =
2594       IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
2595   IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
2596   // Do not write origins for 0 shadows because we do not trace origins for
2597   // untainted sinks.
2598 }
2599 
2600 void DFSanFunction::storePrimitiveShadowOrigin(Value *Addr, uint64_t Size,
2601                                                Align InstAlignment,
2602                                                Value *PrimitiveShadow,
2603                                                Value *Origin,
2604                                                Instruction *Pos) {
2605   const bool ShouldTrackOrigins = DFS.shouldTrackOrigins() && Origin;
2606 
2607   if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
2608     const auto SI = AllocaShadowMap.find(AI);
2609     if (SI != AllocaShadowMap.end()) {
2610       IRBuilder<> IRB(Pos);
2611       IRB.CreateStore(PrimitiveShadow, SI->second);
2612 
2613       // Do not write origins for 0 shadows because we do not trace origins for
2614       // untainted sinks.
2615       if (ShouldTrackOrigins && !DFS.isZeroShadow(PrimitiveShadow)) {
2616         const auto OI = AllocaOriginMap.find(AI);
2617         assert(OI != AllocaOriginMap.end() && Origin);
2618         IRB.CreateStore(Origin, OI->second);
2619       }
2620       return;
2621     }
2622   }
2623 
2624   const Align ShadowAlign = getShadowAlign(InstAlignment);
2625   if (DFS.isZeroShadow(PrimitiveShadow)) {
2626     storeZeroPrimitiveShadow(Addr, Size, ShadowAlign, Pos);
2627     return;
2628   }
2629 
2630   IRBuilder<> IRB(Pos);
2631   Value *ShadowAddr, *OriginAddr;
2632   std::tie(ShadowAddr, OriginAddr) =
2633       DFS.getShadowOriginAddress(Addr, InstAlignment, Pos);
2634 
2635   const unsigned ShadowVecSize = 8;
2636   assert(ShadowVecSize * DFS.ShadowWidthBits <= 128 &&
2637          "Shadow vector is too large!");
2638 
2639   uint64_t Offset = 0;
2640   uint64_t LeftSize = Size;
2641   if (LeftSize >= ShadowVecSize) {
2642     auto *ShadowVecTy =
2643         FixedVectorType::get(DFS.PrimitiveShadowTy, ShadowVecSize);
2644     Value *ShadowVec = UndefValue::get(ShadowVecTy);
2645     for (unsigned I = 0; I != ShadowVecSize; ++I) {
2646       ShadowVec = IRB.CreateInsertElement(
2647           ShadowVec, PrimitiveShadow,
2648           ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), I));
2649     }
2650     Value *ShadowVecAddr =
2651         IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
2652     do {
2653       Value *CurShadowVecAddr =
2654           IRB.CreateConstGEP1_32(ShadowVecTy, ShadowVecAddr, Offset);
2655       IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
2656       LeftSize -= ShadowVecSize;
2657       ++Offset;
2658     } while (LeftSize >= ShadowVecSize);
2659     Offset *= ShadowVecSize;
2660   }
2661   while (LeftSize > 0) {
2662     Value *CurShadowAddr =
2663         IRB.CreateConstGEP1_32(DFS.PrimitiveShadowTy, ShadowAddr, Offset);
2664     IRB.CreateAlignedStore(PrimitiveShadow, CurShadowAddr, ShadowAlign);
2665     --LeftSize;
2666     ++Offset;
2667   }
2668 
2669   if (ShouldTrackOrigins) {
2670     storeOrigin(Pos, Addr, Size, PrimitiveShadow, Origin, OriginAddr,
2671                 InstAlignment);
2672   }
2673 }
2674 
2675 static AtomicOrdering addReleaseOrdering(AtomicOrdering AO) {
2676   switch (AO) {
2677   case AtomicOrdering::NotAtomic:
2678     return AtomicOrdering::NotAtomic;
2679   case AtomicOrdering::Unordered:
2680   case AtomicOrdering::Monotonic:
2681   case AtomicOrdering::Release:
2682     return AtomicOrdering::Release;
2683   case AtomicOrdering::Acquire:
2684   case AtomicOrdering::AcquireRelease:
2685     return AtomicOrdering::AcquireRelease;
2686   case AtomicOrdering::SequentiallyConsistent:
2687     return AtomicOrdering::SequentiallyConsistent;
2688   }
2689   llvm_unreachable("Unknown ordering");
2690 }
2691 
2692 void DFSanVisitor::visitStoreInst(StoreInst &SI) {
2693   auto &DL = SI.getModule()->getDataLayout();
2694   Value *Val = SI.getValueOperand();
2695   uint64_t Size = DL.getTypeStoreSize(Val->getType());
2696   if (Size == 0)
2697     return;
2698 
2699   // When an application store is atomic, increase atomic ordering between
2700   // atomic application loads and stores to ensure happen-before order; load
2701   // shadow data after application data; store zero shadow data before
2702   // application data. This ensure shadow loads return either labels of the
2703   // initial application data or zeros.
2704   if (SI.isAtomic())
2705     SI.setOrdering(addReleaseOrdering(SI.getOrdering()));
2706 
2707   const bool ShouldTrackOrigins =
2708       DFSF.DFS.shouldTrackOrigins() && !SI.isAtomic();
2709   std::vector<Value *> Shadows;
2710   std::vector<Value *> Origins;
2711 
2712   Value *Shadow =
2713       SI.isAtomic() ? DFSF.DFS.getZeroShadow(Val) : DFSF.getShadow(Val);
2714 
2715   if (ShouldTrackOrigins) {
2716     Shadows.push_back(Shadow);
2717     Origins.push_back(DFSF.getOrigin(Val));
2718   }
2719 
2720   Value *PrimitiveShadow;
2721   if (ClCombinePointerLabelsOnStore) {
2722     Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
2723     if (ShouldTrackOrigins) {
2724       Shadows.push_back(PtrShadow);
2725       Origins.push_back(DFSF.getOrigin(SI.getPointerOperand()));
2726     }
2727     PrimitiveShadow = DFSF.combineShadows(Shadow, PtrShadow, &SI);
2728   } else {
2729     PrimitiveShadow = DFSF.collapseToPrimitiveShadow(Shadow, &SI);
2730   }
2731   Value *Origin = nullptr;
2732   if (ShouldTrackOrigins)
2733     Origin = DFSF.combineOrigins(Shadows, Origins, &SI);
2734   DFSF.storePrimitiveShadowOrigin(SI.getPointerOperand(), Size, SI.getAlign(),
2735                                   PrimitiveShadow, Origin, &SI);
2736   if (ClEventCallbacks) {
2737     IRBuilder<> IRB(&SI);
2738     Value *Addr8 = IRB.CreateBitCast(SI.getPointerOperand(), DFSF.DFS.Int8Ptr);
2739     IRB.CreateCall(DFSF.DFS.DFSanStoreCallbackFn, {PrimitiveShadow, Addr8});
2740   }
2741 }
2742 
2743 void DFSanVisitor::visitCASOrRMW(Align InstAlignment, Instruction &I) {
2744   assert(isa<AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I));
2745 
2746   Value *Val = I.getOperand(1);
2747   const auto &DL = I.getModule()->getDataLayout();
2748   uint64_t Size = DL.getTypeStoreSize(Val->getType());
2749   if (Size == 0)
2750     return;
2751 
2752   // Conservatively set data at stored addresses and return with zero shadow to
2753   // prevent shadow data races.
2754   IRBuilder<> IRB(&I);
2755   Value *Addr = I.getOperand(0);
2756   const Align ShadowAlign = DFSF.getShadowAlign(InstAlignment);
2757   DFSF.storeZeroPrimitiveShadow(Addr, Size, ShadowAlign, &I);
2758   DFSF.setShadow(&I, DFSF.DFS.getZeroShadow(&I));
2759   DFSF.setOrigin(&I, DFSF.DFS.ZeroOrigin);
2760 }
2761 
2762 void DFSanVisitor::visitAtomicRMWInst(AtomicRMWInst &I) {
2763   visitCASOrRMW(I.getAlign(), I);
2764   // TODO: The ordering change follows MSan. It is possible not to change
2765   // ordering because we always set and use 0 shadows.
2766   I.setOrdering(addReleaseOrdering(I.getOrdering()));
2767 }
2768 
2769 void DFSanVisitor::visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
2770   visitCASOrRMW(I.getAlign(), I);
2771   // TODO: The ordering change follows MSan. It is possible not to change
2772   // ordering because we always set and use 0 shadows.
2773   I.setSuccessOrdering(addReleaseOrdering(I.getSuccessOrdering()));
2774 }
2775 
2776 void DFSanVisitor::visitUnaryOperator(UnaryOperator &UO) {
2777   visitInstOperands(UO);
2778 }
2779 
2780 void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
2781   visitInstOperands(BO);
2782 }
2783 
2784 void DFSanVisitor::visitBitCastInst(BitCastInst &BCI) {
2785   if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
2786     // Special case: if this is the bitcast (there is exactly 1 allowed) between
2787     // a musttail call and a ret, don't instrument. New instructions are not
2788     // allowed after a musttail call.
2789     if (auto *CI = dyn_cast<CallInst>(BCI.getOperand(0)))
2790       if (CI->isMustTailCall())
2791         return;
2792   }
2793   // TODO: handle musttail call returns for IA_Args.
2794   visitInstOperands(BCI);
2795 }
2796 
2797 void DFSanVisitor::visitCastInst(CastInst &CI) { visitInstOperands(CI); }
2798 
2799 void DFSanVisitor::visitCmpInst(CmpInst &CI) {
2800   visitInstOperands(CI);
2801   if (ClEventCallbacks) {
2802     IRBuilder<> IRB(&CI);
2803     Value *CombinedShadow = DFSF.getShadow(&CI);
2804     IRB.CreateCall(DFSF.DFS.DFSanCmpCallbackFn, CombinedShadow);
2805   }
2806 }
2807 
2808 void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
2809   if (ClCombineOffsetLabelsOnGEP) {
2810     visitInstOperands(GEPI);
2811     return;
2812   }
2813 
2814   // Only propagate shadow/origin of base pointer value but ignore those of
2815   // offset operands.
2816   Value *BasePointer = GEPI.getPointerOperand();
2817   DFSF.setShadow(&GEPI, DFSF.getShadow(BasePointer));
2818   if (DFSF.DFS.shouldTrackOrigins())
2819     DFSF.setOrigin(&GEPI, DFSF.getOrigin(BasePointer));
2820 }
2821 
2822 void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
2823   visitInstOperands(I);
2824 }
2825 
2826 void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
2827   visitInstOperands(I);
2828 }
2829 
2830 void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
2831   visitInstOperands(I);
2832 }
2833 
2834 void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
2835   if (!DFSF.DFS.shouldTrackFieldsAndIndices()) {
2836     visitInstOperands(I);
2837     return;
2838   }
2839 
2840   IRBuilder<> IRB(&I);
2841   Value *Agg = I.getAggregateOperand();
2842   Value *AggShadow = DFSF.getShadow(Agg);
2843   Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
2844   DFSF.setShadow(&I, ResShadow);
2845   visitInstOperandOrigins(I);
2846 }
2847 
2848 void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
2849   if (!DFSF.DFS.shouldTrackFieldsAndIndices()) {
2850     visitInstOperands(I);
2851     return;
2852   }
2853 
2854   IRBuilder<> IRB(&I);
2855   Value *AggShadow = DFSF.getShadow(I.getAggregateOperand());
2856   Value *InsShadow = DFSF.getShadow(I.getInsertedValueOperand());
2857   Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
2858   DFSF.setShadow(&I, Res);
2859   visitInstOperandOrigins(I);
2860 }
2861 
2862 void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
2863   bool AllLoadsStores = true;
2864   for (User *U : I.users()) {
2865     if (isa<LoadInst>(U))
2866       continue;
2867 
2868     if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
2869       if (SI->getPointerOperand() == &I)
2870         continue;
2871     }
2872 
2873     AllLoadsStores = false;
2874     break;
2875   }
2876   if (AllLoadsStores) {
2877     IRBuilder<> IRB(&I);
2878     DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.PrimitiveShadowTy);
2879     if (DFSF.DFS.shouldTrackOrigins()) {
2880       DFSF.AllocaOriginMap[&I] =
2881           IRB.CreateAlloca(DFSF.DFS.OriginTy, nullptr, "_dfsa");
2882     }
2883   }
2884   DFSF.setShadow(&I, DFSF.DFS.ZeroPrimitiveShadow);
2885   DFSF.setOrigin(&I, DFSF.DFS.ZeroOrigin);
2886 }
2887 
2888 void DFSanVisitor::visitSelectInst(SelectInst &I) {
2889   Value *CondShadow = DFSF.getShadow(I.getCondition());
2890   Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
2891   Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
2892   Value *ShadowSel = nullptr;
2893   const bool ShouldTrackOrigins = DFSF.DFS.shouldTrackOrigins();
2894   std::vector<Value *> Shadows;
2895   std::vector<Value *> Origins;
2896   Value *TrueOrigin =
2897       ShouldTrackOrigins ? DFSF.getOrigin(I.getTrueValue()) : nullptr;
2898   Value *FalseOrigin =
2899       ShouldTrackOrigins ? DFSF.getOrigin(I.getFalseValue()) : nullptr;
2900 
2901   if (isa<VectorType>(I.getCondition()->getType())) {
2902     ShadowSel = DFSF.combineShadowsThenConvert(I.getType(), TrueShadow,
2903                                                FalseShadow, &I);
2904     if (ShouldTrackOrigins) {
2905       Shadows.push_back(TrueShadow);
2906       Shadows.push_back(FalseShadow);
2907       Origins.push_back(TrueOrigin);
2908       Origins.push_back(FalseOrigin);
2909     }
2910   } else {
2911     if (TrueShadow == FalseShadow) {
2912       ShadowSel = TrueShadow;
2913       if (ShouldTrackOrigins) {
2914         Shadows.push_back(TrueShadow);
2915         Origins.push_back(TrueOrigin);
2916       }
2917     } else {
2918       ShadowSel =
2919           SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
2920       if (ShouldTrackOrigins) {
2921         Shadows.push_back(ShadowSel);
2922         Origins.push_back(SelectInst::Create(I.getCondition(), TrueOrigin,
2923                                              FalseOrigin, "", &I));
2924       }
2925     }
2926   }
2927   DFSF.setShadow(&I, ClTrackSelectControlFlow
2928                          ? DFSF.combineShadowsThenConvert(
2929                                I.getType(), CondShadow, ShadowSel, &I)
2930                          : ShadowSel);
2931   if (ShouldTrackOrigins) {
2932     if (ClTrackSelectControlFlow) {
2933       Shadows.push_back(CondShadow);
2934       Origins.push_back(DFSF.getOrigin(I.getCondition()));
2935     }
2936     DFSF.setOrigin(&I, DFSF.combineOrigins(Shadows, Origins, &I));
2937   }
2938 }
2939 
2940 void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
2941   IRBuilder<> IRB(&I);
2942   Value *ValShadow = DFSF.getShadow(I.getValue());
2943   Value *ValOrigin = DFSF.DFS.shouldTrackOrigins()
2944                          ? DFSF.getOrigin(I.getValue())
2945                          : DFSF.DFS.ZeroOrigin;
2946   auto *CB = IRB.CreateCall(
2947       DFSF.DFS.DFSanSetLabelFn,
2948       {ValShadow, ValOrigin,
2949        IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(*DFSF.DFS.Ctx)),
2950        IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy)});
2951   CB->setAttributes(CB->getCalledFunction()->getAttributes());
2952 }
2953 
2954 void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
2955   IRBuilder<> IRB(&I);
2956 
2957   // CopyOrMoveOrigin transfers origins by refering to their shadows. So we
2958   // need to move origins before moving shadows.
2959   if (DFSF.DFS.shouldTrackOrigins()) {
2960     IRB.CreateCall(
2961         DFSF.DFS.DFSanMemOriginTransferFn,
2962         {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
2963          IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
2964          IRB.CreateIntCast(I.getArgOperand(2), DFSF.DFS.IntptrTy, false)});
2965   }
2966 
2967   Value *RawDestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
2968   Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
2969   Value *LenShadow =
2970       IRB.CreateMul(I.getLength(), ConstantInt::get(I.getLength()->getType(),
2971                                                     DFSF.DFS.ShadowWidthBytes));
2972   Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
2973   Value *DestShadow = IRB.CreateBitCast(RawDestShadow, Int8Ptr);
2974   SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
2975   auto *MTI = cast<MemTransferInst>(
2976       IRB.CreateCall(I.getFunctionType(), I.getCalledOperand(),
2977                      {DestShadow, SrcShadow, LenShadow, I.getVolatileCst()}));
2978   if (ClPreserveAlignment) {
2979     MTI->setDestAlignment(I.getDestAlign() * DFSF.DFS.ShadowWidthBytes);
2980     MTI->setSourceAlignment(I.getSourceAlign() * DFSF.DFS.ShadowWidthBytes);
2981   } else {
2982     MTI->setDestAlignment(Align(DFSF.DFS.ShadowWidthBytes));
2983     MTI->setSourceAlignment(Align(DFSF.DFS.ShadowWidthBytes));
2984   }
2985   if (ClEventCallbacks) {
2986     IRB.CreateCall(DFSF.DFS.DFSanMemTransferCallbackFn,
2987                    {RawDestShadow,
2988                     IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy)});
2989   }
2990 }
2991 
2992 static bool isAMustTailRetVal(Value *RetVal) {
2993   // Tail call may have a bitcast between return.
2994   if (auto *I = dyn_cast<BitCastInst>(RetVal)) {
2995     RetVal = I->getOperand(0);
2996   }
2997   if (auto *I = dyn_cast<CallInst>(RetVal)) {
2998     return I->isMustTailCall();
2999   }
3000   return false;
3001 }
3002 
3003 void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
3004   if (!DFSF.IsNativeABI && RI.getReturnValue()) {
3005     switch (DFSF.IA) {
3006     case DataFlowSanitizer::IA_TLS: {
3007       // Don't emit the instrumentation for musttail call returns.
3008       if (isAMustTailRetVal(RI.getReturnValue()))
3009         return;
3010 
3011       Value *S = DFSF.getShadow(RI.getReturnValue());
3012       IRBuilder<> IRB(&RI);
3013       Type *RT = DFSF.F->getFunctionType()->getReturnType();
3014       unsigned Size =
3015           getDataLayout().getTypeAllocSize(DFSF.DFS.getShadowTy(RT));
3016       if (Size <= RetvalTLSSize) {
3017         // If the size overflows, stores nothing. At callsite, oversized return
3018         // shadows are set to zero.
3019         IRB.CreateAlignedStore(S, DFSF.getRetvalTLS(RT, IRB),
3020                                ShadowTLSAlignment);
3021       }
3022       if (DFSF.DFS.shouldTrackOrigins()) {
3023         Value *O = DFSF.getOrigin(RI.getReturnValue());
3024         IRB.CreateStore(O, DFSF.getRetvalOriginTLS());
3025       }
3026       break;
3027     }
3028     case DataFlowSanitizer::IA_Args: {
3029       // TODO: handle musttail call returns for IA_Args.
3030 
3031       IRBuilder<> IRB(&RI);
3032       Type *RT = DFSF.F->getFunctionType()->getReturnType();
3033       Value *InsVal =
3034           IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
3035       Value *InsShadow =
3036           IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
3037       RI.setOperand(0, InsShadow);
3038       break;
3039     }
3040     }
3041   }
3042 }
3043 
3044 void DFSanVisitor::addShadowArguments(Function &F, CallBase &CB,
3045                                       std::vector<Value *> &Args,
3046                                       IRBuilder<> &IRB) {
3047   FunctionType *FT = F.getFunctionType();
3048 
3049   auto *I = CB.arg_begin();
3050 
3051   // Adds non-variable argument shadows.
3052   for (unsigned N = FT->getNumParams(); N != 0; ++I, --N)
3053     Args.push_back(DFSF.collapseToPrimitiveShadow(DFSF.getShadow(*I), &CB));
3054 
3055   // Adds variable argument shadows.
3056   if (FT->isVarArg()) {
3057     auto *LabelVATy = ArrayType::get(DFSF.DFS.PrimitiveShadowTy,
3058                                      CB.arg_size() - FT->getNumParams());
3059     auto *LabelVAAlloca =
3060         new AllocaInst(LabelVATy, getDataLayout().getAllocaAddrSpace(),
3061                        "labelva", &DFSF.F->getEntryBlock().front());
3062 
3063     for (unsigned N = 0; I != CB.arg_end(); ++I, ++N) {
3064       auto *LabelVAPtr = IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, N);
3065       IRB.CreateStore(DFSF.collapseToPrimitiveShadow(DFSF.getShadow(*I), &CB),
3066                       LabelVAPtr);
3067     }
3068 
3069     Args.push_back(IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, 0));
3070   }
3071 
3072   // Adds the return value shadow.
3073   if (!FT->getReturnType()->isVoidTy()) {
3074     if (!DFSF.LabelReturnAlloca) {
3075       DFSF.LabelReturnAlloca = new AllocaInst(
3076           DFSF.DFS.PrimitiveShadowTy, getDataLayout().getAllocaAddrSpace(),
3077           "labelreturn", &DFSF.F->getEntryBlock().front());
3078     }
3079     Args.push_back(DFSF.LabelReturnAlloca);
3080   }
3081 }
3082 
3083 void DFSanVisitor::addOriginArguments(Function &F, CallBase &CB,
3084                                       std::vector<Value *> &Args,
3085                                       IRBuilder<> &IRB) {
3086   FunctionType *FT = F.getFunctionType();
3087 
3088   auto *I = CB.arg_begin();
3089 
3090   // Add non-variable argument origins.
3091   for (unsigned N = FT->getNumParams(); N != 0; ++I, --N)
3092     Args.push_back(DFSF.getOrigin(*I));
3093 
3094   // Add variable argument origins.
3095   if (FT->isVarArg()) {
3096     auto *OriginVATy =
3097         ArrayType::get(DFSF.DFS.OriginTy, CB.arg_size() - FT->getNumParams());
3098     auto *OriginVAAlloca =
3099         new AllocaInst(OriginVATy, getDataLayout().getAllocaAddrSpace(),
3100                        "originva", &DFSF.F->getEntryBlock().front());
3101 
3102     for (unsigned N = 0; I != CB.arg_end(); ++I, ++N) {
3103       auto *OriginVAPtr = IRB.CreateStructGEP(OriginVATy, OriginVAAlloca, N);
3104       IRB.CreateStore(DFSF.getOrigin(*I), OriginVAPtr);
3105     }
3106 
3107     Args.push_back(IRB.CreateStructGEP(OriginVATy, OriginVAAlloca, 0));
3108   }
3109 
3110   // Add the return value origin.
3111   if (!FT->getReturnType()->isVoidTy()) {
3112     if (!DFSF.OriginReturnAlloca) {
3113       DFSF.OriginReturnAlloca = new AllocaInst(
3114           DFSF.DFS.OriginTy, getDataLayout().getAllocaAddrSpace(),
3115           "originreturn", &DFSF.F->getEntryBlock().front());
3116     }
3117     Args.push_back(DFSF.OriginReturnAlloca);
3118   }
3119 }
3120 
3121 bool DFSanVisitor::visitWrappedCallBase(Function &F, CallBase &CB) {
3122   IRBuilder<> IRB(&CB);
3123   switch (DFSF.DFS.getWrapperKind(&F)) {
3124   case DataFlowSanitizer::WK_Warning:
3125     CB.setCalledFunction(&F);
3126     IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
3127                    IRB.CreateGlobalStringPtr(F.getName()));
3128     DFSF.setShadow(&CB, DFSF.DFS.getZeroShadow(&CB));
3129     DFSF.setOrigin(&CB, DFSF.DFS.ZeroOrigin);
3130     return true;
3131   case DataFlowSanitizer::WK_Discard:
3132     CB.setCalledFunction(&F);
3133     DFSF.setShadow(&CB, DFSF.DFS.getZeroShadow(&CB));
3134     DFSF.setOrigin(&CB, DFSF.DFS.ZeroOrigin);
3135     return true;
3136   case DataFlowSanitizer::WK_Functional:
3137     CB.setCalledFunction(&F);
3138     visitInstOperands(CB);
3139     return true;
3140   case DataFlowSanitizer::WK_Custom:
3141     // Don't try to handle invokes of custom functions, it's too complicated.
3142     // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
3143     // wrapper.
3144     CallInst *CI = dyn_cast<CallInst>(&CB);
3145     if (!CI)
3146       return false;
3147 
3148     const bool ShouldTrackOrigins = DFSF.DFS.shouldTrackOrigins();
3149     FunctionType *FT = F.getFunctionType();
3150     TransformedFunction CustomFn = DFSF.DFS.getCustomFunctionType(FT);
3151     std::string CustomFName = ShouldTrackOrigins ? "__dfso_" : "__dfsw_";
3152     CustomFName += F.getName();
3153     FunctionCallee CustomF = DFSF.DFS.Mod->getOrInsertFunction(
3154         CustomFName, CustomFn.TransformedType);
3155     if (Function *CustomFn = dyn_cast<Function>(CustomF.getCallee())) {
3156       CustomFn->copyAttributesFrom(&F);
3157 
3158       // Custom functions returning non-void will write to the return label.
3159       if (!FT->getReturnType()->isVoidTy()) {
3160         CustomFn->removeAttributes(AttributeList::FunctionIndex,
3161                                    DFSF.DFS.ReadOnlyNoneAttrs);
3162       }
3163     }
3164 
3165     std::vector<Value *> Args;
3166 
3167     // Adds non-variable arguments.
3168     auto *I = CB.arg_begin();
3169     for (unsigned N = FT->getNumParams(); N != 0; ++I, --N) {
3170       Type *T = (*I)->getType();
3171       FunctionType *ParamFT;
3172       if (isa<PointerType>(T) &&
3173           (ParamFT = dyn_cast<FunctionType>(T->getPointerElementType()))) {
3174         std::string TName = "dfst";
3175         TName += utostr(FT->getNumParams() - N);
3176         TName += "$";
3177         TName += F.getName();
3178         Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
3179         Args.push_back(T);
3180         Args.push_back(
3181             IRB.CreateBitCast(*I, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
3182       } else {
3183         Args.push_back(*I);
3184       }
3185     }
3186 
3187     // Adds shadow arguments.
3188     const unsigned ShadowArgStart = Args.size();
3189     addShadowArguments(F, CB, Args, IRB);
3190 
3191     // Adds origin arguments.
3192     const unsigned OriginArgStart = Args.size();
3193     if (ShouldTrackOrigins)
3194       addOriginArguments(F, CB, Args, IRB);
3195 
3196     // Adds variable arguments.
3197     append_range(Args, drop_begin(CB.args(), FT->getNumParams()));
3198 
3199     CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
3200     CustomCI->setCallingConv(CI->getCallingConv());
3201     CustomCI->setAttributes(transformFunctionAttributes(
3202         CustomFn, CI->getContext(), CI->getAttributes()));
3203 
3204     // Update the parameter attributes of the custom call instruction to
3205     // zero extend the shadow parameters. This is required for targets
3206     // which consider PrimitiveShadowTy an illegal type.
3207     for (unsigned N = 0; N < FT->getNumParams(); N++) {
3208       const unsigned ArgNo = ShadowArgStart + N;
3209       if (CustomCI->getArgOperand(ArgNo)->getType() ==
3210           DFSF.DFS.PrimitiveShadowTy)
3211         CustomCI->addParamAttr(ArgNo, Attribute::ZExt);
3212       if (ShouldTrackOrigins) {
3213         const unsigned OriginArgNo = OriginArgStart + N;
3214         if (CustomCI->getArgOperand(OriginArgNo)->getType() ==
3215             DFSF.DFS.OriginTy)
3216           CustomCI->addParamAttr(OriginArgNo, Attribute::ZExt);
3217       }
3218     }
3219 
3220     // Loads the return value shadow and origin.
3221     if (!FT->getReturnType()->isVoidTy()) {
3222       LoadInst *LabelLoad =
3223           IRB.CreateLoad(DFSF.DFS.PrimitiveShadowTy, DFSF.LabelReturnAlloca);
3224       DFSF.setShadow(CustomCI, DFSF.expandFromPrimitiveShadow(
3225                                    FT->getReturnType(), LabelLoad, &CB));
3226       if (ShouldTrackOrigins) {
3227         LoadInst *OriginLoad =
3228             IRB.CreateLoad(DFSF.DFS.OriginTy, DFSF.OriginReturnAlloca);
3229         DFSF.setOrigin(CustomCI, OriginLoad);
3230       }
3231     }
3232 
3233     CI->replaceAllUsesWith(CustomCI);
3234     CI->eraseFromParent();
3235     return true;
3236   }
3237   return false;
3238 }
3239 
3240 void DFSanVisitor::visitCallBase(CallBase &CB) {
3241   Function *F = CB.getCalledFunction();
3242   if ((F && F->isIntrinsic()) || CB.isInlineAsm()) {
3243     visitInstOperands(CB);
3244     return;
3245   }
3246 
3247   // Calls to this function are synthesized in wrappers, and we shouldn't
3248   // instrument them.
3249   if (F == DFSF.DFS.DFSanVarargWrapperFn.getCallee()->stripPointerCasts())
3250     return;
3251 
3252   DenseMap<Value *, Function *>::iterator UnwrappedFnIt =
3253       DFSF.DFS.UnwrappedFnMap.find(CB.getCalledOperand());
3254   if (UnwrappedFnIt != DFSF.DFS.UnwrappedFnMap.end())
3255     if (visitWrappedCallBase(*UnwrappedFnIt->second, CB))
3256       return;
3257 
3258   IRBuilder<> IRB(&CB);
3259 
3260   const bool ShouldTrackOrigins = DFSF.DFS.shouldTrackOrigins();
3261   FunctionType *FT = CB.getFunctionType();
3262   if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
3263     // Stores argument shadows.
3264     unsigned ArgOffset = 0;
3265     const DataLayout &DL = getDataLayout();
3266     for (unsigned I = 0, N = FT->getNumParams(); I != N; ++I) {
3267       if (ShouldTrackOrigins) {
3268         // Ignore overflowed origins
3269         Value *ArgShadow = DFSF.getShadow(CB.getArgOperand(I));
3270         if (I < DFSF.DFS.NumOfElementsInArgOrgTLS &&
3271             !DFSF.DFS.isZeroShadow(ArgShadow))
3272           IRB.CreateStore(DFSF.getOrigin(CB.getArgOperand(I)),
3273                           DFSF.getArgOriginTLS(I, IRB));
3274       }
3275 
3276       unsigned Size =
3277           DL.getTypeAllocSize(DFSF.DFS.getShadowTy(FT->getParamType(I)));
3278       // Stop storing if arguments' size overflows. Inside a function, arguments
3279       // after overflow have zero shadow values.
3280       if (ArgOffset + Size > ArgTLSSize)
3281         break;
3282       IRB.CreateAlignedStore(
3283           DFSF.getShadow(CB.getArgOperand(I)),
3284           DFSF.getArgTLS(FT->getParamType(I), ArgOffset, IRB),
3285           ShadowTLSAlignment);
3286       ArgOffset += alignTo(Size, ShadowTLSAlignment);
3287     }
3288   }
3289 
3290   Instruction *Next = nullptr;
3291   if (!CB.getType()->isVoidTy()) {
3292     if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
3293       if (II->getNormalDest()->getSinglePredecessor()) {
3294         Next = &II->getNormalDest()->front();
3295       } else {
3296         BasicBlock *NewBB =
3297             SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DT);
3298         Next = &NewBB->front();
3299       }
3300     } else {
3301       assert(CB.getIterator() != CB.getParent()->end());
3302       Next = CB.getNextNode();
3303     }
3304 
3305     if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
3306       // Don't emit the epilogue for musttail call returns.
3307       if (isa<CallInst>(CB) && cast<CallInst>(CB).isMustTailCall())
3308         return;
3309 
3310       // Loads the return value shadow.
3311       IRBuilder<> NextIRB(Next);
3312       const DataLayout &DL = getDataLayout();
3313       unsigned Size = DL.getTypeAllocSize(DFSF.DFS.getShadowTy(&CB));
3314       if (Size > RetvalTLSSize) {
3315         // Set overflowed return shadow to be zero.
3316         DFSF.setShadow(&CB, DFSF.DFS.getZeroShadow(&CB));
3317       } else {
3318         LoadInst *LI = NextIRB.CreateAlignedLoad(
3319             DFSF.DFS.getShadowTy(&CB), DFSF.getRetvalTLS(CB.getType(), NextIRB),
3320             ShadowTLSAlignment, "_dfsret");
3321         DFSF.SkipInsts.insert(LI);
3322         DFSF.setShadow(&CB, LI);
3323         DFSF.NonZeroChecks.push_back(LI);
3324       }
3325 
3326       if (ShouldTrackOrigins) {
3327         LoadInst *LI = NextIRB.CreateLoad(
3328             DFSF.DFS.OriginTy, DFSF.getRetvalOriginTLS(), "_dfsret_o");
3329         DFSF.SkipInsts.insert(LI);
3330         DFSF.setOrigin(&CB, LI);
3331       }
3332     }
3333   }
3334 
3335   // Do all instrumentation for IA_Args down here to defer tampering with the
3336   // CFG in a way that SplitEdge may be able to detect.
3337   if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
3338     // TODO: handle musttail call returns for IA_Args.
3339 
3340     FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
3341     Value *Func =
3342         IRB.CreateBitCast(CB.getCalledOperand(), PointerType::getUnqual(NewFT));
3343 
3344     const unsigned NumParams = FT->getNumParams();
3345 
3346     // Copy original arguments.
3347     auto *ArgIt = CB.arg_begin(), *ArgEnd = CB.arg_end();
3348     std::vector<Value *> Args(NumParams);
3349     std::copy_n(ArgIt, NumParams, Args.begin());
3350 
3351     // Add shadow arguments by transforming original arguments.
3352     std::generate_n(std::back_inserter(Args), NumParams,
3353                     [&]() { return DFSF.getShadow(*ArgIt++); });
3354 
3355     if (FT->isVarArg()) {
3356       unsigned VarArgSize = CB.arg_size() - NumParams;
3357       ArrayType *VarArgArrayTy =
3358           ArrayType::get(DFSF.DFS.PrimitiveShadowTy, VarArgSize);
3359       AllocaInst *VarArgShadow =
3360           new AllocaInst(VarArgArrayTy, getDataLayout().getAllocaAddrSpace(),
3361                          "", &DFSF.F->getEntryBlock().front());
3362       Args.push_back(IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, 0));
3363 
3364       // Copy remaining var args.
3365       unsigned GepIndex = 0;
3366       std::for_each(ArgIt, ArgEnd, [&](Value *Arg) {
3367         IRB.CreateStore(
3368             DFSF.getShadow(Arg),
3369             IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, GepIndex++));
3370         Args.push_back(Arg);
3371       });
3372     }
3373 
3374     CallBase *NewCB;
3375     if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
3376       NewCB = IRB.CreateInvoke(NewFT, Func, II->getNormalDest(),
3377                                II->getUnwindDest(), Args);
3378     } else {
3379       NewCB = IRB.CreateCall(NewFT, Func, Args);
3380     }
3381     NewCB->setCallingConv(CB.getCallingConv());
3382     NewCB->setAttributes(CB.getAttributes().removeAttributes(
3383         *DFSF.DFS.Ctx, AttributeList::ReturnIndex,
3384         AttributeFuncs::typeIncompatible(NewCB->getType())));
3385 
3386     if (Next) {
3387       ExtractValueInst *ExVal = ExtractValueInst::Create(NewCB, 0, "", Next);
3388       DFSF.SkipInsts.insert(ExVal);
3389       ExtractValueInst *ExShadow = ExtractValueInst::Create(NewCB, 1, "", Next);
3390       DFSF.SkipInsts.insert(ExShadow);
3391       DFSF.setShadow(ExVal, ExShadow);
3392       DFSF.NonZeroChecks.push_back(ExShadow);
3393 
3394       CB.replaceAllUsesWith(ExVal);
3395     }
3396 
3397     CB.eraseFromParent();
3398   }
3399 }
3400 
3401 void DFSanVisitor::visitPHINode(PHINode &PN) {
3402   Type *ShadowTy = DFSF.DFS.getShadowTy(&PN);
3403   PHINode *ShadowPN =
3404       PHINode::Create(ShadowTy, PN.getNumIncomingValues(), "", &PN);
3405 
3406   // Give the shadow phi node valid predecessors to fool SplitEdge into working.
3407   Value *UndefShadow = UndefValue::get(ShadowTy);
3408   for (BasicBlock *BB : PN.blocks())
3409     ShadowPN->addIncoming(UndefShadow, BB);
3410 
3411   DFSF.setShadow(&PN, ShadowPN);
3412 
3413   PHINode *OriginPN = nullptr;
3414   if (DFSF.DFS.shouldTrackOrigins()) {
3415     OriginPN =
3416         PHINode::Create(DFSF.DFS.OriginTy, PN.getNumIncomingValues(), "", &PN);
3417     Value *UndefOrigin = UndefValue::get(DFSF.DFS.OriginTy);
3418     for (BasicBlock *BB : PN.blocks())
3419       OriginPN->addIncoming(UndefOrigin, BB);
3420     DFSF.setOrigin(&PN, OriginPN);
3421   }
3422 
3423   DFSF.PHIFixups.push_back({&PN, ShadowPN, OriginPN});
3424 }
3425 
3426 namespace {
3427 class DataFlowSanitizerLegacyPass : public ModulePass {
3428 private:
3429   std::vector<std::string> ABIListFiles;
3430 
3431 public:
3432   static char ID;
3433 
3434   DataFlowSanitizerLegacyPass(
3435       const std::vector<std::string> &ABIListFiles = std::vector<std::string>())
3436       : ModulePass(ID), ABIListFiles(ABIListFiles) {}
3437 
3438   bool runOnModule(Module &M) override {
3439     return DataFlowSanitizer(ABIListFiles).runImpl(M);
3440   }
3441 };
3442 } // namespace
3443 
3444 char DataFlowSanitizerLegacyPass::ID;
3445 
3446 INITIALIZE_PASS(DataFlowSanitizerLegacyPass, "dfsan",
3447                 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
3448 
3449 ModulePass *llvm::createDataFlowSanitizerLegacyPassPass(
3450     const std::vector<std::string> &ABIListFiles) {
3451   return new DataFlowSanitizerLegacyPass(ABIListFiles);
3452 }
3453 
3454 PreservedAnalyses DataFlowSanitizerPass::run(Module &M,
3455                                              ModuleAnalysisManager &AM) {
3456   if (DataFlowSanitizer(ABIListFiles).runImpl(M)) {
3457     return PreservedAnalyses::none();
3458   }
3459   return PreservedAnalyses::all();
3460 }
3461