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