1 //===-- ImplicitNullChecks.cpp - Fold null checks into memory accesses ----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass turns explicit null checks of the form
11 //
12 //   test %r10, %r10
13 //   je throw_npe
14 //   movl (%r10), %esi
15 //   ...
16 //
17 // to
18 //
19 //   faulting_load_op("movl (%r10), %esi", throw_npe)
20 //   ...
21 //
22 // With the help of a runtime that understands the .fault_maps section,
23 // faulting_load_op branches to throw_npe if executing movl (%r10), %esi incurs
24 // a page fault.
25 //
26 //===----------------------------------------------------------------------===//
27 
28 #include "llvm/ADT/DenseSet.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/CodeGen/Passes.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineMemOperand.h"
34 #include "llvm/CodeGen/MachineOperand.h"
35 #include "llvm/CodeGen/MachineFunctionPass.h"
36 #include "llvm/CodeGen/MachineInstrBuilder.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/MachineModuleInfo.h"
39 #include "llvm/IR/BasicBlock.h"
40 #include "llvm/IR/Instruction.h"
41 #include "llvm/IR/LLVMContext.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Target/TargetSubtargetInfo.h"
45 #include "llvm/Target/TargetInstrInfo.h"
46 
47 using namespace llvm;
48 
49 static cl::opt<int> PageSize("imp-null-check-page-size",
50                              cl::desc("The page size of the target in bytes"),
51                              cl::init(4096));
52 
53 #define DEBUG_TYPE "implicit-null-checks"
54 
55 STATISTIC(NumImplicitNullChecks,
56           "Number of explicit null checks made implicit");
57 
58 namespace {
59 
60 class ImplicitNullChecks : public MachineFunctionPass {
61   /// Represents one null check that can be made implicit.
62   struct NullCheck {
63     // The memory operation the null check can be folded into.
64     MachineInstr *MemOperation;
65 
66     // The instruction actually doing the null check (Ptr != 0).
67     MachineInstr *CheckOperation;
68 
69     // The block the check resides in.
70     MachineBasicBlock *CheckBlock;
71 
72     // The block branched to if the pointer is non-null.
73     MachineBasicBlock *NotNullSucc;
74 
75     // The block branched to if the pointer is null.
76     MachineBasicBlock *NullSucc;
77 
78     NullCheck()
79         : MemOperation(), CheckOperation(), CheckBlock(), NotNullSucc(),
80           NullSucc() {}
81 
82     explicit NullCheck(MachineInstr *memOperation, MachineInstr *checkOperation,
83                        MachineBasicBlock *checkBlock,
84                        MachineBasicBlock *notNullSucc,
85                        MachineBasicBlock *nullSucc)
86         : MemOperation(memOperation), CheckOperation(checkOperation),
87           CheckBlock(checkBlock), NotNullSucc(notNullSucc), NullSucc(nullSucc) {
88     }
89   };
90 
91   const TargetInstrInfo *TII = nullptr;
92   const TargetRegisterInfo *TRI = nullptr;
93   MachineModuleInfo *MMI = nullptr;
94 
95   bool analyzeBlockForNullChecks(MachineBasicBlock &MBB,
96                                  SmallVectorImpl<NullCheck> &NullCheckList);
97   MachineInstr *insertFaultingLoad(MachineInstr *LoadMI, MachineBasicBlock *MBB,
98                                    MCSymbol *HandlerLabel);
99   void rewriteNullChecks(ArrayRef<NullCheck> NullCheckList);
100 
101 public:
102   static char ID;
103 
104   ImplicitNullChecks() : MachineFunctionPass(ID) {
105     initializeImplicitNullChecksPass(*PassRegistry::getPassRegistry());
106   }
107 
108   bool runOnMachineFunction(MachineFunction &MF) override;
109 };
110 
111 /// \brief Detect re-ordering hazards and dependencies.
112 ///
113 /// This class keeps track of defs and uses, and can be queried if a given
114 /// machine instruction can be re-ordered from after the machine instructions
115 /// seen so far to before them.
116 class HazardDetector {
117   DenseSet<unsigned> RegDefs;
118   DenseSet<unsigned> RegUses;
119   const TargetRegisterInfo &TRI;
120   bool hasSeenClobber;
121 
122 public:
123   explicit HazardDetector(const TargetRegisterInfo &TRI) :
124     TRI(TRI), hasSeenClobber(false) {}
125 
126   /// \brief Make a note of \p MI for later queries to isSafeToHoist.
127   ///
128   /// May clobber this HazardDetector instance.  \see isClobbered.
129   void rememberInstruction(MachineInstr *MI);
130 
131   /// \brief Return true if it is safe to hoist \p MI from after all the
132   /// instructions seen so far (via rememberInstruction) to before it.
133   bool isSafeToHoist(MachineInstr *MI);
134 
135   /// \brief Return true if this instance of HazardDetector has been clobbered
136   /// (i.e. has no more useful information).
137   ///
138   /// A HazardDetecter is clobbered when it sees a construct it cannot
139   /// understand, and it would have to return a conservative answer for all
140   /// future queries.  Having a separate clobbered state lets the client code
141   /// bail early, without making queries about all of the future instructions
142   /// (which would have returned the most conservative answer anyway).
143   ///
144   /// Calling rememberInstruction or isSafeToHoist on a clobbered HazardDetector
145   /// is an error.
146   bool isClobbered() { return hasSeenClobber; }
147 };
148 }
149 
150 
151 void HazardDetector::rememberInstruction(MachineInstr *MI) {
152   assert(!isClobbered() &&
153          "Don't add instructions to a clobbered hazard detector");
154 
155   if (MI->mayStore() || MI->hasUnmodeledSideEffects()) {
156     hasSeenClobber = true;
157     return;
158   }
159 
160   for (auto *MMO : MI->memoperands()) {
161     // Right now we don't want to worry about LLVM's memory model.
162     if (!MMO->isUnordered()) {
163       hasSeenClobber = true;
164       return;
165     }
166   }
167 
168   for (auto &MO : MI->operands()) {
169     if (!MO.isReg() || !MO.getReg())
170       continue;
171 
172     if (MO.isDef())
173       RegDefs.insert(MO.getReg());
174     else
175       RegUses.insert(MO.getReg());
176   }
177 }
178 
179 bool HazardDetector::isSafeToHoist(MachineInstr *MI) {
180   assert(!isClobbered() && "isSafeToHoist cannot do anything useful!");
181 
182   // Right now we don't want to worry about LLVM's memory model.  This can be
183   // made more precise later.
184   for (auto *MMO : MI->memoperands())
185     if (!MMO->isUnordered())
186       return false;
187 
188   for (auto &MO : MI->operands()) {
189     if (MO.isReg() && MO.getReg()) {
190       for (unsigned Reg : RegDefs)
191         if (TRI.regsOverlap(Reg, MO.getReg()))
192           return false;  // We found a write-after-write or read-after-write
193 
194       if (MO.isDef())
195         for (unsigned Reg : RegUses)
196           if (TRI.regsOverlap(Reg, MO.getReg()))
197             return false;  // We found a write-after-read
198     }
199   }
200 
201   return true;
202 }
203 
204 bool ImplicitNullChecks::runOnMachineFunction(MachineFunction &MF) {
205   TII = MF.getSubtarget().getInstrInfo();
206   TRI = MF.getRegInfo().getTargetRegisterInfo();
207   MMI = &MF.getMMI();
208 
209   SmallVector<NullCheck, 16> NullCheckList;
210 
211   for (auto &MBB : MF)
212     analyzeBlockForNullChecks(MBB, NullCheckList);
213 
214   if (!NullCheckList.empty())
215     rewriteNullChecks(NullCheckList);
216 
217   return !NullCheckList.empty();
218 }
219 
220 /// Analyze MBB to check if its terminating branch can be turned into an
221 /// implicit null check.  If yes, append a description of the said null check to
222 /// NullCheckList and return true, else return false.
223 bool ImplicitNullChecks::analyzeBlockForNullChecks(
224     MachineBasicBlock &MBB, SmallVectorImpl<NullCheck> &NullCheckList) {
225   typedef TargetInstrInfo::MachineBranchPredicate MachineBranchPredicate;
226 
227   MDNode *BranchMD = nullptr;
228   if (auto *BB = MBB.getBasicBlock())
229     BranchMD = BB->getTerminator()->getMetadata(LLVMContext::MD_make_implicit);
230 
231   if (!BranchMD)
232     return false;
233 
234   MachineBranchPredicate MBP;
235 
236   if (TII->AnalyzeBranchPredicate(MBB, MBP, true))
237     return false;
238 
239   // Is the predicate comparing an integer to zero?
240   if (!(MBP.LHS.isReg() && MBP.RHS.isImm() && MBP.RHS.getImm() == 0 &&
241         (MBP.Predicate == MachineBranchPredicate::PRED_NE ||
242          MBP.Predicate == MachineBranchPredicate::PRED_EQ)))
243     return false;
244 
245   // If we cannot erase the test instruction itself, then making the null check
246   // implicit does not buy us much.
247   if (!MBP.SingleUseCondition)
248     return false;
249 
250   MachineBasicBlock *NotNullSucc, *NullSucc;
251 
252   if (MBP.Predicate == MachineBranchPredicate::PRED_NE) {
253     NotNullSucc = MBP.TrueDest;
254     NullSucc = MBP.FalseDest;
255   } else {
256     NotNullSucc = MBP.FalseDest;
257     NullSucc = MBP.TrueDest;
258   }
259 
260   // We handle the simplest case for now.  We can potentially do better by using
261   // the machine dominator tree.
262   if (NotNullSucc->pred_size() != 1)
263     return false;
264 
265   // Starting with a code fragment like:
266   //
267   //   test %RAX, %RAX
268   //   jne LblNotNull
269   //
270   //  LblNull:
271   //   callq throw_NullPointerException
272   //
273   //  LblNotNull:
274   //   Inst0
275   //   Inst1
276   //   ...
277   //   Def = Load (%RAX + <offset>)
278   //   ...
279   //
280   //
281   // we want to end up with
282   //
283   //   Def = FaultingLoad (%RAX + <offset>), LblNull
284   //   jmp LblNotNull ;; explicit or fallthrough
285   //
286   //  LblNotNull:
287   //   Inst0
288   //   Inst1
289   //   ...
290   //
291   //  LblNull:
292   //   callq throw_NullPointerException
293   //
294   //
295   // To see why this is legal, consider the two possibilities:
296   //
297   //  1. %RAX is null: since we constrain <offset> to be less than PageSize, the
298   //     load instruction dereferences the null page, causing a segmentation
299   //     fault.
300   //
301   //  2. %RAX is not null: in this case we know that the load cannot fault, as
302   //     otherwise the load would've faulted in the original program too and the
303   //     original program would've been undefined.
304   //
305   // This reasoning cannot be extended to justify hoisting through arbitrary
306   // control flow.  For instance, in the example below (in pseudo-C)
307   //
308   //    if (ptr == null) { throw_npe(); unreachable; }
309   //    if (some_cond) { return 42; }
310   //    v = ptr->field;  // LD
311   //    ...
312   //
313   // we cannot (without code duplication) use the load marked "LD" to null check
314   // ptr -- clause (2) above does not apply in this case.  In the above program
315   // the safety of ptr->field can be dependent on some_cond; and, for instance,
316   // ptr could be some non-null invalid reference that never gets loaded from
317   // because some_cond is always true.
318 
319   unsigned PointerReg = MBP.LHS.getReg();
320 
321   HazardDetector HD(*TRI);
322 
323   for (auto MII = NotNullSucc->begin(), MIE = NotNullSucc->end(); MII != MIE;
324        ++MII) {
325     MachineInstr *MI = &*MII;
326     unsigned BaseReg;
327     int64_t Offset;
328     if (TII->getMemOpBaseRegImmOfs(MI, BaseReg, Offset, TRI))
329       if (MI->mayLoad() && !MI->isPredicable() && BaseReg == PointerReg &&
330           Offset < PageSize && MI->getDesc().getNumDefs() <= 1 &&
331           HD.isSafeToHoist(MI)) {
332         NullCheckList.emplace_back(MI, MBP.ConditionDef, &MBB, NotNullSucc,
333                                    NullSucc);
334         return true;
335       }
336 
337     HD.rememberInstruction(MI);
338     if (HD.isClobbered())
339       return false;
340   }
341 
342   return false;
343 }
344 
345 /// Wrap a machine load instruction, LoadMI, into a FAULTING_LOAD_OP machine
346 /// instruction.  The FAULTING_LOAD_OP instruction does the same load as LoadMI
347 /// (defining the same register), and branches to HandlerLabel if the load
348 /// faults.  The FAULTING_LOAD_OP instruction is inserted at the end of MBB.
349 MachineInstr *ImplicitNullChecks::insertFaultingLoad(MachineInstr *LoadMI,
350                                                      MachineBasicBlock *MBB,
351                                                      MCSymbol *HandlerLabel) {
352   const unsigned NoRegister = 0; // Guaranteed to be the NoRegister value for
353                                  // all targets.
354 
355   DebugLoc DL;
356   unsigned NumDefs = LoadMI->getDesc().getNumDefs();
357   assert(NumDefs <= 1 && "other cases unhandled!");
358 
359   unsigned DefReg = NoRegister;
360   if (NumDefs != 0) {
361     DefReg = LoadMI->defs().begin()->getReg();
362     assert(std::distance(LoadMI->defs().begin(), LoadMI->defs().end()) == 1 &&
363            "expected exactly one def!");
364   }
365 
366   auto MIB = BuildMI(MBB, DL, TII->get(TargetOpcode::FAULTING_LOAD_OP), DefReg)
367                  .addSym(HandlerLabel)
368                  .addImm(LoadMI->getOpcode());
369 
370   for (auto &MO : LoadMI->uses())
371     MIB.addOperand(MO);
372 
373   MIB.setMemRefs(LoadMI->memoperands_begin(), LoadMI->memoperands_end());
374 
375   return MIB;
376 }
377 
378 /// Rewrite the null checks in NullCheckList into implicit null checks.
379 void ImplicitNullChecks::rewriteNullChecks(
380     ArrayRef<ImplicitNullChecks::NullCheck> NullCheckList) {
381   DebugLoc DL;
382 
383   for (auto &NC : NullCheckList) {
384     MCSymbol *HandlerLabel = MMI->getContext().createTempSymbol();
385 
386     // Remove the conditional branch dependent on the null check.
387     unsigned BranchesRemoved = TII->RemoveBranch(*NC.CheckBlock);
388     (void)BranchesRemoved;
389     assert(BranchesRemoved > 0 && "expected at least one branch!");
390 
391     // Insert a faulting load where the conditional branch was originally.  We
392     // check earlier ensures that this bit of code motion is legal.  We do not
393     // touch the successors list for any basic block since we haven't changed
394     // control flow, we've just made it implicit.
395     insertFaultingLoad(NC.MemOperation, NC.CheckBlock, HandlerLabel);
396     NC.MemOperation->eraseFromParent();
397     NC.CheckOperation->eraseFromParent();
398 
399     // Insert an *unconditional* branch to not-null successor.
400     TII->InsertBranch(*NC.CheckBlock, NC.NotNullSucc, nullptr, /*Cond=*/None,
401                       DL);
402 
403     // Emit the HandlerLabel as an EH_LABEL.
404     BuildMI(*NC.NullSucc, NC.NullSucc->begin(), DL,
405             TII->get(TargetOpcode::EH_LABEL)).addSym(HandlerLabel);
406 
407     NumImplicitNullChecks++;
408   }
409 }
410 
411 char ImplicitNullChecks::ID = 0;
412 char &llvm::ImplicitNullChecksID = ImplicitNullChecks::ID;
413 INITIALIZE_PASS_BEGIN(ImplicitNullChecks, "implicit-null-checks",
414                       "Implicit null checks", false, false)
415 INITIALIZE_PASS_END(ImplicitNullChecks, "implicit-null-checks",
416                     "Implicit null checks", false, false)
417