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