blob: 0440555342872e0e6db3214fe18cc91b3961e5b4 [file] [log] [blame]
Sanjoy Das69fad072015-06-15 18:44:27 +00001//===-- 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
Sanjoy Dasb7718452015-07-09 20:13:25 +000028#include "llvm/ADT/DenseSet.h"
Sanjoy Das69fad072015-06-15 18:44:27 +000029#include "llvm/ADT/SmallVector.h"
Sanjoy Das8ee6a302015-07-06 23:32:10 +000030#include "llvm/ADT/Statistic.h"
Sanjoy Dase57bf682016-06-22 22:16:51 +000031#include "llvm/Analysis/AliasAnalysis.h"
Sanjoy Das69fad072015-06-15 18:44:27 +000032#include "llvm/CodeGen/Passes.h"
33#include "llvm/CodeGen/MachineFunction.h"
Sanjoy Dasb7718452015-07-09 20:13:25 +000034#include "llvm/CodeGen/MachineMemOperand.h"
Sanjoy Das69fad072015-06-15 18:44:27 +000035#include "llvm/CodeGen/MachineOperand.h"
36#include "llvm/CodeGen/MachineFunctionPass.h"
37#include "llvm/CodeGen/MachineInstrBuilder.h"
38#include "llvm/CodeGen/MachineRegisterInfo.h"
39#include "llvm/CodeGen/MachineModuleInfo.h"
40#include "llvm/IR/BasicBlock.h"
41#include "llvm/IR/Instruction.h"
Chen Li00038782015-08-04 04:41:34 +000042#include "llvm/IR/LLVMContext.h"
Sanjoy Das69fad072015-06-15 18:44:27 +000043#include "llvm/Support/CommandLine.h"
44#include "llvm/Support/Debug.h"
45#include "llvm/Target/TargetSubtargetInfo.h"
46#include "llvm/Target/TargetInstrInfo.h"
47
48using namespace llvm;
49
Chad Rosierc27a18f2016-03-09 16:00:35 +000050static cl::opt<int> PageSize("imp-null-check-page-size",
51 cl::desc("The page size of the target in bytes"),
52 cl::init(4096));
Sanjoy Das69fad072015-06-15 18:44:27 +000053
Sanjoy Das9a129802016-12-23 00:41:21 +000054static cl::opt<unsigned> MaxInstsToConsider(
55 "imp-null-max-insts-to-consider",
56 cl::desc("The max number of instructions to consider hoisting loads over "
57 "(the algorithm is quadratic over this number)"),
58 cl::init(8));
59
Sanjoy Das8ee6a302015-07-06 23:32:10 +000060#define DEBUG_TYPE "implicit-null-checks"
61
62STATISTIC(NumImplicitNullChecks,
63 "Number of explicit null checks made implicit");
64
Sanjoy Das69fad072015-06-15 18:44:27 +000065namespace {
66
67class ImplicitNullChecks : public MachineFunctionPass {
Sanjoy Das9a129802016-12-23 00:41:21 +000068 /// Return true if \c computeDependence can process \p MI.
69 static bool canHandle(const MachineInstr *MI);
70
71 /// Helper function for \c computeDependence. Return true if \p A
72 /// and \p B do not have any dependences between them, and can be
73 /// re-ordered without changing program semantics.
74 bool canReorder(const MachineInstr *A, const MachineInstr *B);
75
76 /// A data type for representing the result computed by \c
77 /// computeDependence. States whether it is okay to reorder the
78 /// instruction passed to \c computeDependence with at most one
79 /// depednency.
80 struct DependenceResult {
81 /// Can we actually re-order \p MI with \p Insts (see \c
82 /// computeDependence).
83 bool CanReorder;
84
85 /// If non-None, then an instruction in \p Insts that also must be
86 /// hoisted.
87 Optional<ArrayRef<MachineInstr *>::iterator> PotentialDependence;
88
89 /*implicit*/ DependenceResult(
90 bool CanReorder,
91 Optional<ArrayRef<MachineInstr *>::iterator> PotentialDependence)
92 : CanReorder(CanReorder), PotentialDependence(PotentialDependence) {
93 assert((!PotentialDependence || CanReorder) &&
94 "!CanReorder && PotentialDependence.hasValue() not allowed!");
95 }
96 };
97
98 /// Compute a result for the following question: can \p MI be
99 /// re-ordered from after \p Insts to before it.
100 ///
101 /// \c canHandle should return true for all instructions in \p
102 /// Insts.
103 DependenceResult computeDependence(const MachineInstr *MI,
104 ArrayRef<MachineInstr *> Insts);
105
Sanjoy Das69fad072015-06-15 18:44:27 +0000106 /// Represents one null check that can be made implicit.
Sanjoy Dase173b9a2016-06-21 02:10:18 +0000107 class NullCheck {
Sanjoy Das69fad072015-06-15 18:44:27 +0000108 // The memory operation the null check can be folded into.
109 MachineInstr *MemOperation;
110
111 // The instruction actually doing the null check (Ptr != 0).
112 MachineInstr *CheckOperation;
113
114 // The block the check resides in.
115 MachineBasicBlock *CheckBlock;
116
Eric Christopher572e03a2015-06-19 01:53:21 +0000117 // The block branched to if the pointer is non-null.
Sanjoy Das69fad072015-06-15 18:44:27 +0000118 MachineBasicBlock *NotNullSucc;
119
Eric Christopher572e03a2015-06-19 01:53:21 +0000120 // The block branched to if the pointer is null.
Sanjoy Das69fad072015-06-15 18:44:27 +0000121 MachineBasicBlock *NullSucc;
122
Sanjoy Dase57bf682016-06-22 22:16:51 +0000123 // If this is non-null, then MemOperation has a dependency on on this
124 // instruction; and it needs to be hoisted to execute before MemOperation.
125 MachineInstr *OnlyDependency;
126
Sanjoy Dase173b9a2016-06-21 02:10:18 +0000127 public:
Sanjoy Das69fad072015-06-15 18:44:27 +0000128 explicit NullCheck(MachineInstr *memOperation, MachineInstr *checkOperation,
129 MachineBasicBlock *checkBlock,
130 MachineBasicBlock *notNullSucc,
Sanjoy Dase57bf682016-06-22 22:16:51 +0000131 MachineBasicBlock *nullSucc,
132 MachineInstr *onlyDependency)
Sanjoy Das69fad072015-06-15 18:44:27 +0000133 : MemOperation(memOperation), CheckOperation(checkOperation),
Sanjoy Dase57bf682016-06-22 22:16:51 +0000134 CheckBlock(checkBlock), NotNullSucc(notNullSucc), NullSucc(nullSucc),
135 OnlyDependency(onlyDependency) {}
Sanjoy Dase173b9a2016-06-21 02:10:18 +0000136
137 MachineInstr *getMemOperation() const { return MemOperation; }
138
139 MachineInstr *getCheckOperation() const { return CheckOperation; }
140
141 MachineBasicBlock *getCheckBlock() const { return CheckBlock; }
142
143 MachineBasicBlock *getNotNullSucc() const { return NotNullSucc; }
144
145 MachineBasicBlock *getNullSucc() const { return NullSucc; }
Sanjoy Dase57bf682016-06-22 22:16:51 +0000146
147 MachineInstr *getOnlyDependency() const { return OnlyDependency; }
Sanjoy Das69fad072015-06-15 18:44:27 +0000148 };
149
150 const TargetInstrInfo *TII = nullptr;
151 const TargetRegisterInfo *TRI = nullptr;
Sanjoy Dase57bf682016-06-22 22:16:51 +0000152 AliasAnalysis *AA = nullptr;
Sanjoy Das69fad072015-06-15 18:44:27 +0000153 MachineModuleInfo *MMI = nullptr;
154
155 bool analyzeBlockForNullChecks(MachineBasicBlock &MBB,
156 SmallVectorImpl<NullCheck> &NullCheckList);
157 MachineInstr *insertFaultingLoad(MachineInstr *LoadMI, MachineBasicBlock *MBB,
Quentin Colombet4e1d3892016-05-02 22:58:54 +0000158 MachineBasicBlock *HandlerMBB);
Sanjoy Das69fad072015-06-15 18:44:27 +0000159 void rewriteNullChecks(ArrayRef<NullCheck> NullCheckList);
160
Sanjoy Das50fef432016-12-23 00:41:24 +0000161 /// Is \p MI a memory operation that can be used to implicitly null check the
162 /// value in \p PointerReg? \p PrevInsts is the set of instruction seen since
163 /// the explicit null check on \p PointerReg.
164 bool isSuitableMemoryOp(MachineInstr &MI, unsigned PointerReg,
165 ArrayRef<MachineInstr *> PrevInsts);
166
167 /// Return true if \p FaultingMI can be hoisted from after the the
168 /// instructions in \p InstsSeenSoFar to before them. Set \p Dependence to a
169 /// non-null value if we also need to (and legally can) hoist a depedency.
170 bool canHoistLoadInst(MachineInstr *FaultingMI, unsigned PointerReg,
171 ArrayRef<MachineInstr *> InstsSeenSoFar,
172 MachineBasicBlock *NullSucc, MachineInstr *&Dependence);
173
Sanjoy Das69fad072015-06-15 18:44:27 +0000174public:
175 static char ID;
176
177 ImplicitNullChecks() : MachineFunctionPass(ID) {
178 initializeImplicitNullChecksPass(*PassRegistry::getPassRegistry());
179 }
180
181 bool runOnMachineFunction(MachineFunction &MF) override;
Sanjoy Dase57bf682016-06-22 22:16:51 +0000182 void getAnalysisUsage(AnalysisUsage &AU) const override {
183 AU.addRequired<AAResultsWrapperPass>();
184 MachineFunctionPass::getAnalysisUsage(AU);
185 }
Derek Schuffad154c82016-03-28 17:05:30 +0000186
187 MachineFunctionProperties getRequiredProperties() const override {
188 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000189 MachineFunctionProperties::Property::NoVRegs);
Derek Schuffad154c82016-03-28 17:05:30 +0000190 }
Sanjoy Das69fad072015-06-15 18:44:27 +0000191};
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000192
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000193}
194
Sanjoy Das9a129802016-12-23 00:41:21 +0000195bool ImplicitNullChecks::canHandle(const MachineInstr *MI) {
196 if (MI->isCall() || MI->mayStore() || MI->hasUnmodeledSideEffects())
197 return false;
198 auto IsRegMask = [](const MachineOperand &MO) { return MO.isRegMask(); };
199 (void)IsRegMask;
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000200
Sanjoy Das9a129802016-12-23 00:41:21 +0000201 assert(!llvm::any_of(MI->operands(), IsRegMask) &&
202 "Calls were filtered out above!");
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000203
Sanjoy Das9a129802016-12-23 00:41:21 +0000204 auto IsUnordered = [](MachineMemOperand *MMO) { return MMO->isUnordered(); };
205 return llvm::all_of(MI->memoperands(), IsUnordered);
206}
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000207
Sanjoy Das9a129802016-12-23 00:41:21 +0000208ImplicitNullChecks::DependenceResult
209ImplicitNullChecks::computeDependence(const MachineInstr *MI,
210 ArrayRef<MachineInstr *> Block) {
211 assert(llvm::all_of(Block, canHandle) && "Check this first!");
212 assert(!llvm::is_contained(Block, MI) && "Block must be exclusive of MI!");
213
214 Optional<ArrayRef<MachineInstr *>::iterator> Dep;
215
216 for (auto I = Block.begin(), E = Block.end(); I != E; ++I) {
217 if (canReorder(*I, MI))
218 continue;
219
220 if (Dep == None) {
221 // Found one possible dependency, keep track of it.
222 Dep = I;
223 } else {
224 // We found two dependencies, so bail out.
225 return {false, None};
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000226 }
227 }
228
Sanjoy Das9a129802016-12-23 00:41:21 +0000229 return {true, Dep};
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000230}
231
Sanjoy Das9a129802016-12-23 00:41:21 +0000232bool ImplicitNullChecks::canReorder(const MachineInstr *A,
233 const MachineInstr *B) {
234 assert(canHandle(A) && canHandle(B) && "Precondition!");
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000235
Sanjoy Das9a129802016-12-23 00:41:21 +0000236 // canHandle makes sure that we _can_ correctly analyze the dependencies
237 // between A and B here -- for instance, we should not be dealing with heap
238 // load-store dependencies here.
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000239
Sanjoy Das9a129802016-12-23 00:41:21 +0000240 for (auto MOA : A->operands()) {
241 if (!(MOA.isReg() && MOA.getReg()))
242 continue;
Sanjoy Dase57bf682016-06-22 22:16:51 +0000243
Sanjoy Das9a129802016-12-23 00:41:21 +0000244 unsigned RegA = MOA.getReg();
245 for (auto MOB : B->operands()) {
246 if (!(MOB.isReg() && MOB.getReg()))
247 continue;
Sanjoy Dase57bf682016-06-22 22:16:51 +0000248
Sanjoy Das9a129802016-12-23 00:41:21 +0000249 unsigned RegB = MOB.getReg();
Sanjoy Dase57bf682016-06-22 22:16:51 +0000250
Sanjoy Das9a129802016-12-23 00:41:21 +0000251 if (TRI->regsOverlap(RegA, RegB))
252 return false;
Sanjoy Dasedc394f2015-11-12 20:51:44 +0000253 }
254 }
255
256 return true;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000257}
Sanjoy Das69fad072015-06-15 18:44:27 +0000258
259bool ImplicitNullChecks::runOnMachineFunction(MachineFunction &MF) {
260 TII = MF.getSubtarget().getInstrInfo();
261 TRI = MF.getRegInfo().getTargetRegisterInfo();
262 MMI = &MF.getMMI();
Sanjoy Dase57bf682016-06-22 22:16:51 +0000263 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Sanjoy Das69fad072015-06-15 18:44:27 +0000264
265 SmallVector<NullCheck, 16> NullCheckList;
266
267 for (auto &MBB : MF)
268 analyzeBlockForNullChecks(MBB, NullCheckList);
269
270 if (!NullCheckList.empty())
271 rewriteNullChecks(NullCheckList);
272
273 return !NullCheckList.empty();
274}
275
Sanjoy Dase57bf682016-06-22 22:16:51 +0000276// Return true if any register aliasing \p Reg is live-in into \p MBB.
277static bool AnyAliasLiveIn(const TargetRegisterInfo *TRI,
278 MachineBasicBlock *MBB, unsigned Reg) {
279 for (MCRegAliasIterator AR(Reg, TRI, /*IncludeSelf*/ true); AR.isValid();
280 ++AR)
281 if (MBB->isLiveIn(*AR))
282 return true;
283 return false;
284}
285
Sanjoy Das50fef432016-12-23 00:41:24 +0000286bool ImplicitNullChecks::isSuitableMemoryOp(
287 MachineInstr &MI, unsigned PointerReg, ArrayRef<MachineInstr *> PrevInsts) {
288 int64_t Offset;
289 unsigned BaseReg;
290
291 if (!TII->getMemOpBaseRegImmOfs(MI, BaseReg, Offset, TRI) ||
292 BaseReg != PointerReg)
293 return false;
294
295 // We want the load to be issued at a sane offset from PointerReg, so that
296 // if PointerReg is null then the load reliably page faults.
297 if (!(MI.mayLoad() && !MI.isPredicable() && Offset < PageSize))
298 return false;
299
300 // Finally, we need to make sure that the load instruction actually is
301 // loading from PointerReg, and there isn't some re-definition of PointerReg
302 // between the compare and the load.
303 for (auto *PrevMI : PrevInsts)
304 for (auto &PrevMO : PrevMI->operands())
305 if (PrevMO.isReg() && PrevMO.getReg() &&
306 TRI->regsOverlap(PrevMO.getReg(), PointerReg))
307 return false;
308
309 return true;
310}
311
312bool ImplicitNullChecks::canHoistLoadInst(
313 MachineInstr *FaultingMI, unsigned PointerReg,
314 ArrayRef<MachineInstr *> InstsSeenSoFar, MachineBasicBlock *NullSucc,
315 MachineInstr *&Dependence) {
316 auto DepResult = computeDependence(FaultingMI, InstsSeenSoFar);
317 if (!DepResult.CanReorder)
318 return false;
319
320 if (!DepResult.PotentialDependence) {
321 Dependence = nullptr;
322 return true;
323 }
324
325 auto DependenceItr = *DepResult.PotentialDependence;
326 auto *DependenceMI = *DependenceItr;
327
328 // We don't want to reason about speculating loads. Note -- at this point
329 // we should have already filtered out all of the other non-speculatable
330 // things, like calls and stores.
331 assert(canHandle(DependenceMI) && "Should never have reached here!");
332 if (DependenceMI->mayLoad())
333 return false;
334
335 for (auto &DependenceMO : DependenceMI->operands()) {
336 if (!(DependenceMO.isReg() && DependenceMO.getReg()))
337 continue;
338
339 // Make sure that we won't clobber any live ins to the sibling block by
340 // hoisting Dependency. For instance, we can't hoist INST to before the
341 // null check (even if it safe, and does not violate any dependencies in
342 // the non_null_block) if %rdx is live in to _null_block.
343 //
344 // test %rcx, %rcx
345 // je _null_block
346 // _non_null_block:
347 // %rdx<def> = INST
348 // ...
349 //
350 // This restriction does not apply to the faulting load inst because in
351 // case the pointer loaded from is in the null page, the load will not
352 // semantically execute, and affect machine state. That is, if the load
353 // was loading into %rax and it faults, the value of %rax should stay the
354 // same as it would have been had the load not have executed and we'd have
355 // branched to NullSucc directly.
356 if (AnyAliasLiveIn(TRI, NullSucc, DependenceMO.getReg()))
357 return false;
358
359 // The Dependency can't be re-defining the base register -- then we won't
360 // get the memory operation on the address we want. This is already
361 // checked in \c IsSuitableMemoryOp.
362 assert(!TRI->regsOverlap(DependenceMO.getReg(), PointerReg) &&
363 "Should have been checked before!");
364 }
365
366 auto DepDepResult =
367 computeDependence(DependenceMI, {InstsSeenSoFar.begin(), DependenceItr});
368
369 if (!DepDepResult.CanReorder || DepDepResult.PotentialDependence)
370 return false;
371
372 Dependence = DependenceMI;
373 return true;
374}
375
Sanjoy Das69fad072015-06-15 18:44:27 +0000376/// Analyze MBB to check if its terminating branch can be turned into an
377/// implicit null check. If yes, append a description of the said null check to
378/// NullCheckList and return true, else return false.
379bool ImplicitNullChecks::analyzeBlockForNullChecks(
380 MachineBasicBlock &MBB, SmallVectorImpl<NullCheck> &NullCheckList) {
381 typedef TargetInstrInfo::MachineBranchPredicate MachineBranchPredicate;
382
Sanjoy Dase8b81642015-11-12 20:51:49 +0000383 MDNode *BranchMD = nullptr;
384 if (auto *BB = MBB.getBasicBlock())
385 BranchMD = BB->getTerminator()->getMetadata(LLVMContext::MD_make_implicit);
386
Sanjoy Das9c41a932015-06-30 21:22:32 +0000387 if (!BranchMD)
388 return false;
389
Sanjoy Das69fad072015-06-15 18:44:27 +0000390 MachineBranchPredicate MBP;
391
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000392 if (TII->analyzeBranchPredicate(MBB, MBP, true))
Sanjoy Das69fad072015-06-15 18:44:27 +0000393 return false;
394
395 // Is the predicate comparing an integer to zero?
396 if (!(MBP.LHS.isReg() && MBP.RHS.isImm() && MBP.RHS.getImm() == 0 &&
397 (MBP.Predicate == MachineBranchPredicate::PRED_NE ||
398 MBP.Predicate == MachineBranchPredicate::PRED_EQ)))
399 return false;
400
401 // If we cannot erase the test instruction itself, then making the null check
402 // implicit does not buy us much.
403 if (!MBP.SingleUseCondition)
404 return false;
405
406 MachineBasicBlock *NotNullSucc, *NullSucc;
407
408 if (MBP.Predicate == MachineBranchPredicate::PRED_NE) {
409 NotNullSucc = MBP.TrueDest;
410 NullSucc = MBP.FalseDest;
411 } else {
412 NotNullSucc = MBP.FalseDest;
413 NullSucc = MBP.TrueDest;
414 }
415
416 // We handle the simplest case for now. We can potentially do better by using
417 // the machine dominator tree.
418 if (NotNullSucc->pred_size() != 1)
419 return false;
420
421 // Starting with a code fragment like:
422 //
423 // test %RAX, %RAX
424 // jne LblNotNull
425 //
426 // LblNull:
427 // callq throw_NullPointerException
428 //
429 // LblNotNull:
Sanjoy Dasb7718452015-07-09 20:13:25 +0000430 // Inst0
431 // Inst1
432 // ...
Sanjoy Das69fad072015-06-15 18:44:27 +0000433 // Def = Load (%RAX + <offset>)
434 // ...
435 //
436 //
437 // we want to end up with
438 //
Sanjoy Dasac9c5b12015-11-13 08:14:00 +0000439 // Def = FaultingLoad (%RAX + <offset>), LblNull
Sanjoy Das69fad072015-06-15 18:44:27 +0000440 // jmp LblNotNull ;; explicit or fallthrough
441 //
442 // LblNotNull:
Sanjoy Dasb7718452015-07-09 20:13:25 +0000443 // Inst0
444 // Inst1
Sanjoy Das69fad072015-06-15 18:44:27 +0000445 // ...
446 //
447 // LblNull:
448 // callq throw_NullPointerException
449 //
Sanjoy Dasac9c5b12015-11-13 08:14:00 +0000450 //
451 // To see why this is legal, consider the two possibilities:
452 //
453 // 1. %RAX is null: since we constrain <offset> to be less than PageSize, the
454 // load instruction dereferences the null page, causing a segmentation
455 // fault.
456 //
457 // 2. %RAX is not null: in this case we know that the load cannot fault, as
458 // otherwise the load would've faulted in the original program too and the
459 // original program would've been undefined.
460 //
461 // This reasoning cannot be extended to justify hoisting through arbitrary
462 // control flow. For instance, in the example below (in pseudo-C)
463 //
464 // if (ptr == null) { throw_npe(); unreachable; }
465 // if (some_cond) { return 42; }
466 // v = ptr->field; // LD
467 // ...
468 //
469 // we cannot (without code duplication) use the load marked "LD" to null check
470 // ptr -- clause (2) above does not apply in this case. In the above program
471 // the safety of ptr->field can be dependent on some_cond; and, for instance,
472 // ptr could be some non-null invalid reference that never gets loaded from
473 // because some_cond is always true.
Sanjoy Das69fad072015-06-15 18:44:27 +0000474
Sanjoy Das9a129802016-12-23 00:41:21 +0000475 const unsigned PointerReg = MBP.LHS.getReg();
Sanjoy Dasb7718452015-07-09 20:13:25 +0000476
Sanjoy Das9a129802016-12-23 00:41:21 +0000477 SmallVector<MachineInstr *, 8> InstsSeenSoFar;
Sanjoy Dasb7718452015-07-09 20:13:25 +0000478
Sanjoy Das9a129802016-12-23 00:41:21 +0000479 for (auto &MI : *NotNullSucc) {
480 if (!canHandle(&MI) || InstsSeenSoFar.size() >= MaxInstsToConsider)
481 return false;
482
483 MachineInstr *Dependence;
Sanjoy Das50fef432016-12-23 00:41:24 +0000484 if (isSuitableMemoryOp(MI, PointerReg, InstsSeenSoFar) &&
485 canHoistLoadInst(&MI, PointerReg, InstsSeenSoFar, NullSucc,
486 Dependence)) {
Sanjoy Das9a129802016-12-23 00:41:21 +0000487 NullCheckList.emplace_back(&MI, MBP.ConditionDef, &MBB, NotNullSucc,
488 NullSucc, Dependence);
489 return true;
490 }
491
492 InstsSeenSoFar.push_back(&MI);
Sanjoy Dasb7718452015-07-09 20:13:25 +0000493 }
494
Sanjoy Das69fad072015-06-15 18:44:27 +0000495 return false;
496}
497
498/// Wrap a machine load instruction, LoadMI, into a FAULTING_LOAD_OP machine
499/// instruction. The FAULTING_LOAD_OP instruction does the same load as LoadMI
Quentin Colombet4e1d3892016-05-02 22:58:54 +0000500/// (defining the same register), and branches to HandlerMBB if the load
Sanjoy Das69fad072015-06-15 18:44:27 +0000501/// faults. The FAULTING_LOAD_OP instruction is inserted at the end of MBB.
Quentin Colombet4e1d3892016-05-02 22:58:54 +0000502MachineInstr *
503ImplicitNullChecks::insertFaultingLoad(MachineInstr *LoadMI,
504 MachineBasicBlock *MBB,
505 MachineBasicBlock *HandlerMBB) {
Sanjoy Das93d608c2015-07-20 20:31:39 +0000506 const unsigned NoRegister = 0; // Guaranteed to be the NoRegister value for
507 // all targets.
508
Sanjoy Das69fad072015-06-15 18:44:27 +0000509 DebugLoc DL;
510 unsigned NumDefs = LoadMI->getDesc().getNumDefs();
Sanjoy Das93d608c2015-07-20 20:31:39 +0000511 assert(NumDefs <= 1 && "other cases unhandled!");
Sanjoy Das69fad072015-06-15 18:44:27 +0000512
Sanjoy Das93d608c2015-07-20 20:31:39 +0000513 unsigned DefReg = NoRegister;
514 if (NumDefs != 0) {
515 DefReg = LoadMI->defs().begin()->getReg();
516 assert(std::distance(LoadMI->defs().begin(), LoadMI->defs().end()) == 1 &&
517 "expected exactly one def!");
518 }
Sanjoy Das69fad072015-06-15 18:44:27 +0000519
520 auto MIB = BuildMI(MBB, DL, TII->get(TargetOpcode::FAULTING_LOAD_OP), DefReg)
Quentin Colombet4e1d3892016-05-02 22:58:54 +0000521 .addMBB(HandlerMBB)
Sanjoy Das69fad072015-06-15 18:44:27 +0000522 .addImm(LoadMI->getOpcode());
523
524 for (auto &MO : LoadMI->uses())
Diana Picus116bbab2017-01-13 09:58:52 +0000525 MIB.add(MO);
Sanjoy Das69fad072015-06-15 18:44:27 +0000526
527 MIB.setMemRefs(LoadMI->memoperands_begin(), LoadMI->memoperands_end());
528
529 return MIB;
530}
531
532/// Rewrite the null checks in NullCheckList into implicit null checks.
533void ImplicitNullChecks::rewriteNullChecks(
534 ArrayRef<ImplicitNullChecks::NullCheck> NullCheckList) {
535 DebugLoc DL;
536
537 for (auto &NC : NullCheckList) {
Sanjoy Das69fad072015-06-15 18:44:27 +0000538 // Remove the conditional branch dependent on the null check.
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000539 unsigned BranchesRemoved = TII->removeBranch(*NC.getCheckBlock());
Sanjoy Das69fad072015-06-15 18:44:27 +0000540 (void)BranchesRemoved;
541 assert(BranchesRemoved > 0 && "expected at least one branch!");
542
Sanjoy Dase57bf682016-06-22 22:16:51 +0000543 if (auto *DepMI = NC.getOnlyDependency()) {
544 DepMI->removeFromParent();
545 NC.getCheckBlock()->insert(NC.getCheckBlock()->end(), DepMI);
546 }
547
Sanjoy Das69fad072015-06-15 18:44:27 +0000548 // Insert a faulting load where the conditional branch was originally. We
549 // check earlier ensures that this bit of code motion is legal. We do not
550 // touch the successors list for any basic block since we haven't changed
551 // control flow, we've just made it implicit.
Sanjoy Dase173b9a2016-06-21 02:10:18 +0000552 MachineInstr *FaultingLoad = insertFaultingLoad(
553 NC.getMemOperation(), NC.getCheckBlock(), NC.getNullSucc());
Quentin Colombet26dab3a2016-05-03 18:09:06 +0000554 // Now the values defined by MemOperation, if any, are live-in of
555 // the block of MemOperation.
556 // The original load operation may define implicit-defs alongside
557 // the loaded value.
Sanjoy Dase173b9a2016-06-21 02:10:18 +0000558 MachineBasicBlock *MBB = NC.getMemOperation()->getParent();
Quentin Colombet26dab3a2016-05-03 18:09:06 +0000559 for (const MachineOperand &MO : FaultingLoad->operands()) {
560 if (!MO.isReg() || !MO.isDef())
561 continue;
562 unsigned Reg = MO.getReg();
563 if (!Reg || MBB->isLiveIn(Reg))
564 continue;
565 MBB->addLiveIn(Reg);
Quentin Colombet12b69912016-04-27 23:26:40 +0000566 }
Sanjoy Dase57bf682016-06-22 22:16:51 +0000567
568 if (auto *DepMI = NC.getOnlyDependency()) {
569 for (auto &MO : DepMI->operands()) {
570 if (!MO.isReg() || !MO.getReg() || !MO.isDef())
571 continue;
572 if (!NC.getNotNullSucc()->isLiveIn(MO.getReg()))
573 NC.getNotNullSucc()->addLiveIn(MO.getReg());
574 }
575 }
576
Sanjoy Dase173b9a2016-06-21 02:10:18 +0000577 NC.getMemOperation()->eraseFromParent();
578 NC.getCheckOperation()->eraseFromParent();
Sanjoy Das69fad072015-06-15 18:44:27 +0000579
580 // Insert an *unconditional* branch to not-null successor.
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +0000581 TII->insertBranch(*NC.getCheckBlock(), NC.getNotNullSucc(), nullptr,
Sanjoy Dase173b9a2016-06-21 02:10:18 +0000582 /*Cond=*/None, DL);
Sanjoy Das69fad072015-06-15 18:44:27 +0000583
Sanjoy Das8ee6a302015-07-06 23:32:10 +0000584 NumImplicitNullChecks++;
Sanjoy Das69fad072015-06-15 18:44:27 +0000585 }
586}
587
Sanjoy Das9a129802016-12-23 00:41:21 +0000588
Sanjoy Das69fad072015-06-15 18:44:27 +0000589char ImplicitNullChecks::ID = 0;
590char &llvm::ImplicitNullChecksID = ImplicitNullChecks::ID;
591INITIALIZE_PASS_BEGIN(ImplicitNullChecks, "implicit-null-checks",
592 "Implicit null checks", false, false)
Sanjoy Dase57bf682016-06-22 22:16:51 +0000593INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Sanjoy Das69fad072015-06-15 18:44:27 +0000594INITIALIZE_PASS_END(ImplicitNullChecks, "implicit-null-checks",
595 "Implicit null checks", false, false)