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     // The Dependency can't be re-defining the base register -- then we won't
439     // get the memory operation on the address we want.  This is already
440     // checked in \c IsSuitableMemoryOp.
441     assert(!(DependenceMO.isDef() &&
442              TRI->regsOverlap(DependenceMO.getReg(), PointerReg)) &&
443            "Should have been checked before!");
444   }
445 
446   // The dependence does not clobber live-ins in NullSucc block.
447   return false;
448 }
449 
450 bool ImplicitNullChecks::canHoistInst(MachineInstr *FaultingMI,
451                                       unsigned PointerReg,
452                                       ArrayRef<MachineInstr *> InstsSeenSoFar,
453                                       MachineBasicBlock *NullSucc,
454                                       MachineInstr *&Dependence) {
455   auto DepResult = computeDependence(FaultingMI, InstsSeenSoFar);
456   if (!DepResult.CanReorder)
457     return false;
458 
459   if (!DepResult.PotentialDependence) {
460     Dependence = nullptr;
461     return true;
462   }
463 
464   auto DependenceItr = *DepResult.PotentialDependence;
465   auto *DependenceMI = *DependenceItr;
466 
467   // We don't want to reason about speculating loads.  Note -- at this point
468   // we should have already filtered out all of the other non-speculatable
469   // things, like calls and stores.
470   // We also do not want to hoist stores because it might change the memory
471   // while the FaultingMI may result in faulting.
472   assert(canHandle(DependenceMI) && "Should never have reached here!");
473   if (DependenceMI->mayLoadOrStore())
474     return false;
475 
476   if (canDependenceHoistingClobberLiveIns(DependenceMI, NullSucc, PointerReg))
477     return false;
478 
479   auto DepDepResult =
480       computeDependence(DependenceMI, {InstsSeenSoFar.begin(), DependenceItr});
481 
482   if (!DepDepResult.CanReorder || DepDepResult.PotentialDependence)
483     return false;
484 
485   Dependence = DependenceMI;
486   return true;
487 }
488 
489 /// Analyze MBB to check if its terminating branch can be turned into an
490 /// implicit null check.  If yes, append a description of the said null check to
491 /// NullCheckList and return true, else return false.
492 bool ImplicitNullChecks::analyzeBlockForNullChecks(
493     MachineBasicBlock &MBB, SmallVectorImpl<NullCheck> &NullCheckList) {
494   using MachineBranchPredicate = TargetInstrInfo::MachineBranchPredicate;
495 
496   MDNode *BranchMD = nullptr;
497   if (auto *BB = MBB.getBasicBlock())
498     BranchMD = BB->getTerminator()->getMetadata(LLVMContext::MD_make_implicit);
499 
500   if (!BranchMD)
501     return false;
502 
503   MachineBranchPredicate MBP;
504 
505   if (TII->analyzeBranchPredicate(MBB, MBP, true))
506     return false;
507 
508   // Is the predicate comparing an integer to zero?
509   if (!(MBP.LHS.isReg() && MBP.RHS.isImm() && MBP.RHS.getImm() == 0 &&
510         (MBP.Predicate == MachineBranchPredicate::PRED_NE ||
511          MBP.Predicate == MachineBranchPredicate::PRED_EQ)))
512     return false;
513 
514   // If we cannot erase the test instruction itself, then making the null check
515   // implicit does not buy us much.
516   if (!MBP.SingleUseCondition)
517     return false;
518 
519   MachineBasicBlock *NotNullSucc, *NullSucc;
520 
521   if (MBP.Predicate == MachineBranchPredicate::PRED_NE) {
522     NotNullSucc = MBP.TrueDest;
523     NullSucc = MBP.FalseDest;
524   } else {
525     NotNullSucc = MBP.FalseDest;
526     NullSucc = MBP.TrueDest;
527   }
528 
529   // We handle the simplest case for now.  We can potentially do better by using
530   // the machine dominator tree.
531   if (NotNullSucc->pred_size() != 1)
532     return false;
533 
534   // To prevent the invalid transformation of the following code:
535   //
536   //   mov %rax, %rcx
537   //   test %rax, %rax
538   //   %rax = ...
539   //   je throw_npe
540   //   mov(%rcx), %r9
541   //   mov(%rax), %r10
542   //
543   // into:
544   //
545   //   mov %rax, %rcx
546   //   %rax = ....
547   //   faulting_load_op("movl (%rax), %r10", throw_npe)
548   //   mov(%rcx), %r9
549   //
550   // we must ensure that there are no instructions between the 'test' and
551   // conditional jump that modify %rax.
552   const Register PointerReg = MBP.LHS.getReg();
553 
554   assert(MBP.ConditionDef->getParent() ==  &MBB && "Should be in basic block");
555 
556   for (auto I = MBB.rbegin(); MBP.ConditionDef != &*I; ++I)
557     if (I->modifiesRegister(PointerReg, TRI))
558       return false;
559 
560   // Starting with a code fragment like:
561   //
562   //   test %rax, %rax
563   //   jne LblNotNull
564   //
565   //  LblNull:
566   //   callq throw_NullPointerException
567   //
568   //  LblNotNull:
569   //   Inst0
570   //   Inst1
571   //   ...
572   //   Def = Load (%rax + <offset>)
573   //   ...
574   //
575   //
576   // we want to end up with
577   //
578   //   Def = FaultingLoad (%rax + <offset>), LblNull
579   //   jmp LblNotNull ;; explicit or fallthrough
580   //
581   //  LblNotNull:
582   //   Inst0
583   //   Inst1
584   //   ...
585   //
586   //  LblNull:
587   //   callq throw_NullPointerException
588   //
589   //
590   // To see why this is legal, consider the two possibilities:
591   //
592   //  1. %rax is null: since we constrain <offset> to be less than PageSize, the
593   //     load instruction dereferences the null page, causing a segmentation
594   //     fault.
595   //
596   //  2. %rax is not null: in this case we know that the load cannot fault, as
597   //     otherwise the load would've faulted in the original program too and the
598   //     original program would've been undefined.
599   //
600   // This reasoning cannot be extended to justify hoisting through arbitrary
601   // control flow.  For instance, in the example below (in pseudo-C)
602   //
603   //    if (ptr == null) { throw_npe(); unreachable; }
604   //    if (some_cond) { return 42; }
605   //    v = ptr->field;  // LD
606   //    ...
607   //
608   // we cannot (without code duplication) use the load marked "LD" to null check
609   // ptr -- clause (2) above does not apply in this case.  In the above program
610   // the safety of ptr->field can be dependent on some_cond; and, for instance,
611   // ptr could be some non-null invalid reference that never gets loaded from
612   // because some_cond is always true.
613 
614   SmallVector<MachineInstr *, 8> InstsSeenSoFar;
615 
616   for (auto &MI : *NotNullSucc) {
617     if (!canHandle(&MI) || InstsSeenSoFar.size() >= MaxInstsToConsider)
618       return false;
619 
620     MachineInstr *Dependence;
621     SuitabilityResult SR = isSuitableMemoryOp(MI, PointerReg, InstsSeenSoFar);
622     if (SR == SR_Impossible)
623       return false;
624     if (SR == SR_Suitable &&
625         canHoistInst(&MI, PointerReg, InstsSeenSoFar, NullSucc, Dependence)) {
626       NullCheckList.emplace_back(&MI, MBP.ConditionDef, &MBB, NotNullSucc,
627                                  NullSucc, Dependence);
628       return true;
629     }
630 
631     // If MI re-defines the PointerReg then we cannot move further.
632     if (llvm::any_of(MI.operands(), [&](MachineOperand &MO) {
633           return MO.isReg() && MO.getReg() && MO.isDef() &&
634                  TRI->regsOverlap(MO.getReg(), PointerReg);
635         }))
636       return false;
637     InstsSeenSoFar.push_back(&MI);
638   }
639 
640   return false;
641 }
642 
643 /// Wrap a machine instruction, MI, into a FAULTING machine instruction.
644 /// The FAULTING instruction does the same load/store as MI
645 /// (defining the same register), and branches to HandlerMBB if the mem access
646 /// faults.  The FAULTING instruction is inserted at the end of MBB.
647 MachineInstr *ImplicitNullChecks::insertFaultingInstr(
648     MachineInstr *MI, MachineBasicBlock *MBB, MachineBasicBlock *HandlerMBB) {
649   const unsigned NoRegister = 0; // Guaranteed to be the NoRegister value for
650                                  // all targets.
651 
652   DebugLoc DL;
653   unsigned NumDefs = MI->getDesc().getNumDefs();
654   assert(NumDefs <= 1 && "other cases unhandled!");
655 
656   unsigned DefReg = NoRegister;
657   if (NumDefs != 0) {
658     DefReg = MI->getOperand(0).getReg();
659     assert(NumDefs == 1 && "expected exactly one def!");
660   }
661 
662   FaultMaps::FaultKind FK;
663   if (MI->mayLoad())
664     FK =
665         MI->mayStore() ? FaultMaps::FaultingLoadStore : FaultMaps::FaultingLoad;
666   else
667     FK = FaultMaps::FaultingStore;
668 
669   auto MIB = BuildMI(MBB, DL, TII->get(TargetOpcode::FAULTING_OP), DefReg)
670                  .addImm(FK)
671                  .addMBB(HandlerMBB)
672                  .addImm(MI->getOpcode());
673 
674   for (auto &MO : MI->uses()) {
675     if (MO.isReg()) {
676       MachineOperand NewMO = MO;
677       if (MO.isUse()) {
678         NewMO.setIsKill(false);
679       } else {
680         assert(MO.isDef() && "Expected def or use");
681         NewMO.setIsDead(false);
682       }
683       MIB.add(NewMO);
684     } else {
685       MIB.add(MO);
686     }
687   }
688 
689   MIB.setMemRefs(MI->memoperands());
690 
691   return MIB;
692 }
693 
694 /// Rewrite the null checks in NullCheckList into implicit null checks.
695 void ImplicitNullChecks::rewriteNullChecks(
696     ArrayRef<ImplicitNullChecks::NullCheck> NullCheckList) {
697   DebugLoc DL;
698 
699   for (auto &NC : NullCheckList) {
700     // Remove the conditional branch dependent on the null check.
701     unsigned BranchesRemoved = TII->removeBranch(*NC.getCheckBlock());
702     (void)BranchesRemoved;
703     assert(BranchesRemoved > 0 && "expected at least one branch!");
704 
705     if (auto *DepMI = NC.getOnlyDependency()) {
706       DepMI->removeFromParent();
707       NC.getCheckBlock()->insert(NC.getCheckBlock()->end(), DepMI);
708     }
709 
710     // Insert a faulting instruction where the conditional branch was
711     // originally. We check earlier ensures that this bit of code motion
712     // is legal.  We do not touch the successors list for any basic block
713     // since we haven't changed control flow, we've just made it implicit.
714     MachineInstr *FaultingInstr = insertFaultingInstr(
715         NC.getMemOperation(), NC.getCheckBlock(), NC.getNullSucc());
716     // Now the values defined by MemOperation, if any, are live-in of
717     // the block of MemOperation.
718     // The original operation may define implicit-defs alongside
719     // the value.
720     MachineBasicBlock *MBB = NC.getMemOperation()->getParent();
721     for (const MachineOperand &MO : FaultingInstr->operands()) {
722       if (!MO.isReg() || !MO.isDef())
723         continue;
724       Register Reg = MO.getReg();
725       if (!Reg || MBB->isLiveIn(Reg))
726         continue;
727       MBB->addLiveIn(Reg);
728     }
729 
730     if (auto *DepMI = NC.getOnlyDependency()) {
731       for (auto &MO : DepMI->operands()) {
732         if (!MO.isReg() || !MO.getReg() || !MO.isDef() || MO.isDead())
733           continue;
734         if (!NC.getNotNullSucc()->isLiveIn(MO.getReg()))
735           NC.getNotNullSucc()->addLiveIn(MO.getReg());
736       }
737     }
738 
739     NC.getMemOperation()->eraseFromParent();
740     NC.getCheckOperation()->eraseFromParent();
741 
742     // Insert an *unconditional* branch to not-null successor.
743     TII->insertBranch(*NC.getCheckBlock(), NC.getNotNullSucc(), nullptr,
744                       /*Cond=*/None, DL);
745 
746     NumImplicitNullChecks++;
747   }
748 }
749 
750 char ImplicitNullChecks::ID = 0;
751 
752 char &llvm::ImplicitNullChecksID = ImplicitNullChecks::ID;
753 
754 INITIALIZE_PASS_BEGIN(ImplicitNullChecks, DEBUG_TYPE,
755                       "Implicit null checks", false, false)
756 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
757 INITIALIZE_PASS_END(ImplicitNullChecks, DEBUG_TYPE,
758                     "Implicit null checks", false, false)
759