xref: /src/contrib/llvm-project/llvm/lib/CodeGen/ImplicitNullChecks.cpp (revision 5f757f3ff9144b609b3c433dfd370cc6bdc191ad)
1044eb2f6SDimitry Andric //===- ImplicitNullChecks.cpp - Fold null checks into memory accesses -----===//
23a0822f0SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
63a0822f0SDimitry Andric //
73a0822f0SDimitry Andric //===----------------------------------------------------------------------===//
83a0822f0SDimitry Andric //
93a0822f0SDimitry Andric // This pass turns explicit null checks of the form
103a0822f0SDimitry Andric //
113a0822f0SDimitry Andric //   test %r10, %r10
123a0822f0SDimitry Andric //   je throw_npe
133a0822f0SDimitry Andric //   movl (%r10), %esi
143a0822f0SDimitry Andric //   ...
153a0822f0SDimitry Andric //
163a0822f0SDimitry Andric // to
173a0822f0SDimitry Andric //
183a0822f0SDimitry Andric //   faulting_load_op("movl (%r10), %esi", throw_npe)
193a0822f0SDimitry Andric //   ...
203a0822f0SDimitry Andric //
213a0822f0SDimitry Andric // With the help of a runtime that understands the .fault_maps section,
223a0822f0SDimitry Andric // faulting_load_op branches to throw_npe if executing movl (%r10), %esi incurs
233a0822f0SDimitry Andric // a page fault.
2471d5a254SDimitry Andric // Store and LoadStore are also supported.
253a0822f0SDimitry Andric //
263a0822f0SDimitry Andric //===----------------------------------------------------------------------===//
273a0822f0SDimitry Andric 
28044eb2f6SDimitry Andric #include "llvm/ADT/ArrayRef.h"
29044eb2f6SDimitry Andric #include "llvm/ADT/STLExtras.h"
303a0822f0SDimitry Andric #include "llvm/ADT/SmallVector.h"
31ee8648bdSDimitry Andric #include "llvm/ADT/Statistic.h"
3201095a5dSDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
33044eb2f6SDimitry Andric #include "llvm/Analysis/MemoryLocation.h"
3471d5a254SDimitry Andric #include "llvm/CodeGen/FaultMaps.h"
35044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
363a0822f0SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
373a0822f0SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
38044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
393a0822f0SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
407ab83427SDimitry Andric #include "llvm/CodeGen/MachineMemOperand.h"
417ab83427SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
427ab83427SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
43044eb2f6SDimitry Andric #include "llvm/CodeGen/PseudoSourceValue.h"
44044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
45044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h"
46044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
47044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
483a0822f0SDimitry Andric #include "llvm/IR/BasicBlock.h"
49044eb2f6SDimitry Andric #include "llvm/IR/DebugLoc.h"
50dd58ef01SDimitry Andric #include "llvm/IR/LLVMContext.h"
51706b4fc4SDimitry Andric #include "llvm/InitializePasses.h"
52044eb2f6SDimitry Andric #include "llvm/MC/MCInstrDesc.h"
53044eb2f6SDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
54044eb2f6SDimitry Andric #include "llvm/Pass.h"
553a0822f0SDimitry Andric #include "llvm/Support/CommandLine.h"
56044eb2f6SDimitry Andric #include <cassert>
57044eb2f6SDimitry Andric #include <cstdint>
58044eb2f6SDimitry Andric #include <iterator>
593a0822f0SDimitry Andric 
603a0822f0SDimitry Andric using namespace llvm;
613a0822f0SDimitry Andric 
6201095a5dSDimitry Andric static cl::opt<int> PageSize("imp-null-check-page-size",
6301095a5dSDimitry Andric                              cl::desc("The page size of the target in bytes"),
64044eb2f6SDimitry Andric                              cl::init(4096), cl::Hidden);
653a0822f0SDimitry Andric 
66b915e9e0SDimitry Andric static cl::opt<unsigned> MaxInstsToConsider(
67b915e9e0SDimitry Andric     "imp-null-max-insts-to-consider",
68b915e9e0SDimitry Andric     cl::desc("The max number of instructions to consider hoisting loads over "
69b915e9e0SDimitry Andric              "(the algorithm is quadratic over this number)"),
70044eb2f6SDimitry Andric     cl::Hidden, cl::init(8));
71b915e9e0SDimitry Andric 
72ee8648bdSDimitry Andric #define DEBUG_TYPE "implicit-null-checks"
73ee8648bdSDimitry Andric 
74ee8648bdSDimitry Andric STATISTIC(NumImplicitNullChecks,
75ee8648bdSDimitry Andric           "Number of explicit null checks made implicit");
76ee8648bdSDimitry Andric 
773a0822f0SDimitry Andric namespace {
783a0822f0SDimitry Andric 
793a0822f0SDimitry Andric class ImplicitNullChecks : public MachineFunctionPass {
80b915e9e0SDimitry Andric   /// Return true if \c computeDependence can process \p MI.
81b915e9e0SDimitry Andric   static bool canHandle(const MachineInstr *MI);
82b915e9e0SDimitry Andric 
83b915e9e0SDimitry Andric   /// Helper function for \c computeDependence.  Return true if \p A
84b915e9e0SDimitry Andric   /// and \p B do not have any dependences between them, and can be
85b915e9e0SDimitry Andric   /// re-ordered without changing program semantics.
86b915e9e0SDimitry Andric   bool canReorder(const MachineInstr *A, const MachineInstr *B);
87b915e9e0SDimitry Andric 
88b915e9e0SDimitry Andric   /// A data type for representing the result computed by \c
89b915e9e0SDimitry Andric   /// computeDependence.  States whether it is okay to reorder the
90b915e9e0SDimitry Andric   /// instruction passed to \c computeDependence with at most one
91d8e91e46SDimitry Andric   /// dependency.
92b915e9e0SDimitry Andric   struct DependenceResult {
93b915e9e0SDimitry Andric     /// Can we actually re-order \p MI with \p Insts (see \c
94b915e9e0SDimitry Andric     /// computeDependence).
95b915e9e0SDimitry Andric     bool CanReorder;
96b915e9e0SDimitry Andric 
977fa27ce4SDimitry Andric     /// If non-std::nullopt, then an instruction in \p Insts that also must be
98b915e9e0SDimitry Andric     /// hoisted.
99e3b55780SDimitry Andric     std::optional<ArrayRef<MachineInstr *>::iterator> PotentialDependence;
100b915e9e0SDimitry Andric 
DependenceResult__anone418d9300111::ImplicitNullChecks::DependenceResult101b915e9e0SDimitry Andric     /*implicit*/ DependenceResult(
102b915e9e0SDimitry Andric         bool CanReorder,
103e3b55780SDimitry Andric         std::optional<ArrayRef<MachineInstr *>::iterator> PotentialDependence)
104b915e9e0SDimitry Andric         : CanReorder(CanReorder), PotentialDependence(PotentialDependence) {
105b915e9e0SDimitry Andric       assert((!PotentialDependence || CanReorder) &&
106b915e9e0SDimitry Andric              "!CanReorder && PotentialDependence.hasValue() not allowed!");
107b915e9e0SDimitry Andric     }
108b915e9e0SDimitry Andric   };
109b915e9e0SDimitry Andric 
110b915e9e0SDimitry Andric   /// Compute a result for the following question: can \p MI be
111b915e9e0SDimitry Andric   /// re-ordered from after \p Insts to before it.
112b915e9e0SDimitry Andric   ///
113b915e9e0SDimitry Andric   /// \c canHandle should return true for all instructions in \p
114b915e9e0SDimitry Andric   /// Insts.
115b915e9e0SDimitry Andric   DependenceResult computeDependence(const MachineInstr *MI,
116eb11fae6SDimitry Andric                                      ArrayRef<MachineInstr *> Block);
117b915e9e0SDimitry Andric 
1183a0822f0SDimitry Andric   /// Represents one null check that can be made implicit.
11901095a5dSDimitry Andric   class NullCheck {
1203a0822f0SDimitry Andric     // The memory operation the null check can be folded into.
1213a0822f0SDimitry Andric     MachineInstr *MemOperation;
1223a0822f0SDimitry Andric 
1233a0822f0SDimitry Andric     // The instruction actually doing the null check (Ptr != 0).
1243a0822f0SDimitry Andric     MachineInstr *CheckOperation;
1253a0822f0SDimitry Andric 
1263a0822f0SDimitry Andric     // The block the check resides in.
1273a0822f0SDimitry Andric     MachineBasicBlock *CheckBlock;
1283a0822f0SDimitry Andric 
1293a0822f0SDimitry Andric     // The block branched to if the pointer is non-null.
1303a0822f0SDimitry Andric     MachineBasicBlock *NotNullSucc;
1313a0822f0SDimitry Andric 
1323a0822f0SDimitry Andric     // The block branched to if the pointer is null.
1333a0822f0SDimitry Andric     MachineBasicBlock *NullSucc;
1343a0822f0SDimitry Andric 
135eb11fae6SDimitry Andric     // If this is non-null, then MemOperation has a dependency on this
13601095a5dSDimitry Andric     // instruction; and it needs to be hoisted to execute before MemOperation.
13701095a5dSDimitry Andric     MachineInstr *OnlyDependency;
1383a0822f0SDimitry Andric 
13901095a5dSDimitry Andric   public:
NullCheck(MachineInstr * memOperation,MachineInstr * checkOperation,MachineBasicBlock * checkBlock,MachineBasicBlock * notNullSucc,MachineBasicBlock * nullSucc,MachineInstr * onlyDependency)1403a0822f0SDimitry Andric     explicit NullCheck(MachineInstr *memOperation, MachineInstr *checkOperation,
1413a0822f0SDimitry Andric                        MachineBasicBlock *checkBlock,
1423a0822f0SDimitry Andric                        MachineBasicBlock *notNullSucc,
14301095a5dSDimitry Andric                        MachineBasicBlock *nullSucc,
14401095a5dSDimitry Andric                        MachineInstr *onlyDependency)
1453a0822f0SDimitry Andric         : MemOperation(memOperation), CheckOperation(checkOperation),
14601095a5dSDimitry Andric           CheckBlock(checkBlock), NotNullSucc(notNullSucc), NullSucc(nullSucc),
14701095a5dSDimitry Andric           OnlyDependency(onlyDependency) {}
14801095a5dSDimitry Andric 
getMemOperation() const14901095a5dSDimitry Andric     MachineInstr *getMemOperation() const { return MemOperation; }
15001095a5dSDimitry Andric 
getCheckOperation() const15101095a5dSDimitry Andric     MachineInstr *getCheckOperation() const { return CheckOperation; }
15201095a5dSDimitry Andric 
getCheckBlock() const15301095a5dSDimitry Andric     MachineBasicBlock *getCheckBlock() const { return CheckBlock; }
15401095a5dSDimitry Andric 
getNotNullSucc() const15501095a5dSDimitry Andric     MachineBasicBlock *getNotNullSucc() const { return NotNullSucc; }
15601095a5dSDimitry Andric 
getNullSucc() const15701095a5dSDimitry Andric     MachineBasicBlock *getNullSucc() const { return NullSucc; }
15801095a5dSDimitry Andric 
getOnlyDependency() const15901095a5dSDimitry Andric     MachineInstr *getOnlyDependency() const { return OnlyDependency; }
1603a0822f0SDimitry Andric   };
1613a0822f0SDimitry Andric 
1623a0822f0SDimitry Andric   const TargetInstrInfo *TII = nullptr;
1633a0822f0SDimitry Andric   const TargetRegisterInfo *TRI = nullptr;
16401095a5dSDimitry Andric   AliasAnalysis *AA = nullptr;
16571d5a254SDimitry Andric   MachineFrameInfo *MFI = nullptr;
1663a0822f0SDimitry Andric 
1673a0822f0SDimitry Andric   bool analyzeBlockForNullChecks(MachineBasicBlock &MBB,
1683a0822f0SDimitry Andric                                  SmallVectorImpl<NullCheck> &NullCheckList);
16971d5a254SDimitry Andric   MachineInstr *insertFaultingInstr(MachineInstr *MI, MachineBasicBlock *MBB,
17001095a5dSDimitry Andric                                     MachineBasicBlock *HandlerMBB);
1713a0822f0SDimitry Andric   void rewriteNullChecks(ArrayRef<NullCheck> NullCheckList);
1723a0822f0SDimitry Andric 
17371d5a254SDimitry Andric   enum AliasResult {
17471d5a254SDimitry Andric     AR_NoAlias,
17571d5a254SDimitry Andric     AR_MayAlias,
17671d5a254SDimitry Andric     AR_WillAliasEverything
17771d5a254SDimitry Andric   };
178044eb2f6SDimitry Andric 
17971d5a254SDimitry Andric   /// Returns AR_NoAlias if \p MI memory operation does not alias with
18071d5a254SDimitry Andric   /// \p PrevMI, AR_MayAlias if they may alias and AR_WillAliasEverything if
18171d5a254SDimitry Andric   /// they may alias and any further memory operation may alias with \p PrevMI.
182e6d15924SDimitry Andric   AliasResult areMemoryOpsAliased(const MachineInstr &MI,
183e6d15924SDimitry Andric                                   const MachineInstr *PrevMI) const;
18471d5a254SDimitry Andric 
18571d5a254SDimitry Andric   enum SuitabilityResult {
18671d5a254SDimitry Andric     SR_Suitable,
18771d5a254SDimitry Andric     SR_Unsuitable,
18871d5a254SDimitry Andric     SR_Impossible
18971d5a254SDimitry Andric   };
190044eb2f6SDimitry Andric 
19171d5a254SDimitry Andric   /// Return SR_Suitable if \p MI a memory operation that can be used to
19271d5a254SDimitry Andric   /// implicitly null check the value in \p PointerReg, SR_Unsuitable if
19371d5a254SDimitry Andric   /// \p MI cannot be used to null check and SR_Impossible if there is
19471d5a254SDimitry Andric   /// no sense to continue lookup due to any other instruction will not be able
19571d5a254SDimitry Andric   /// to be used. \p PrevInsts is the set of instruction seen since
196b915e9e0SDimitry Andric   /// the explicit null check on \p PointerReg.
197e6d15924SDimitry Andric   SuitabilityResult isSuitableMemoryOp(const MachineInstr &MI,
198e6d15924SDimitry Andric                                        unsigned PointerReg,
199b915e9e0SDimitry Andric                                        ArrayRef<MachineInstr *> PrevInsts);
200b915e9e0SDimitry Andric 
201b60736ecSDimitry Andric   /// Returns true if \p DependenceMI can clobber the liveIns in NullSucc block
202b60736ecSDimitry Andric   /// if it was hoisted to the NullCheck block. This is used by caller
203b60736ecSDimitry Andric   /// canHoistInst to decide if DependenceMI can be hoisted safely.
204b60736ecSDimitry Andric   bool canDependenceHoistingClobberLiveIns(MachineInstr *DependenceMI,
205b60736ecSDimitry Andric                                            MachineBasicBlock *NullSucc);
206b60736ecSDimitry Andric 
207eb11fae6SDimitry Andric   /// Return true if \p FaultingMI can be hoisted from after the
208b915e9e0SDimitry Andric   /// instructions in \p InstsSeenSoFar to before them.  Set \p Dependence to a
209b60736ecSDimitry Andric   /// non-null value if we also need to (and legally can) hoist a dependency.
210b60736ecSDimitry Andric   bool canHoistInst(MachineInstr *FaultingMI,
211b915e9e0SDimitry Andric                     ArrayRef<MachineInstr *> InstsSeenSoFar,
212b915e9e0SDimitry Andric                     MachineBasicBlock *NullSucc, MachineInstr *&Dependence);
213b915e9e0SDimitry Andric 
2143a0822f0SDimitry Andric public:
2153a0822f0SDimitry Andric   static char ID;
2163a0822f0SDimitry Andric 
ImplicitNullChecks()2173a0822f0SDimitry Andric   ImplicitNullChecks() : MachineFunctionPass(ID) {
2183a0822f0SDimitry Andric     initializeImplicitNullChecksPass(*PassRegistry::getPassRegistry());
2193a0822f0SDimitry Andric   }
2203a0822f0SDimitry Andric 
2213a0822f0SDimitry Andric   bool runOnMachineFunction(MachineFunction &MF) override;
222044eb2f6SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const22301095a5dSDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
22401095a5dSDimitry Andric     AU.addRequired<AAResultsWrapperPass>();
22501095a5dSDimitry Andric     MachineFunctionPass::getAnalysisUsage(AU);
22601095a5dSDimitry Andric   }
22701095a5dSDimitry Andric 
getRequiredProperties() const22801095a5dSDimitry Andric   MachineFunctionProperties getRequiredProperties() const override {
22901095a5dSDimitry Andric     return MachineFunctionProperties().set(
230b915e9e0SDimitry Andric         MachineFunctionProperties::Property::NoVRegs);
23101095a5dSDimitry Andric   }
2323a0822f0SDimitry Andric };
233dd58ef01SDimitry Andric 
234044eb2f6SDimitry Andric } // end anonymous namespace
23501095a5dSDimitry Andric 
canHandle(const MachineInstr * MI)236b915e9e0SDimitry Andric bool ImplicitNullChecks::canHandle(const MachineInstr *MI) {
237e6d15924SDimitry Andric   if (MI->isCall() || MI->mayRaiseFPException() ||
238e6d15924SDimitry Andric       MI->hasUnmodeledSideEffects())
239b915e9e0SDimitry Andric     return false;
240b915e9e0SDimitry Andric   auto IsRegMask = [](const MachineOperand &MO) { return MO.isRegMask(); };
241b915e9e0SDimitry Andric   (void)IsRegMask;
242dd58ef01SDimitry Andric 
24377fc4c14SDimitry Andric   assert(llvm::none_of(MI->operands(), IsRegMask) &&
244b915e9e0SDimitry Andric          "Calls were filtered out above!");
245dd58ef01SDimitry Andric 
246b915e9e0SDimitry Andric   auto IsUnordered = [](MachineMemOperand *MMO) { return MMO->isUnordered(); };
247b915e9e0SDimitry Andric   return llvm::all_of(MI->memoperands(), IsUnordered);
248dd58ef01SDimitry Andric }
249dd58ef01SDimitry Andric 
250b915e9e0SDimitry Andric ImplicitNullChecks::DependenceResult
computeDependence(const MachineInstr * MI,ArrayRef<MachineInstr * > Block)251b915e9e0SDimitry Andric ImplicitNullChecks::computeDependence(const MachineInstr *MI,
252b915e9e0SDimitry Andric                                       ArrayRef<MachineInstr *> Block) {
253b915e9e0SDimitry Andric   assert(llvm::all_of(Block, canHandle) && "Check this first!");
254044eb2f6SDimitry Andric   assert(!is_contained(Block, MI) && "Block must be exclusive of MI!");
255dd58ef01SDimitry Andric 
256e3b55780SDimitry Andric   std::optional<ArrayRef<MachineInstr *>::iterator> Dep;
257dd58ef01SDimitry Andric 
258b915e9e0SDimitry Andric   for (auto I = Block.begin(), E = Block.end(); I != E; ++I) {
259b915e9e0SDimitry Andric     if (canReorder(*I, MI))
260dd58ef01SDimitry Andric       continue;
261dd58ef01SDimitry Andric 
262e3b55780SDimitry Andric     if (Dep == std::nullopt) {
263b915e9e0SDimitry Andric       // Found one possible dependency, keep track of it.
264b915e9e0SDimitry Andric       Dep = I;
265b915e9e0SDimitry Andric     } else {
266b915e9e0SDimitry Andric       // We found two dependencies, so bail out.
267e3b55780SDimitry Andric       return {false, std::nullopt};
268dd58ef01SDimitry Andric     }
269dd58ef01SDimitry Andric   }
270dd58ef01SDimitry Andric 
271b915e9e0SDimitry Andric   return {true, Dep};
272b915e9e0SDimitry Andric }
273dd58ef01SDimitry Andric 
canReorder(const MachineInstr * A,const MachineInstr * B)274b915e9e0SDimitry Andric bool ImplicitNullChecks::canReorder(const MachineInstr *A,
275b915e9e0SDimitry Andric                                     const MachineInstr *B) {
276b915e9e0SDimitry Andric   assert(canHandle(A) && canHandle(B) && "Precondition!");
277dd58ef01SDimitry Andric 
278b915e9e0SDimitry Andric   // canHandle makes sure that we _can_ correctly analyze the dependencies
279b915e9e0SDimitry Andric   // between A and B here -- for instance, we should not be dealing with heap
280b915e9e0SDimitry Andric   // load-store dependencies here.
281b915e9e0SDimitry Andric 
282b60736ecSDimitry Andric   for (const auto &MOA : A->operands()) {
283b915e9e0SDimitry Andric     if (!(MOA.isReg() && MOA.getReg()))
28401095a5dSDimitry Andric       continue;
28501095a5dSDimitry Andric 
2861d5ae102SDimitry Andric     Register RegA = MOA.getReg();
287b60736ecSDimitry Andric     for (const auto &MOB : B->operands()) {
288b915e9e0SDimitry Andric       if (!(MOB.isReg() && MOB.getReg()))
28901095a5dSDimitry Andric         continue;
290b915e9e0SDimitry Andric 
2911d5ae102SDimitry Andric       Register RegB = MOB.getReg();
292b915e9e0SDimitry Andric 
29371d5a254SDimitry Andric       if (TRI->regsOverlap(RegA, RegB) && (MOA.isDef() || MOB.isDef()))
29401095a5dSDimitry Andric         return false;
29501095a5dSDimitry Andric     }
296dd58ef01SDimitry Andric   }
297dd58ef01SDimitry Andric 
298dd58ef01SDimitry Andric   return true;
2991a82d4c0SDimitry Andric }
3003a0822f0SDimitry Andric 
runOnMachineFunction(MachineFunction & MF)3013a0822f0SDimitry Andric bool ImplicitNullChecks::runOnMachineFunction(MachineFunction &MF) {
3023a0822f0SDimitry Andric   TII = MF.getSubtarget().getInstrInfo();
3033a0822f0SDimitry Andric   TRI = MF.getRegInfo().getTargetRegisterInfo();
30471d5a254SDimitry Andric   MFI = &MF.getFrameInfo();
30501095a5dSDimitry Andric   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3063a0822f0SDimitry Andric 
3073a0822f0SDimitry Andric   SmallVector<NullCheck, 16> NullCheckList;
3083a0822f0SDimitry Andric 
3093a0822f0SDimitry Andric   for (auto &MBB : MF)
3103a0822f0SDimitry Andric     analyzeBlockForNullChecks(MBB, NullCheckList);
3113a0822f0SDimitry Andric 
3123a0822f0SDimitry Andric   if (!NullCheckList.empty())
3133a0822f0SDimitry Andric     rewriteNullChecks(NullCheckList);
3143a0822f0SDimitry Andric 
3153a0822f0SDimitry Andric   return !NullCheckList.empty();
3163a0822f0SDimitry Andric }
3173a0822f0SDimitry Andric 
31801095a5dSDimitry Andric // Return true if any register aliasing \p Reg is live-in into \p MBB.
AnyAliasLiveIn(const TargetRegisterInfo * TRI,MachineBasicBlock * MBB,unsigned Reg)31901095a5dSDimitry Andric static bool AnyAliasLiveIn(const TargetRegisterInfo *TRI,
32001095a5dSDimitry Andric                            MachineBasicBlock *MBB, unsigned Reg) {
32101095a5dSDimitry Andric   for (MCRegAliasIterator AR(Reg, TRI, /*IncludeSelf*/ true); AR.isValid();
32201095a5dSDimitry Andric        ++AR)
32301095a5dSDimitry Andric     if (MBB->isLiveIn(*AR))
32401095a5dSDimitry Andric       return true;
32501095a5dSDimitry Andric   return false;
32601095a5dSDimitry Andric }
32701095a5dSDimitry Andric 
32871d5a254SDimitry Andric ImplicitNullChecks::AliasResult
areMemoryOpsAliased(const MachineInstr & MI,const MachineInstr * PrevMI) const329e6d15924SDimitry Andric ImplicitNullChecks::areMemoryOpsAliased(const MachineInstr &MI,
330e6d15924SDimitry Andric                                         const MachineInstr *PrevMI) const {
33171d5a254SDimitry Andric   // If it is not memory access, skip the check.
33271d5a254SDimitry Andric   if (!(PrevMI->mayStore() || PrevMI->mayLoad()))
33371d5a254SDimitry Andric     return AR_NoAlias;
33471d5a254SDimitry Andric   // Load-Load may alias
33571d5a254SDimitry Andric   if (!(MI.mayStore() || PrevMI->mayStore()))
33671d5a254SDimitry Andric     return AR_NoAlias;
33771d5a254SDimitry Andric   // We lost info, conservatively alias. If it was store then no sense to
33871d5a254SDimitry Andric   // continue because we won't be able to check against it further.
33971d5a254SDimitry Andric   if (MI.memoperands_empty())
34071d5a254SDimitry Andric     return MI.mayStore() ? AR_WillAliasEverything : AR_MayAlias;
34171d5a254SDimitry Andric   if (PrevMI->memoperands_empty())
34271d5a254SDimitry Andric     return PrevMI->mayStore() ? AR_WillAliasEverything : AR_MayAlias;
34371d5a254SDimitry Andric 
34471d5a254SDimitry Andric   for (MachineMemOperand *MMO1 : MI.memoperands()) {
34571d5a254SDimitry Andric     // MMO1 should have a value due it comes from operation we'd like to use
34671d5a254SDimitry Andric     // as implicit null check.
34771d5a254SDimitry Andric     assert(MMO1->getValue() && "MMO1 should have a Value!");
34871d5a254SDimitry Andric     for (MachineMemOperand *MMO2 : PrevMI->memoperands()) {
34971d5a254SDimitry Andric       if (const PseudoSourceValue *PSV = MMO2->getPseudoValue()) {
35071d5a254SDimitry Andric         if (PSV->mayAlias(MFI))
35171d5a254SDimitry Andric           return AR_MayAlias;
35271d5a254SDimitry Andric         continue;
35371d5a254SDimitry Andric       }
354344a3780SDimitry Andric       if (!AA->isNoAlias(
355b60736ecSDimitry Andric               MemoryLocation::getAfter(MMO1->getValue(), MMO1->getAAInfo()),
356344a3780SDimitry Andric               MemoryLocation::getAfter(MMO2->getValue(), MMO2->getAAInfo())))
35771d5a254SDimitry Andric         return AR_MayAlias;
35871d5a254SDimitry Andric     }
35971d5a254SDimitry Andric   }
36071d5a254SDimitry Andric   return AR_NoAlias;
36171d5a254SDimitry Andric }
36271d5a254SDimitry Andric 
36371d5a254SDimitry Andric ImplicitNullChecks::SuitabilityResult
isSuitableMemoryOp(const MachineInstr & MI,unsigned PointerReg,ArrayRef<MachineInstr * > PrevInsts)364e6d15924SDimitry Andric ImplicitNullChecks::isSuitableMemoryOp(const MachineInstr &MI,
365e6d15924SDimitry Andric                                        unsigned PointerReg,
36671d5a254SDimitry Andric                                        ArrayRef<MachineInstr *> PrevInsts) {
367b60736ecSDimitry Andric   // Implementation restriction for faulting_op insertion
368b60736ecSDimitry Andric   // TODO: This could be relaxed if we find a test case which warrants it.
369b60736ecSDimitry Andric   if (MI.getDesc().getNumDefs() > 1)
37071d5a254SDimitry Andric    return SR_Unsuitable;
371b915e9e0SDimitry Andric 
372b60736ecSDimitry Andric   if (!MI.mayLoadOrStore() || MI.isPredicable())
373b60736ecSDimitry Andric     return SR_Unsuitable;
374b60736ecSDimitry Andric   auto AM = TII->getAddrModeFromMemoryOp(MI, TRI);
375b1c73532SDimitry Andric   if (!AM || AM->Form != ExtAddrMode::Formula::Basic)
376b60736ecSDimitry Andric     return SR_Unsuitable;
377b60736ecSDimitry Andric   auto AddrMode = *AM;
378b60736ecSDimitry Andric   const Register BaseReg = AddrMode.BaseReg, ScaledReg = AddrMode.ScaledReg;
379b60736ecSDimitry Andric   int64_t Displacement = AddrMode.Displacement;
380b60736ecSDimitry Andric 
381b60736ecSDimitry Andric   // We need the base of the memory instruction to be same as the register
382b60736ecSDimitry Andric   // where the null check is performed (i.e. PointerReg).
383b60736ecSDimitry Andric   if (BaseReg != PointerReg && ScaledReg != PointerReg)
384b60736ecSDimitry Andric     return SR_Unsuitable;
385b60736ecSDimitry Andric   const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
386b60736ecSDimitry Andric   unsigned PointerRegSizeInBits = TRI->getRegSizeInBits(PointerReg, MRI);
387b60736ecSDimitry Andric   // Bail out of the sizes of BaseReg, ScaledReg and PointerReg are not the
388b60736ecSDimitry Andric   // same.
389b60736ecSDimitry Andric   if ((BaseReg &&
390b60736ecSDimitry Andric        TRI->getRegSizeInBits(BaseReg, MRI) != PointerRegSizeInBits) ||
391b60736ecSDimitry Andric       (ScaledReg &&
392b60736ecSDimitry Andric        TRI->getRegSizeInBits(ScaledReg, MRI) != PointerRegSizeInBits))
393b60736ecSDimitry Andric     return SR_Unsuitable;
394b60736ecSDimitry Andric 
395b60736ecSDimitry Andric   // Returns true if RegUsedInAddr is used for calculating the displacement
396b60736ecSDimitry Andric   // depending on addressing mode. Also calculates the Displacement.
397b60736ecSDimitry Andric   auto CalculateDisplacementFromAddrMode = [&](Register RegUsedInAddr,
398b60736ecSDimitry Andric                                                int64_t Multiplier) {
399b60736ecSDimitry Andric     // The register can be NoRegister, which is defined as zero for all targets.
400b60736ecSDimitry Andric     // Consider instruction of interest as `movq 8(,%rdi,8), %rax`. Here the
401b60736ecSDimitry Andric     // ScaledReg is %rdi, while there is no BaseReg.
402b60736ecSDimitry Andric     if (!RegUsedInAddr)
403b60736ecSDimitry Andric       return false;
404b60736ecSDimitry Andric     assert(Multiplier && "expected to be non-zero!");
405b60736ecSDimitry Andric     MachineInstr *ModifyingMI = nullptr;
406b60736ecSDimitry Andric     for (auto It = std::next(MachineBasicBlock::const_reverse_iterator(&MI));
407b60736ecSDimitry Andric          It != MI.getParent()->rend(); It++) {
408b60736ecSDimitry Andric       const MachineInstr *CurrMI = &*It;
409b60736ecSDimitry Andric       if (CurrMI->modifiesRegister(RegUsedInAddr, TRI)) {
410b60736ecSDimitry Andric         ModifyingMI = const_cast<MachineInstr *>(CurrMI);
411b60736ecSDimitry Andric         break;
412b60736ecSDimitry Andric       }
413b60736ecSDimitry Andric     }
414b60736ecSDimitry Andric     if (!ModifyingMI)
415b60736ecSDimitry Andric       return false;
416b60736ecSDimitry Andric     // Check for the const value defined in register by ModifyingMI. This means
417b60736ecSDimitry Andric     // all other previous values for that register has been invalidated.
418b60736ecSDimitry Andric     int64_t ImmVal;
419b60736ecSDimitry Andric     if (!TII->getConstValDefinedInReg(*ModifyingMI, RegUsedInAddr, ImmVal))
420b60736ecSDimitry Andric       return false;
421b60736ecSDimitry Andric     // Calculate the reg size in bits, since this is needed for bailing out in
422b60736ecSDimitry Andric     // case of overflow.
423b60736ecSDimitry Andric     int32_t RegSizeInBits = TRI->getRegSizeInBits(RegUsedInAddr, MRI);
424b60736ecSDimitry Andric     APInt ImmValC(RegSizeInBits, ImmVal, true /*IsSigned*/);
425b60736ecSDimitry Andric     APInt MultiplierC(RegSizeInBits, Multiplier);
426b60736ecSDimitry Andric     assert(MultiplierC.isStrictlyPositive() &&
427b60736ecSDimitry Andric            "expected to be a positive value!");
428b60736ecSDimitry Andric     bool IsOverflow;
429b60736ecSDimitry Andric     // Sign of the product depends on the sign of the ImmVal, since Multiplier
430b60736ecSDimitry Andric     // is always positive.
431b60736ecSDimitry Andric     APInt Product = ImmValC.smul_ov(MultiplierC, IsOverflow);
432b60736ecSDimitry Andric     if (IsOverflow)
433b60736ecSDimitry Andric       return false;
434b60736ecSDimitry Andric     APInt DisplacementC(64, Displacement, true /*isSigned*/);
435b60736ecSDimitry Andric     DisplacementC = Product.sadd_ov(DisplacementC, IsOverflow);
436b60736ecSDimitry Andric     if (IsOverflow)
437b60736ecSDimitry Andric       return false;
438b60736ecSDimitry Andric 
439b60736ecSDimitry Andric     // We only handle diplacements upto 64 bits wide.
440b60736ecSDimitry Andric     if (DisplacementC.getActiveBits() > 64)
441b60736ecSDimitry Andric       return false;
442b60736ecSDimitry Andric     Displacement = DisplacementC.getSExtValue();
443b60736ecSDimitry Andric     return true;
444b60736ecSDimitry Andric   };
445b60736ecSDimitry Andric 
446b60736ecSDimitry Andric   // If a register used in the address is constant, fold it's effect into the
447b60736ecSDimitry Andric   // displacement for ease of analysis.
448b60736ecSDimitry Andric   bool BaseRegIsConstVal = false, ScaledRegIsConstVal = false;
449b60736ecSDimitry Andric   if (CalculateDisplacementFromAddrMode(BaseReg, 1))
450b60736ecSDimitry Andric     BaseRegIsConstVal = true;
451b60736ecSDimitry Andric   if (CalculateDisplacementFromAddrMode(ScaledReg, AddrMode.Scale))
452b60736ecSDimitry Andric     ScaledRegIsConstVal = true;
453b60736ecSDimitry Andric 
454b60736ecSDimitry Andric   // The register which is not null checked should be part of the Displacement
455b60736ecSDimitry Andric   // calculation, otherwise we do not know whether the Displacement is made up
456b60736ecSDimitry Andric   // by some symbolic values.
457b60736ecSDimitry Andric   // This matters because we do not want to incorrectly assume that load from
458b60736ecSDimitry Andric   // falls in the zeroth faulting page in the "sane offset check" below.
459b60736ecSDimitry Andric   if ((BaseReg && BaseReg != PointerReg && !BaseRegIsConstVal) ||
460b60736ecSDimitry Andric       (ScaledReg && ScaledReg != PointerReg && !ScaledRegIsConstVal))
461cfca06d7SDimitry Andric     return SR_Unsuitable;
462cfca06d7SDimitry Andric 
46371d5a254SDimitry Andric   // We want the mem access to be issued at a sane offset from PointerReg,
46471d5a254SDimitry Andric   // so that if PointerReg is null then the access reliably page faults.
465b60736ecSDimitry Andric   if (!(-PageSize < Displacement && Displacement < PageSize))
46671d5a254SDimitry Andric     return SR_Unsuitable;
467b915e9e0SDimitry Andric 
46808bbd35aSDimitry Andric   // Finally, check whether the current memory access aliases with previous one.
46908bbd35aSDimitry Andric   for (auto *PrevMI : PrevInsts) {
47071d5a254SDimitry Andric     AliasResult AR = areMemoryOpsAliased(MI, PrevMI);
47171d5a254SDimitry Andric     if (AR == AR_WillAliasEverything)
47271d5a254SDimitry Andric       return SR_Impossible;
47371d5a254SDimitry Andric     if (AR == AR_MayAlias)
47408bbd35aSDimitry Andric       return SR_Unsuitable;
47571d5a254SDimitry Andric   }
47608bbd35aSDimitry Andric   return SR_Suitable;
477b915e9e0SDimitry Andric }
478b915e9e0SDimitry Andric 
canDependenceHoistingClobberLiveIns(MachineInstr * DependenceMI,MachineBasicBlock * NullSucc)479b60736ecSDimitry Andric bool ImplicitNullChecks::canDependenceHoistingClobberLiveIns(
480b60736ecSDimitry Andric     MachineInstr *DependenceMI, MachineBasicBlock *NullSucc) {
481b60736ecSDimitry Andric   for (const auto &DependenceMO : DependenceMI->operands()) {
482b60736ecSDimitry Andric     if (!(DependenceMO.isReg() && DependenceMO.getReg()))
483b60736ecSDimitry Andric       continue;
484b60736ecSDimitry Andric 
485b60736ecSDimitry Andric     // Make sure that we won't clobber any live ins to the sibling block by
486b60736ecSDimitry Andric     // hoisting Dependency.  For instance, we can't hoist INST to before the
487b60736ecSDimitry Andric     // null check (even if it safe, and does not violate any dependencies in
488b60736ecSDimitry Andric     // the non_null_block) if %rdx is live in to _null_block.
489b60736ecSDimitry Andric     //
490b60736ecSDimitry Andric     //    test %rcx, %rcx
491b60736ecSDimitry Andric     //    je _null_block
492b60736ecSDimitry Andric     //  _non_null_block:
493b60736ecSDimitry Andric     //    %rdx = INST
494b60736ecSDimitry Andric     //    ...
495b60736ecSDimitry Andric     //
496b60736ecSDimitry Andric     // This restriction does not apply to the faulting load inst because in
497b60736ecSDimitry Andric     // case the pointer loaded from is in the null page, the load will not
498b60736ecSDimitry Andric     // semantically execute, and affect machine state.  That is, if the load
499b60736ecSDimitry Andric     // was loading into %rax and it faults, the value of %rax should stay the
500b60736ecSDimitry Andric     // same as it would have been had the load not have executed and we'd have
501b60736ecSDimitry Andric     // branched to NullSucc directly.
502b60736ecSDimitry Andric     if (AnyAliasLiveIn(TRI, NullSucc, DependenceMO.getReg()))
503b60736ecSDimitry Andric       return true;
504b60736ecSDimitry Andric 
505b60736ecSDimitry Andric   }
506b60736ecSDimitry Andric 
507b60736ecSDimitry Andric   // The dependence does not clobber live-ins in NullSucc block.
508b60736ecSDimitry Andric   return false;
509b60736ecSDimitry Andric }
510b60736ecSDimitry Andric 
canHoistInst(MachineInstr * FaultingMI,ArrayRef<MachineInstr * > InstsSeenSoFar,MachineBasicBlock * NullSucc,MachineInstr * & Dependence)51171d5a254SDimitry Andric bool ImplicitNullChecks::canHoistInst(MachineInstr *FaultingMI,
51271d5a254SDimitry Andric                                       ArrayRef<MachineInstr *> InstsSeenSoFar,
51371d5a254SDimitry Andric                                       MachineBasicBlock *NullSucc,
514b915e9e0SDimitry Andric                                       MachineInstr *&Dependence) {
515b915e9e0SDimitry Andric   auto DepResult = computeDependence(FaultingMI, InstsSeenSoFar);
516b915e9e0SDimitry Andric   if (!DepResult.CanReorder)
517b915e9e0SDimitry Andric     return false;
518b915e9e0SDimitry Andric 
519b915e9e0SDimitry Andric   if (!DepResult.PotentialDependence) {
520b915e9e0SDimitry Andric     Dependence = nullptr;
521b915e9e0SDimitry Andric     return true;
522b915e9e0SDimitry Andric   }
523b915e9e0SDimitry Andric 
524b915e9e0SDimitry Andric   auto DependenceItr = *DepResult.PotentialDependence;
525b915e9e0SDimitry Andric   auto *DependenceMI = *DependenceItr;
526b915e9e0SDimitry Andric 
527b915e9e0SDimitry Andric   // We don't want to reason about speculating loads.  Note -- at this point
528b915e9e0SDimitry Andric   // we should have already filtered out all of the other non-speculatable
529b915e9e0SDimitry Andric   // things, like calls and stores.
530044eb2f6SDimitry Andric   // We also do not want to hoist stores because it might change the memory
531044eb2f6SDimitry Andric   // while the FaultingMI may result in faulting.
532b915e9e0SDimitry Andric   assert(canHandle(DependenceMI) && "Should never have reached here!");
533044eb2f6SDimitry Andric   if (DependenceMI->mayLoadOrStore())
534b915e9e0SDimitry Andric     return false;
535b915e9e0SDimitry Andric 
536b60736ecSDimitry Andric   if (canDependenceHoistingClobberLiveIns(DependenceMI, NullSucc))
537b915e9e0SDimitry Andric     return false;
538b915e9e0SDimitry Andric 
539b915e9e0SDimitry Andric   auto DepDepResult =
540b915e9e0SDimitry Andric       computeDependence(DependenceMI, {InstsSeenSoFar.begin(), DependenceItr});
541b915e9e0SDimitry Andric 
542b915e9e0SDimitry Andric   if (!DepDepResult.CanReorder || DepDepResult.PotentialDependence)
543b915e9e0SDimitry Andric     return false;
544b915e9e0SDimitry Andric 
545b915e9e0SDimitry Andric   Dependence = DependenceMI;
546b915e9e0SDimitry Andric   return true;
547b915e9e0SDimitry Andric }
548b915e9e0SDimitry Andric 
5493a0822f0SDimitry Andric /// Analyze MBB to check if its terminating branch can be turned into an
5503a0822f0SDimitry Andric /// implicit null check.  If yes, append a description of the said null check to
5513a0822f0SDimitry Andric /// NullCheckList and return true, else return false.
analyzeBlockForNullChecks(MachineBasicBlock & MBB,SmallVectorImpl<NullCheck> & NullCheckList)5523a0822f0SDimitry Andric bool ImplicitNullChecks::analyzeBlockForNullChecks(
5533a0822f0SDimitry Andric     MachineBasicBlock &MBB, SmallVectorImpl<NullCheck> &NullCheckList) {
554044eb2f6SDimitry Andric   using MachineBranchPredicate = TargetInstrInfo::MachineBranchPredicate;
5553a0822f0SDimitry Andric 
556dd58ef01SDimitry Andric   MDNode *BranchMD = nullptr;
557dd58ef01SDimitry Andric   if (auto *BB = MBB.getBasicBlock())
558dd58ef01SDimitry Andric     BranchMD = BB->getTerminator()->getMetadata(LLVMContext::MD_make_implicit);
559dd58ef01SDimitry Andric 
5601a82d4c0SDimitry Andric   if (!BranchMD)
5611a82d4c0SDimitry Andric     return false;
5621a82d4c0SDimitry Andric 
5633a0822f0SDimitry Andric   MachineBranchPredicate MBP;
5643a0822f0SDimitry Andric 
56501095a5dSDimitry Andric   if (TII->analyzeBranchPredicate(MBB, MBP, true))
5663a0822f0SDimitry Andric     return false;
5673a0822f0SDimitry Andric 
5683a0822f0SDimitry Andric   // Is the predicate comparing an integer to zero?
5693a0822f0SDimitry Andric   if (!(MBP.LHS.isReg() && MBP.RHS.isImm() && MBP.RHS.getImm() == 0 &&
5703a0822f0SDimitry Andric         (MBP.Predicate == MachineBranchPredicate::PRED_NE ||
5713a0822f0SDimitry Andric          MBP.Predicate == MachineBranchPredicate::PRED_EQ)))
5723a0822f0SDimitry Andric     return false;
5733a0822f0SDimitry Andric 
574b60736ecSDimitry Andric   // If there is a separate condition generation instruction, we chose not to
575b60736ecSDimitry Andric   // transform unless we can remove both condition and consuming branch.
576b60736ecSDimitry Andric   if (MBP.ConditionDef && !MBP.SingleUseCondition)
5773a0822f0SDimitry Andric     return false;
5783a0822f0SDimitry Andric 
5793a0822f0SDimitry Andric   MachineBasicBlock *NotNullSucc, *NullSucc;
5803a0822f0SDimitry Andric 
5813a0822f0SDimitry Andric   if (MBP.Predicate == MachineBranchPredicate::PRED_NE) {
5823a0822f0SDimitry Andric     NotNullSucc = MBP.TrueDest;
5833a0822f0SDimitry Andric     NullSucc = MBP.FalseDest;
5843a0822f0SDimitry Andric   } else {
5853a0822f0SDimitry Andric     NotNullSucc = MBP.FalseDest;
5863a0822f0SDimitry Andric     NullSucc = MBP.TrueDest;
5873a0822f0SDimitry Andric   }
5883a0822f0SDimitry Andric 
5893a0822f0SDimitry Andric   // We handle the simplest case for now.  We can potentially do better by using
5903a0822f0SDimitry Andric   // the machine dominator tree.
5913a0822f0SDimitry Andric   if (NotNullSucc->pred_size() != 1)
5923a0822f0SDimitry Andric     return false;
5933a0822f0SDimitry Andric 
594b60736ecSDimitry Andric   const Register PointerReg = MBP.LHS.getReg();
595b60736ecSDimitry Andric 
596b60736ecSDimitry Andric   if (MBP.ConditionDef) {
597eb11fae6SDimitry Andric     // To prevent the invalid transformation of the following code:
598eb11fae6SDimitry Andric     //
599eb11fae6SDimitry Andric     //   mov %rax, %rcx
600eb11fae6SDimitry Andric     //   test %rax, %rax
601eb11fae6SDimitry Andric     //   %rax = ...
602eb11fae6SDimitry Andric     //   je throw_npe
603eb11fae6SDimitry Andric     //   mov(%rcx), %r9
604eb11fae6SDimitry Andric     //   mov(%rax), %r10
605eb11fae6SDimitry Andric     //
606eb11fae6SDimitry Andric     // into:
607eb11fae6SDimitry Andric     //
608eb11fae6SDimitry Andric     //   mov %rax, %rcx
609eb11fae6SDimitry Andric     //   %rax = ....
610eb11fae6SDimitry Andric     //   faulting_load_op("movl (%rax), %r10", throw_npe)
611eb11fae6SDimitry Andric     //   mov(%rcx), %r9
612eb11fae6SDimitry Andric     //
613eb11fae6SDimitry Andric     // we must ensure that there are no instructions between the 'test' and
614eb11fae6SDimitry Andric     // conditional jump that modify %rax.
615b60736ecSDimitry Andric     assert(MBP.ConditionDef->getParent() ==  &MBB &&
616b60736ecSDimitry Andric            "Should be in basic block");
617eb11fae6SDimitry Andric 
618eb11fae6SDimitry Andric     for (auto I = MBB.rbegin(); MBP.ConditionDef != &*I; ++I)
619eb11fae6SDimitry Andric       if (I->modifiesRegister(PointerReg, TRI))
620eb11fae6SDimitry Andric         return false;
621b60736ecSDimitry Andric   }
6223a0822f0SDimitry Andric   // Starting with a code fragment like:
6233a0822f0SDimitry Andric   //
624044eb2f6SDimitry Andric   //   test %rax, %rax
6253a0822f0SDimitry Andric   //   jne LblNotNull
6263a0822f0SDimitry Andric   //
6273a0822f0SDimitry Andric   //  LblNull:
6283a0822f0SDimitry Andric   //   callq throw_NullPointerException
6293a0822f0SDimitry Andric   //
6303a0822f0SDimitry Andric   //  LblNotNull:
631ee8648bdSDimitry Andric   //   Inst0
632ee8648bdSDimitry Andric   //   Inst1
633ee8648bdSDimitry Andric   //   ...
634044eb2f6SDimitry Andric   //   Def = Load (%rax + <offset>)
6353a0822f0SDimitry Andric   //   ...
6363a0822f0SDimitry Andric   //
6373a0822f0SDimitry Andric   //
6383a0822f0SDimitry Andric   // we want to end up with
6393a0822f0SDimitry Andric   //
640044eb2f6SDimitry Andric   //   Def = FaultingLoad (%rax + <offset>), LblNull
6413a0822f0SDimitry Andric   //   jmp LblNotNull ;; explicit or fallthrough
6423a0822f0SDimitry Andric   //
6433a0822f0SDimitry Andric   //  LblNotNull:
644ee8648bdSDimitry Andric   //   Inst0
645ee8648bdSDimitry Andric   //   Inst1
6463a0822f0SDimitry Andric   //   ...
6473a0822f0SDimitry Andric   //
6483a0822f0SDimitry Andric   //  LblNull:
6493a0822f0SDimitry Andric   //   callq throw_NullPointerException
6503a0822f0SDimitry Andric   //
651dd58ef01SDimitry Andric   //
652dd58ef01SDimitry Andric   // To see why this is legal, consider the two possibilities:
653dd58ef01SDimitry Andric   //
654044eb2f6SDimitry Andric   //  1. %rax is null: since we constrain <offset> to be less than PageSize, the
655dd58ef01SDimitry Andric   //     load instruction dereferences the null page, causing a segmentation
656dd58ef01SDimitry Andric   //     fault.
657dd58ef01SDimitry Andric   //
658044eb2f6SDimitry Andric   //  2. %rax is not null: in this case we know that the load cannot fault, as
659dd58ef01SDimitry Andric   //     otherwise the load would've faulted in the original program too and the
660dd58ef01SDimitry Andric   //     original program would've been undefined.
661dd58ef01SDimitry Andric   //
662dd58ef01SDimitry Andric   // This reasoning cannot be extended to justify hoisting through arbitrary
663dd58ef01SDimitry Andric   // control flow.  For instance, in the example below (in pseudo-C)
664dd58ef01SDimitry Andric   //
665dd58ef01SDimitry Andric   //    if (ptr == null) { throw_npe(); unreachable; }
666dd58ef01SDimitry Andric   //    if (some_cond) { return 42; }
667dd58ef01SDimitry Andric   //    v = ptr->field;  // LD
668dd58ef01SDimitry Andric   //    ...
669dd58ef01SDimitry Andric   //
670dd58ef01SDimitry Andric   // we cannot (without code duplication) use the load marked "LD" to null check
671dd58ef01SDimitry Andric   // ptr -- clause (2) above does not apply in this case.  In the above program
672dd58ef01SDimitry Andric   // the safety of ptr->field can be dependent on some_cond; and, for instance,
673dd58ef01SDimitry Andric   // ptr could be some non-null invalid reference that never gets loaded from
674dd58ef01SDimitry Andric   // because some_cond is always true.
6753a0822f0SDimitry Andric 
676b915e9e0SDimitry Andric   SmallVector<MachineInstr *, 8> InstsSeenSoFar;
677ee8648bdSDimitry Andric 
678b915e9e0SDimitry Andric   for (auto &MI : *NotNullSucc) {
679b915e9e0SDimitry Andric     if (!canHandle(&MI) || InstsSeenSoFar.size() >= MaxInstsToConsider)
68001095a5dSDimitry Andric       return false;
68101095a5dSDimitry Andric 
682b915e9e0SDimitry Andric     MachineInstr *Dependence;
68371d5a254SDimitry Andric     SuitabilityResult SR = isSuitableMemoryOp(MI, PointerReg, InstsSeenSoFar);
68471d5a254SDimitry Andric     if (SR == SR_Impossible)
68571d5a254SDimitry Andric       return false;
68671d5a254SDimitry Andric     if (SR == SR_Suitable &&
687b60736ecSDimitry Andric         canHoistInst(&MI, InstsSeenSoFar, NullSucc, Dependence)) {
68801095a5dSDimitry Andric       NullCheckList.emplace_back(&MI, MBP.ConditionDef, &MBB, NotNullSucc,
689b915e9e0SDimitry Andric                                  NullSucc, Dependence);
6903a0822f0SDimitry Andric       return true;
6913a0822f0SDimitry Andric     }
6923a0822f0SDimitry Andric 
693b60736ecSDimitry Andric     // If MI re-defines the PointerReg in a way that changes the value of
694b60736ecSDimitry Andric     // PointerReg if it was null, then we cannot move further.
695b60736ecSDimitry Andric     if (!TII->preservesZeroValueInReg(&MI, PointerReg, TRI))
69608bbd35aSDimitry Andric       return false;
697b915e9e0SDimitry Andric     InstsSeenSoFar.push_back(&MI);
698ee8648bdSDimitry Andric   }
699ee8648bdSDimitry Andric 
7003a0822f0SDimitry Andric   return false;
7013a0822f0SDimitry Andric }
7023a0822f0SDimitry Andric 
70371d5a254SDimitry Andric /// Wrap a machine instruction, MI, into a FAULTING machine instruction.
70471d5a254SDimitry Andric /// The FAULTING instruction does the same load/store as MI
70571d5a254SDimitry Andric /// (defining the same register), and branches to HandlerMBB if the mem access
70671d5a254SDimitry Andric /// faults.  The FAULTING instruction is inserted at the end of MBB.
insertFaultingInstr(MachineInstr * MI,MachineBasicBlock * MBB,MachineBasicBlock * HandlerMBB)70771d5a254SDimitry Andric MachineInstr *ImplicitNullChecks::insertFaultingInstr(
70871d5a254SDimitry Andric     MachineInstr *MI, MachineBasicBlock *MBB, MachineBasicBlock *HandlerMBB) {
709dd58ef01SDimitry Andric   const unsigned NoRegister = 0; // Guaranteed to be the NoRegister value for
710dd58ef01SDimitry Andric                                  // all targets.
711dd58ef01SDimitry Andric 
7123a0822f0SDimitry Andric   DebugLoc DL;
71371d5a254SDimitry Andric   unsigned NumDefs = MI->getDesc().getNumDefs();
714dd58ef01SDimitry Andric   assert(NumDefs <= 1 && "other cases unhandled!");
7153a0822f0SDimitry Andric 
716dd58ef01SDimitry Andric   unsigned DefReg = NoRegister;
717dd58ef01SDimitry Andric   if (NumDefs != 0) {
718eb11fae6SDimitry Andric     DefReg = MI->getOperand(0).getReg();
719eb11fae6SDimitry Andric     assert(NumDefs == 1 && "expected exactly one def!");
720dd58ef01SDimitry Andric   }
7213a0822f0SDimitry Andric 
72271d5a254SDimitry Andric   FaultMaps::FaultKind FK;
72371d5a254SDimitry Andric   if (MI->mayLoad())
72471d5a254SDimitry Andric     FK =
72571d5a254SDimitry Andric         MI->mayStore() ? FaultMaps::FaultingLoadStore : FaultMaps::FaultingLoad;
72671d5a254SDimitry Andric   else
72771d5a254SDimitry Andric     FK = FaultMaps::FaultingStore;
72871d5a254SDimitry Andric 
72971d5a254SDimitry Andric   auto MIB = BuildMI(MBB, DL, TII->get(TargetOpcode::FAULTING_OP), DefReg)
73071d5a254SDimitry Andric                  .addImm(FK)
73101095a5dSDimitry Andric                  .addMBB(HandlerMBB)
73271d5a254SDimitry Andric                  .addImm(MI->getOpcode());
7333a0822f0SDimitry Andric 
734f382538dSDimitry Andric   for (auto &MO : MI->uses()) {
735f382538dSDimitry Andric     if (MO.isReg()) {
736f382538dSDimitry Andric       MachineOperand NewMO = MO;
737f382538dSDimitry Andric       if (MO.isUse()) {
738f382538dSDimitry Andric         NewMO.setIsKill(false);
739f382538dSDimitry Andric       } else {
740f382538dSDimitry Andric         assert(MO.isDef() && "Expected def or use");
741f382538dSDimitry Andric         NewMO.setIsDead(false);
742f382538dSDimitry Andric       }
743f382538dSDimitry Andric       MIB.add(NewMO);
744f382538dSDimitry Andric     } else {
74571d5a254SDimitry Andric       MIB.add(MO);
746f382538dSDimitry Andric     }
747f382538dSDimitry Andric   }
7483a0822f0SDimitry Andric 
749d8e91e46SDimitry Andric   MIB.setMemRefs(MI->memoperands());
7503a0822f0SDimitry Andric 
7513a0822f0SDimitry Andric   return MIB;
7523a0822f0SDimitry Andric }
7533a0822f0SDimitry Andric 
7543a0822f0SDimitry Andric /// Rewrite the null checks in NullCheckList into implicit null checks.
rewriteNullChecks(ArrayRef<ImplicitNullChecks::NullCheck> NullCheckList)7553a0822f0SDimitry Andric void ImplicitNullChecks::rewriteNullChecks(
7563a0822f0SDimitry Andric     ArrayRef<ImplicitNullChecks::NullCheck> NullCheckList) {
7573a0822f0SDimitry Andric   DebugLoc DL;
7583a0822f0SDimitry Andric 
7594b4fe385SDimitry Andric   for (const auto &NC : NullCheckList) {
7603a0822f0SDimitry Andric     // Remove the conditional branch dependent on the null check.
761b915e9e0SDimitry Andric     unsigned BranchesRemoved = TII->removeBranch(*NC.getCheckBlock());
7623a0822f0SDimitry Andric     (void)BranchesRemoved;
7633a0822f0SDimitry Andric     assert(BranchesRemoved > 0 && "expected at least one branch!");
7643a0822f0SDimitry Andric 
76501095a5dSDimitry Andric     if (auto *DepMI = NC.getOnlyDependency()) {
76601095a5dSDimitry Andric       DepMI->removeFromParent();
76701095a5dSDimitry Andric       NC.getCheckBlock()->insert(NC.getCheckBlock()->end(), DepMI);
76801095a5dSDimitry Andric     }
76901095a5dSDimitry Andric 
77071d5a254SDimitry Andric     // Insert a faulting instruction where the conditional branch was
77171d5a254SDimitry Andric     // originally. We check earlier ensures that this bit of code motion
77271d5a254SDimitry Andric     // is legal.  We do not touch the successors list for any basic block
77371d5a254SDimitry Andric     // since we haven't changed control flow, we've just made it implicit.
77471d5a254SDimitry Andric     MachineInstr *FaultingInstr = insertFaultingInstr(
77501095a5dSDimitry Andric         NC.getMemOperation(), NC.getCheckBlock(), NC.getNullSucc());
77601095a5dSDimitry Andric     // Now the values defined by MemOperation, if any, are live-in of
77701095a5dSDimitry Andric     // the block of MemOperation.
77871d5a254SDimitry Andric     // The original operation may define implicit-defs alongside
77971d5a254SDimitry Andric     // the value.
78001095a5dSDimitry Andric     MachineBasicBlock *MBB = NC.getMemOperation()->getParent();
7817fa27ce4SDimitry Andric     for (const MachineOperand &MO : FaultingInstr->all_defs()) {
7821d5ae102SDimitry Andric       Register Reg = MO.getReg();
78301095a5dSDimitry Andric       if (!Reg || MBB->isLiveIn(Reg))
78401095a5dSDimitry Andric         continue;
78501095a5dSDimitry Andric       MBB->addLiveIn(Reg);
78601095a5dSDimitry Andric     }
78701095a5dSDimitry Andric 
78801095a5dSDimitry Andric     if (auto *DepMI = NC.getOnlyDependency()) {
7897fa27ce4SDimitry Andric       for (auto &MO : DepMI->all_defs()) {
7907fa27ce4SDimitry Andric         if (!MO.getReg() || MO.isDead())
79101095a5dSDimitry Andric           continue;
79201095a5dSDimitry Andric         if (!NC.getNotNullSucc()->isLiveIn(MO.getReg()))
79301095a5dSDimitry Andric           NC.getNotNullSucc()->addLiveIn(MO.getReg());
79401095a5dSDimitry Andric       }
79501095a5dSDimitry Andric     }
79601095a5dSDimitry Andric 
79701095a5dSDimitry Andric     NC.getMemOperation()->eraseFromParent();
798b60736ecSDimitry Andric     if (auto *CheckOp = NC.getCheckOperation())
799b60736ecSDimitry Andric       CheckOp->eraseFromParent();
8003a0822f0SDimitry Andric 
801b60736ecSDimitry Andric     // Insert an *unconditional* branch to not-null successor - we expect
802b60736ecSDimitry Andric     // block placement to remove fallthroughs later.
803b915e9e0SDimitry Andric     TII->insertBranch(*NC.getCheckBlock(), NC.getNotNullSucc(), nullptr,
804e3b55780SDimitry Andric                       /*Cond=*/std::nullopt, DL);
805ee8648bdSDimitry Andric 
806ee8648bdSDimitry Andric     NumImplicitNullChecks++;
8073a0822f0SDimitry Andric   }
8083a0822f0SDimitry Andric }
8093a0822f0SDimitry Andric 
8103a0822f0SDimitry Andric char ImplicitNullChecks::ID = 0;
811044eb2f6SDimitry Andric 
8123a0822f0SDimitry Andric char &llvm::ImplicitNullChecksID = ImplicitNullChecks::ID;
813044eb2f6SDimitry Andric 
814ab44ce3dSDimitry Andric INITIALIZE_PASS_BEGIN(ImplicitNullChecks, DEBUG_TYPE,
8153a0822f0SDimitry Andric                       "Implicit null checks", false, false)
81601095a5dSDimitry Andric INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
817ab44ce3dSDimitry Andric INITIALIZE_PASS_END(ImplicitNullChecks, DEBUG_TYPE,
8183a0822f0SDimitry Andric                     "Implicit null checks", false, false)
819