1 //===- ImplicitNullChecks.cpp - Fold null checks into memory accesses -----===//
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 // This pass turns explicit null checks of the form
10 //
11 //   test %r10, %r10
12 //   je throw_npe
13 //   movl (%r10), %esi
14 //   ...
15 //
16 // to
17 //
18 //   faulting_load_op("movl (%r10), %esi", throw_npe)
19 //   ...
20 //
21 // With the help of a runtime that understands the .fault_maps section,
22 // faulting_load_op branches to throw_npe if executing movl (%r10), %esi incurs
23 // a page fault.
24 // Store and LoadStore are also supported.
25 //
26 //===----------------------------------------------------------------------===//
27 
28 #include "llvm/ADT/ArrayRef.h"
29 #include "llvm/ADT/None.h"
30 #include "llvm/ADT/Optional.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/Analysis/AliasAnalysis.h"
35 #include "llvm/Analysis/MemoryLocation.h"
36 #include "llvm/CodeGen/FaultMaps.h"
37 #include "llvm/CodeGen/MachineBasicBlock.h"
38 #include "llvm/CodeGen/MachineFunction.h"
39 #include "llvm/CodeGen/MachineFunctionPass.h"
40 #include "llvm/CodeGen/MachineInstr.h"
41 #include "llvm/CodeGen/MachineInstrBuilder.h"
42 #include "llvm/CodeGen/MachineMemOperand.h"
43 #include "llvm/CodeGen/MachineOperand.h"
44 #include "llvm/CodeGen/MachineRegisterInfo.h"
45 #include "llvm/CodeGen/PseudoSourceValue.h"
46 #include "llvm/CodeGen/TargetInstrInfo.h"
47 #include "llvm/CodeGen/TargetOpcodes.h"
48 #include "llvm/CodeGen/TargetRegisterInfo.h"
49 #include "llvm/CodeGen/TargetSubtargetInfo.h"
50 #include "llvm/IR/BasicBlock.h"
51 #include "llvm/IR/DebugLoc.h"
52 #include "llvm/IR/LLVMContext.h"
53 #include "llvm/MC/MCInstrDesc.h"
54 #include "llvm/MC/MCRegisterInfo.h"
55 #include "llvm/Pass.h"
56 #include "llvm/Support/CommandLine.h"
57 #include <cassert>
58 #include <cstdint>
59 #include <iterator>
60 
61 using namespace llvm;
62 
63 static cl::opt<int> PageSize("imp-null-check-page-size",
64                              cl::desc("The page size of the target in bytes"),
65                              cl::init(4096), cl::Hidden);
66 
67 static cl::opt<unsigned> MaxInstsToConsider(
68     "imp-null-max-insts-to-consider",
69     cl::desc("The max number of instructions to consider hoisting loads over "
70              "(the algorithm is quadratic over this number)"),
71     cl::Hidden, cl::init(8));
72 
73 #define DEBUG_TYPE "implicit-null-checks"
74 
75 STATISTIC(NumImplicitNullChecks,
76           "Number of explicit null checks made implicit");
77 
78 namespace {
79 
80 class ImplicitNullChecks : public MachineFunctionPass {
81   /// Return true if \c computeDependence can process \p MI.
82   static bool canHandle(const MachineInstr *MI);
83 
84   /// Helper function for \c computeDependence.  Return true if \p A
85   /// and \p B do not have any dependences between them, and can be
86   /// re-ordered without changing program semantics.
87   bool canReorder(const MachineInstr *A, const MachineInstr *B);
88 
89   /// A data type for representing the result computed by \c
90   /// computeDependence.  States whether it is okay to reorder the
91   /// instruction passed to \c computeDependence with at most one
92   /// dependency.
93   struct DependenceResult {
94     /// Can we actually re-order \p MI with \p Insts (see \c
95     /// computeDependence).
96     bool CanReorder;
97 
98     /// If non-None, then an instruction in \p Insts that also must be
99     /// hoisted.
100     Optional<ArrayRef<MachineInstr *>::iterator> PotentialDependence;
101 
102     /*implicit*/ DependenceResult(
103         bool CanReorder,
104         Optional<ArrayRef<MachineInstr *>::iterator> PotentialDependence)
105         : CanReorder(CanReorder), PotentialDependence(PotentialDependence) {
106       assert((!PotentialDependence || CanReorder) &&
107              "!CanReorder && PotentialDependence.hasValue() not allowed!");
108     }
109   };
110 
111   /// Compute a result for the following question: can \p MI be
112   /// re-ordered from after \p Insts to before it.
113   ///
114   /// \c canHandle should return true for all instructions in \p
115   /// Insts.
116   DependenceResult computeDependence(const MachineInstr *MI,
117                                      ArrayRef<MachineInstr *> Block);
118 
119   /// Represents one null check that can be made implicit.
120   class NullCheck {
121     // The memory operation the null check can be folded into.
122     MachineInstr *MemOperation;
123 
124     // The instruction actually doing the null check (Ptr != 0).
125     MachineInstr *CheckOperation;
126 
127     // The block the check resides in.
128     MachineBasicBlock *CheckBlock;
129 
130     // The block branched to if the pointer is non-null.
131     MachineBasicBlock *NotNullSucc;
132 
133     // The block branched to if the pointer is null.
134     MachineBasicBlock *NullSucc;
135 
136     // If this is non-null, then MemOperation has a dependency on this
137     // instruction; and it needs to be hoisted to execute before MemOperation.
138     MachineInstr *OnlyDependency;
139 
140   public:
141     explicit NullCheck(MachineInstr *memOperation, MachineInstr *checkOperation,
142                        MachineBasicBlock *checkBlock,
143                        MachineBasicBlock *notNullSucc,
144                        MachineBasicBlock *nullSucc,
145                        MachineInstr *onlyDependency)
146         : MemOperation(memOperation), CheckOperation(checkOperation),
147           CheckBlock(checkBlock), NotNullSucc(notNullSucc), NullSucc(nullSucc),
148           OnlyDependency(onlyDependency) {}
149 
150     MachineInstr *getMemOperation() const { return MemOperation; }
151 
152     MachineInstr *getCheckOperation() const { return CheckOperation; }
153 
154     MachineBasicBlock *getCheckBlock() const { return CheckBlock; }
155 
156     MachineBasicBlock *getNotNullSucc() const { return NotNullSucc; }
157 
158     MachineBasicBlock *getNullSucc() const { return NullSucc; }
159 
160     MachineInstr *getOnlyDependency() const { return OnlyDependency; }
161   };
162 
163   const TargetInstrInfo *TII = nullptr;
164   const TargetRegisterInfo *TRI = nullptr;
165   AliasAnalysis *AA = nullptr;
166   MachineFrameInfo *MFI = nullptr;
167 
168   bool analyzeBlockForNullChecks(MachineBasicBlock &MBB,
169                                  SmallVectorImpl<NullCheck> &NullCheckList);
170   MachineInstr *insertFaultingInstr(MachineInstr *MI, MachineBasicBlock *MBB,
171                                     MachineBasicBlock *HandlerMBB);
172   void rewriteNullChecks(ArrayRef<NullCheck> NullCheckList);
173 
174   enum AliasResult {
175     AR_NoAlias,
176     AR_MayAlias,
177     AR_WillAliasEverything
178   };
179 
180   /// Returns AR_NoAlias if \p MI memory operation does not alias with
181   /// \p PrevMI, AR_MayAlias if they may alias and AR_WillAliasEverything if
182   /// they may alias and any further memory operation may alias with \p PrevMI.
183   AliasResult areMemoryOpsAliased(MachineInstr &MI, MachineInstr *PrevMI);
184 
185   enum SuitabilityResult {
186     SR_Suitable,
187     SR_Unsuitable,
188     SR_Impossible
189   };
190 
191   /// Return SR_Suitable if \p MI a memory operation that can be used to
192   /// implicitly null check the value in \p PointerReg, SR_Unsuitable if
193   /// \p MI cannot be used to null check and SR_Impossible if there is
194   /// no sense to continue lookup due to any other instruction will not be able
195   /// to be used. \p PrevInsts is the set of instruction seen since
196   /// the explicit null check on \p PointerReg.
197   SuitabilityResult isSuitableMemoryOp(MachineInstr &MI, unsigned PointerReg,
198                                        ArrayRef<MachineInstr *> PrevInsts);
199 
200   /// Return true if \p FaultingMI can be hoisted from after the
201   /// instructions in \p InstsSeenSoFar to before them.  Set \p Dependence to a
202   /// non-null value if we also need to (and legally can) hoist a depedency.
203   bool canHoistInst(MachineInstr *FaultingMI, unsigned PointerReg,
204                     ArrayRef<MachineInstr *> InstsSeenSoFar,
205                     MachineBasicBlock *NullSucc, MachineInstr *&Dependence);
206 
207 public:
208   static char ID;
209 
210   ImplicitNullChecks() : MachineFunctionPass(ID) {
211     initializeImplicitNullChecksPass(*PassRegistry::getPassRegistry());
212   }
213 
214   bool runOnMachineFunction(MachineFunction &MF) override;
215 
216   void getAnalysisUsage(AnalysisUsage &AU) const override {
217     AU.addRequired<AAResultsWrapperPass>();
218     MachineFunctionPass::getAnalysisUsage(AU);
219   }
220 
221   MachineFunctionProperties getRequiredProperties() const override {
222     return MachineFunctionProperties().set(
223         MachineFunctionProperties::Property::NoVRegs);
224   }
225 };
226 
227 } // end anonymous namespace
228 
229 bool ImplicitNullChecks::canHandle(const MachineInstr *MI) {
230   if (MI->isCall() || MI->hasUnmodeledSideEffects())
231     return false;
232   auto IsRegMask = [](const MachineOperand &MO) { return MO.isRegMask(); };
233   (void)IsRegMask;
234 
235   assert(!llvm::any_of(MI->operands(), IsRegMask) &&
236          "Calls were filtered out above!");
237 
238   auto IsUnordered = [](MachineMemOperand *MMO) { return MMO->isUnordered(); };
239   return llvm::all_of(MI->memoperands(), IsUnordered);
240 }
241 
242 ImplicitNullChecks::DependenceResult
243 ImplicitNullChecks::computeDependence(const MachineInstr *MI,
244                                       ArrayRef<MachineInstr *> Block) {
245   assert(llvm::all_of(Block, canHandle) && "Check this first!");
246   assert(!is_contained(Block, MI) && "Block must be exclusive of MI!");
247 
248   Optional<ArrayRef<MachineInstr *>::iterator> Dep;
249 
250   for (auto I = Block.begin(), E = Block.end(); I != E; ++I) {
251     if (canReorder(*I, MI))
252       continue;
253 
254     if (Dep == None) {
255       // Found one possible dependency, keep track of it.
256       Dep = I;
257     } else {
258       // We found two dependencies, so bail out.
259       return {false, None};
260     }
261   }
262 
263   return {true, Dep};
264 }
265 
266 bool ImplicitNullChecks::canReorder(const MachineInstr *A,
267                                     const MachineInstr *B) {
268   assert(canHandle(A) && canHandle(B) && "Precondition!");
269 
270   // canHandle makes sure that we _can_ correctly analyze the dependencies
271   // between A and B here -- for instance, we should not be dealing with heap
272   // load-store dependencies here.
273 
274   for (auto MOA : A->operands()) {
275     if (!(MOA.isReg() && MOA.getReg()))
276       continue;
277 
278     unsigned RegA = MOA.getReg();
279     for (auto MOB : B->operands()) {
280       if (!(MOB.isReg() && MOB.getReg()))
281         continue;
282 
283       unsigned RegB = MOB.getReg();
284 
285       if (TRI->regsOverlap(RegA, RegB) && (MOA.isDef() || MOB.isDef()))
286         return false;
287     }
288   }
289 
290   return true;
291 }
292 
293 bool ImplicitNullChecks::runOnMachineFunction(MachineFunction &MF) {
294   TII = MF.getSubtarget().getInstrInfo();
295   TRI = MF.getRegInfo().getTargetRegisterInfo();
296   MFI = &MF.getFrameInfo();
297   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
298 
299   SmallVector<NullCheck, 16> NullCheckList;
300 
301   for (auto &MBB : MF)
302     analyzeBlockForNullChecks(MBB, NullCheckList);
303 
304   if (!NullCheckList.empty())
305     rewriteNullChecks(NullCheckList);
306 
307   return !NullCheckList.empty();
308 }
309 
310 // Return true if any register aliasing \p Reg is live-in into \p MBB.
311 static bool AnyAliasLiveIn(const TargetRegisterInfo *TRI,
312                            MachineBasicBlock *MBB, unsigned Reg) {
313   for (MCRegAliasIterator AR(Reg, TRI, /*IncludeSelf*/ true); AR.isValid();
314        ++AR)
315     if (MBB->isLiveIn(*AR))
316       return true;
317   return false;
318 }
319 
320 ImplicitNullChecks::AliasResult
321 ImplicitNullChecks::areMemoryOpsAliased(MachineInstr &MI,
322                                         MachineInstr *PrevMI) {
323   // If it is not memory access, skip the check.
324   if (!(PrevMI->mayStore() || PrevMI->mayLoad()))
325     return AR_NoAlias;
326   // Load-Load may alias
327   if (!(MI.mayStore() || PrevMI->mayStore()))
328     return AR_NoAlias;
329   // We lost info, conservatively alias. If it was store then no sense to
330   // continue because we won't be able to check against it further.
331   if (MI.memoperands_empty())
332     return MI.mayStore() ? AR_WillAliasEverything : AR_MayAlias;
333   if (PrevMI->memoperands_empty())
334     return PrevMI->mayStore() ? AR_WillAliasEverything : AR_MayAlias;
335 
336   for (MachineMemOperand *MMO1 : MI.memoperands()) {
337     // MMO1 should have a value due it comes from operation we'd like to use
338     // as implicit null check.
339     assert(MMO1->getValue() && "MMO1 should have a Value!");
340     for (MachineMemOperand *MMO2 : PrevMI->memoperands()) {
341       if (const PseudoSourceValue *PSV = MMO2->getPseudoValue()) {
342         if (PSV->mayAlias(MFI))
343           return AR_MayAlias;
344         continue;
345       }
346       llvm::AliasResult AAResult =
347           AA->alias(MemoryLocation(MMO1->getValue(), LocationSize::unknown(),
348                                    MMO1->getAAInfo()),
349                     MemoryLocation(MMO2->getValue(), LocationSize::unknown(),
350                                    MMO2->getAAInfo()));
351       if (AAResult != NoAlias)
352         return AR_MayAlias;
353     }
354   }
355   return AR_NoAlias;
356 }
357 
358 ImplicitNullChecks::SuitabilityResult
359 ImplicitNullChecks::isSuitableMemoryOp(MachineInstr &MI, unsigned PointerReg,
360                                        ArrayRef<MachineInstr *> PrevInsts) {
361   int64_t Offset;
362   MachineOperand *BaseOp;
363 
364   if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, TRI) ||
365       !BaseOp->isReg() || BaseOp->getReg() != PointerReg)
366     return SR_Unsuitable;
367 
368   // We want the mem access to be issued at a sane offset from PointerReg,
369   // so that if PointerReg is null then the access reliably page faults.
370   if (!((MI.mayLoad() || MI.mayStore()) && !MI.isPredicable() &&
371         -PageSize < Offset && Offset < PageSize))
372     return SR_Unsuitable;
373 
374   // Finally, check whether the current memory access aliases with previous one.
375   for (auto *PrevMI : PrevInsts) {
376     AliasResult AR = areMemoryOpsAliased(MI, PrevMI);
377     if (AR == AR_WillAliasEverything)
378       return SR_Impossible;
379     if (AR == AR_MayAlias)
380       return SR_Unsuitable;
381   }
382   return SR_Suitable;
383 }
384 
385 bool ImplicitNullChecks::canHoistInst(MachineInstr *FaultingMI,
386                                       unsigned PointerReg,
387                                       ArrayRef<MachineInstr *> InstsSeenSoFar,
388                                       MachineBasicBlock *NullSucc,
389                                       MachineInstr *&Dependence) {
390   auto DepResult = computeDependence(FaultingMI, InstsSeenSoFar);
391   if (!DepResult.CanReorder)
392     return false;
393 
394   if (!DepResult.PotentialDependence) {
395     Dependence = nullptr;
396     return true;
397   }
398 
399   auto DependenceItr = *DepResult.PotentialDependence;
400   auto *DependenceMI = *DependenceItr;
401 
402   // We don't want to reason about speculating loads.  Note -- at this point
403   // we should have already filtered out all of the other non-speculatable
404   // things, like calls and stores.
405   // We also do not want to hoist stores because it might change the memory
406   // while the FaultingMI may result in faulting.
407   assert(canHandle(DependenceMI) && "Should never have reached here!");
408   if (DependenceMI->mayLoadOrStore())
409     return false;
410 
411   for (auto &DependenceMO : DependenceMI->operands()) {
412     if (!(DependenceMO.isReg() && DependenceMO.getReg()))
413       continue;
414 
415     // Make sure that we won't clobber any live ins to the sibling block by
416     // hoisting Dependency.  For instance, we can't hoist INST to before the
417     // null check (even if it safe, and does not violate any dependencies in
418     // the non_null_block) if %rdx is live in to _null_block.
419     //
420     //    test %rcx, %rcx
421     //    je _null_block
422     //  _non_null_block:
423     //    %rdx = INST
424     //    ...
425     //
426     // This restriction does not apply to the faulting load inst because in
427     // case the pointer loaded from is in the null page, the load will not
428     // semantically execute, and affect machine state.  That is, if the load
429     // was loading into %rax and it faults, the value of %rax should stay the
430     // same as it would have been had the load not have executed and we'd have
431     // branched to NullSucc directly.
432     if (AnyAliasLiveIn(TRI, NullSucc, DependenceMO.getReg()))
433       return false;
434 
435     // The Dependency can't be re-defining the base register -- then we won't
436     // get the memory operation on the address we want.  This is already
437     // checked in \c IsSuitableMemoryOp.
438     assert(!(DependenceMO.isDef() &&
439              TRI->regsOverlap(DependenceMO.getReg(), PointerReg)) &&
440            "Should have been checked before!");
441   }
442 
443   auto DepDepResult =
444       computeDependence(DependenceMI, {InstsSeenSoFar.begin(), DependenceItr});
445 
446   if (!DepDepResult.CanReorder || DepDepResult.PotentialDependence)
447     return false;
448 
449   Dependence = DependenceMI;
450   return true;
451 }
452 
453 /// Analyze MBB to check if its terminating branch can be turned into an
454 /// implicit null check.  If yes, append a description of the said null check to
455 /// NullCheckList and return true, else return false.
456 bool ImplicitNullChecks::analyzeBlockForNullChecks(
457     MachineBasicBlock &MBB, SmallVectorImpl<NullCheck> &NullCheckList) {
458   using MachineBranchPredicate = TargetInstrInfo::MachineBranchPredicate;
459 
460   MDNode *BranchMD = nullptr;
461   if (auto *BB = MBB.getBasicBlock())
462     BranchMD = BB->getTerminator()->getMetadata(LLVMContext::MD_make_implicit);
463 
464   if (!BranchMD)
465     return false;
466 
467   MachineBranchPredicate MBP;
468 
469   if (TII->analyzeBranchPredicate(MBB, MBP, true))
470     return false;
471 
472   // Is the predicate comparing an integer to zero?
473   if (!(MBP.LHS.isReg() && MBP.RHS.isImm() && MBP.RHS.getImm() == 0 &&
474         (MBP.Predicate == MachineBranchPredicate::PRED_NE ||
475          MBP.Predicate == MachineBranchPredicate::PRED_EQ)))
476     return false;
477 
478   // If we cannot erase the test instruction itself, then making the null check
479   // implicit does not buy us much.
480   if (!MBP.SingleUseCondition)
481     return false;
482 
483   MachineBasicBlock *NotNullSucc, *NullSucc;
484 
485   if (MBP.Predicate == MachineBranchPredicate::PRED_NE) {
486     NotNullSucc = MBP.TrueDest;
487     NullSucc = MBP.FalseDest;
488   } else {
489     NotNullSucc = MBP.FalseDest;
490     NullSucc = MBP.TrueDest;
491   }
492 
493   // We handle the simplest case for now.  We can potentially do better by using
494   // the machine dominator tree.
495   if (NotNullSucc->pred_size() != 1)
496     return false;
497 
498   // To prevent the invalid transformation of the following code:
499   //
500   //   mov %rax, %rcx
501   //   test %rax, %rax
502   //   %rax = ...
503   //   je throw_npe
504   //   mov(%rcx), %r9
505   //   mov(%rax), %r10
506   //
507   // into:
508   //
509   //   mov %rax, %rcx
510   //   %rax = ....
511   //   faulting_load_op("movl (%rax), %r10", throw_npe)
512   //   mov(%rcx), %r9
513   //
514   // we must ensure that there are no instructions between the 'test' and
515   // conditional jump that modify %rax.
516   const unsigned PointerReg = MBP.LHS.getReg();
517 
518   assert(MBP.ConditionDef->getParent() ==  &MBB && "Should be in basic block");
519 
520   for (auto I = MBB.rbegin(); MBP.ConditionDef != &*I; ++I)
521     if (I->modifiesRegister(PointerReg, TRI))
522       return false;
523 
524   // Starting with a code fragment like:
525   //
526   //   test %rax, %rax
527   //   jne LblNotNull
528   //
529   //  LblNull:
530   //   callq throw_NullPointerException
531   //
532   //  LblNotNull:
533   //   Inst0
534   //   Inst1
535   //   ...
536   //   Def = Load (%rax + <offset>)
537   //   ...
538   //
539   //
540   // we want to end up with
541   //
542   //   Def = FaultingLoad (%rax + <offset>), LblNull
543   //   jmp LblNotNull ;; explicit or fallthrough
544   //
545   //  LblNotNull:
546   //   Inst0
547   //   Inst1
548   //   ...
549   //
550   //  LblNull:
551   //   callq throw_NullPointerException
552   //
553   //
554   // To see why this is legal, consider the two possibilities:
555   //
556   //  1. %rax is null: since we constrain <offset> to be less than PageSize, the
557   //     load instruction dereferences the null page, causing a segmentation
558   //     fault.
559   //
560   //  2. %rax is not null: in this case we know that the load cannot fault, as
561   //     otherwise the load would've faulted in the original program too and the
562   //     original program would've been undefined.
563   //
564   // This reasoning cannot be extended to justify hoisting through arbitrary
565   // control flow.  For instance, in the example below (in pseudo-C)
566   //
567   //    if (ptr == null) { throw_npe(); unreachable; }
568   //    if (some_cond) { return 42; }
569   //    v = ptr->field;  // LD
570   //    ...
571   //
572   // we cannot (without code duplication) use the load marked "LD" to null check
573   // ptr -- clause (2) above does not apply in this case.  In the above program
574   // the safety of ptr->field can be dependent on some_cond; and, for instance,
575   // ptr could be some non-null invalid reference that never gets loaded from
576   // because some_cond is always true.
577 
578   SmallVector<MachineInstr *, 8> InstsSeenSoFar;
579 
580   for (auto &MI : *NotNullSucc) {
581     if (!canHandle(&MI) || InstsSeenSoFar.size() >= MaxInstsToConsider)
582       return false;
583 
584     MachineInstr *Dependence;
585     SuitabilityResult SR = isSuitableMemoryOp(MI, PointerReg, InstsSeenSoFar);
586     if (SR == SR_Impossible)
587       return false;
588     if (SR == SR_Suitable &&
589         canHoistInst(&MI, PointerReg, InstsSeenSoFar, NullSucc, Dependence)) {
590       NullCheckList.emplace_back(&MI, MBP.ConditionDef, &MBB, NotNullSucc,
591                                  NullSucc, Dependence);
592       return true;
593     }
594 
595     // If MI re-defines the PointerReg then we cannot move further.
596     if (llvm::any_of(MI.operands(), [&](MachineOperand &MO) {
597           return MO.isReg() && MO.getReg() && MO.isDef() &&
598                  TRI->regsOverlap(MO.getReg(), PointerReg);
599         }))
600       return false;
601     InstsSeenSoFar.push_back(&MI);
602   }
603 
604   return false;
605 }
606 
607 /// Wrap a machine instruction, MI, into a FAULTING machine instruction.
608 /// The FAULTING instruction does the same load/store as MI
609 /// (defining the same register), and branches to HandlerMBB if the mem access
610 /// faults.  The FAULTING instruction is inserted at the end of MBB.
611 MachineInstr *ImplicitNullChecks::insertFaultingInstr(
612     MachineInstr *MI, MachineBasicBlock *MBB, MachineBasicBlock *HandlerMBB) {
613   const unsigned NoRegister = 0; // Guaranteed to be the NoRegister value for
614                                  // all targets.
615 
616   DebugLoc DL;
617   unsigned NumDefs = MI->getDesc().getNumDefs();
618   assert(NumDefs <= 1 && "other cases unhandled!");
619 
620   unsigned DefReg = NoRegister;
621   if (NumDefs != 0) {
622     DefReg = MI->getOperand(0).getReg();
623     assert(NumDefs == 1 && "expected exactly one def!");
624   }
625 
626   FaultMaps::FaultKind FK;
627   if (MI->mayLoad())
628     FK =
629         MI->mayStore() ? FaultMaps::FaultingLoadStore : FaultMaps::FaultingLoad;
630   else
631     FK = FaultMaps::FaultingStore;
632 
633   auto MIB = BuildMI(MBB, DL, TII->get(TargetOpcode::FAULTING_OP), DefReg)
634                  .addImm(FK)
635                  .addMBB(HandlerMBB)
636                  .addImm(MI->getOpcode());
637 
638   for (auto &MO : MI->uses()) {
639     if (MO.isReg()) {
640       MachineOperand NewMO = MO;
641       if (MO.isUse()) {
642         NewMO.setIsKill(false);
643       } else {
644         assert(MO.isDef() && "Expected def or use");
645         NewMO.setIsDead(false);
646       }
647       MIB.add(NewMO);
648     } else {
649       MIB.add(MO);
650     }
651   }
652 
653   MIB.setMemRefs(MI->memoperands());
654 
655   return MIB;
656 }
657 
658 /// Rewrite the null checks in NullCheckList into implicit null checks.
659 void ImplicitNullChecks::rewriteNullChecks(
660     ArrayRef<ImplicitNullChecks::NullCheck> NullCheckList) {
661   DebugLoc DL;
662 
663   for (auto &NC : NullCheckList) {
664     // Remove the conditional branch dependent on the null check.
665     unsigned BranchesRemoved = TII->removeBranch(*NC.getCheckBlock());
666     (void)BranchesRemoved;
667     assert(BranchesRemoved > 0 && "expected at least one branch!");
668 
669     if (auto *DepMI = NC.getOnlyDependency()) {
670       DepMI->removeFromParent();
671       NC.getCheckBlock()->insert(NC.getCheckBlock()->end(), DepMI);
672     }
673 
674     // Insert a faulting instruction where the conditional branch was
675     // originally. We check earlier ensures that this bit of code motion
676     // is legal.  We do not touch the successors list for any basic block
677     // since we haven't changed control flow, we've just made it implicit.
678     MachineInstr *FaultingInstr = insertFaultingInstr(
679         NC.getMemOperation(), NC.getCheckBlock(), NC.getNullSucc());
680     // Now the values defined by MemOperation, if any, are live-in of
681     // the block of MemOperation.
682     // The original operation may define implicit-defs alongside
683     // the value.
684     MachineBasicBlock *MBB = NC.getMemOperation()->getParent();
685     for (const MachineOperand &MO : FaultingInstr->operands()) {
686       if (!MO.isReg() || !MO.isDef())
687         continue;
688       unsigned Reg = MO.getReg();
689       if (!Reg || MBB->isLiveIn(Reg))
690         continue;
691       MBB->addLiveIn(Reg);
692     }
693 
694     if (auto *DepMI = NC.getOnlyDependency()) {
695       for (auto &MO : DepMI->operands()) {
696         if (!MO.isReg() || !MO.getReg() || !MO.isDef())
697           continue;
698         if (!NC.getNotNullSucc()->isLiveIn(MO.getReg()))
699           NC.getNotNullSucc()->addLiveIn(MO.getReg());
700       }
701     }
702 
703     NC.getMemOperation()->eraseFromParent();
704     NC.getCheckOperation()->eraseFromParent();
705 
706     // Insert an *unconditional* branch to not-null successor.
707     TII->insertBranch(*NC.getCheckBlock(), NC.getNotNullSucc(), nullptr,
708                       /*Cond=*/None, DL);
709 
710     NumImplicitNullChecks++;
711   }
712 }
713 
714 char ImplicitNullChecks::ID = 0;
715 
716 char &llvm::ImplicitNullChecksID = ImplicitNullChecks::ID;
717 
718 INITIALIZE_PASS_BEGIN(ImplicitNullChecks, DEBUG_TYPE,
719                       "Implicit null checks", false, false)
720 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
721 INITIALIZE_PASS_END(ImplicitNullChecks, DEBUG_TYPE,
722                     "Implicit null checks", false, false)
723