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