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.  Each
20 /// byte of application memory is backed by two bytes of shadow memory which
21 /// hold the label.  On Linux/x86_64, memory is laid out as follows:
22 ///
23 /// +--------------------+ 0x800000000000 (top of memory)
24 /// | application memory |
25 /// +--------------------+ 0x700000008000 (kAppAddr)
26 /// |                    |
27 /// |       unused       |
28 /// |                    |
29 /// +--------------------+ 0x200200000000 (kUnusedAddr)
30 /// |    union table     |
31 /// +--------------------+ 0x200000000000 (kUnionTableAddr)
32 /// |   shadow memory    |
33 /// +--------------------+ 0x000000010000 (kShadowAddr)
34 /// | reserved by kernel |
35 /// +--------------------+ 0x000000000000
36 ///
37 /// To derive a shadow memory address from an application memory address,
38 /// bits 44-46 are cleared to bring the address into the range
39 /// [0x000000008000,0x100000000000).  Then the address is shifted left by 1 to
40 /// account for the double byte representation of shadow labels and move the
41 /// address into the shadow memory range.  See the function
42 /// DataFlowSanitizer::getShadowAddress below.
43 ///
44 /// For more information, please refer to the design document:
45 /// http://clang.llvm.org/docs/DataFlowSanitizerDesign.html
46 //
47 //===----------------------------------------------------------------------===//
48 
49 #include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
50 #include "llvm/ADT/DenseMap.h"
51 #include "llvm/ADT/DenseSet.h"
52 #include "llvm/ADT/DepthFirstIterator.h"
53 #include "llvm/ADT/None.h"
54 #include "llvm/ADT/SmallPtrSet.h"
55 #include "llvm/ADT/SmallVector.h"
56 #include "llvm/ADT/StringExtras.h"
57 #include "llvm/ADT/StringRef.h"
58 #include "llvm/ADT/Triple.h"
59 #include "llvm/Analysis/ValueTracking.h"
60 #include "llvm/IR/Argument.h"
61 #include "llvm/IR/Attributes.h"
62 #include "llvm/IR/BasicBlock.h"
63 #include "llvm/IR/Constant.h"
64 #include "llvm/IR/Constants.h"
65 #include "llvm/IR/DataLayout.h"
66 #include "llvm/IR/DerivedTypes.h"
67 #include "llvm/IR/Dominators.h"
68 #include "llvm/IR/Function.h"
69 #include "llvm/IR/GlobalAlias.h"
70 #include "llvm/IR/GlobalValue.h"
71 #include "llvm/IR/GlobalVariable.h"
72 #include "llvm/IR/IRBuilder.h"
73 #include "llvm/IR/InlineAsm.h"
74 #include "llvm/IR/InstVisitor.h"
75 #include "llvm/IR/InstrTypes.h"
76 #include "llvm/IR/Instruction.h"
77 #include "llvm/IR/Instructions.h"
78 #include "llvm/IR/IntrinsicInst.h"
79 #include "llvm/IR/LLVMContext.h"
80 #include "llvm/IR/MDBuilder.h"
81 #include "llvm/IR/Module.h"
82 #include "llvm/IR/PassManager.h"
83 #include "llvm/IR/Type.h"
84 #include "llvm/IR/User.h"
85 #include "llvm/IR/Value.h"
86 #include "llvm/InitializePasses.h"
87 #include "llvm/Pass.h"
88 #include "llvm/Support/Casting.h"
89 #include "llvm/Support/CommandLine.h"
90 #include "llvm/Support/ErrorHandling.h"
91 #include "llvm/Support/SpecialCaseList.h"
92 #include "llvm/Support/VirtualFileSystem.h"
93 #include "llvm/Transforms/Instrumentation.h"
94 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
95 #include "llvm/Transforms/Utils/Local.h"
96 #include <algorithm>
97 #include <cassert>
98 #include <cstddef>
99 #include <cstdint>
100 #include <iterator>
101 #include <memory>
102 #include <set>
103 #include <string>
104 #include <utility>
105 #include <vector>
106 
107 using namespace llvm;
108 
109 // This must be consistent with ShadowWidthBits.
110 static const Align kShadowTLSAlignment = Align(2);
111 
112 // The size of TLS variables. These constants must be kept in sync with the ones
113 // in dfsan.cpp.
114 static const unsigned kArgTLSSize = 800;
115 static const unsigned kRetvalTLSSize = 800;
116 
117 // External symbol to be used when generating the shadow address for
118 // architectures with multiple VMAs. Instead of using a constant integer
119 // the runtime will set the external mask based on the VMA range.
120 const char kDFSanExternShadowPtrMask[] = "__dfsan_shadow_ptr_mask";
121 
122 // The -dfsan-preserve-alignment flag controls whether this pass assumes that
123 // alignment requirements provided by the input IR are correct.  For example,
124 // if the input IR contains a load with alignment 8, this flag will cause
125 // the shadow load to have alignment 16.  This flag is disabled by default as
126 // we have unfortunately encountered too much code (including Clang itself;
127 // see PR14291) which performs misaligned access.
128 static cl::opt<bool> ClPreserveAlignment(
129     "dfsan-preserve-alignment",
130     cl::desc("respect alignment requirements provided by input IR"), cl::Hidden,
131     cl::init(false));
132 
133 // The ABI list files control how shadow parameters are passed. The pass treats
134 // every function labelled "uninstrumented" in the ABI list file as conforming
135 // to the "native" (i.e. unsanitized) ABI.  Unless the ABI list contains
136 // additional annotations for those functions, a call to one of those functions
137 // will produce a warning message, as the labelling behaviour of the function is
138 // unknown.  The other supported annotations are "functional" and "discard",
139 // which are described below under DataFlowSanitizer::WrapperKind.
140 static cl::list<std::string> ClABIListFiles(
141     "dfsan-abilist",
142     cl::desc("File listing native ABI functions and how the pass treats them"),
143     cl::Hidden);
144 
145 // Controls whether the pass uses IA_Args or IA_TLS as the ABI for instrumented
146 // functions (see DataFlowSanitizer::InstrumentedABI below).
147 static cl::opt<bool> ClArgsABI(
148     "dfsan-args-abi",
149     cl::desc("Use the argument ABI rather than the TLS ABI"),
150     cl::Hidden);
151 
152 // Controls whether the pass includes or ignores the labels of pointers in load
153 // instructions.
154 static cl::opt<bool> ClCombinePointerLabelsOnLoad(
155     "dfsan-combine-pointer-labels-on-load",
156     cl::desc("Combine the label of the pointer with the label of the data when "
157              "loading from memory."),
158     cl::Hidden, cl::init(true));
159 
160 // Controls whether the pass includes or ignores the labels of pointers in
161 // stores instructions.
162 static cl::opt<bool> ClCombinePointerLabelsOnStore(
163     "dfsan-combine-pointer-labels-on-store",
164     cl::desc("Combine the label of the pointer with the label of the data when "
165              "storing in memory."),
166     cl::Hidden, cl::init(false));
167 
168 static cl::opt<bool> ClDebugNonzeroLabels(
169     "dfsan-debug-nonzero-labels",
170     cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, "
171              "load or return with a nonzero label"),
172     cl::Hidden);
173 
174 // Experimental feature that inserts callbacks for certain data events.
175 // Currently callbacks are only inserted for loads, stores, memory transfers
176 // (i.e. memcpy and memmove), and comparisons.
177 //
178 // If this flag is set to true, the user must provide definitions for the
179 // following callback functions:
180 //   void __dfsan_load_callback(dfsan_label Label, void* addr);
181 //   void __dfsan_store_callback(dfsan_label Label, void* addr);
182 //   void __dfsan_mem_transfer_callback(dfsan_label *Start, size_t Len);
183 //   void __dfsan_cmp_callback(dfsan_label CombinedLabel);
184 static cl::opt<bool> ClEventCallbacks(
185     "dfsan-event-callbacks",
186     cl::desc("Insert calls to __dfsan_*_callback functions on data events."),
187     cl::Hidden, cl::init(false));
188 
189 // Use a distinct bit for each base label, enabling faster unions with less
190 // instrumentation.  Limits the max number of base labels to 16.
191 static cl::opt<bool> ClFast16Labels(
192     "dfsan-fast-16-labels",
193     cl::desc("Use more efficient instrumentation, limiting the number of "
194              "labels to 16."),
195     cl::Hidden, cl::init(false));
196 
197 // Controls whether the pass tracks the control flow of select instructions.
198 static cl::opt<bool> ClTrackSelectControlFlow(
199     "dfsan-track-select-control-flow",
200     cl::desc("Propagate labels from condition values of select instructions "
201              "to results."),
202     cl::Hidden, cl::init(true));
203 
204 static StringRef GetGlobalTypeString(const GlobalValue &G) {
205   // Types of GlobalVariables are always pointer types.
206   Type *GType = G.getValueType();
207   // For now we support excluding struct types only.
208   if (StructType *SGType = dyn_cast<StructType>(GType)) {
209     if (!SGType->isLiteral())
210       return SGType->getName();
211   }
212   return "<unknown type>";
213 }
214 
215 namespace {
216 
217 class DFSanABIList {
218   std::unique_ptr<SpecialCaseList> SCL;
219 
220  public:
221   DFSanABIList() = default;
222 
223   void set(std::unique_ptr<SpecialCaseList> List) { SCL = std::move(List); }
224 
225   /// Returns whether either this function or its source file are listed in the
226   /// given category.
227   bool isIn(const Function &F, StringRef Category) const {
228     return isIn(*F.getParent(), Category) ||
229            SCL->inSection("dataflow", "fun", F.getName(), Category);
230   }
231 
232   /// Returns whether this global alias is listed in the given category.
233   ///
234   /// If GA aliases a function, the alias's name is matched as a function name
235   /// would be.  Similarly, aliases of globals are matched like globals.
236   bool isIn(const GlobalAlias &GA, StringRef Category) const {
237     if (isIn(*GA.getParent(), Category))
238       return true;
239 
240     if (isa<FunctionType>(GA.getValueType()))
241       return SCL->inSection("dataflow", "fun", GA.getName(), Category);
242 
243     return SCL->inSection("dataflow", "global", GA.getName(), Category) ||
244            SCL->inSection("dataflow", "type", GetGlobalTypeString(GA),
245                           Category);
246   }
247 
248   /// Returns whether this module is listed in the given category.
249   bool isIn(const Module &M, StringRef Category) const {
250     return SCL->inSection("dataflow", "src", M.getModuleIdentifier(), Category);
251   }
252 };
253 
254 /// TransformedFunction is used to express the result of transforming one
255 /// function type into another.  This struct is immutable.  It holds metadata
256 /// useful for updating calls of the old function to the new type.
257 struct TransformedFunction {
258   TransformedFunction(FunctionType* OriginalType,
259                       FunctionType* TransformedType,
260                       std::vector<unsigned> ArgumentIndexMapping)
261       : OriginalType(OriginalType),
262         TransformedType(TransformedType),
263         ArgumentIndexMapping(ArgumentIndexMapping) {}
264 
265   // Disallow copies.
266   TransformedFunction(const TransformedFunction&) = delete;
267   TransformedFunction& operator=(const TransformedFunction&) = delete;
268 
269   // Allow moves.
270   TransformedFunction(TransformedFunction&&) = default;
271   TransformedFunction& operator=(TransformedFunction&&) = default;
272 
273   /// Type of the function before the transformation.
274   FunctionType *OriginalType;
275 
276   /// Type of the function after the transformation.
277   FunctionType *TransformedType;
278 
279   /// Transforming a function may change the position of arguments.  This
280   /// member records the mapping from each argument's old position to its new
281   /// position.  Argument positions are zero-indexed.  If the transformation
282   /// from F to F' made the first argument of F into the third argument of F',
283   /// then ArgumentIndexMapping[0] will equal 2.
284   std::vector<unsigned> ArgumentIndexMapping;
285 };
286 
287 /// Given function attributes from a call site for the original function,
288 /// return function attributes appropriate for a call to the transformed
289 /// function.
290 AttributeList TransformFunctionAttributes(
291     const TransformedFunction& TransformedFunction,
292     LLVMContext& Ctx, AttributeList CallSiteAttrs) {
293 
294   // Construct a vector of AttributeSet for each function argument.
295   std::vector<llvm::AttributeSet> ArgumentAttributes(
296       TransformedFunction.TransformedType->getNumParams());
297 
298   // Copy attributes from the parameter of the original function to the
299   // transformed version.  'ArgumentIndexMapping' holds the mapping from
300   // old argument position to new.
301   for (unsigned i=0, ie = TransformedFunction.ArgumentIndexMapping.size();
302        i < ie; ++i) {
303     unsigned TransformedIndex = TransformedFunction.ArgumentIndexMapping[i];
304     ArgumentAttributes[TransformedIndex] = CallSiteAttrs.getParamAttributes(i);
305   }
306 
307   // Copy annotations on varargs arguments.
308   for (unsigned i = TransformedFunction.OriginalType->getNumParams(),
309        ie = CallSiteAttrs.getNumAttrSets(); i<ie; ++i) {
310     ArgumentAttributes.push_back(CallSiteAttrs.getParamAttributes(i));
311   }
312 
313   return AttributeList::get(
314       Ctx,
315       CallSiteAttrs.getFnAttributes(),
316       CallSiteAttrs.getRetAttributes(),
317       llvm::makeArrayRef(ArgumentAttributes));
318 }
319 
320 class DataFlowSanitizer {
321   friend struct DFSanFunction;
322   friend class DFSanVisitor;
323 
324   enum { ShadowWidthBits = 16, ShadowWidthBytes = ShadowWidthBits / 8 };
325 
326   /// Which ABI should be used for instrumented functions?
327   enum InstrumentedABI {
328     /// Argument and return value labels are passed through additional
329     /// arguments and by modifying the return type.
330     IA_Args,
331 
332     /// Argument and return value labels are passed through TLS variables
333     /// __dfsan_arg_tls and __dfsan_retval_tls.
334     IA_TLS
335   };
336 
337   /// How should calls to uninstrumented functions be handled?
338   enum WrapperKind {
339     /// This function is present in an uninstrumented form but we don't know
340     /// how it should be handled.  Print a warning and call the function anyway.
341     /// Don't label the return value.
342     WK_Warning,
343 
344     /// This function does not write to (user-accessible) memory, and its return
345     /// value is unlabelled.
346     WK_Discard,
347 
348     /// This function does not write to (user-accessible) memory, and the label
349     /// of its return value is the union of the label of its arguments.
350     WK_Functional,
351 
352     /// Instead of calling the function, a custom wrapper __dfsw_F is called,
353     /// where F is the name of the function.  This function may wrap the
354     /// original function or provide its own implementation.  This is similar to
355     /// the IA_Args ABI, except that IA_Args uses a struct return type to
356     /// pass the return value shadow in a register, while WK_Custom uses an
357     /// extra pointer argument to return the shadow.  This allows the wrapped
358     /// form of the function type to be expressed in C.
359     WK_Custom
360   };
361 
362   Module *Mod;
363   LLVMContext *Ctx;
364   Type *Int8Ptr;
365   /// The shadow type for all primitive types and vector types.
366   IntegerType *PrimitiveShadowTy;
367   PointerType *PrimitiveShadowPtrTy;
368   IntegerType *IntptrTy;
369   ConstantInt *ZeroPrimitiveShadow;
370   ConstantInt *ShadowPtrMask;
371   ConstantInt *ShadowPtrMul;
372   Constant *ArgTLS;
373   Constant *RetvalTLS;
374   Constant *ExternalShadowMask;
375   FunctionType *DFSanUnionFnTy;
376   FunctionType *DFSanUnionLoadFnTy;
377   FunctionType *DFSanUnimplementedFnTy;
378   FunctionType *DFSanSetLabelFnTy;
379   FunctionType *DFSanNonzeroLabelFnTy;
380   FunctionType *DFSanVarargWrapperFnTy;
381   FunctionType *DFSanCmpCallbackFnTy;
382   FunctionType *DFSanLoadStoreCallbackFnTy;
383   FunctionType *DFSanMemTransferCallbackFnTy;
384   FunctionCallee DFSanUnionFn;
385   FunctionCallee DFSanCheckedUnionFn;
386   FunctionCallee DFSanUnionLoadFn;
387   FunctionCallee DFSanUnionLoadFast16LabelsFn;
388   FunctionCallee DFSanUnimplementedFn;
389   FunctionCallee DFSanSetLabelFn;
390   FunctionCallee DFSanNonzeroLabelFn;
391   FunctionCallee DFSanVarargWrapperFn;
392   FunctionCallee DFSanLoadCallbackFn;
393   FunctionCallee DFSanStoreCallbackFn;
394   FunctionCallee DFSanMemTransferCallbackFn;
395   FunctionCallee DFSanCmpCallbackFn;
396   MDNode *ColdCallWeights;
397   DFSanABIList ABIList;
398   DenseMap<Value *, Function *> UnwrappedFnMap;
399   AttrBuilder ReadOnlyNoneAttrs;
400   bool DFSanRuntimeShadowMask = false;
401 
402   Value *getShadowAddress(Value *Addr, Instruction *Pos);
403   bool isInstrumented(const Function *F);
404   bool isInstrumented(const GlobalAlias *GA);
405   FunctionType *getArgsFunctionType(FunctionType *T);
406   FunctionType *getTrampolineFunctionType(FunctionType *T);
407   TransformedFunction getCustomFunctionType(FunctionType *T);
408   InstrumentedABI getInstrumentedABI();
409   WrapperKind getWrapperKind(Function *F);
410   void addGlobalNamePrefix(GlobalValue *GV);
411   Function *buildWrapperFunction(Function *F, StringRef NewFName,
412                                  GlobalValue::LinkageTypes NewFLink,
413                                  FunctionType *NewFT);
414   Constant *getOrBuildTrampolineFunction(FunctionType *FT, StringRef FName);
415   void initializeCallbackFunctions(Module &M);
416   void initializeRuntimeFunctions(Module &M);
417 
418   bool init(Module &M);
419 
420   /// Returns whether the pass tracks labels for struct fields and array
421   /// indices. Support only fast16 mode in TLS ABI mode.
422   bool shouldTrackFieldsAndIndices();
423 
424   /// Returns a zero constant with the shadow type of OrigTy.
425   ///
426   /// getZeroShadow({T1,T2,...}) = {getZeroShadow(T1),getZeroShadow(T2,...}
427   /// getZeroShadow([n x T]) = [n x getZeroShadow(T)]
428   /// getZeroShadow(other type) = i16(0)
429   ///
430   /// Note that a zero shadow is always i16(0) when shouldTrackFieldsAndIndices
431   /// returns false.
432   Constant *getZeroShadow(Type *OrigTy);
433   /// Returns a zero constant with the shadow type of V's type.
434   Constant *getZeroShadow(Value *V);
435 
436   /// Checks if V is a zero shadow.
437   bool isZeroShadow(Value *V);
438 
439   /// Returns the shadow type of OrigTy.
440   ///
441   /// getShadowTy({T1,T2,...}) = {getShadowTy(T1),getShadowTy(T2),...}
442   /// getShadowTy([n x T]) = [n x getShadowTy(T)]
443   /// getShadowTy(other type) = i16
444   ///
445   /// Note that a shadow type is always i16 when shouldTrackFieldsAndIndices
446   /// returns false.
447   Type *getShadowTy(Type *OrigTy);
448   /// Returns the shadow type of of V's type.
449   Type *getShadowTy(Value *V);
450 
451 public:
452   DataFlowSanitizer(const std::vector<std::string> &ABIListFiles);
453 
454   bool runImpl(Module &M);
455 };
456 
457 struct DFSanFunction {
458   DataFlowSanitizer &DFS;
459   Function *F;
460   DominatorTree DT;
461   DataFlowSanitizer::InstrumentedABI IA;
462   bool IsNativeABI;
463   AllocaInst *LabelReturnAlloca = nullptr;
464   DenseMap<Value *, Value *> ValShadowMap;
465   DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
466   std::vector<std::pair<PHINode *, PHINode *>> PHIFixups;
467   DenseSet<Instruction *> SkipInsts;
468   std::vector<Value *> NonZeroChecks;
469   bool AvoidNewBlocks;
470 
471   struct CachedShadow {
472     BasicBlock *Block; // The block where Shadow is defined.
473     Value *Shadow;
474   };
475   /// Maps a value to its latest shadow value in terms of domination tree.
476   DenseMap<std::pair<Value *, Value *>, CachedShadow> CachedShadows;
477   /// Maps a value to its latest collapsed shadow value it was converted to in
478   /// terms of domination tree. When ClDebugNonzeroLabels is on, this cache is
479   /// used at a post process where CFG blocks are split. So it does not cache
480   /// BasicBlock like CachedShadows, but uses domination between values.
481   DenseMap<Value *, Value *> CachedCollapsedShadows;
482   DenseMap<Value *, std::set<Value *>> ShadowElements;
483 
484   DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI)
485       : DFS(DFS), F(F), IA(DFS.getInstrumentedABI()), IsNativeABI(IsNativeABI) {
486     DT.recalculate(*F);
487     // FIXME: Need to track down the register allocator issue which causes poor
488     // performance in pathological cases with large numbers of basic blocks.
489     AvoidNewBlocks = F->size() > 1000;
490   }
491 
492   /// Computes the shadow address for a given function argument.
493   ///
494   /// Shadow = ArgTLS+ArgOffset.
495   Value *getArgTLS(Type *T, unsigned ArgOffset, IRBuilder<> &IRB);
496 
497   /// Computes the shadow address for a retval.
498   Value *getRetvalTLS(Type *T, IRBuilder<> &IRB);
499 
500   Value *getShadow(Value *V);
501   void setShadow(Instruction *I, Value *Shadow);
502   /// Generates IR to compute the union of the two given shadows, inserting it
503   /// before Pos. The combined value is with primitive type.
504   Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
505   /// Combines the shadow values of V1 and V2, then converts the combined value
506   /// with primitive type into a shadow value with the original type T.
507   Value *combineShadowsThenConvert(Type *T, Value *V1, Value *V2,
508                                    Instruction *Pos);
509   Value *combineOperandShadows(Instruction *Inst);
510   Value *loadShadow(Value *ShadowAddr, uint64_t Size, uint64_t Align,
511                     Instruction *Pos);
512   void storePrimitiveShadow(Value *Addr, uint64_t Size, Align Alignment,
513                             Value *PrimitiveShadow, Instruction *Pos);
514   /// Applies PrimitiveShadow to all primitive subtypes of T, returning
515   /// the expanded shadow value.
516   ///
517   /// EFP({T1,T2, ...}, PS) = {EFP(T1,PS),EFP(T2,PS),...}
518   /// EFP([n x T], PS) = [n x EFP(T,PS)]
519   /// EFP(other types, PS) = PS
520   Value *expandFromPrimitiveShadow(Type *T, Value *PrimitiveShadow,
521                                    Instruction *Pos);
522   /// Collapses Shadow into a single primitive shadow value, unioning all
523   /// primitive shadow values in the process. Returns the final primitive
524   /// shadow value.
525   ///
526   /// CTP({V1,V2, ...}) = UNION(CFP(V1,PS),CFP(V2,PS),...)
527   /// CTP([V1,V2,...]) = UNION(CFP(V1,PS),CFP(V2,PS),...)
528   /// CTP(other types, PS) = PS
529   Value *collapseToPrimitiveShadow(Value *Shadow, Instruction *Pos);
530 
531 private:
532   /// Collapses the shadow with aggregate type into a single primitive shadow
533   /// value.
534   template <class AggregateType>
535   Value *collapseAggregateShadow(AggregateType *AT, Value *Shadow,
536                                  IRBuilder<> &IRB);
537 
538   Value *collapseToPrimitiveShadow(Value *Shadow, IRBuilder<> &IRB);
539 
540   /// Returns the shadow value of an argument A.
541   Value *getShadowForTLSArgument(Argument *A);
542 };
543 
544 class DFSanVisitor : public InstVisitor<DFSanVisitor> {
545 public:
546   DFSanFunction &DFSF;
547 
548   DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
549 
550   const DataLayout &getDataLayout() const {
551     return DFSF.F->getParent()->getDataLayout();
552   }
553 
554   // Combines shadow values for all of I's operands. Returns the combined shadow
555   // value.
556   Value *visitOperandShadowInst(Instruction &I);
557 
558   void visitUnaryOperator(UnaryOperator &UO);
559   void visitBinaryOperator(BinaryOperator &BO);
560   void visitCastInst(CastInst &CI);
561   void visitCmpInst(CmpInst &CI);
562   void visitGetElementPtrInst(GetElementPtrInst &GEPI);
563   void visitLoadInst(LoadInst &LI);
564   void visitStoreInst(StoreInst &SI);
565   void visitReturnInst(ReturnInst &RI);
566   void visitCallBase(CallBase &CB);
567   void visitPHINode(PHINode &PN);
568   void visitExtractElementInst(ExtractElementInst &I);
569   void visitInsertElementInst(InsertElementInst &I);
570   void visitShuffleVectorInst(ShuffleVectorInst &I);
571   void visitExtractValueInst(ExtractValueInst &I);
572   void visitInsertValueInst(InsertValueInst &I);
573   void visitAllocaInst(AllocaInst &I);
574   void visitSelectInst(SelectInst &I);
575   void visitMemSetInst(MemSetInst &I);
576   void visitMemTransferInst(MemTransferInst &I);
577 };
578 
579 } // end anonymous namespace
580 
581 DataFlowSanitizer::DataFlowSanitizer(
582     const std::vector<std::string> &ABIListFiles) {
583   std::vector<std::string> AllABIListFiles(std::move(ABIListFiles));
584   AllABIListFiles.insert(AllABIListFiles.end(), ClABIListFiles.begin(),
585                          ClABIListFiles.end());
586   // FIXME: should we propagate vfs::FileSystem to this constructor?
587   ABIList.set(
588       SpecialCaseList::createOrDie(AllABIListFiles, *vfs::getRealFileSystem()));
589 }
590 
591 FunctionType *DataFlowSanitizer::getArgsFunctionType(FunctionType *T) {
592   SmallVector<Type *, 4> ArgTypes(T->param_begin(), T->param_end());
593   ArgTypes.append(T->getNumParams(), PrimitiveShadowTy);
594   if (T->isVarArg())
595     ArgTypes.push_back(PrimitiveShadowPtrTy);
596   Type *RetType = T->getReturnType();
597   if (!RetType->isVoidTy())
598     RetType = StructType::get(RetType, PrimitiveShadowTy);
599   return FunctionType::get(RetType, ArgTypes, T->isVarArg());
600 }
601 
602 FunctionType *DataFlowSanitizer::getTrampolineFunctionType(FunctionType *T) {
603   assert(!T->isVarArg());
604   SmallVector<Type *, 4> ArgTypes;
605   ArgTypes.push_back(T->getPointerTo());
606   ArgTypes.append(T->param_begin(), T->param_end());
607   ArgTypes.append(T->getNumParams(), PrimitiveShadowTy);
608   Type *RetType = T->getReturnType();
609   if (!RetType->isVoidTy())
610     ArgTypes.push_back(PrimitiveShadowPtrTy);
611   return FunctionType::get(T->getReturnType(), ArgTypes, false);
612 }
613 
614 TransformedFunction DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
615   SmallVector<Type *, 4> ArgTypes;
616 
617   // Some parameters of the custom function being constructed are
618   // parameters of T.  Record the mapping from parameters of T to
619   // parameters of the custom function, so that parameter attributes
620   // at call sites can be updated.
621   std::vector<unsigned> ArgumentIndexMapping;
622   for (unsigned i = 0, ie = T->getNumParams(); i != ie; ++i) {
623     Type* param_type = T->getParamType(i);
624     FunctionType *FT;
625     if (isa<PointerType>(param_type) && (FT = dyn_cast<FunctionType>(
626             cast<PointerType>(param_type)->getElementType()))) {
627       ArgumentIndexMapping.push_back(ArgTypes.size());
628       ArgTypes.push_back(getTrampolineFunctionType(FT)->getPointerTo());
629       ArgTypes.push_back(Type::getInt8PtrTy(*Ctx));
630     } else {
631       ArgumentIndexMapping.push_back(ArgTypes.size());
632       ArgTypes.push_back(param_type);
633     }
634   }
635   for (unsigned i = 0, e = T->getNumParams(); i != e; ++i)
636     ArgTypes.push_back(PrimitiveShadowTy);
637   if (T->isVarArg())
638     ArgTypes.push_back(PrimitiveShadowPtrTy);
639   Type *RetType = T->getReturnType();
640   if (!RetType->isVoidTy())
641     ArgTypes.push_back(PrimitiveShadowPtrTy);
642   return TransformedFunction(
643       T, FunctionType::get(T->getReturnType(), ArgTypes, T->isVarArg()),
644       ArgumentIndexMapping);
645 }
646 
647 bool DataFlowSanitizer::isZeroShadow(Value *V) {
648   if (!shouldTrackFieldsAndIndices())
649     return ZeroPrimitiveShadow == V;
650 
651   Type *T = V->getType();
652   if (!isa<ArrayType>(T) && !isa<StructType>(T)) {
653     if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
654       return CI->isZero();
655     return false;
656   }
657 
658   return isa<ConstantAggregateZero>(V);
659 }
660 
661 bool DataFlowSanitizer::shouldTrackFieldsAndIndices() {
662   return getInstrumentedABI() == DataFlowSanitizer::IA_TLS && ClFast16Labels;
663 }
664 
665 Constant *DataFlowSanitizer::getZeroShadow(Type *OrigTy) {
666   if (!shouldTrackFieldsAndIndices())
667     return ZeroPrimitiveShadow;
668 
669   if (!isa<ArrayType>(OrigTy) && !isa<StructType>(OrigTy))
670     return ZeroPrimitiveShadow;
671   Type *ShadowTy = getShadowTy(OrigTy);
672   return ConstantAggregateZero::get(ShadowTy);
673 }
674 
675 Constant *DataFlowSanitizer::getZeroShadow(Value *V) {
676   return getZeroShadow(V->getType());
677 }
678 
679 static Value *expandFromPrimitiveShadowRecursive(
680     Value *Shadow, SmallVector<unsigned, 4> &Indices, Type *SubShadowTy,
681     Value *PrimitiveShadow, IRBuilder<> &IRB) {
682   if (!isa<ArrayType>(SubShadowTy) && !isa<StructType>(SubShadowTy))
683     return IRB.CreateInsertValue(Shadow, PrimitiveShadow, Indices);
684 
685   if (ArrayType *AT = dyn_cast<ArrayType>(SubShadowTy)) {
686     for (unsigned Idx = 0; Idx < AT->getNumElements(); Idx++) {
687       Indices.push_back(Idx);
688       Shadow = expandFromPrimitiveShadowRecursive(
689           Shadow, Indices, AT->getElementType(), PrimitiveShadow, IRB);
690       Indices.pop_back();
691     }
692     return Shadow;
693   }
694 
695   if (StructType *ST = dyn_cast<StructType>(SubShadowTy)) {
696     for (unsigned Idx = 0; Idx < ST->getNumElements(); Idx++) {
697       Indices.push_back(Idx);
698       Shadow = expandFromPrimitiveShadowRecursive(
699           Shadow, Indices, ST->getElementType(Idx), PrimitiveShadow, IRB);
700       Indices.pop_back();
701     }
702     return Shadow;
703   }
704   llvm_unreachable("Unexpected shadow type");
705 }
706 
707 Value *DFSanFunction::expandFromPrimitiveShadow(Type *T, Value *PrimitiveShadow,
708                                                 Instruction *Pos) {
709   Type *ShadowTy = DFS.getShadowTy(T);
710 
711   if (!isa<ArrayType>(ShadowTy) && !isa<StructType>(ShadowTy))
712     return PrimitiveShadow;
713 
714   if (DFS.isZeroShadow(PrimitiveShadow))
715     return DFS.getZeroShadow(ShadowTy);
716 
717   IRBuilder<> IRB(Pos);
718   SmallVector<unsigned, 4> Indices;
719   Value *Shadow = UndefValue::get(ShadowTy);
720   Shadow = expandFromPrimitiveShadowRecursive(Shadow, Indices, ShadowTy,
721                                               PrimitiveShadow, IRB);
722 
723   // Caches the primitive shadow value that built the shadow value.
724   CachedCollapsedShadows[Shadow] = PrimitiveShadow;
725   return Shadow;
726 }
727 
728 template <class AggregateType>
729 Value *DFSanFunction::collapseAggregateShadow(AggregateType *AT, Value *Shadow,
730                                               IRBuilder<> &IRB) {
731   if (!AT->getNumElements())
732     return DFS.ZeroPrimitiveShadow;
733 
734   Value *FirstItem = IRB.CreateExtractValue(Shadow, 0);
735   Value *Aggregator = collapseToPrimitiveShadow(FirstItem, IRB);
736 
737   for (unsigned Idx = 1; Idx < AT->getNumElements(); Idx++) {
738     Value *ShadowItem = IRB.CreateExtractValue(Shadow, Idx);
739     Value *ShadowInner = collapseToPrimitiveShadow(ShadowItem, IRB);
740     Aggregator = IRB.CreateOr(Aggregator, ShadowInner);
741   }
742   return Aggregator;
743 }
744 
745 Value *DFSanFunction::collapseToPrimitiveShadow(Value *Shadow,
746                                                 IRBuilder<> &IRB) {
747   Type *ShadowTy = Shadow->getType();
748   if (!isa<ArrayType>(ShadowTy) && !isa<StructType>(ShadowTy))
749     return Shadow;
750   if (ArrayType *AT = dyn_cast<ArrayType>(ShadowTy))
751     return collapseAggregateShadow<>(AT, Shadow, IRB);
752   if (StructType *ST = dyn_cast<StructType>(ShadowTy))
753     return collapseAggregateShadow<>(ST, Shadow, IRB);
754   llvm_unreachable("Unexpected shadow type");
755 }
756 
757 Value *DFSanFunction::collapseToPrimitiveShadow(Value *Shadow,
758                                                 Instruction *Pos) {
759   Type *ShadowTy = Shadow->getType();
760   if (!isa<ArrayType>(ShadowTy) && !isa<StructType>(ShadowTy))
761     return Shadow;
762 
763   assert(DFS.shouldTrackFieldsAndIndices());
764 
765   // Checks if the cached collapsed shadow value dominates Pos.
766   Value *&CS = CachedCollapsedShadows[Shadow];
767   if (CS && DT.dominates(CS, Pos))
768     return CS;
769 
770   IRBuilder<> IRB(Pos);
771   Value *PrimitiveShadow = collapseToPrimitiveShadow(Shadow, IRB);
772   // Caches the converted primitive shadow value.
773   CS = PrimitiveShadow;
774   return PrimitiveShadow;
775 }
776 
777 Type *DataFlowSanitizer::getShadowTy(Type *OrigTy) {
778   if (!shouldTrackFieldsAndIndices())
779     return PrimitiveShadowTy;
780 
781   if (!OrigTy->isSized())
782     return PrimitiveShadowTy;
783   if (isa<IntegerType>(OrigTy))
784     return PrimitiveShadowTy;
785   if (isa<VectorType>(OrigTy))
786     return PrimitiveShadowTy;
787   if (ArrayType *AT = dyn_cast<ArrayType>(OrigTy))
788     return ArrayType::get(getShadowTy(AT->getElementType()),
789                           AT->getNumElements());
790   if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
791     SmallVector<Type *, 4> Elements;
792     for (unsigned I = 0, N = ST->getNumElements(); I < N; ++I)
793       Elements.push_back(getShadowTy(ST->getElementType(I)));
794     return StructType::get(*Ctx, Elements);
795   }
796   return PrimitiveShadowTy;
797 }
798 
799 Type *DataFlowSanitizer::getShadowTy(Value *V) {
800   return getShadowTy(V->getType());
801 }
802 
803 bool DataFlowSanitizer::init(Module &M) {
804   Triple TargetTriple(M.getTargetTriple());
805   bool IsX86_64 = TargetTriple.getArch() == Triple::x86_64;
806   bool IsMIPS64 = TargetTriple.isMIPS64();
807   bool IsAArch64 = TargetTriple.getArch() == Triple::aarch64 ||
808                    TargetTriple.getArch() == Triple::aarch64_be;
809 
810   const DataLayout &DL = M.getDataLayout();
811 
812   Mod = &M;
813   Ctx = &M.getContext();
814   Int8Ptr = Type::getInt8PtrTy(*Ctx);
815   PrimitiveShadowTy = IntegerType::get(*Ctx, ShadowWidthBits);
816   PrimitiveShadowPtrTy = PointerType::getUnqual(PrimitiveShadowTy);
817   IntptrTy = DL.getIntPtrType(*Ctx);
818   ZeroPrimitiveShadow = ConstantInt::getSigned(PrimitiveShadowTy, 0);
819   ShadowPtrMul = ConstantInt::getSigned(IntptrTy, ShadowWidthBytes);
820   if (IsX86_64)
821     ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0x700000000000LL);
822   else if (IsMIPS64)
823     ShadowPtrMask = ConstantInt::getSigned(IntptrTy, ~0xF000000000LL);
824   // AArch64 supports multiple VMAs and the shadow mask is set at runtime.
825   else if (IsAArch64)
826     DFSanRuntimeShadowMask = true;
827   else
828     report_fatal_error("unsupported triple");
829 
830   Type *DFSanUnionArgs[2] = {PrimitiveShadowTy, PrimitiveShadowTy};
831   DFSanUnionFnTy =
832       FunctionType::get(PrimitiveShadowTy, DFSanUnionArgs, /*isVarArg=*/false);
833   Type *DFSanUnionLoadArgs[2] = {PrimitiveShadowPtrTy, IntptrTy};
834   DFSanUnionLoadFnTy = FunctionType::get(PrimitiveShadowTy, DFSanUnionLoadArgs,
835                                          /*isVarArg=*/false);
836   DFSanUnimplementedFnTy = FunctionType::get(
837       Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
838   Type *DFSanSetLabelArgs[3] = {PrimitiveShadowTy, Type::getInt8PtrTy(*Ctx),
839                                 IntptrTy};
840   DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
841                                         DFSanSetLabelArgs, /*isVarArg=*/false);
842   DFSanNonzeroLabelFnTy =
843       FunctionType::get(Type::getVoidTy(*Ctx), None, /*isVarArg=*/false);
844   DFSanVarargWrapperFnTy = FunctionType::get(
845       Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
846   DFSanCmpCallbackFnTy =
847       FunctionType::get(Type::getVoidTy(*Ctx), PrimitiveShadowTy,
848                         /*isVarArg=*/false);
849   Type *DFSanLoadStoreCallbackArgs[2] = {PrimitiveShadowTy, Int8Ptr};
850   DFSanLoadStoreCallbackFnTy =
851       FunctionType::get(Type::getVoidTy(*Ctx), DFSanLoadStoreCallbackArgs,
852                         /*isVarArg=*/false);
853   Type *DFSanMemTransferCallbackArgs[2] = {PrimitiveShadowPtrTy, IntptrTy};
854   DFSanMemTransferCallbackFnTy =
855       FunctionType::get(Type::getVoidTy(*Ctx), DFSanMemTransferCallbackArgs,
856                         /*isVarArg=*/false);
857 
858   ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
859   return true;
860 }
861 
862 bool DataFlowSanitizer::isInstrumented(const Function *F) {
863   return !ABIList.isIn(*F, "uninstrumented");
864 }
865 
866 bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
867   return !ABIList.isIn(*GA, "uninstrumented");
868 }
869 
870 DataFlowSanitizer::InstrumentedABI DataFlowSanitizer::getInstrumentedABI() {
871   return ClArgsABI ? IA_Args : IA_TLS;
872 }
873 
874 DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
875   if (ABIList.isIn(*F, "functional"))
876     return WK_Functional;
877   if (ABIList.isIn(*F, "discard"))
878     return WK_Discard;
879   if (ABIList.isIn(*F, "custom"))
880     return WK_Custom;
881 
882   return WK_Warning;
883 }
884 
885 void DataFlowSanitizer::addGlobalNamePrefix(GlobalValue *GV) {
886   std::string GVName = std::string(GV->getName()), Prefix = "dfs$";
887   GV->setName(Prefix + GVName);
888 
889   // Try to change the name of the function in module inline asm.  We only do
890   // this for specific asm directives, currently only ".symver", to try to avoid
891   // corrupting asm which happens to contain the symbol name as a substring.
892   // Note that the substitution for .symver assumes that the versioned symbol
893   // also has an instrumented name.
894   std::string Asm = GV->getParent()->getModuleInlineAsm();
895   std::string SearchStr = ".symver " + GVName + ",";
896   size_t Pos = Asm.find(SearchStr);
897   if (Pos != std::string::npos) {
898     Asm.replace(Pos, SearchStr.size(),
899                 ".symver " + Prefix + GVName + "," + Prefix);
900     GV->getParent()->setModuleInlineAsm(Asm);
901   }
902 }
903 
904 Function *
905 DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
906                                         GlobalValue::LinkageTypes NewFLink,
907                                         FunctionType *NewFT) {
908   FunctionType *FT = F->getFunctionType();
909   Function *NewF = Function::Create(NewFT, NewFLink, F->getAddressSpace(),
910                                     NewFName, F->getParent());
911   NewF->copyAttributesFrom(F);
912   NewF->removeAttributes(
913       AttributeList::ReturnIndex,
914       AttributeFuncs::typeIncompatible(NewFT->getReturnType()));
915 
916   BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
917   if (F->isVarArg()) {
918     NewF->removeAttributes(AttributeList::FunctionIndex,
919                            AttrBuilder().addAttribute("split-stack"));
920     CallInst::Create(DFSanVarargWrapperFn,
921                      IRBuilder<>(BB).CreateGlobalStringPtr(F->getName()), "",
922                      BB);
923     new UnreachableInst(*Ctx, BB);
924   } else {
925     std::vector<Value *> Args;
926     unsigned n = FT->getNumParams();
927     for (Function::arg_iterator ai = NewF->arg_begin(); n != 0; ++ai, --n)
928       Args.push_back(&*ai);
929     CallInst *CI = CallInst::Create(F, Args, "", BB);
930     if (FT->getReturnType()->isVoidTy())
931       ReturnInst::Create(*Ctx, BB);
932     else
933       ReturnInst::Create(*Ctx, CI, BB);
934   }
935 
936   return NewF;
937 }
938 
939 Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
940                                                           StringRef FName) {
941   FunctionType *FTT = getTrampolineFunctionType(FT);
942   FunctionCallee C = Mod->getOrInsertFunction(FName, FTT);
943   Function *F = dyn_cast<Function>(C.getCallee());
944   if (F && F->isDeclaration()) {
945     F->setLinkage(GlobalValue::LinkOnceODRLinkage);
946     BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
947     std::vector<Value *> Args;
948     Function::arg_iterator AI = F->arg_begin(); ++AI;
949     for (unsigned N = FT->getNumParams(); N != 0; ++AI, --N)
950       Args.push_back(&*AI);
951     CallInst *CI = CallInst::Create(FT, &*F->arg_begin(), Args, "", BB);
952     ReturnInst *RI;
953     if (FT->getReturnType()->isVoidTy())
954       RI = ReturnInst::Create(*Ctx, BB);
955     else
956       RI = ReturnInst::Create(*Ctx, CI, BB);
957 
958     // F is called by a wrapped custom function with primitive shadows. So
959     // its arguments and return value need conversion.
960     DFSanFunction DFSF(*this, F, /*IsNativeABI=*/true);
961     Function::arg_iterator ValAI = F->arg_begin(), ShadowAI = AI; ++ValAI;
962     for (unsigned N = FT->getNumParams(); N != 0; ++ValAI, ++ShadowAI, --N) {
963       Value *Shadow =
964           DFSF.expandFromPrimitiveShadow(ValAI->getType(), &*ShadowAI, CI);
965       DFSF.ValShadowMap[&*ValAI] = Shadow;
966     }
967     DFSanVisitor(DFSF).visitCallInst(*CI);
968     if (!FT->getReturnType()->isVoidTy()) {
969       Value *PrimitiveShadow = DFSF.collapseToPrimitiveShadow(
970           DFSF.getShadow(RI->getReturnValue()), RI);
971       new StoreInst(PrimitiveShadow, &*std::prev(F->arg_end()), RI);
972     }
973   }
974 
975   return cast<Constant>(C.getCallee());
976 }
977 
978 // Initialize DataFlowSanitizer runtime functions and declare them in the module
979 void DataFlowSanitizer::initializeRuntimeFunctions(Module &M) {
980   {
981     AttributeList AL;
982     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
983                          Attribute::NoUnwind);
984     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
985                          Attribute::ReadNone);
986     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
987                          Attribute::ZExt);
988     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
989     AL = AL.addParamAttribute(M.getContext(), 1, Attribute::ZExt);
990     DFSanUnionFn =
991         Mod->getOrInsertFunction("__dfsan_union", DFSanUnionFnTy, AL);
992   }
993   {
994     AttributeList AL;
995     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
996                          Attribute::NoUnwind);
997     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
998                          Attribute::ReadNone);
999     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1000                          Attribute::ZExt);
1001     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1002     AL = AL.addParamAttribute(M.getContext(), 1, Attribute::ZExt);
1003     DFSanCheckedUnionFn =
1004         Mod->getOrInsertFunction("dfsan_union", DFSanUnionFnTy, AL);
1005   }
1006   {
1007     AttributeList AL;
1008     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1009                          Attribute::NoUnwind);
1010     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1011                          Attribute::ReadOnly);
1012     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1013                          Attribute::ZExt);
1014     DFSanUnionLoadFn =
1015         Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy, AL);
1016   }
1017   {
1018     AttributeList AL;
1019     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1020                          Attribute::NoUnwind);
1021     AL = AL.addAttribute(M.getContext(), AttributeList::FunctionIndex,
1022                          Attribute::ReadOnly);
1023     AL = AL.addAttribute(M.getContext(), AttributeList::ReturnIndex,
1024                          Attribute::ZExt);
1025     DFSanUnionLoadFast16LabelsFn = Mod->getOrInsertFunction(
1026         "__dfsan_union_load_fast16labels", DFSanUnionLoadFnTy, AL);
1027   }
1028   DFSanUnimplementedFn =
1029       Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
1030   {
1031     AttributeList AL;
1032     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1033     DFSanSetLabelFn =
1034         Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy, AL);
1035   }
1036   DFSanNonzeroLabelFn =
1037       Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
1038   DFSanVarargWrapperFn = Mod->getOrInsertFunction("__dfsan_vararg_wrapper",
1039                                                   DFSanVarargWrapperFnTy);
1040 }
1041 
1042 // Initializes event callback functions and declare them in the module
1043 void DataFlowSanitizer::initializeCallbackFunctions(Module &M) {
1044   DFSanLoadCallbackFn = Mod->getOrInsertFunction("__dfsan_load_callback",
1045                                                  DFSanLoadStoreCallbackFnTy);
1046   DFSanStoreCallbackFn = Mod->getOrInsertFunction("__dfsan_store_callback",
1047                                                   DFSanLoadStoreCallbackFnTy);
1048   DFSanMemTransferCallbackFn = Mod->getOrInsertFunction(
1049       "__dfsan_mem_transfer_callback", DFSanMemTransferCallbackFnTy);
1050   DFSanCmpCallbackFn =
1051       Mod->getOrInsertFunction("__dfsan_cmp_callback", DFSanCmpCallbackFnTy);
1052 }
1053 
1054 bool DataFlowSanitizer::runImpl(Module &M) {
1055   init(M);
1056 
1057   if (ABIList.isIn(M, "skip"))
1058     return false;
1059 
1060   const unsigned InitialGlobalSize = M.global_size();
1061   const unsigned InitialModuleSize = M.size();
1062 
1063   bool Changed = false;
1064 
1065   Type *ArgTLSTy = ArrayType::get(Type::getInt64Ty(*Ctx), kArgTLSSize / 8);
1066   ArgTLS = Mod->getOrInsertGlobal("__dfsan_arg_tls", ArgTLSTy);
1067   if (GlobalVariable *G = dyn_cast<GlobalVariable>(ArgTLS)) {
1068     Changed |= G->getThreadLocalMode() != GlobalVariable::InitialExecTLSModel;
1069     G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
1070   }
1071   Type *RetvalTLSTy =
1072       ArrayType::get(Type::getInt64Ty(*Ctx), kRetvalTLSSize / 8);
1073   RetvalTLS = Mod->getOrInsertGlobal("__dfsan_retval_tls", RetvalTLSTy);
1074   if (GlobalVariable *G = dyn_cast<GlobalVariable>(RetvalTLS)) {
1075     Changed |= G->getThreadLocalMode() != GlobalVariable::InitialExecTLSModel;
1076     G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
1077   }
1078 
1079   ExternalShadowMask =
1080       Mod->getOrInsertGlobal(kDFSanExternShadowPtrMask, IntptrTy);
1081 
1082   initializeCallbackFunctions(M);
1083   initializeRuntimeFunctions(M);
1084 
1085   std::vector<Function *> FnsToInstrument;
1086   SmallPtrSet<Function *, 2> FnsWithNativeABI;
1087   for (Function &i : M) {
1088     if (!i.isIntrinsic() &&
1089         &i != DFSanUnionFn.getCallee()->stripPointerCasts() &&
1090         &i != DFSanCheckedUnionFn.getCallee()->stripPointerCasts() &&
1091         &i != DFSanUnionLoadFn.getCallee()->stripPointerCasts() &&
1092         &i != DFSanUnionLoadFast16LabelsFn.getCallee()->stripPointerCasts() &&
1093         &i != DFSanUnimplementedFn.getCallee()->stripPointerCasts() &&
1094         &i != DFSanSetLabelFn.getCallee()->stripPointerCasts() &&
1095         &i != DFSanNonzeroLabelFn.getCallee()->stripPointerCasts() &&
1096         &i != DFSanVarargWrapperFn.getCallee()->stripPointerCasts() &&
1097         &i != DFSanLoadCallbackFn.getCallee()->stripPointerCasts() &&
1098         &i != DFSanStoreCallbackFn.getCallee()->stripPointerCasts() &&
1099         &i != DFSanMemTransferCallbackFn.getCallee()->stripPointerCasts() &&
1100         &i != DFSanCmpCallbackFn.getCallee()->stripPointerCasts())
1101       FnsToInstrument.push_back(&i);
1102   }
1103 
1104   // Give function aliases prefixes when necessary, and build wrappers where the
1105   // instrumentedness is inconsistent.
1106   for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e;) {
1107     GlobalAlias *GA = &*i;
1108     ++i;
1109     // Don't stop on weak.  We assume people aren't playing games with the
1110     // instrumentedness of overridden weak aliases.
1111     if (auto F = dyn_cast<Function>(GA->getBaseObject())) {
1112       bool GAInst = isInstrumented(GA), FInst = isInstrumented(F);
1113       if (GAInst && FInst) {
1114         addGlobalNamePrefix(GA);
1115       } else if (GAInst != FInst) {
1116         // Non-instrumented alias of an instrumented function, or vice versa.
1117         // Replace the alias with a native-ABI wrapper of the aliasee.  The pass
1118         // below will take care of instrumenting it.
1119         Function *NewF =
1120             buildWrapperFunction(F, "", GA->getLinkage(), F->getFunctionType());
1121         GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA->getType()));
1122         NewF->takeName(GA);
1123         GA->eraseFromParent();
1124         FnsToInstrument.push_back(NewF);
1125       }
1126     }
1127   }
1128 
1129   ReadOnlyNoneAttrs.addAttribute(Attribute::ReadOnly)
1130       .addAttribute(Attribute::ReadNone);
1131 
1132   // First, change the ABI of every function in the module.  ABI-listed
1133   // functions keep their original ABI and get a wrapper function.
1134   for (std::vector<Function *>::iterator i = FnsToInstrument.begin(),
1135                                          e = FnsToInstrument.end();
1136        i != e; ++i) {
1137     Function &F = **i;
1138     FunctionType *FT = F.getFunctionType();
1139 
1140     bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
1141                               FT->getReturnType()->isVoidTy());
1142 
1143     if (isInstrumented(&F)) {
1144       // Instrumented functions get a 'dfs$' prefix.  This allows us to more
1145       // easily identify cases of mismatching ABIs.
1146       if (getInstrumentedABI() == IA_Args && !IsZeroArgsVoidRet) {
1147         FunctionType *NewFT = getArgsFunctionType(FT);
1148         Function *NewF = Function::Create(NewFT, F.getLinkage(),
1149                                           F.getAddressSpace(), "", &M);
1150         NewF->copyAttributesFrom(&F);
1151         NewF->removeAttributes(
1152             AttributeList::ReturnIndex,
1153             AttributeFuncs::typeIncompatible(NewFT->getReturnType()));
1154         for (Function::arg_iterator FArg = F.arg_begin(),
1155                                     NewFArg = NewF->arg_begin(),
1156                                     FArgEnd = F.arg_end();
1157              FArg != FArgEnd; ++FArg, ++NewFArg) {
1158           FArg->replaceAllUsesWith(&*NewFArg);
1159         }
1160         NewF->getBasicBlockList().splice(NewF->begin(), F.getBasicBlockList());
1161 
1162         for (Function::user_iterator UI = F.user_begin(), UE = F.user_end();
1163              UI != UE;) {
1164           BlockAddress *BA = dyn_cast<BlockAddress>(*UI);
1165           ++UI;
1166           if (BA) {
1167             BA->replaceAllUsesWith(
1168                 BlockAddress::get(NewF, BA->getBasicBlock()));
1169             delete BA;
1170           }
1171         }
1172         F.replaceAllUsesWith(
1173             ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT)));
1174         NewF->takeName(&F);
1175         F.eraseFromParent();
1176         *i = NewF;
1177         addGlobalNamePrefix(NewF);
1178       } else {
1179         addGlobalNamePrefix(&F);
1180       }
1181     } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
1182       // Build a wrapper function for F.  The wrapper simply calls F, and is
1183       // added to FnsToInstrument so that any instrumentation according to its
1184       // WrapperKind is done in the second pass below.
1185       FunctionType *NewFT = getInstrumentedABI() == IA_Args
1186                                 ? getArgsFunctionType(FT)
1187                                 : FT;
1188 
1189       // If the function being wrapped has local linkage, then preserve the
1190       // function's linkage in the wrapper function.
1191       GlobalValue::LinkageTypes wrapperLinkage =
1192           F.hasLocalLinkage()
1193               ? F.getLinkage()
1194               : GlobalValue::LinkOnceODRLinkage;
1195 
1196       Function *NewF = buildWrapperFunction(
1197           &F, std::string("dfsw$") + std::string(F.getName()),
1198           wrapperLinkage, NewFT);
1199       if (getInstrumentedABI() == IA_TLS)
1200         NewF->removeAttributes(AttributeList::FunctionIndex, ReadOnlyNoneAttrs);
1201 
1202       Value *WrappedFnCst =
1203           ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
1204       F.replaceAllUsesWith(WrappedFnCst);
1205 
1206       UnwrappedFnMap[WrappedFnCst] = &F;
1207       *i = NewF;
1208 
1209       if (!F.isDeclaration()) {
1210         // This function is probably defining an interposition of an
1211         // uninstrumented function and hence needs to keep the original ABI.
1212         // But any functions it may call need to use the instrumented ABI, so
1213         // we instrument it in a mode which preserves the original ABI.
1214         FnsWithNativeABI.insert(&F);
1215 
1216         // This code needs to rebuild the iterators, as they may be invalidated
1217         // by the push_back, taking care that the new range does not include
1218         // any functions added by this code.
1219         size_t N = i - FnsToInstrument.begin(),
1220                Count = e - FnsToInstrument.begin();
1221         FnsToInstrument.push_back(&F);
1222         i = FnsToInstrument.begin() + N;
1223         e = FnsToInstrument.begin() + Count;
1224       }
1225                // Hopefully, nobody will try to indirectly call a vararg
1226                // function... yet.
1227     } else if (FT->isVarArg()) {
1228       UnwrappedFnMap[&F] = &F;
1229       *i = nullptr;
1230     }
1231   }
1232 
1233   for (Function *i : FnsToInstrument) {
1234     if (!i || i->isDeclaration())
1235       continue;
1236 
1237     removeUnreachableBlocks(*i);
1238 
1239     DFSanFunction DFSF(*this, i, FnsWithNativeABI.count(i));
1240 
1241     // DFSanVisitor may create new basic blocks, which confuses df_iterator.
1242     // Build a copy of the list before iterating over it.
1243     SmallVector<BasicBlock *, 4> BBList(depth_first(&i->getEntryBlock()));
1244 
1245     for (BasicBlock *i : BBList) {
1246       Instruction *Inst = &i->front();
1247       while (true) {
1248         // DFSanVisitor may split the current basic block, changing the current
1249         // instruction's next pointer and moving the next instruction to the
1250         // tail block from which we should continue.
1251         Instruction *Next = Inst->getNextNode();
1252         // DFSanVisitor may delete Inst, so keep track of whether it was a
1253         // terminator.
1254         bool IsTerminator = Inst->isTerminator();
1255         if (!DFSF.SkipInsts.count(Inst))
1256           DFSanVisitor(DFSF).visit(Inst);
1257         if (IsTerminator)
1258           break;
1259         Inst = Next;
1260       }
1261     }
1262 
1263     // We will not necessarily be able to compute the shadow for every phi node
1264     // until we have visited every block.  Therefore, the code that handles phi
1265     // nodes adds them to the PHIFixups list so that they can be properly
1266     // handled here.
1267     for (std::vector<std::pair<PHINode *, PHINode *>>::iterator
1268              i = DFSF.PHIFixups.begin(),
1269              e = DFSF.PHIFixups.end();
1270          i != e; ++i) {
1271       for (unsigned val = 0, n = i->first->getNumIncomingValues(); val != n;
1272            ++val) {
1273         i->second->setIncomingValue(
1274             val, DFSF.getShadow(i->first->getIncomingValue(val)));
1275       }
1276     }
1277 
1278     // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
1279     // places (i.e. instructions in basic blocks we haven't even begun visiting
1280     // yet).  To make our life easier, do this work in a pass after the main
1281     // instrumentation.
1282     if (ClDebugNonzeroLabels) {
1283       for (Value *V : DFSF.NonZeroChecks) {
1284         Instruction *Pos;
1285         if (Instruction *I = dyn_cast<Instruction>(V))
1286           Pos = I->getNextNode();
1287         else
1288           Pos = &DFSF.F->getEntryBlock().front();
1289         while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
1290           Pos = Pos->getNextNode();
1291         IRBuilder<> IRB(Pos);
1292         Value *PrimitiveShadow = DFSF.collapseToPrimitiveShadow(V, Pos);
1293         Value *Ne =
1294             IRB.CreateICmpNE(PrimitiveShadow, DFSF.DFS.ZeroPrimitiveShadow);
1295         BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
1296             Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
1297         IRBuilder<> ThenIRB(BI);
1298         ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn, {});
1299       }
1300     }
1301   }
1302 
1303   return Changed || !FnsToInstrument.empty() ||
1304          M.global_size() != InitialGlobalSize || M.size() != InitialModuleSize;
1305 }
1306 
1307 Value *DFSanFunction::getArgTLS(Type *T, unsigned ArgOffset, IRBuilder<> &IRB) {
1308   Value *Base = IRB.CreatePointerCast(DFS.ArgTLS, DFS.IntptrTy);
1309   if (ArgOffset)
1310     Base = IRB.CreateAdd(Base, ConstantInt::get(DFS.IntptrTy, ArgOffset));
1311   return IRB.CreateIntToPtr(Base, PointerType::get(DFS.getShadowTy(T), 0),
1312                             "_dfsarg");
1313 }
1314 
1315 Value *DFSanFunction::getRetvalTLS(Type *T, IRBuilder<> &IRB) {
1316   return IRB.CreatePointerCast(
1317       DFS.RetvalTLS, PointerType::get(DFS.getShadowTy(T), 0), "_dfsret");
1318 }
1319 
1320 Value *DFSanFunction::getShadowForTLSArgument(Argument *A) {
1321   unsigned ArgOffset = 0;
1322   const DataLayout &DL = F->getParent()->getDataLayout();
1323   for (auto &FArg : F->args()) {
1324     if (!FArg.getType()->isSized()) {
1325       if (A == &FArg)
1326         break;
1327       continue;
1328     }
1329 
1330     unsigned Size = DL.getTypeAllocSize(DFS.getShadowTy(&FArg));
1331     if (A != &FArg) {
1332       ArgOffset += alignTo(Size, kShadowTLSAlignment);
1333       if (ArgOffset > kArgTLSSize)
1334         break; // ArgTLS overflows, uses a zero shadow.
1335       continue;
1336     }
1337 
1338     if (ArgOffset + Size > kArgTLSSize)
1339       break; // ArgTLS overflows, uses a zero shadow.
1340 
1341     Instruction *ArgTLSPos = &*F->getEntryBlock().begin();
1342     IRBuilder<> IRB(ArgTLSPos);
1343     Value *ArgShadowPtr = getArgTLS(FArg.getType(), ArgOffset, IRB);
1344     return IRB.CreateAlignedLoad(DFS.getShadowTy(&FArg), ArgShadowPtr,
1345                                  kShadowTLSAlignment);
1346   }
1347 
1348   return DFS.getZeroShadow(A);
1349 }
1350 
1351 Value *DFSanFunction::getShadow(Value *V) {
1352   if (!isa<Argument>(V) && !isa<Instruction>(V))
1353     return DFS.getZeroShadow(V);
1354   Value *&Shadow = ValShadowMap[V];
1355   if (!Shadow) {
1356     if (Argument *A = dyn_cast<Argument>(V)) {
1357       if (IsNativeABI)
1358         return DFS.getZeroShadow(V);
1359       switch (IA) {
1360       case DataFlowSanitizer::IA_TLS: {
1361         Shadow = getShadowForTLSArgument(A);
1362         break;
1363       }
1364       case DataFlowSanitizer::IA_Args: {
1365         unsigned ArgIdx = A->getArgNo() + F->arg_size() / 2;
1366         Function::arg_iterator i = F->arg_begin();
1367         while (ArgIdx--)
1368           ++i;
1369         Shadow = &*i;
1370         assert(Shadow->getType() == DFS.PrimitiveShadowTy);
1371         break;
1372       }
1373       }
1374       NonZeroChecks.push_back(Shadow);
1375     } else {
1376       Shadow = DFS.getZeroShadow(V);
1377     }
1378   }
1379   return Shadow;
1380 }
1381 
1382 void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
1383   assert(!ValShadowMap.count(I));
1384   assert(DFS.shouldTrackFieldsAndIndices() ||
1385          Shadow->getType() == DFS.PrimitiveShadowTy);
1386   ValShadowMap[I] = Shadow;
1387 }
1388 
1389 Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
1390   assert(Addr != RetvalTLS && "Reinstrumenting?");
1391   IRBuilder<> IRB(Pos);
1392   Value *ShadowPtrMaskValue;
1393   if (DFSanRuntimeShadowMask)
1394     ShadowPtrMaskValue = IRB.CreateLoad(IntptrTy, ExternalShadowMask);
1395   else
1396     ShadowPtrMaskValue = ShadowPtrMask;
1397   return IRB.CreateIntToPtr(
1398       IRB.CreateMul(
1399           IRB.CreateAnd(IRB.CreatePtrToInt(Addr, IntptrTy),
1400                         IRB.CreatePtrToInt(ShadowPtrMaskValue, IntptrTy)),
1401           ShadowPtrMul),
1402       PrimitiveShadowPtrTy);
1403 }
1404 
1405 Value *DFSanFunction::combineShadowsThenConvert(Type *T, Value *V1, Value *V2,
1406                                                 Instruction *Pos) {
1407   Value *PrimitiveValue = combineShadows(V1, V2, Pos);
1408   return expandFromPrimitiveShadow(T, PrimitiveValue, Pos);
1409 }
1410 
1411 // Generates IR to compute the union of the two given shadows, inserting it
1412 // before Pos. The combined value is with primitive type.
1413 Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) {
1414   if (DFS.isZeroShadow(V1))
1415     return collapseToPrimitiveShadow(V2, Pos);
1416   if (DFS.isZeroShadow(V2))
1417     return collapseToPrimitiveShadow(V1, Pos);
1418   if (V1 == V2)
1419     return collapseToPrimitiveShadow(V1, Pos);
1420 
1421   auto V1Elems = ShadowElements.find(V1);
1422   auto V2Elems = ShadowElements.find(V2);
1423   if (V1Elems != ShadowElements.end() && V2Elems != ShadowElements.end()) {
1424     if (std::includes(V1Elems->second.begin(), V1Elems->second.end(),
1425                       V2Elems->second.begin(), V2Elems->second.end())) {
1426       return collapseToPrimitiveShadow(V1, Pos);
1427     } else if (std::includes(V2Elems->second.begin(), V2Elems->second.end(),
1428                              V1Elems->second.begin(), V1Elems->second.end())) {
1429       return collapseToPrimitiveShadow(V2, Pos);
1430     }
1431   } else if (V1Elems != ShadowElements.end()) {
1432     if (V1Elems->second.count(V2))
1433       return collapseToPrimitiveShadow(V1, Pos);
1434   } else if (V2Elems != ShadowElements.end()) {
1435     if (V2Elems->second.count(V1))
1436       return collapseToPrimitiveShadow(V2, Pos);
1437   }
1438 
1439   auto Key = std::make_pair(V1, V2);
1440   if (V1 > V2)
1441     std::swap(Key.first, Key.second);
1442   CachedShadow &CCS = CachedShadows[Key];
1443   if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent()))
1444     return CCS.Shadow;
1445 
1446   // Converts inputs shadows to shadows with primitive types.
1447   Value *PV1 = collapseToPrimitiveShadow(V1, Pos);
1448   Value *PV2 = collapseToPrimitiveShadow(V2, Pos);
1449 
1450   IRBuilder<> IRB(Pos);
1451   if (ClFast16Labels) {
1452     CCS.Block = Pos->getParent();
1453     CCS.Shadow = IRB.CreateOr(PV1, PV2);
1454   } else if (AvoidNewBlocks) {
1455     CallInst *Call = IRB.CreateCall(DFS.DFSanCheckedUnionFn, {PV1, PV2});
1456     Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
1457     Call->addParamAttr(0, Attribute::ZExt);
1458     Call->addParamAttr(1, Attribute::ZExt);
1459 
1460     CCS.Block = Pos->getParent();
1461     CCS.Shadow = Call;
1462   } else {
1463     BasicBlock *Head = Pos->getParent();
1464     Value *Ne = IRB.CreateICmpNE(PV1, PV2);
1465     BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
1466         Ne, Pos, /*Unreachable=*/false, DFS.ColdCallWeights, &DT));
1467     IRBuilder<> ThenIRB(BI);
1468     CallInst *Call = ThenIRB.CreateCall(DFS.DFSanUnionFn, {PV1, PV2});
1469     Call->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
1470     Call->addParamAttr(0, Attribute::ZExt);
1471     Call->addParamAttr(1, Attribute::ZExt);
1472 
1473     BasicBlock *Tail = BI->getSuccessor(0);
1474     PHINode *Phi =
1475         PHINode::Create(DFS.PrimitiveShadowTy, 2, "", &Tail->front());
1476     Phi->addIncoming(Call, Call->getParent());
1477     Phi->addIncoming(PV1, Head);
1478 
1479     CCS.Block = Tail;
1480     CCS.Shadow = Phi;
1481   }
1482 
1483   std::set<Value *> UnionElems;
1484   if (V1Elems != ShadowElements.end()) {
1485     UnionElems = V1Elems->second;
1486   } else {
1487     UnionElems.insert(V1);
1488   }
1489   if (V2Elems != ShadowElements.end()) {
1490     UnionElems.insert(V2Elems->second.begin(), V2Elems->second.end());
1491   } else {
1492     UnionElems.insert(V2);
1493   }
1494   ShadowElements[CCS.Shadow] = std::move(UnionElems);
1495 
1496   return CCS.Shadow;
1497 }
1498 
1499 // A convenience function which folds the shadows of each of the operands
1500 // of the provided instruction Inst, inserting the IR before Inst.  Returns
1501 // the computed union Value.
1502 Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
1503   if (Inst->getNumOperands() == 0)
1504     return DFS.getZeroShadow(Inst);
1505 
1506   Value *Shadow = getShadow(Inst->getOperand(0));
1507   for (unsigned i = 1, n = Inst->getNumOperands(); i != n; ++i) {
1508     Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(i)), Inst);
1509   }
1510   return expandFromPrimitiveShadow(Inst->getType(), Shadow, Inst);
1511 }
1512 
1513 Value *DFSanVisitor::visitOperandShadowInst(Instruction &I) {
1514   Value *CombinedShadow = DFSF.combineOperandShadows(&I);
1515   DFSF.setShadow(&I, CombinedShadow);
1516   return CombinedShadow;
1517 }
1518 
1519 // Generates IR to load shadow corresponding to bytes [Addr, Addr+Size), where
1520 // Addr has alignment Align, and take the union of each of those shadows. The
1521 // returned shadow always has primitive type.
1522 Value *DFSanFunction::loadShadow(Value *Addr, uint64_t Size, uint64_t Align,
1523                                  Instruction *Pos) {
1524   if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1525     const auto i = AllocaShadowMap.find(AI);
1526     if (i != AllocaShadowMap.end()) {
1527       IRBuilder<> IRB(Pos);
1528       return IRB.CreateLoad(DFS.PrimitiveShadowTy, i->second);
1529     }
1530   }
1531 
1532   const llvm::Align ShadowAlign(Align * DFS.ShadowWidthBytes);
1533   SmallVector<const Value *, 2> Objs;
1534   getUnderlyingObjects(Addr, Objs);
1535   bool AllConstants = true;
1536   for (const Value *Obj : Objs) {
1537     if (isa<Function>(Obj) || isa<BlockAddress>(Obj))
1538       continue;
1539     if (isa<GlobalVariable>(Obj) && cast<GlobalVariable>(Obj)->isConstant())
1540       continue;
1541 
1542     AllConstants = false;
1543     break;
1544   }
1545   if (AllConstants)
1546     return DFS.ZeroPrimitiveShadow;
1547 
1548   Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1549   switch (Size) {
1550   case 0:
1551     return DFS.ZeroPrimitiveShadow;
1552   case 1: {
1553     LoadInst *LI = new LoadInst(DFS.PrimitiveShadowTy, ShadowAddr, "", Pos);
1554     LI->setAlignment(ShadowAlign);
1555     return LI;
1556   }
1557   case 2: {
1558     IRBuilder<> IRB(Pos);
1559     Value *ShadowAddr1 = IRB.CreateGEP(DFS.PrimitiveShadowTy, ShadowAddr,
1560                                        ConstantInt::get(DFS.IntptrTy, 1));
1561     return combineShadows(
1562         IRB.CreateAlignedLoad(DFS.PrimitiveShadowTy, ShadowAddr, ShadowAlign),
1563         IRB.CreateAlignedLoad(DFS.PrimitiveShadowTy, ShadowAddr1, ShadowAlign),
1564         Pos);
1565   }
1566   }
1567 
1568   if (ClFast16Labels && Size % (64 / DFS.ShadowWidthBits) == 0) {
1569     // First OR all the WideShadows, then OR individual shadows within the
1570     // combined WideShadow.  This is fewer instructions than ORing shadows
1571     // individually.
1572     IRBuilder<> IRB(Pos);
1573     Value *WideAddr =
1574         IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
1575     Value *CombinedWideShadow =
1576         IRB.CreateAlignedLoad(IRB.getInt64Ty(), WideAddr, ShadowAlign);
1577     for (uint64_t Ofs = 64 / DFS.ShadowWidthBits; Ofs != Size;
1578          Ofs += 64 / DFS.ShadowWidthBits) {
1579       WideAddr = IRB.CreateGEP(Type::getInt64Ty(*DFS.Ctx), WideAddr,
1580                                ConstantInt::get(DFS.IntptrTy, 1));
1581       Value *NextWideShadow =
1582           IRB.CreateAlignedLoad(IRB.getInt64Ty(), WideAddr, ShadowAlign);
1583       CombinedWideShadow = IRB.CreateOr(CombinedWideShadow, NextWideShadow);
1584     }
1585     for (unsigned Width = 32; Width >= DFS.ShadowWidthBits; Width >>= 1) {
1586       Value *ShrShadow = IRB.CreateLShr(CombinedWideShadow, Width);
1587       CombinedWideShadow = IRB.CreateOr(CombinedWideShadow, ShrShadow);
1588     }
1589     return IRB.CreateTrunc(CombinedWideShadow, DFS.PrimitiveShadowTy);
1590   }
1591   if (!AvoidNewBlocks && Size % (64 / DFS.ShadowWidthBits) == 0) {
1592     // Fast path for the common case where each byte has identical shadow: load
1593     // shadow 64 bits at a time, fall out to a __dfsan_union_load call if any
1594     // shadow is non-equal.
1595     BasicBlock *FallbackBB = BasicBlock::Create(*DFS.Ctx, "", F);
1596     IRBuilder<> FallbackIRB(FallbackBB);
1597     CallInst *FallbackCall = FallbackIRB.CreateCall(
1598         DFS.DFSanUnionLoadFn,
1599         {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
1600     FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
1601 
1602     // Compare each of the shadows stored in the loaded 64 bits to each other,
1603     // by computing (WideShadow rotl ShadowWidthBits) == WideShadow.
1604     IRBuilder<> IRB(Pos);
1605     Value *WideAddr =
1606         IRB.CreateBitCast(ShadowAddr, Type::getInt64PtrTy(*DFS.Ctx));
1607     Value *WideShadow =
1608         IRB.CreateAlignedLoad(IRB.getInt64Ty(), WideAddr, ShadowAlign);
1609     Value *TruncShadow = IRB.CreateTrunc(WideShadow, DFS.PrimitiveShadowTy);
1610     Value *ShlShadow = IRB.CreateShl(WideShadow, DFS.ShadowWidthBits);
1611     Value *ShrShadow = IRB.CreateLShr(WideShadow, 64 - DFS.ShadowWidthBits);
1612     Value *RotShadow = IRB.CreateOr(ShlShadow, ShrShadow);
1613     Value *ShadowsEq = IRB.CreateICmpEQ(WideShadow, RotShadow);
1614 
1615     BasicBlock *Head = Pos->getParent();
1616     BasicBlock *Tail = Head->splitBasicBlock(Pos->getIterator());
1617 
1618     if (DomTreeNode *OldNode = DT.getNode(Head)) {
1619       std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
1620 
1621       DomTreeNode *NewNode = DT.addNewBlock(Tail, Head);
1622       for (auto Child : Children)
1623         DT.changeImmediateDominator(Child, NewNode);
1624     }
1625 
1626     // In the following code LastBr will refer to the previous basic block's
1627     // conditional branch instruction, whose true successor is fixed up to point
1628     // to the next block during the loop below or to the tail after the final
1629     // iteration.
1630     BranchInst *LastBr = BranchInst::Create(FallbackBB, FallbackBB, ShadowsEq);
1631     ReplaceInstWithInst(Head->getTerminator(), LastBr);
1632     DT.addNewBlock(FallbackBB, Head);
1633 
1634     for (uint64_t Ofs = 64 / DFS.ShadowWidthBits; Ofs != Size;
1635          Ofs += 64 / DFS.ShadowWidthBits) {
1636       BasicBlock *NextBB = BasicBlock::Create(*DFS.Ctx, "", F);
1637       DT.addNewBlock(NextBB, LastBr->getParent());
1638       IRBuilder<> NextIRB(NextBB);
1639       WideAddr = NextIRB.CreateGEP(Type::getInt64Ty(*DFS.Ctx), WideAddr,
1640                                    ConstantInt::get(DFS.IntptrTy, 1));
1641       Value *NextWideShadow = NextIRB.CreateAlignedLoad(NextIRB.getInt64Ty(),
1642                                                         WideAddr, ShadowAlign);
1643       ShadowsEq = NextIRB.CreateICmpEQ(WideShadow, NextWideShadow);
1644       LastBr->setSuccessor(0, NextBB);
1645       LastBr = NextIRB.CreateCondBr(ShadowsEq, FallbackBB, FallbackBB);
1646     }
1647 
1648     LastBr->setSuccessor(0, Tail);
1649     FallbackIRB.CreateBr(Tail);
1650     PHINode *Shadow =
1651         PHINode::Create(DFS.PrimitiveShadowTy, 2, "", &Tail->front());
1652     Shadow->addIncoming(FallbackCall, FallbackBB);
1653     Shadow->addIncoming(TruncShadow, LastBr->getParent());
1654     return Shadow;
1655   }
1656 
1657   IRBuilder<> IRB(Pos);
1658   FunctionCallee &UnionLoadFn =
1659       ClFast16Labels ? DFS.DFSanUnionLoadFast16LabelsFn : DFS.DFSanUnionLoadFn;
1660   CallInst *FallbackCall = IRB.CreateCall(
1661       UnionLoadFn, {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
1662   FallbackCall->addAttribute(AttributeList::ReturnIndex, Attribute::ZExt);
1663   return FallbackCall;
1664 }
1665 
1666 void DFSanVisitor::visitLoadInst(LoadInst &LI) {
1667   auto &DL = LI.getModule()->getDataLayout();
1668   uint64_t Size = DL.getTypeStoreSize(LI.getType());
1669   if (Size == 0) {
1670     DFSF.setShadow(&LI, DFSF.DFS.getZeroShadow(&LI));
1671     return;
1672   }
1673 
1674   Align Alignment = ClPreserveAlignment ? LI.getAlign() : Align(1);
1675   Value *PrimitiveShadow =
1676       DFSF.loadShadow(LI.getPointerOperand(), Size, Alignment.value(), &LI);
1677   if (ClCombinePointerLabelsOnLoad) {
1678     Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
1679     PrimitiveShadow = DFSF.combineShadows(PrimitiveShadow, PtrShadow, &LI);
1680   }
1681   if (!DFSF.DFS.isZeroShadow(PrimitiveShadow))
1682     DFSF.NonZeroChecks.push_back(PrimitiveShadow);
1683 
1684   Value *Shadow =
1685       DFSF.expandFromPrimitiveShadow(LI.getType(), PrimitiveShadow, &LI);
1686   DFSF.setShadow(&LI, Shadow);
1687   if (ClEventCallbacks) {
1688     IRBuilder<> IRB(&LI);
1689     Value *Addr8 = IRB.CreateBitCast(LI.getPointerOperand(), DFSF.DFS.Int8Ptr);
1690     IRB.CreateCall(DFSF.DFS.DFSanLoadCallbackFn, {PrimitiveShadow, Addr8});
1691   }
1692 }
1693 
1694 void DFSanFunction::storePrimitiveShadow(Value *Addr, uint64_t Size,
1695                                          Align Alignment,
1696                                          Value *PrimitiveShadow,
1697                                          Instruction *Pos) {
1698   if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
1699     const auto i = AllocaShadowMap.find(AI);
1700     if (i != AllocaShadowMap.end()) {
1701       IRBuilder<> IRB(Pos);
1702       IRB.CreateStore(PrimitiveShadow, i->second);
1703       return;
1704     }
1705   }
1706 
1707   const Align ShadowAlign(Alignment.value() * DFS.ShadowWidthBytes);
1708   IRBuilder<> IRB(Pos);
1709   Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
1710   if (DFS.isZeroShadow(PrimitiveShadow)) {
1711     IntegerType *ShadowTy =
1712         IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidthBits);
1713     Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
1714     Value *ExtShadowAddr =
1715         IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
1716     IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
1717     return;
1718   }
1719 
1720   const unsigned ShadowVecSize = 128 / DFS.ShadowWidthBits;
1721   uint64_t Offset = 0;
1722   if (Size >= ShadowVecSize) {
1723     auto *ShadowVecTy =
1724         FixedVectorType::get(DFS.PrimitiveShadowTy, ShadowVecSize);
1725     Value *ShadowVec = UndefValue::get(ShadowVecTy);
1726     for (unsigned i = 0; i != ShadowVecSize; ++i) {
1727       ShadowVec = IRB.CreateInsertElement(
1728           ShadowVec, PrimitiveShadow,
1729           ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), i));
1730     }
1731     Value *ShadowVecAddr =
1732         IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
1733     do {
1734       Value *CurShadowVecAddr =
1735           IRB.CreateConstGEP1_32(ShadowVecTy, ShadowVecAddr, Offset);
1736       IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
1737       Size -= ShadowVecSize;
1738       ++Offset;
1739     } while (Size >= ShadowVecSize);
1740     Offset *= ShadowVecSize;
1741   }
1742   while (Size > 0) {
1743     Value *CurShadowAddr =
1744         IRB.CreateConstGEP1_32(DFS.PrimitiveShadowTy, ShadowAddr, Offset);
1745     IRB.CreateAlignedStore(PrimitiveShadow, CurShadowAddr, ShadowAlign);
1746     --Size;
1747     ++Offset;
1748   }
1749 }
1750 
1751 void DFSanVisitor::visitStoreInst(StoreInst &SI) {
1752   auto &DL = SI.getModule()->getDataLayout();
1753   uint64_t Size = DL.getTypeStoreSize(SI.getValueOperand()->getType());
1754   if (Size == 0)
1755     return;
1756 
1757   const Align Alignment = ClPreserveAlignment ? SI.getAlign() : Align(1);
1758 
1759   Value* Shadow = DFSF.getShadow(SI.getValueOperand());
1760   Value *PrimitiveShadow;
1761   if (ClCombinePointerLabelsOnStore) {
1762     Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
1763     PrimitiveShadow = DFSF.combineShadows(Shadow, PtrShadow, &SI);
1764   } else {
1765     PrimitiveShadow = DFSF.collapseToPrimitiveShadow(Shadow, &SI);
1766   }
1767   DFSF.storePrimitiveShadow(SI.getPointerOperand(), Size, Alignment,
1768                             PrimitiveShadow, &SI);
1769   if (ClEventCallbacks) {
1770     IRBuilder<> IRB(&SI);
1771     Value *Addr8 = IRB.CreateBitCast(SI.getPointerOperand(), DFSF.DFS.Int8Ptr);
1772     IRB.CreateCall(DFSF.DFS.DFSanStoreCallbackFn, {PrimitiveShadow, Addr8});
1773   }
1774 }
1775 
1776 void DFSanVisitor::visitUnaryOperator(UnaryOperator &UO) {
1777   visitOperandShadowInst(UO);
1778 }
1779 
1780 void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
1781   visitOperandShadowInst(BO);
1782 }
1783 
1784 void DFSanVisitor::visitCastInst(CastInst &CI) { visitOperandShadowInst(CI); }
1785 
1786 void DFSanVisitor::visitCmpInst(CmpInst &CI) {
1787   Value *CombinedShadow = visitOperandShadowInst(CI);
1788   if (ClEventCallbacks) {
1789     IRBuilder<> IRB(&CI);
1790     IRB.CreateCall(DFSF.DFS.DFSanCmpCallbackFn, CombinedShadow);
1791   }
1792 }
1793 
1794 void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
1795   visitOperandShadowInst(GEPI);
1796 }
1797 
1798 void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
1799   visitOperandShadowInst(I);
1800 }
1801 
1802 void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
1803   visitOperandShadowInst(I);
1804 }
1805 
1806 void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
1807   visitOperandShadowInst(I);
1808 }
1809 
1810 void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
1811   if (!DFSF.DFS.shouldTrackFieldsAndIndices()) {
1812     visitOperandShadowInst(I);
1813     return;
1814   }
1815 
1816   IRBuilder<> IRB(&I);
1817   Value *Agg = I.getAggregateOperand();
1818   Value *AggShadow = DFSF.getShadow(Agg);
1819   Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
1820   DFSF.setShadow(&I, ResShadow);
1821 }
1822 
1823 void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
1824   if (!DFSF.DFS.shouldTrackFieldsAndIndices()) {
1825     visitOperandShadowInst(I);
1826     return;
1827   }
1828 
1829   IRBuilder<> IRB(&I);
1830   Value *AggShadow = DFSF.getShadow(I.getAggregateOperand());
1831   Value *InsShadow = DFSF.getShadow(I.getInsertedValueOperand());
1832   Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
1833   DFSF.setShadow(&I, Res);
1834 }
1835 
1836 void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
1837   bool AllLoadsStores = true;
1838   for (User *U : I.users()) {
1839     if (isa<LoadInst>(U))
1840       continue;
1841 
1842     if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1843       if (SI->getPointerOperand() == &I)
1844         continue;
1845     }
1846 
1847     AllLoadsStores = false;
1848     break;
1849   }
1850   if (AllLoadsStores) {
1851     IRBuilder<> IRB(&I);
1852     DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.PrimitiveShadowTy);
1853   }
1854   DFSF.setShadow(&I, DFSF.DFS.ZeroPrimitiveShadow);
1855 }
1856 
1857 void DFSanVisitor::visitSelectInst(SelectInst &I) {
1858   Value *CondShadow = DFSF.getShadow(I.getCondition());
1859   Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
1860   Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
1861   Value *ShadowSel = nullptr;
1862 
1863   if (isa<VectorType>(I.getCondition()->getType())) {
1864     ShadowSel = DFSF.combineShadowsThenConvert(I.getType(), TrueShadow,
1865                                                FalseShadow, &I);
1866   } else {
1867     if (TrueShadow == FalseShadow) {
1868       ShadowSel = TrueShadow;
1869     } else {
1870       ShadowSel =
1871           SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
1872     }
1873   }
1874   DFSF.setShadow(&I, ClTrackSelectControlFlow
1875                          ? DFSF.combineShadowsThenConvert(
1876                                I.getType(), CondShadow, ShadowSel, &I)
1877                          : ShadowSel);
1878 }
1879 
1880 void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
1881   IRBuilder<> IRB(&I);
1882   Value *ValShadow = DFSF.getShadow(I.getValue());
1883   IRB.CreateCall(DFSF.DFS.DFSanSetLabelFn,
1884                  {ValShadow, IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(
1885                                                                 *DFSF.DFS.Ctx)),
1886                   IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy)});
1887 }
1888 
1889 void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
1890   IRBuilder<> IRB(&I);
1891   Value *RawDestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
1892   Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
1893   Value *LenShadow =
1894       IRB.CreateMul(I.getLength(), ConstantInt::get(I.getLength()->getType(),
1895                                                     DFSF.DFS.ShadowWidthBytes));
1896   Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
1897   Value *DestShadow = IRB.CreateBitCast(RawDestShadow, Int8Ptr);
1898   SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
1899   auto *MTI = cast<MemTransferInst>(
1900       IRB.CreateCall(I.getFunctionType(), I.getCalledOperand(),
1901                      {DestShadow, SrcShadow, LenShadow, I.getVolatileCst()}));
1902   if (ClPreserveAlignment) {
1903     MTI->setDestAlignment(I.getDestAlign() * DFSF.DFS.ShadowWidthBytes);
1904     MTI->setSourceAlignment(I.getSourceAlign() * DFSF.DFS.ShadowWidthBytes);
1905   } else {
1906     MTI->setDestAlignment(Align(DFSF.DFS.ShadowWidthBytes));
1907     MTI->setSourceAlignment(Align(DFSF.DFS.ShadowWidthBytes));
1908   }
1909   if (ClEventCallbacks) {
1910     IRB.CreateCall(DFSF.DFS.DFSanMemTransferCallbackFn,
1911                    {RawDestShadow, I.getLength()});
1912   }
1913 }
1914 
1915 void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
1916   if (!DFSF.IsNativeABI && RI.getReturnValue()) {
1917     switch (DFSF.IA) {
1918     case DataFlowSanitizer::IA_TLS: {
1919       Value *S = DFSF.getShadow(RI.getReturnValue());
1920       IRBuilder<> IRB(&RI);
1921       Type *RT = DFSF.F->getFunctionType()->getReturnType();
1922       unsigned Size =
1923           getDataLayout().getTypeAllocSize(DFSF.DFS.getShadowTy(RT));
1924       if (Size <= kRetvalTLSSize) {
1925         // If the size overflows, stores nothing. At callsite, oversized return
1926         // shadows are set to zero.
1927         IRB.CreateAlignedStore(S, DFSF.getRetvalTLS(RT, IRB),
1928                                kShadowTLSAlignment);
1929       }
1930       break;
1931     }
1932     case DataFlowSanitizer::IA_Args: {
1933       IRBuilder<> IRB(&RI);
1934       Type *RT = DFSF.F->getFunctionType()->getReturnType();
1935       Value *InsVal =
1936           IRB.CreateInsertValue(UndefValue::get(RT), RI.getReturnValue(), 0);
1937       Value *InsShadow =
1938           IRB.CreateInsertValue(InsVal, DFSF.getShadow(RI.getReturnValue()), 1);
1939       RI.setOperand(0, InsShadow);
1940       break;
1941     }
1942     }
1943   }
1944 }
1945 
1946 void DFSanVisitor::visitCallBase(CallBase &CB) {
1947   Function *F = CB.getCalledFunction();
1948   if ((F && F->isIntrinsic()) || CB.isInlineAsm()) {
1949     visitOperandShadowInst(CB);
1950     return;
1951   }
1952 
1953   // Calls to this function are synthesized in wrappers, and we shouldn't
1954   // instrument them.
1955   if (F == DFSF.DFS.DFSanVarargWrapperFn.getCallee()->stripPointerCasts())
1956     return;
1957 
1958   IRBuilder<> IRB(&CB);
1959 
1960   DenseMap<Value *, Function *>::iterator i =
1961       DFSF.DFS.UnwrappedFnMap.find(CB.getCalledOperand());
1962   if (i != DFSF.DFS.UnwrappedFnMap.end()) {
1963     Function *F = i->second;
1964     switch (DFSF.DFS.getWrapperKind(F)) {
1965     case DataFlowSanitizer::WK_Warning:
1966       CB.setCalledFunction(F);
1967       IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
1968                      IRB.CreateGlobalStringPtr(F->getName()));
1969       DFSF.setShadow(&CB, DFSF.DFS.getZeroShadow(&CB));
1970       return;
1971     case DataFlowSanitizer::WK_Discard:
1972       CB.setCalledFunction(F);
1973       DFSF.setShadow(&CB, DFSF.DFS.getZeroShadow(&CB));
1974       return;
1975     case DataFlowSanitizer::WK_Functional:
1976       CB.setCalledFunction(F);
1977       visitOperandShadowInst(CB);
1978       return;
1979     case DataFlowSanitizer::WK_Custom:
1980       // Don't try to handle invokes of custom functions, it's too complicated.
1981       // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
1982       // wrapper.
1983       if (CallInst *CI = dyn_cast<CallInst>(&CB)) {
1984         FunctionType *FT = F->getFunctionType();
1985         TransformedFunction CustomFn = DFSF.DFS.getCustomFunctionType(FT);
1986         std::string CustomFName = "__dfsw_";
1987         CustomFName += F->getName();
1988         FunctionCallee CustomF = DFSF.DFS.Mod->getOrInsertFunction(
1989             CustomFName, CustomFn.TransformedType);
1990         if (Function *CustomFn = dyn_cast<Function>(CustomF.getCallee())) {
1991           CustomFn->copyAttributesFrom(F);
1992 
1993           // Custom functions returning non-void will write to the return label.
1994           if (!FT->getReturnType()->isVoidTy()) {
1995             CustomFn->removeAttributes(AttributeList::FunctionIndex,
1996                                        DFSF.DFS.ReadOnlyNoneAttrs);
1997           }
1998         }
1999 
2000         std::vector<Value *> Args;
2001 
2002         auto i = CB.arg_begin();
2003         for (unsigned n = FT->getNumParams(); n != 0; ++i, --n) {
2004           Type *T = (*i)->getType();
2005           FunctionType *ParamFT;
2006           if (isa<PointerType>(T) &&
2007               (ParamFT = dyn_cast<FunctionType>(
2008                    cast<PointerType>(T)->getElementType()))) {
2009             std::string TName = "dfst";
2010             TName += utostr(FT->getNumParams() - n);
2011             TName += "$";
2012             TName += F->getName();
2013             Constant *T = DFSF.DFS.getOrBuildTrampolineFunction(ParamFT, TName);
2014             Args.push_back(T);
2015             Args.push_back(
2016                 IRB.CreateBitCast(*i, Type::getInt8PtrTy(*DFSF.DFS.Ctx)));
2017           } else {
2018             Args.push_back(*i);
2019           }
2020         }
2021 
2022         i = CB.arg_begin();
2023         const unsigned ShadowArgStart = Args.size();
2024         for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
2025           Args.push_back(
2026               DFSF.collapseToPrimitiveShadow(DFSF.getShadow(*i), &CB));
2027 
2028         if (FT->isVarArg()) {
2029           auto *LabelVATy = ArrayType::get(DFSF.DFS.PrimitiveShadowTy,
2030                                            CB.arg_size() - FT->getNumParams());
2031           auto *LabelVAAlloca = new AllocaInst(
2032               LabelVATy, getDataLayout().getAllocaAddrSpace(),
2033               "labelva", &DFSF.F->getEntryBlock().front());
2034 
2035           for (unsigned n = 0; i != CB.arg_end(); ++i, ++n) {
2036             auto LabelVAPtr = IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, n);
2037             IRB.CreateStore(
2038                 DFSF.collapseToPrimitiveShadow(DFSF.getShadow(*i), &CB),
2039                 LabelVAPtr);
2040           }
2041 
2042           Args.push_back(IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, 0));
2043         }
2044 
2045         if (!FT->getReturnType()->isVoidTy()) {
2046           if (!DFSF.LabelReturnAlloca) {
2047             DFSF.LabelReturnAlloca =
2048                 new AllocaInst(DFSF.DFS.PrimitiveShadowTy,
2049                                getDataLayout().getAllocaAddrSpace(),
2050                                "labelreturn", &DFSF.F->getEntryBlock().front());
2051           }
2052           Args.push_back(DFSF.LabelReturnAlloca);
2053         }
2054 
2055         for (i = CB.arg_begin() + FT->getNumParams(); i != CB.arg_end(); ++i)
2056           Args.push_back(*i);
2057 
2058         CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
2059         CustomCI->setCallingConv(CI->getCallingConv());
2060         CustomCI->setAttributes(TransformFunctionAttributes(CustomFn,
2061             CI->getContext(), CI->getAttributes()));
2062 
2063         // Update the parameter attributes of the custom call instruction to
2064         // zero extend the shadow parameters. This is required for targets
2065         // which consider PrimitiveShadowTy an illegal type.
2066         for (unsigned n = 0; n < FT->getNumParams(); n++) {
2067           const unsigned ArgNo = ShadowArgStart + n;
2068           if (CustomCI->getArgOperand(ArgNo)->getType() ==
2069               DFSF.DFS.PrimitiveShadowTy)
2070             CustomCI->addParamAttr(ArgNo, Attribute::ZExt);
2071         }
2072 
2073         if (!FT->getReturnType()->isVoidTy()) {
2074           LoadInst *LabelLoad = IRB.CreateLoad(DFSF.DFS.PrimitiveShadowTy,
2075                                                DFSF.LabelReturnAlloca);
2076           DFSF.setShadow(CustomCI, DFSF.expandFromPrimitiveShadow(
2077                                        FT->getReturnType(), LabelLoad, &CB));
2078         }
2079 
2080         CI->replaceAllUsesWith(CustomCI);
2081         CI->eraseFromParent();
2082         return;
2083       }
2084       break;
2085     }
2086   }
2087 
2088   FunctionType *FT = CB.getFunctionType();
2089   if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
2090     unsigned ArgOffset = 0;
2091     const DataLayout &DL = getDataLayout();
2092     for (unsigned I = 0, N = FT->getNumParams(); I != N; ++I) {
2093       unsigned Size =
2094           DL.getTypeAllocSize(DFSF.DFS.getShadowTy(FT->getParamType(I)));
2095       // Stop storing if arguments' size overflows. Inside a function, arguments
2096       // after overflow have zero shadow values.
2097       if (ArgOffset + Size > kArgTLSSize)
2098         break;
2099       IRB.CreateAlignedStore(
2100           DFSF.getShadow(CB.getArgOperand(I)),
2101           DFSF.getArgTLS(FT->getParamType(I), ArgOffset, IRB),
2102           kShadowTLSAlignment);
2103       ArgOffset += alignTo(Size, kShadowTLSAlignment);
2104     }
2105   }
2106 
2107   Instruction *Next = nullptr;
2108   if (!CB.getType()->isVoidTy()) {
2109     if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
2110       if (II->getNormalDest()->getSinglePredecessor()) {
2111         Next = &II->getNormalDest()->front();
2112       } else {
2113         BasicBlock *NewBB =
2114             SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DT);
2115         Next = &NewBB->front();
2116       }
2117     } else {
2118       assert(CB.getIterator() != CB.getParent()->end());
2119       Next = CB.getNextNode();
2120     }
2121 
2122     if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_TLS) {
2123       IRBuilder<> NextIRB(Next);
2124       const DataLayout &DL = getDataLayout();
2125       unsigned Size = DL.getTypeAllocSize(DFSF.DFS.getShadowTy(&CB));
2126       if (Size > kRetvalTLSSize) {
2127         // Set overflowed return shadow to be zero.
2128         DFSF.setShadow(&CB, DFSF.DFS.getZeroShadow(&CB));
2129       } else {
2130         LoadInst *LI = NextIRB.CreateAlignedLoad(
2131             DFSF.DFS.getShadowTy(&CB), DFSF.getRetvalTLS(CB.getType(), NextIRB),
2132             kShadowTLSAlignment, "_dfsret");
2133         DFSF.SkipInsts.insert(LI);
2134         DFSF.setShadow(&CB, LI);
2135         DFSF.NonZeroChecks.push_back(LI);
2136       }
2137     }
2138   }
2139 
2140   // Do all instrumentation for IA_Args down here to defer tampering with the
2141   // CFG in a way that SplitEdge may be able to detect.
2142   if (DFSF.DFS.getInstrumentedABI() == DataFlowSanitizer::IA_Args) {
2143     FunctionType *NewFT = DFSF.DFS.getArgsFunctionType(FT);
2144     Value *Func =
2145         IRB.CreateBitCast(CB.getCalledOperand(), PointerType::getUnqual(NewFT));
2146     std::vector<Value *> Args;
2147 
2148     auto i = CB.arg_begin(), E = CB.arg_end();
2149     for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
2150       Args.push_back(*i);
2151 
2152     i = CB.arg_begin();
2153     for (unsigned n = FT->getNumParams(); n != 0; ++i, --n)
2154       Args.push_back(DFSF.getShadow(*i));
2155 
2156     if (FT->isVarArg()) {
2157       unsigned VarArgSize = CB.arg_size() - FT->getNumParams();
2158       ArrayType *VarArgArrayTy =
2159           ArrayType::get(DFSF.DFS.PrimitiveShadowTy, VarArgSize);
2160       AllocaInst *VarArgShadow =
2161         new AllocaInst(VarArgArrayTy, getDataLayout().getAllocaAddrSpace(),
2162                        "", &DFSF.F->getEntryBlock().front());
2163       Args.push_back(IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, 0));
2164       for (unsigned n = 0; i != E; ++i, ++n) {
2165         IRB.CreateStore(
2166             DFSF.getShadow(*i),
2167             IRB.CreateConstGEP2_32(VarArgArrayTy, VarArgShadow, 0, n));
2168         Args.push_back(*i);
2169       }
2170     }
2171 
2172     CallBase *NewCB;
2173     if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
2174       NewCB = IRB.CreateInvoke(NewFT, Func, II->getNormalDest(),
2175                                II->getUnwindDest(), Args);
2176     } else {
2177       NewCB = IRB.CreateCall(NewFT, Func, Args);
2178     }
2179     NewCB->setCallingConv(CB.getCallingConv());
2180     NewCB->setAttributes(CB.getAttributes().removeAttributes(
2181         *DFSF.DFS.Ctx, AttributeList::ReturnIndex,
2182         AttributeFuncs::typeIncompatible(NewCB->getType())));
2183 
2184     if (Next) {
2185       ExtractValueInst *ExVal = ExtractValueInst::Create(NewCB, 0, "", Next);
2186       DFSF.SkipInsts.insert(ExVal);
2187       ExtractValueInst *ExShadow = ExtractValueInst::Create(NewCB, 1, "", Next);
2188       DFSF.SkipInsts.insert(ExShadow);
2189       DFSF.setShadow(ExVal, ExShadow);
2190       DFSF.NonZeroChecks.push_back(ExShadow);
2191 
2192       CB.replaceAllUsesWith(ExVal);
2193     }
2194 
2195     CB.eraseFromParent();
2196   }
2197 }
2198 
2199 void DFSanVisitor::visitPHINode(PHINode &PN) {
2200   Type *ShadowTy = DFSF.DFS.getShadowTy(&PN);
2201   PHINode *ShadowPN =
2202       PHINode::Create(ShadowTy, PN.getNumIncomingValues(), "", &PN);
2203 
2204   // Give the shadow phi node valid predecessors to fool SplitEdge into working.
2205   Value *UndefShadow = UndefValue::get(ShadowTy);
2206   for (PHINode::block_iterator i = PN.block_begin(), e = PN.block_end(); i != e;
2207        ++i) {
2208     ShadowPN->addIncoming(UndefShadow, *i);
2209   }
2210 
2211   DFSF.PHIFixups.push_back(std::make_pair(&PN, ShadowPN));
2212   DFSF.setShadow(&PN, ShadowPN);
2213 }
2214 
2215 namespace {
2216 class DataFlowSanitizerLegacyPass : public ModulePass {
2217 private:
2218   std::vector<std::string> ABIListFiles;
2219 
2220 public:
2221   static char ID;
2222 
2223   DataFlowSanitizerLegacyPass(
2224       const std::vector<std::string> &ABIListFiles = std::vector<std::string>())
2225       : ModulePass(ID), ABIListFiles(ABIListFiles) {}
2226 
2227   bool runOnModule(Module &M) override {
2228     return DataFlowSanitizer(ABIListFiles).runImpl(M);
2229   }
2230 };
2231 } // namespace
2232 
2233 char DataFlowSanitizerLegacyPass::ID;
2234 
2235 INITIALIZE_PASS(DataFlowSanitizerLegacyPass, "dfsan",
2236                 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
2237 
2238 ModulePass *llvm::createDataFlowSanitizerLegacyPassPass(
2239     const std::vector<std::string> &ABIListFiles) {
2240   return new DataFlowSanitizerLegacyPass(ABIListFiles);
2241 }
2242 
2243 PreservedAnalyses DataFlowSanitizerPass::run(Module &M,
2244                                              ModuleAnalysisManager &AM) {
2245   if (DataFlowSanitizer(ABIListFiles).runImpl(M)) {
2246     return PreservedAnalyses::none();
2247   }
2248   return PreservedAnalyses::all();
2249 }
2250