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