MachineVerifier: Add missing linebreak
[oota-llvm.git] / lib / CodeGen / MachineVerifier.cpp
1 //===-- MachineVerifier.cpp - Machine Code Verifier -----------------------===//
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 // Pass to verify generated machine code. The following is checked:
11 //
12 // Operand counts: All explicit operands must be present.
13 //
14 // Register classes: All physical and virtual register operands must be
15 // compatible with the register class required by the instruction descriptor.
16 //
17 // Register live intervals: Registers must be defined only once, and must be
18 // defined before use.
19 //
20 // The machine code verifier is enabled from LLVMTargetMachine.cpp with the
21 // command-line option -verify-machineinstrs, or by defining the environment
22 // variable LLVM_VERIFY_MACHINEINSTRS to the name of a file that will receive
23 // the verifier errors.
24 //===----------------------------------------------------------------------===//
25
26 #include "llvm/CodeGen/Passes.h"
27 #include "llvm/ADT/DenseSet.h"
28 #include "llvm/ADT/DepthFirstIterator.h"
29 #include "llvm/ADT/SetOperations.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/Analysis/LibCallSemantics.h"
32 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
33 #include "llvm/CodeGen/LiveStackAnalysis.h"
34 #include "llvm/CodeGen/LiveVariables.h"
35 #include "llvm/CodeGen/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineFunctionPass.h"
37 #include "llvm/CodeGen/MachineMemOperand.h"
38 #include "llvm/CodeGen/MachineRegisterInfo.h"
39 #include "llvm/IR/BasicBlock.h"
40 #include "llvm/IR/InlineAsm.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/FileSystem.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include "llvm/Target/TargetInstrInfo.h"
48 #include "llvm/Target/TargetMachine.h"
49 #include "llvm/Target/TargetRegisterInfo.h"
50 #include "llvm/Target/TargetSubtargetInfo.h"
51 using namespace llvm;
52
53 namespace {
54   struct MachineVerifier {
55
56     MachineVerifier(Pass *pass, const char *b) :
57       PASS(pass),
58       Banner(b)
59       {}
60
61     bool runOnMachineFunction(MachineFunction &MF);
62
63     Pass *const PASS;
64     const char *Banner;
65     const MachineFunction *MF;
66     const TargetMachine *TM;
67     const TargetInstrInfo *TII;
68     const TargetRegisterInfo *TRI;
69     const MachineRegisterInfo *MRI;
70
71     unsigned foundErrors;
72
73     typedef SmallVector<unsigned, 16> RegVector;
74     typedef SmallVector<const uint32_t*, 4> RegMaskVector;
75     typedef DenseSet<unsigned> RegSet;
76     typedef DenseMap<unsigned, const MachineInstr*> RegMap;
77     typedef SmallPtrSet<const MachineBasicBlock*, 8> BlockSet;
78
79     const MachineInstr *FirstTerminator;
80     BlockSet FunctionBlocks;
81
82     BitVector regsReserved;
83     RegSet regsLive;
84     RegVector regsDefined, regsDead, regsKilled;
85     RegMaskVector regMasks;
86     RegSet regsLiveInButUnused;
87
88     SlotIndex lastIndex;
89
90     // Add Reg and any sub-registers to RV
91     void addRegWithSubRegs(RegVector &RV, unsigned Reg) {
92       RV.push_back(Reg);
93       if (TargetRegisterInfo::isPhysicalRegister(Reg))
94         for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs)
95           RV.push_back(*SubRegs);
96     }
97
98     struct BBInfo {
99       // Is this MBB reachable from the MF entry point?
100       bool reachable;
101
102       // Vregs that must be live in because they are used without being
103       // defined. Map value is the user.
104       RegMap vregsLiveIn;
105
106       // Regs killed in MBB. They may be defined again, and will then be in both
107       // regsKilled and regsLiveOut.
108       RegSet regsKilled;
109
110       // Regs defined in MBB and live out. Note that vregs passing through may
111       // be live out without being mentioned here.
112       RegSet regsLiveOut;
113
114       // Vregs that pass through MBB untouched. This set is disjoint from
115       // regsKilled and regsLiveOut.
116       RegSet vregsPassed;
117
118       // Vregs that must pass through MBB because they are needed by a successor
119       // block. This set is disjoint from regsLiveOut.
120       RegSet vregsRequired;
121
122       // Set versions of block's predecessor and successor lists.
123       BlockSet Preds, Succs;
124
125       BBInfo() : reachable(false) {}
126
127       // Add register to vregsPassed if it belongs there. Return true if
128       // anything changed.
129       bool addPassed(unsigned Reg) {
130         if (!TargetRegisterInfo::isVirtualRegister(Reg))
131           return false;
132         if (regsKilled.count(Reg) || regsLiveOut.count(Reg))
133           return false;
134         return vregsPassed.insert(Reg).second;
135       }
136
137       // Same for a full set.
138       bool addPassed(const RegSet &RS) {
139         bool changed = false;
140         for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
141           if (addPassed(*I))
142             changed = true;
143         return changed;
144       }
145
146       // Add register to vregsRequired if it belongs there. Return true if
147       // anything changed.
148       bool addRequired(unsigned Reg) {
149         if (!TargetRegisterInfo::isVirtualRegister(Reg))
150           return false;
151         if (regsLiveOut.count(Reg))
152           return false;
153         return vregsRequired.insert(Reg).second;
154       }
155
156       // Same for a full set.
157       bool addRequired(const RegSet &RS) {
158         bool changed = false;
159         for (RegSet::const_iterator I = RS.begin(), E = RS.end(); I != E; ++I)
160           if (addRequired(*I))
161             changed = true;
162         return changed;
163       }
164
165       // Same for a full map.
166       bool addRequired(const RegMap &RM) {
167         bool changed = false;
168         for (RegMap::const_iterator I = RM.begin(), E = RM.end(); I != E; ++I)
169           if (addRequired(I->first))
170             changed = true;
171         return changed;
172       }
173
174       // Live-out registers are either in regsLiveOut or vregsPassed.
175       bool isLiveOut(unsigned Reg) const {
176         return regsLiveOut.count(Reg) || vregsPassed.count(Reg);
177       }
178     };
179
180     // Extra register info per MBB.
181     DenseMap<const MachineBasicBlock*, BBInfo> MBBInfoMap;
182
183     bool isReserved(unsigned Reg) {
184       return Reg < regsReserved.size() && regsReserved.test(Reg);
185     }
186
187     bool isAllocatable(unsigned Reg) {
188       return Reg < TRI->getNumRegs() && MRI->isAllocatable(Reg);
189     }
190
191     // Analysis information if available
192     LiveVariables *LiveVars;
193     LiveIntervals *LiveInts;
194     LiveStacks *LiveStks;
195     SlotIndexes *Indexes;
196
197     void visitMachineFunctionBefore();
198     void visitMachineBasicBlockBefore(const MachineBasicBlock *MBB);
199     void visitMachineBundleBefore(const MachineInstr *MI);
200     void visitMachineInstrBefore(const MachineInstr *MI);
201     void visitMachineOperand(const MachineOperand *MO, unsigned MONum);
202     void visitMachineInstrAfter(const MachineInstr *MI);
203     void visitMachineBundleAfter(const MachineInstr *MI);
204     void visitMachineBasicBlockAfter(const MachineBasicBlock *MBB);
205     void visitMachineFunctionAfter();
206
207     template <typename T> void report(const char *msg, ilist_iterator<T> I) {
208       report(msg, &*I);
209     }
210     void report(const char *msg, const MachineFunction *MF);
211     void report(const char *msg, const MachineBasicBlock *MBB);
212     void report(const char *msg, const MachineInstr *MI);
213     void report(const char *msg, const MachineOperand *MO, unsigned MONum);
214     void report(const char *msg, const MachineFunction *MF,
215                 const LiveInterval &LI);
216     void report(const char *msg, const MachineBasicBlock *MBB,
217                 const LiveInterval &LI);
218     void report(const char *msg, const MachineFunction *MF,
219                 const LiveRange &LR, unsigned Reg, LaneBitmask LaneMask);
220     void report(const char *msg, const MachineBasicBlock *MBB,
221                 const LiveRange &LR, unsigned Reg, LaneBitmask LaneMask);
222
223     void verifyInlineAsm(const MachineInstr *MI);
224
225     void checkLiveness(const MachineOperand *MO, unsigned MONum);
226     void markReachable(const MachineBasicBlock *MBB);
227     void calcRegsPassed();
228     void checkPHIOps(const MachineBasicBlock *MBB);
229
230     void calcRegsRequired();
231     void verifyLiveVariables();
232     void verifyLiveIntervals();
233     void verifyLiveInterval(const LiveInterval&);
234     void verifyLiveRangeValue(const LiveRange&, const VNInfo*, unsigned,
235                               unsigned);
236     void verifyLiveRangeSegment(const LiveRange&,
237                                 const LiveRange::const_iterator I, unsigned,
238                                 unsigned);
239     void verifyLiveRange(const LiveRange&, unsigned, LaneBitmask LaneMask = 0);
240
241     void verifyStackFrame();
242
243     void verifySlotIndexes() const;
244   };
245
246   struct MachineVerifierPass : public MachineFunctionPass {
247     static char ID; // Pass ID, replacement for typeid
248     const std::string Banner;
249
250     MachineVerifierPass(const std::string &banner = nullptr)
251       : MachineFunctionPass(ID), Banner(banner) {
252         initializeMachineVerifierPassPass(*PassRegistry::getPassRegistry());
253       }
254
255     void getAnalysisUsage(AnalysisUsage &AU) const override {
256       AU.setPreservesAll();
257       MachineFunctionPass::getAnalysisUsage(AU);
258     }
259
260     bool runOnMachineFunction(MachineFunction &MF) override {
261       MF.verify(this, Banner.c_str());
262       return false;
263     }
264   };
265
266 }
267
268 char MachineVerifierPass::ID = 0;
269 INITIALIZE_PASS(MachineVerifierPass, "machineverifier",
270                 "Verify generated machine code", false, false)
271
272 FunctionPass *llvm::createMachineVerifierPass(const std::string &Banner) {
273   return new MachineVerifierPass(Banner);
274 }
275
276 void MachineFunction::verify(Pass *p, const char *Banner) const {
277   MachineVerifier(p, Banner)
278     .runOnMachineFunction(const_cast<MachineFunction&>(*this));
279 }
280
281 void MachineVerifier::verifySlotIndexes() const {
282   if (Indexes == nullptr)
283     return;
284
285   // Ensure the IdxMBB list is sorted by slot indexes.
286   SlotIndex Last;
287   for (SlotIndexes::MBBIndexIterator I = Indexes->MBBIndexBegin(),
288        E = Indexes->MBBIndexEnd(); I != E; ++I) {
289     assert(!Last.isValid() || I->first > Last);
290     Last = I->first;
291   }
292 }
293
294 bool MachineVerifier::runOnMachineFunction(MachineFunction &MF) {
295   foundErrors = 0;
296
297   this->MF = &MF;
298   TM = &MF.getTarget();
299   TII = MF.getSubtarget().getInstrInfo();
300   TRI = MF.getSubtarget().getRegisterInfo();
301   MRI = &MF.getRegInfo();
302
303   LiveVars = nullptr;
304   LiveInts = nullptr;
305   LiveStks = nullptr;
306   Indexes = nullptr;
307   if (PASS) {
308     LiveInts = PASS->getAnalysisIfAvailable<LiveIntervals>();
309     // We don't want to verify LiveVariables if LiveIntervals is available.
310     if (!LiveInts)
311       LiveVars = PASS->getAnalysisIfAvailable<LiveVariables>();
312     LiveStks = PASS->getAnalysisIfAvailable<LiveStacks>();
313     Indexes = PASS->getAnalysisIfAvailable<SlotIndexes>();
314   }
315
316   verifySlotIndexes();
317
318   visitMachineFunctionBefore();
319   for (MachineFunction::const_iterator MFI = MF.begin(), MFE = MF.end();
320        MFI!=MFE; ++MFI) {
321     visitMachineBasicBlockBefore(&*MFI);
322     // Keep track of the current bundle header.
323     const MachineInstr *CurBundle = nullptr;
324     // Do we expect the next instruction to be part of the same bundle?
325     bool InBundle = false;
326
327     for (MachineBasicBlock::const_instr_iterator MBBI = MFI->instr_begin(),
328            MBBE = MFI->instr_end(); MBBI != MBBE; ++MBBI) {
329       if (MBBI->getParent() != &*MFI) {
330         report("Bad instruction parent pointer", MFI);
331         errs() << "Instruction: " << *MBBI;
332         continue;
333       }
334
335       // Check for consistent bundle flags.
336       if (InBundle && !MBBI->isBundledWithPred())
337         report("Missing BundledPred flag, "
338                "BundledSucc was set on predecessor",
339                &*MBBI);
340       if (!InBundle && MBBI->isBundledWithPred())
341         report("BundledPred flag is set, "
342                "but BundledSucc not set on predecessor",
343                &*MBBI);
344
345       // Is this a bundle header?
346       if (!MBBI->isInsideBundle()) {
347         if (CurBundle)
348           visitMachineBundleAfter(CurBundle);
349         CurBundle = &*MBBI;
350         visitMachineBundleBefore(CurBundle);
351       } else if (!CurBundle)
352         report("No bundle header", MBBI);
353       visitMachineInstrBefore(&*MBBI);
354       for (unsigned I = 0, E = MBBI->getNumOperands(); I != E; ++I) {
355         const MachineInstr &MI = *MBBI;
356         const MachineOperand &Op = MI.getOperand(I);
357         if (Op.getParent() != &MI) {
358           // Make sure to use correct addOperand / RemoveOperand / ChangeTo
359           // functions when replacing operands of a MachineInstr.
360           report("Instruction has operand with wrong parent set", &MI);
361         }
362
363         visitMachineOperand(&Op, I);
364       }
365
366       visitMachineInstrAfter(&*MBBI);
367
368       // Was this the last bundled instruction?
369       InBundle = MBBI->isBundledWithSucc();
370     }
371     if (CurBundle)
372       visitMachineBundleAfter(CurBundle);
373     if (InBundle)
374       report("BundledSucc flag set on last instruction in block", &MFI->back());
375     visitMachineBasicBlockAfter(&*MFI);
376   }
377   visitMachineFunctionAfter();
378
379   if (foundErrors)
380     report_fatal_error("Found "+Twine(foundErrors)+" machine code errors.");
381
382   // Clean up.
383   regsLive.clear();
384   regsDefined.clear();
385   regsDead.clear();
386   regsKilled.clear();
387   regMasks.clear();
388   regsLiveInButUnused.clear();
389   MBBInfoMap.clear();
390
391   return false;                 // no changes
392 }
393
394 void MachineVerifier::report(const char *msg, const MachineFunction *MF) {
395   assert(MF);
396   errs() << '\n';
397   if (!foundErrors++) {
398     if (Banner)
399       errs() << "# " << Banner << '\n';
400     if (LiveInts != nullptr)
401       LiveInts->print(errs());
402     else
403       MF->print(errs(), Indexes);
404   }
405   errs() << "*** Bad machine code: " << msg << " ***\n"
406       << "- function:    " << MF->getName() << "\n";
407 }
408
409 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB) {
410   assert(MBB);
411   report(msg, MBB->getParent());
412   errs() << "- basic block: BB#" << MBB->getNumber()
413       << ' ' << MBB->getName()
414       << " (" << (const void*)MBB << ')';
415   if (Indexes)
416     errs() << " [" << Indexes->getMBBStartIdx(MBB)
417         << ';' <<  Indexes->getMBBEndIdx(MBB) << ')';
418   errs() << '\n';
419 }
420
421 void MachineVerifier::report(const char *msg, const MachineInstr *MI) {
422   assert(MI);
423   report(msg, MI->getParent());
424   errs() << "- instruction: ";
425   if (Indexes && Indexes->hasIndex(MI))
426     errs() << Indexes->getInstructionIndex(MI) << '\t';
427   MI->print(errs(), /*SkipOpers=*/true);
428   errs() << '\n';
429 }
430
431 void MachineVerifier::report(const char *msg,
432                              const MachineOperand *MO, unsigned MONum) {
433   assert(MO);
434   report(msg, MO->getParent());
435   errs() << "- operand " << MONum << ":   ";
436   MO->print(errs(), TRI);
437   errs() << "\n";
438 }
439
440 void MachineVerifier::report(const char *msg, const MachineFunction *MF,
441                              const LiveInterval &LI) {
442   report(msg, MF);
443   errs() << "- interval:    " << LI << '\n';
444 }
445
446 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB,
447                              const LiveInterval &LI) {
448   report(msg, MBB);
449   errs() << "- interval:    " << LI << '\n';
450 }
451
452 void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB,
453                              const LiveRange &LR, unsigned Reg,
454                              LaneBitmask LaneMask) {
455   report(msg, MBB);
456   errs() << "- liverange:   " << LR << '\n';
457   errs() << "- register:    " << PrintReg(Reg, TRI) << '\n';
458   if (LaneMask != 0)
459     errs() << "- lanemask:    " << PrintLaneMask(LaneMask) << '\n';
460 }
461
462 void MachineVerifier::report(const char *msg, const MachineFunction *MF,
463                              const LiveRange &LR, unsigned Reg,
464                              LaneBitmask LaneMask) {
465   report(msg, MF);
466   errs() << "- liverange:   " << LR << '\n';
467   errs() << "- register:    " << PrintReg(Reg, TRI) << '\n';
468   if (LaneMask != 0)
469     errs() << "- lanemask:    " << PrintLaneMask(LaneMask) << '\n';
470 }
471
472 void MachineVerifier::markReachable(const MachineBasicBlock *MBB) {
473   BBInfo &MInfo = MBBInfoMap[MBB];
474   if (!MInfo.reachable) {
475     MInfo.reachable = true;
476     for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
477            SuE = MBB->succ_end(); SuI != SuE; ++SuI)
478       markReachable(*SuI);
479   }
480 }
481
482 void MachineVerifier::visitMachineFunctionBefore() {
483   lastIndex = SlotIndex();
484   regsReserved = MRI->getReservedRegs();
485
486   // A sub-register of a reserved register is also reserved
487   for (int Reg = regsReserved.find_first(); Reg>=0;
488        Reg = regsReserved.find_next(Reg)) {
489     for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
490       // FIXME: This should probably be:
491       // assert(regsReserved.test(*SubRegs) && "Non-reserved sub-register");
492       regsReserved.set(*SubRegs);
493     }
494   }
495
496   markReachable(&MF->front());
497
498   // Build a set of the basic blocks in the function.
499   FunctionBlocks.clear();
500   for (const auto &MBB : *MF) {
501     FunctionBlocks.insert(&MBB);
502     BBInfo &MInfo = MBBInfoMap[&MBB];
503
504     MInfo.Preds.insert(MBB.pred_begin(), MBB.pred_end());
505     if (MInfo.Preds.size() != MBB.pred_size())
506       report("MBB has duplicate entries in its predecessor list.", &MBB);
507
508     MInfo.Succs.insert(MBB.succ_begin(), MBB.succ_end());
509     if (MInfo.Succs.size() != MBB.succ_size())
510       report("MBB has duplicate entries in its successor list.", &MBB);
511   }
512
513   // Check that the register use lists are sane.
514   MRI->verifyUseLists();
515
516   verifyStackFrame();
517 }
518
519 // Does iterator point to a and b as the first two elements?
520 static bool matchPair(MachineBasicBlock::const_succ_iterator i,
521                       const MachineBasicBlock *a, const MachineBasicBlock *b) {
522   if (*i == a)
523     return *++i == b;
524   if (*i == b)
525     return *++i == a;
526   return false;
527 }
528
529 void
530 MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB) {
531   FirstTerminator = nullptr;
532
533   if (MRI->isSSA()) {
534     // If this block has allocatable physical registers live-in, check that
535     // it is an entry block or landing pad.
536     for (const auto &LI : MBB->liveins()) {
537       if (isAllocatable(LI.PhysReg) && !MBB->isEHPad() &&
538           MBB != MBB->getParent()->begin()) {
539         report("MBB has allocable live-in, but isn't entry or landing-pad.", MBB);
540       }
541     }
542   }
543
544   // Count the number of landing pad successors.
545   SmallPtrSet<MachineBasicBlock*, 4> LandingPadSuccs;
546   for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
547        E = MBB->succ_end(); I != E; ++I) {
548     if ((*I)->isEHPad())
549       LandingPadSuccs.insert(*I);
550     if (!FunctionBlocks.count(*I))
551       report("MBB has successor that isn't part of the function.", MBB);
552     if (!MBBInfoMap[*I].Preds.count(MBB)) {
553       report("Inconsistent CFG", MBB);
554       errs() << "MBB is not in the predecessor list of the successor BB#"
555           << (*I)->getNumber() << ".\n";
556     }
557   }
558
559   // Check the predecessor list.
560   for (MachineBasicBlock::const_pred_iterator I = MBB->pred_begin(),
561        E = MBB->pred_end(); I != E; ++I) {
562     if (!FunctionBlocks.count(*I))
563       report("MBB has predecessor that isn't part of the function.", MBB);
564     if (!MBBInfoMap[*I].Succs.count(MBB)) {
565       report("Inconsistent CFG", MBB);
566       errs() << "MBB is not in the successor list of the predecessor BB#"
567           << (*I)->getNumber() << ".\n";
568     }
569   }
570
571   const MCAsmInfo *AsmInfo = TM->getMCAsmInfo();
572   const BasicBlock *BB = MBB->getBasicBlock();
573   const Function *Fn = MF->getFunction();
574   if (LandingPadSuccs.size() > 1 &&
575       !(AsmInfo &&
576         AsmInfo->getExceptionHandlingType() == ExceptionHandling::SjLj &&
577         BB && isa<SwitchInst>(BB->getTerminator())) &&
578       !isFuncletEHPersonality(classifyEHPersonality(Fn->getPersonalityFn())))
579     report("MBB has more than one landing pad successor", MBB);
580
581   // Call AnalyzeBranch. If it succeeds, there several more conditions to check.
582   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
583   SmallVector<MachineOperand, 4> Cond;
584   if (!TII->AnalyzeBranch(*const_cast<MachineBasicBlock *>(MBB),
585                           TBB, FBB, Cond)) {
586     // Ok, AnalyzeBranch thinks it knows what's going on with this block. Let's
587     // check whether its answers match up with reality.
588     if (!TBB && !FBB) {
589       // Block falls through to its successor.
590       MachineFunction::const_iterator MBBI = MBB->getIterator();
591       ++MBBI;
592       if (MBBI == MF->end()) {
593         // It's possible that the block legitimately ends with a noreturn
594         // call or an unreachable, in which case it won't actually fall
595         // out the bottom of the function.
596       } else if (MBB->succ_size() == LandingPadSuccs.size()) {
597         // It's possible that the block legitimately ends with a noreturn
598         // call or an unreachable, in which case it won't actuall fall
599         // out of the block.
600       } else if (MBB->succ_size() != 1+LandingPadSuccs.size()) {
601         report("MBB exits via unconditional fall-through but doesn't have "
602                "exactly one CFG successor!", MBB);
603       } else if (!MBB->isSuccessor(&*MBBI)) {
604         report("MBB exits via unconditional fall-through but its successor "
605                "differs from its CFG successor!", MBB);
606       }
607       if (!MBB->empty() && MBB->back().isBarrier() &&
608           !TII->isPredicated(&MBB->back())) {
609         report("MBB exits via unconditional fall-through but ends with a "
610                "barrier instruction!", MBB);
611       }
612       if (!Cond.empty()) {
613         report("MBB exits via unconditional fall-through but has a condition!",
614                MBB);
615       }
616     } else if (TBB && !FBB && Cond.empty()) {
617       // Block unconditionally branches somewhere.
618       // If the block has exactly one successor, that happens to be a
619       // landingpad, accept it as valid control flow.
620       if (MBB->succ_size() != 1+LandingPadSuccs.size() &&
621           (MBB->succ_size() != 1 || LandingPadSuccs.size() != 1 ||
622            *MBB->succ_begin() != *LandingPadSuccs.begin())) {
623         report("MBB exits via unconditional branch but doesn't have "
624                "exactly one CFG successor!", MBB);
625       } else if (!MBB->isSuccessor(TBB)) {
626         report("MBB exits via unconditional branch but the CFG "
627                "successor doesn't match the actual successor!", MBB);
628       }
629       if (MBB->empty()) {
630         report("MBB exits via unconditional branch but doesn't contain "
631                "any instructions!", MBB);
632       } else if (!MBB->back().isBarrier()) {
633         report("MBB exits via unconditional branch but doesn't end with a "
634                "barrier instruction!", MBB);
635       } else if (!MBB->back().isTerminator()) {
636         report("MBB exits via unconditional branch but the branch isn't a "
637                "terminator instruction!", MBB);
638       }
639     } else if (TBB && !FBB && !Cond.empty()) {
640       // Block conditionally branches somewhere, otherwise falls through.
641       MachineFunction::const_iterator MBBI = MBB->getIterator();
642       ++MBBI;
643       if (MBBI == MF->end()) {
644         report("MBB conditionally falls through out of function!", MBB);
645       } else if (MBB->succ_size() == 1) {
646         // A conditional branch with only one successor is weird, but allowed.
647         if (&*MBBI != TBB)
648           report("MBB exits via conditional branch/fall-through but only has "
649                  "one CFG successor!", MBB);
650         else if (TBB != *MBB->succ_begin())
651           report("MBB exits via conditional branch/fall-through but the CFG "
652                  "successor don't match the actual successor!", MBB);
653       } else if (MBB->succ_size() != 2) {
654         report("MBB exits via conditional branch/fall-through but doesn't have "
655                "exactly two CFG successors!", MBB);
656       } else if (!matchPair(MBB->succ_begin(), TBB, &*MBBI)) {
657         report("MBB exits via conditional branch/fall-through but the CFG "
658                "successors don't match the actual successors!", MBB);
659       }
660       if (MBB->empty()) {
661         report("MBB exits via conditional branch/fall-through but doesn't "
662                "contain any instructions!", MBB);
663       } else if (MBB->back().isBarrier()) {
664         report("MBB exits via conditional branch/fall-through but ends with a "
665                "barrier instruction!", MBB);
666       } else if (!MBB->back().isTerminator()) {
667         report("MBB exits via conditional branch/fall-through but the branch "
668                "isn't a terminator instruction!", MBB);
669       }
670     } else if (TBB && FBB) {
671       // Block conditionally branches somewhere, otherwise branches
672       // somewhere else.
673       if (MBB->succ_size() == 1) {
674         // A conditional branch with only one successor is weird, but allowed.
675         if (FBB != TBB)
676           report("MBB exits via conditional branch/branch through but only has "
677                  "one CFG successor!", MBB);
678         else if (TBB != *MBB->succ_begin())
679           report("MBB exits via conditional branch/branch through but the CFG "
680                  "successor don't match the actual successor!", MBB);
681       } else if (MBB->succ_size() != 2) {
682         report("MBB exits via conditional branch/branch but doesn't have "
683                "exactly two CFG successors!", MBB);
684       } else if (!matchPair(MBB->succ_begin(), TBB, FBB)) {
685         report("MBB exits via conditional branch/branch but the CFG "
686                "successors don't match the actual successors!", MBB);
687       }
688       if (MBB->empty()) {
689         report("MBB exits via conditional branch/branch but doesn't "
690                "contain any instructions!", MBB);
691       } else if (!MBB->back().isBarrier()) {
692         report("MBB exits via conditional branch/branch but doesn't end with a "
693                "barrier instruction!", MBB);
694       } else if (!MBB->back().isTerminator()) {
695         report("MBB exits via conditional branch/branch but the branch "
696                "isn't a terminator instruction!", MBB);
697       }
698       if (Cond.empty()) {
699         report("MBB exits via conditinal branch/branch but there's no "
700                "condition!", MBB);
701       }
702     } else {
703       report("AnalyzeBranch returned invalid data!", MBB);
704     }
705   }
706
707   regsLive.clear();
708   for (const auto &LI : MBB->liveins()) {
709     if (!TargetRegisterInfo::isPhysicalRegister(LI.PhysReg)) {
710       report("MBB live-in list contains non-physical register", MBB);
711       continue;
712     }
713     for (MCSubRegIterator SubRegs(LI.PhysReg, TRI, /*IncludeSelf=*/true);
714          SubRegs.isValid(); ++SubRegs)
715       regsLive.insert(*SubRegs);
716   }
717   regsLiveInButUnused = regsLive;
718
719   const MachineFrameInfo *MFI = MF->getFrameInfo();
720   assert(MFI && "Function has no frame info");
721   BitVector PR = MFI->getPristineRegs(*MF);
722   for (int I = PR.find_first(); I>0; I = PR.find_next(I)) {
723     for (MCSubRegIterator SubRegs(I, TRI, /*IncludeSelf=*/true);
724          SubRegs.isValid(); ++SubRegs)
725       regsLive.insert(*SubRegs);
726   }
727
728   regsKilled.clear();
729   regsDefined.clear();
730
731   if (Indexes)
732     lastIndex = Indexes->getMBBStartIdx(MBB);
733 }
734
735 // This function gets called for all bundle headers, including normal
736 // stand-alone unbundled instructions.
737 void MachineVerifier::visitMachineBundleBefore(const MachineInstr *MI) {
738   if (Indexes && Indexes->hasIndex(MI)) {
739     SlotIndex idx = Indexes->getInstructionIndex(MI);
740     if (!(idx > lastIndex)) {
741       report("Instruction index out of order", MI);
742       errs() << "Last instruction was at " << lastIndex << '\n';
743     }
744     lastIndex = idx;
745   }
746
747   // Ensure non-terminators don't follow terminators.
748   // Ignore predicated terminators formed by if conversion.
749   // FIXME: If conversion shouldn't need to violate this rule.
750   if (MI->isTerminator() && !TII->isPredicated(MI)) {
751     if (!FirstTerminator)
752       FirstTerminator = MI;
753   } else if (FirstTerminator) {
754     report("Non-terminator instruction after the first terminator", MI);
755     errs() << "First terminator was:\t" << *FirstTerminator;
756   }
757 }
758
759 // The operands on an INLINEASM instruction must follow a template.
760 // Verify that the flag operands make sense.
761 void MachineVerifier::verifyInlineAsm(const MachineInstr *MI) {
762   // The first two operands on INLINEASM are the asm string and global flags.
763   if (MI->getNumOperands() < 2) {
764     report("Too few operands on inline asm", MI);
765     return;
766   }
767   if (!MI->getOperand(0).isSymbol())
768     report("Asm string must be an external symbol", MI);
769   if (!MI->getOperand(1).isImm())
770     report("Asm flags must be an immediate", MI);
771   // Allowed flags are Extra_HasSideEffects = 1, Extra_IsAlignStack = 2,
772   // Extra_AsmDialect = 4, Extra_MayLoad = 8, and Extra_MayStore = 16.
773   if (!isUInt<5>(MI->getOperand(1).getImm()))
774     report("Unknown asm flags", &MI->getOperand(1), 1);
775
776   static_assert(InlineAsm::MIOp_FirstOperand == 2, "Asm format changed");
777
778   unsigned OpNo = InlineAsm::MIOp_FirstOperand;
779   unsigned NumOps;
780   for (unsigned e = MI->getNumOperands(); OpNo < e; OpNo += NumOps) {
781     const MachineOperand &MO = MI->getOperand(OpNo);
782     // There may be implicit ops after the fixed operands.
783     if (!MO.isImm())
784       break;
785     NumOps = 1 + InlineAsm::getNumOperandRegisters(MO.getImm());
786   }
787
788   if (OpNo > MI->getNumOperands())
789     report("Missing operands in last group", MI);
790
791   // An optional MDNode follows the groups.
792   if (OpNo < MI->getNumOperands() && MI->getOperand(OpNo).isMetadata())
793     ++OpNo;
794
795   // All trailing operands must be implicit registers.
796   for (unsigned e = MI->getNumOperands(); OpNo < e; ++OpNo) {
797     const MachineOperand &MO = MI->getOperand(OpNo);
798     if (!MO.isReg() || !MO.isImplicit())
799       report("Expected implicit register after groups", &MO, OpNo);
800   }
801 }
802
803 void MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI) {
804   const MCInstrDesc &MCID = MI->getDesc();
805   if (MI->getNumOperands() < MCID.getNumOperands()) {
806     report("Too few operands", MI);
807     errs() << MCID.getNumOperands() << " operands expected, but "
808         << MI->getNumOperands() << " given.\n";
809   }
810
811   // Check the tied operands.
812   if (MI->isInlineAsm())
813     verifyInlineAsm(MI);
814
815   // Check the MachineMemOperands for basic consistency.
816   for (MachineInstr::mmo_iterator I = MI->memoperands_begin(),
817        E = MI->memoperands_end(); I != E; ++I) {
818     if ((*I)->isLoad() && !MI->mayLoad())
819       report("Missing mayLoad flag", MI);
820     if ((*I)->isStore() && !MI->mayStore())
821       report("Missing mayStore flag", MI);
822   }
823
824   // Debug values must not have a slot index.
825   // Other instructions must have one, unless they are inside a bundle.
826   if (LiveInts) {
827     bool mapped = !LiveInts->isNotInMIMap(MI);
828     if (MI->isDebugValue()) {
829       if (mapped)
830         report("Debug instruction has a slot index", MI);
831     } else if (MI->isInsideBundle()) {
832       if (mapped)
833         report("Instruction inside bundle has a slot index", MI);
834     } else {
835       if (!mapped)
836         report("Missing slot index", MI);
837     }
838   }
839
840   StringRef ErrorInfo;
841   if (!TII->verifyInstruction(MI, ErrorInfo))
842     report(ErrorInfo.data(), MI);
843 }
844
845 void
846 MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) {
847   const MachineInstr *MI = MO->getParent();
848   const MCInstrDesc &MCID = MI->getDesc();
849   unsigned NumDefs = MCID.getNumDefs();
850   if (MCID.getOpcode() == TargetOpcode::PATCHPOINT)
851     NumDefs = (MONum == 0 && MO->isReg()) ? NumDefs : 0;
852
853   // The first MCID.NumDefs operands must be explicit register defines
854   if (MONum < NumDefs) {
855     const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
856     if (!MO->isReg())
857       report("Explicit definition must be a register", MO, MONum);
858     else if (!MO->isDef() && !MCOI.isOptionalDef())
859       report("Explicit definition marked as use", MO, MONum);
860     else if (MO->isImplicit())
861       report("Explicit definition marked as implicit", MO, MONum);
862   } else if (MONum < MCID.getNumOperands()) {
863     const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
864     // Don't check if it's the last operand in a variadic instruction. See,
865     // e.g., LDM_RET in the arm back end.
866     if (MO->isReg() &&
867         !(MI->isVariadic() && MONum == MCID.getNumOperands()-1)) {
868       if (MO->isDef() && !MCOI.isOptionalDef())
869         report("Explicit operand marked as def", MO, MONum);
870       if (MO->isImplicit())
871         report("Explicit operand marked as implicit", MO, MONum);
872     }
873
874     int TiedTo = MCID.getOperandConstraint(MONum, MCOI::TIED_TO);
875     if (TiedTo != -1) {
876       if (!MO->isReg())
877         report("Tied use must be a register", MO, MONum);
878       else if (!MO->isTied())
879         report("Operand should be tied", MO, MONum);
880       else if (unsigned(TiedTo) != MI->findTiedOperandIdx(MONum))
881         report("Tied def doesn't match MCInstrDesc", MO, MONum);
882     } else if (MO->isReg() && MO->isTied())
883       report("Explicit operand should not be tied", MO, MONum);
884   } else {
885     // ARM adds %reg0 operands to indicate predicates. We'll allow that.
886     if (MO->isReg() && !MO->isImplicit() && !MI->isVariadic() && MO->getReg())
887       report("Extra explicit operand on non-variadic instruction", MO, MONum);
888   }
889
890   switch (MO->getType()) {
891   case MachineOperand::MO_Register: {
892     const unsigned Reg = MO->getReg();
893     if (!Reg)
894       return;
895     if (MRI->tracksLiveness() && !MI->isDebugValue())
896       checkLiveness(MO, MONum);
897
898     // Verify the consistency of tied operands.
899     if (MO->isTied()) {
900       unsigned OtherIdx = MI->findTiedOperandIdx(MONum);
901       const MachineOperand &OtherMO = MI->getOperand(OtherIdx);
902       if (!OtherMO.isReg())
903         report("Must be tied to a register", MO, MONum);
904       if (!OtherMO.isTied())
905         report("Missing tie flags on tied operand", MO, MONum);
906       if (MI->findTiedOperandIdx(OtherIdx) != MONum)
907         report("Inconsistent tie links", MO, MONum);
908       if (MONum < MCID.getNumDefs()) {
909         if (OtherIdx < MCID.getNumOperands()) {
910           if (-1 == MCID.getOperandConstraint(OtherIdx, MCOI::TIED_TO))
911             report("Explicit def tied to explicit use without tie constraint",
912                    MO, MONum);
913         } else {
914           if (!OtherMO.isImplicit())
915             report("Explicit def should be tied to implicit use", MO, MONum);
916         }
917       }
918     }
919
920     // Verify two-address constraints after leaving SSA form.
921     unsigned DefIdx;
922     if (!MRI->isSSA() && MO->isUse() &&
923         MI->isRegTiedToDefOperand(MONum, &DefIdx) &&
924         Reg != MI->getOperand(DefIdx).getReg())
925       report("Two-address instruction operands must be identical", MO, MONum);
926
927     // Check register classes.
928     if (MONum < MCID.getNumOperands() && !MO->isImplicit()) {
929       unsigned SubIdx = MO->getSubReg();
930
931       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
932         if (SubIdx) {
933           report("Illegal subregister index for physical register", MO, MONum);
934           return;
935         }
936         if (const TargetRegisterClass *DRC =
937               TII->getRegClass(MCID, MONum, TRI, *MF)) {
938           if (!DRC->contains(Reg)) {
939             report("Illegal physical register for instruction", MO, MONum);
940             errs() << TRI->getName(Reg) << " is not a "
941                 << TRI->getRegClassName(DRC) << " register.\n";
942           }
943         }
944       } else {
945         // Virtual register.
946         const TargetRegisterClass *RC = MRI->getRegClass(Reg);
947         if (SubIdx) {
948           const TargetRegisterClass *SRC =
949             TRI->getSubClassWithSubReg(RC, SubIdx);
950           if (!SRC) {
951             report("Invalid subregister index for virtual register", MO, MONum);
952             errs() << "Register class " << TRI->getRegClassName(RC)
953                 << " does not support subreg index " << SubIdx << "\n";
954             return;
955           }
956           if (RC != SRC) {
957             report("Invalid register class for subregister index", MO, MONum);
958             errs() << "Register class " << TRI->getRegClassName(RC)
959                 << " does not fully support subreg index " << SubIdx << "\n";
960             return;
961           }
962         }
963         if (const TargetRegisterClass *DRC =
964               TII->getRegClass(MCID, MONum, TRI, *MF)) {
965           if (SubIdx) {
966             const TargetRegisterClass *SuperRC =
967                 TRI->getLargestLegalSuperClass(RC, *MF);
968             if (!SuperRC) {
969               report("No largest legal super class exists.", MO, MONum);
970               return;
971             }
972             DRC = TRI->getMatchingSuperRegClass(SuperRC, DRC, SubIdx);
973             if (!DRC) {
974               report("No matching super-reg register class.", MO, MONum);
975               return;
976             }
977           }
978           if (!RC->hasSuperClassEq(DRC)) {
979             report("Illegal virtual register for instruction", MO, MONum);
980             errs() << "Expected a " << TRI->getRegClassName(DRC)
981                 << " register, but got a " << TRI->getRegClassName(RC)
982                 << " register\n";
983           }
984         }
985       }
986     }
987     break;
988   }
989
990   case MachineOperand::MO_RegisterMask:
991     regMasks.push_back(MO->getRegMask());
992     break;
993
994   case MachineOperand::MO_MachineBasicBlock:
995     if (MI->isPHI() && !MO->getMBB()->isSuccessor(MI->getParent()))
996       report("PHI operand is not in the CFG", MO, MONum);
997     break;
998
999   case MachineOperand::MO_FrameIndex:
1000     if (LiveStks && LiveStks->hasInterval(MO->getIndex()) &&
1001         LiveInts && !LiveInts->isNotInMIMap(MI)) {
1002       int FI = MO->getIndex();
1003       LiveInterval &LI = LiveStks->getInterval(FI);
1004       SlotIndex Idx = LiveInts->getInstructionIndex(MI);
1005
1006       bool stores = MI->mayStore();
1007       bool loads = MI->mayLoad();
1008       // For a memory-to-memory move, we need to check if the frame
1009       // index is used for storing or loading, by inspecting the
1010       // memory operands.
1011       if (stores && loads) {
1012         for (auto *MMO : MI->memoperands()) {
1013           const PseudoSourceValue *PSV = MMO->getPseudoValue();
1014           if (PSV == nullptr) continue;
1015           const FixedStackPseudoSourceValue *Value =
1016             dyn_cast<FixedStackPseudoSourceValue>(PSV);
1017           if (Value == nullptr) continue;
1018           if (Value->getFrameIndex() != FI) continue;
1019
1020           if (MMO->isStore())
1021             loads = false;
1022           else
1023             stores = false;
1024           break;
1025         }
1026         if (loads == stores)
1027           report("Missing fixed stack memoperand.", MI);
1028       }
1029       if (loads && !LI.liveAt(Idx.getRegSlot(true))) {
1030         report("Instruction loads from dead spill slot", MO, MONum);
1031         errs() << "Live stack: " << LI << '\n';
1032       }
1033       if (stores && !LI.liveAt(Idx.getRegSlot())) {
1034         report("Instruction stores to dead spill slot", MO, MONum);
1035         errs() << "Live stack: " << LI << '\n';
1036       }
1037     }
1038     break;
1039
1040   default:
1041     break;
1042   }
1043 }
1044
1045 void MachineVerifier::checkLiveness(const MachineOperand *MO, unsigned MONum) {
1046   const MachineInstr *MI = MO->getParent();
1047   const unsigned Reg = MO->getReg();
1048
1049   // Both use and def operands can read a register.
1050   if (MO->readsReg()) {
1051     regsLiveInButUnused.erase(Reg);
1052
1053     if (MO->isKill())
1054       addRegWithSubRegs(regsKilled, Reg);
1055
1056     // Check that LiveVars knows this kill.
1057     if (LiveVars && TargetRegisterInfo::isVirtualRegister(Reg) &&
1058         MO->isKill()) {
1059       LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
1060       if (std::find(VI.Kills.begin(), VI.Kills.end(), MI) == VI.Kills.end())
1061         report("Kill missing from LiveVariables", MO, MONum);
1062     }
1063
1064     // Check LiveInts liveness and kill.
1065     if (LiveInts && !LiveInts->isNotInMIMap(MI)) {
1066       SlotIndex UseIdx = LiveInts->getInstructionIndex(MI);
1067       // Check the cached regunit intervals.
1068       if (TargetRegisterInfo::isPhysicalRegister(Reg) && !isReserved(Reg)) {
1069         for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
1070           if (const LiveRange *LR = LiveInts->getCachedRegUnit(*Units)) {
1071             LiveQueryResult LRQ = LR->Query(UseIdx);
1072             if (!LRQ.valueIn()) {
1073               report("No live segment at use", MO, MONum);
1074               errs() << UseIdx << " is not live in " << PrintRegUnit(*Units, TRI)
1075                   << ' ' << *LR << '\n';
1076             }
1077             if (MO->isKill() && !LRQ.isKill()) {
1078               report("Live range continues after kill flag", MO, MONum);
1079               errs() << PrintRegUnit(*Units, TRI) << ' ' << *LR << '\n';
1080             }
1081           }
1082         }
1083       }
1084
1085       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1086         if (LiveInts->hasInterval(Reg)) {
1087           // This is a virtual register interval.
1088           const LiveInterval &LI = LiveInts->getInterval(Reg);
1089           LiveQueryResult LRQ = LI.Query(UseIdx);
1090           if (!LRQ.valueIn()) {
1091             report("No live segment at use", MO, MONum);
1092             errs() << UseIdx << " is not live in " << LI << '\n';
1093           }
1094           // Check for extra kill flags.
1095           // Note that we allow missing kill flags for now.
1096           if (MO->isKill() && !LRQ.isKill()) {
1097             report("Live range continues after kill flag", MO, MONum);
1098             errs() << "Live range: " << LI << '\n';
1099           }
1100         } else {
1101           report("Virtual register has no live interval", MO, MONum);
1102         }
1103       }
1104     }
1105
1106     // Use of a dead register.
1107     if (!regsLive.count(Reg)) {
1108       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1109         // Reserved registers may be used even when 'dead'.
1110         bool Bad = !isReserved(Reg);
1111         // We are fine if just any subregister has a defined value.
1112         if (Bad) {
1113           for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid();
1114                ++SubRegs) {
1115             if (regsLive.count(*SubRegs)) {
1116               Bad = false;
1117               break;
1118             }
1119           }
1120         }
1121         // If there is an additional implicit-use of a super register we stop
1122         // here. By definition we are fine if the super register is not
1123         // (completely) dead, if the complete super register is dead we will
1124         // get a report for its operand.
1125         if (Bad) {
1126           for (const MachineOperand &MOP : MI->uses()) {
1127             if (!MOP.isReg())
1128               continue;
1129             if (!MOP.isImplicit())
1130               continue;
1131             for (MCSubRegIterator SubRegs(MOP.getReg(), TRI); SubRegs.isValid();
1132                  ++SubRegs) {
1133               if (*SubRegs == Reg) {
1134                 Bad = false;
1135                 break;
1136               }
1137             }
1138           }
1139         }
1140         if (Bad)
1141           report("Using an undefined physical register", MO, MONum);
1142       } else if (MRI->def_empty(Reg)) {
1143         report("Reading virtual register without a def", MO, MONum);
1144       } else {
1145         BBInfo &MInfo = MBBInfoMap[MI->getParent()];
1146         // We don't know which virtual registers are live in, so only complain
1147         // if vreg was killed in this MBB. Otherwise keep track of vregs that
1148         // must be live in. PHI instructions are handled separately.
1149         if (MInfo.regsKilled.count(Reg))
1150           report("Using a killed virtual register", MO, MONum);
1151         else if (!MI->isPHI())
1152           MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI));
1153       }
1154     }
1155   }
1156
1157   if (MO->isDef()) {
1158     // Register defined.
1159     // TODO: verify that earlyclobber ops are not used.
1160     if (MO->isDead())
1161       addRegWithSubRegs(regsDead, Reg);
1162     else
1163       addRegWithSubRegs(regsDefined, Reg);
1164
1165     // Verify SSA form.
1166     if (MRI->isSSA() && TargetRegisterInfo::isVirtualRegister(Reg) &&
1167         std::next(MRI->def_begin(Reg)) != MRI->def_end())
1168       report("Multiple virtual register defs in SSA form", MO, MONum);
1169
1170     // Check LiveInts for a live segment, but only for virtual registers.
1171     if (LiveInts && TargetRegisterInfo::isVirtualRegister(Reg) &&
1172         !LiveInts->isNotInMIMap(MI)) {
1173       SlotIndex DefIdx = LiveInts->getInstructionIndex(MI);
1174       DefIdx = DefIdx.getRegSlot(MO->isEarlyClobber());
1175       if (LiveInts->hasInterval(Reg)) {
1176         const LiveInterval &LI = LiveInts->getInterval(Reg);
1177         if (const VNInfo *VNI = LI.getVNInfoAt(DefIdx)) {
1178           assert(VNI && "NULL valno is not allowed");
1179           if (VNI->def != DefIdx) {
1180             report("Inconsistent valno->def", MO, MONum);
1181             errs() << "Valno " << VNI->id << " is not defined at "
1182               << DefIdx << " in " << LI << '\n';
1183           }
1184         } else {
1185           report("No live segment at def", MO, MONum);
1186           errs() << DefIdx << " is not live in " << LI << '\n';
1187         }
1188         // Check that, if the dead def flag is present, LiveInts agree.
1189         if (MO->isDead()) {
1190           LiveQueryResult LRQ = LI.Query(DefIdx);
1191           if (!LRQ.isDeadDef()) {
1192             report("Live range continues after dead def flag", MO, MONum);
1193             errs() << "Live range: " << LI << '\n';
1194           }
1195         }
1196       } else {
1197         report("Virtual register has no Live interval", MO, MONum);
1198       }
1199     }
1200   }
1201 }
1202
1203 void MachineVerifier::visitMachineInstrAfter(const MachineInstr *MI) {
1204 }
1205
1206 // This function gets called after visiting all instructions in a bundle. The
1207 // argument points to the bundle header.
1208 // Normal stand-alone instructions are also considered 'bundles', and this
1209 // function is called for all of them.
1210 void MachineVerifier::visitMachineBundleAfter(const MachineInstr *MI) {
1211   BBInfo &MInfo = MBBInfoMap[MI->getParent()];
1212   set_union(MInfo.regsKilled, regsKilled);
1213   set_subtract(regsLive, regsKilled); regsKilled.clear();
1214   // Kill any masked registers.
1215   while (!regMasks.empty()) {
1216     const uint32_t *Mask = regMasks.pop_back_val();
1217     for (RegSet::iterator I = regsLive.begin(), E = regsLive.end(); I != E; ++I)
1218       if (TargetRegisterInfo::isPhysicalRegister(*I) &&
1219           MachineOperand::clobbersPhysReg(Mask, *I))
1220         regsDead.push_back(*I);
1221   }
1222   set_subtract(regsLive, regsDead);   regsDead.clear();
1223   set_union(regsLive, regsDefined);   regsDefined.clear();
1224 }
1225
1226 void
1227 MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB) {
1228   MBBInfoMap[MBB].regsLiveOut = regsLive;
1229   regsLive.clear();
1230
1231   if (Indexes) {
1232     SlotIndex stop = Indexes->getMBBEndIdx(MBB);
1233     if (!(stop > lastIndex)) {
1234       report("Block ends before last instruction index", MBB);
1235       errs() << "Block ends at " << stop
1236           << " last instruction was at " << lastIndex << '\n';
1237     }
1238     lastIndex = stop;
1239   }
1240 }
1241
1242 // Calculate the largest possible vregsPassed sets. These are the registers that
1243 // can pass through an MBB live, but may not be live every time. It is assumed
1244 // that all vregsPassed sets are empty before the call.
1245 void MachineVerifier::calcRegsPassed() {
1246   // First push live-out regs to successors' vregsPassed. Remember the MBBs that
1247   // have any vregsPassed.
1248   SmallPtrSet<const MachineBasicBlock*, 8> todo;
1249   for (const auto &MBB : *MF) {
1250     BBInfo &MInfo = MBBInfoMap[&MBB];
1251     if (!MInfo.reachable)
1252       continue;
1253     for (MachineBasicBlock::const_succ_iterator SuI = MBB.succ_begin(),
1254            SuE = MBB.succ_end(); SuI != SuE; ++SuI) {
1255       BBInfo &SInfo = MBBInfoMap[*SuI];
1256       if (SInfo.addPassed(MInfo.regsLiveOut))
1257         todo.insert(*SuI);
1258     }
1259   }
1260
1261   // Iteratively push vregsPassed to successors. This will converge to the same
1262   // final state regardless of DenseSet iteration order.
1263   while (!todo.empty()) {
1264     const MachineBasicBlock *MBB = *todo.begin();
1265     todo.erase(MBB);
1266     BBInfo &MInfo = MBBInfoMap[MBB];
1267     for (MachineBasicBlock::const_succ_iterator SuI = MBB->succ_begin(),
1268            SuE = MBB->succ_end(); SuI != SuE; ++SuI) {
1269       if (*SuI == MBB)
1270         continue;
1271       BBInfo &SInfo = MBBInfoMap[*SuI];
1272       if (SInfo.addPassed(MInfo.vregsPassed))
1273         todo.insert(*SuI);
1274     }
1275   }
1276 }
1277
1278 // Calculate the set of virtual registers that must be passed through each basic
1279 // block in order to satisfy the requirements of successor blocks. This is very
1280 // similar to calcRegsPassed, only backwards.
1281 void MachineVerifier::calcRegsRequired() {
1282   // First push live-in regs to predecessors' vregsRequired.
1283   SmallPtrSet<const MachineBasicBlock*, 8> todo;
1284   for (const auto &MBB : *MF) {
1285     BBInfo &MInfo = MBBInfoMap[&MBB];
1286     for (MachineBasicBlock::const_pred_iterator PrI = MBB.pred_begin(),
1287            PrE = MBB.pred_end(); PrI != PrE; ++PrI) {
1288       BBInfo &PInfo = MBBInfoMap[*PrI];
1289       if (PInfo.addRequired(MInfo.vregsLiveIn))
1290         todo.insert(*PrI);
1291     }
1292   }
1293
1294   // Iteratively push vregsRequired to predecessors. This will converge to the
1295   // same final state regardless of DenseSet iteration order.
1296   while (!todo.empty()) {
1297     const MachineBasicBlock *MBB = *todo.begin();
1298     todo.erase(MBB);
1299     BBInfo &MInfo = MBBInfoMap[MBB];
1300     for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
1301            PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
1302       if (*PrI == MBB)
1303         continue;
1304       BBInfo &SInfo = MBBInfoMap[*PrI];
1305       if (SInfo.addRequired(MInfo.vregsRequired))
1306         todo.insert(*PrI);
1307     }
1308   }
1309 }
1310
1311 // Check PHI instructions at the beginning of MBB. It is assumed that
1312 // calcRegsPassed has been run so BBInfo::isLiveOut is valid.
1313 void MachineVerifier::checkPHIOps(const MachineBasicBlock *MBB) {
1314   SmallPtrSet<const MachineBasicBlock*, 8> seen;
1315   for (const auto &BBI : *MBB) {
1316     if (!BBI.isPHI())
1317       break;
1318     seen.clear();
1319
1320     for (unsigned i = 1, e = BBI.getNumOperands(); i != e; i += 2) {
1321       unsigned Reg = BBI.getOperand(i).getReg();
1322       const MachineBasicBlock *Pre = BBI.getOperand(i + 1).getMBB();
1323       if (!Pre->isSuccessor(MBB))
1324         continue;
1325       seen.insert(Pre);
1326       BBInfo &PrInfo = MBBInfoMap[Pre];
1327       if (PrInfo.reachable && !PrInfo.isLiveOut(Reg))
1328         report("PHI operand is not live-out from predecessor",
1329                &BBI.getOperand(i), i);
1330     }
1331
1332     // Did we see all predecessors?
1333     for (MachineBasicBlock::const_pred_iterator PrI = MBB->pred_begin(),
1334            PrE = MBB->pred_end(); PrI != PrE; ++PrI) {
1335       if (!seen.count(*PrI)) {
1336         report("Missing PHI operand", &BBI);
1337         errs() << "BB#" << (*PrI)->getNumber()
1338             << " is a predecessor according to the CFG.\n";
1339       }
1340     }
1341   }
1342 }
1343
1344 void MachineVerifier::visitMachineFunctionAfter() {
1345   calcRegsPassed();
1346
1347   for (const auto &MBB : *MF) {
1348     BBInfo &MInfo = MBBInfoMap[&MBB];
1349
1350     // Skip unreachable MBBs.
1351     if (!MInfo.reachable)
1352       continue;
1353
1354     checkPHIOps(&MBB);
1355   }
1356
1357   // Now check liveness info if available
1358   calcRegsRequired();
1359
1360   // Check for killed virtual registers that should be live out.
1361   for (const auto &MBB : *MF) {
1362     BBInfo &MInfo = MBBInfoMap[&MBB];
1363     for (RegSet::iterator
1364          I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E;
1365          ++I)
1366       if (MInfo.regsKilled.count(*I)) {
1367         report("Virtual register killed in block, but needed live out.", &MBB);
1368         errs() << "Virtual register " << PrintReg(*I)
1369             << " is used after the block.\n";
1370       }
1371   }
1372
1373   if (!MF->empty()) {
1374     BBInfo &MInfo = MBBInfoMap[&MF->front()];
1375     for (RegSet::iterator
1376          I = MInfo.vregsRequired.begin(), E = MInfo.vregsRequired.end(); I != E;
1377          ++I)
1378       report("Virtual register def doesn't dominate all uses.",
1379              MRI->getVRegDef(*I));
1380   }
1381
1382   if (LiveVars)
1383     verifyLiveVariables();
1384   if (LiveInts)
1385     verifyLiveIntervals();
1386 }
1387
1388 void MachineVerifier::verifyLiveVariables() {
1389   assert(LiveVars && "Don't call verifyLiveVariables without LiveVars");
1390   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1391     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
1392     LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
1393     for (const auto &MBB : *MF) {
1394       BBInfo &MInfo = MBBInfoMap[&MBB];
1395
1396       // Our vregsRequired should be identical to LiveVariables' AliveBlocks
1397       if (MInfo.vregsRequired.count(Reg)) {
1398         if (!VI.AliveBlocks.test(MBB.getNumber())) {
1399           report("LiveVariables: Block missing from AliveBlocks", &MBB);
1400           errs() << "Virtual register " << PrintReg(Reg)
1401               << " must be live through the block.\n";
1402         }
1403       } else {
1404         if (VI.AliveBlocks.test(MBB.getNumber())) {
1405           report("LiveVariables: Block should not be in AliveBlocks", &MBB);
1406           errs() << "Virtual register " << PrintReg(Reg)
1407               << " is not needed live through the block.\n";
1408         }
1409       }
1410     }
1411   }
1412 }
1413
1414 void MachineVerifier::verifyLiveIntervals() {
1415   assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts");
1416   for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
1417     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
1418
1419     // Spilling and splitting may leave unused registers around. Skip them.
1420     if (MRI->reg_nodbg_empty(Reg))
1421       continue;
1422
1423     if (!LiveInts->hasInterval(Reg)) {
1424       report("Missing live interval for virtual register", MF);
1425       errs() << PrintReg(Reg, TRI) << " still has defs or uses\n";
1426       continue;
1427     }
1428
1429     const LiveInterval &LI = LiveInts->getInterval(Reg);
1430     assert(Reg == LI.reg && "Invalid reg to interval mapping");
1431     verifyLiveInterval(LI);
1432   }
1433
1434   // Verify all the cached regunit intervals.
1435   for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
1436     if (const LiveRange *LR = LiveInts->getCachedRegUnit(i))
1437       verifyLiveRange(*LR, i);
1438 }
1439
1440 void MachineVerifier::verifyLiveRangeValue(const LiveRange &LR,
1441                                            const VNInfo *VNI, unsigned Reg,
1442                                            LaneBitmask LaneMask) {
1443   if (VNI->isUnused())
1444     return;
1445
1446   const VNInfo *DefVNI = LR.getVNInfoAt(VNI->def);
1447
1448   if (!DefVNI) {
1449     report("Valno not live at def and not marked unused", MF, LR, Reg,
1450            LaneMask);
1451     errs() << "Valno #" << VNI->id << '\n';
1452     return;
1453   }
1454
1455   if (DefVNI != VNI) {
1456     report("Live segment at def has different valno", MF, LR, Reg, LaneMask);
1457     errs() << "Valno #" << VNI->id << " is defined at " << VNI->def
1458         << " where valno #" << DefVNI->id << " is live\n";
1459     return;
1460   }
1461
1462   const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(VNI->def);
1463   if (!MBB) {
1464     report("Invalid definition index", MF, LR, Reg, LaneMask);
1465     errs() << "Valno #" << VNI->id << " is defined at " << VNI->def
1466         << " in " << LR << '\n';
1467     return;
1468   }
1469
1470   if (VNI->isPHIDef()) {
1471     if (VNI->def != LiveInts->getMBBStartIdx(MBB)) {
1472       report("PHIDef value is not defined at MBB start", MBB, LR, Reg,
1473              LaneMask);
1474       errs() << "Valno #" << VNI->id << " is defined at " << VNI->def
1475           << ", not at the beginning of BB#" << MBB->getNumber() << '\n';
1476     }
1477     return;
1478   }
1479
1480   // Non-PHI def.
1481   const MachineInstr *MI = LiveInts->getInstructionFromIndex(VNI->def);
1482   if (!MI) {
1483     report("No instruction at def index", MBB, LR, Reg, LaneMask);
1484     errs() << "Valno #" << VNI->id << " is defined at " << VNI->def << '\n';
1485     return;
1486   }
1487
1488   if (Reg != 0) {
1489     bool hasDef = false;
1490     bool isEarlyClobber = false;
1491     for (ConstMIBundleOperands MOI(MI); MOI.isValid(); ++MOI) {
1492       if (!MOI->isReg() || !MOI->isDef())
1493         continue;
1494       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1495         if (MOI->getReg() != Reg)
1496           continue;
1497       } else {
1498         if (!TargetRegisterInfo::isPhysicalRegister(MOI->getReg()) ||
1499             !TRI->hasRegUnit(MOI->getReg(), Reg))
1500           continue;
1501       }
1502       if (LaneMask != 0 &&
1503           (TRI->getSubRegIndexLaneMask(MOI->getSubReg()) & LaneMask) == 0)
1504         continue;
1505       hasDef = true;
1506       if (MOI->isEarlyClobber())
1507         isEarlyClobber = true;
1508     }
1509
1510     if (!hasDef) {
1511       report("Defining instruction does not modify register", MI);
1512       errs() << "Valno #" << VNI->id << " in " << LR << '\n';
1513     }
1514
1515     // Early clobber defs begin at USE slots, but other defs must begin at
1516     // DEF slots.
1517     if (isEarlyClobber) {
1518       if (!VNI->def.isEarlyClobber()) {
1519         report("Early clobber def must be at an early-clobber slot", MBB, LR,
1520                Reg, LaneMask);
1521         errs() << "Valno #" << VNI->id << " is defined at " << VNI->def << '\n';
1522       }
1523     } else if (!VNI->def.isRegister()) {
1524       report("Non-PHI, non-early clobber def must be at a register slot",
1525              MBB, LR, Reg, LaneMask);
1526       errs() << "Valno #" << VNI->id << " is defined at " << VNI->def << '\n';
1527     }
1528   }
1529 }
1530
1531 void MachineVerifier::verifyLiveRangeSegment(const LiveRange &LR,
1532                                              const LiveRange::const_iterator I,
1533                                              unsigned Reg, LaneBitmask LaneMask)
1534 {
1535   const LiveRange::Segment &S = *I;
1536   const VNInfo *VNI = S.valno;
1537   assert(VNI && "Live segment has no valno");
1538
1539   if (VNI->id >= LR.getNumValNums() || VNI != LR.getValNumInfo(VNI->id)) {
1540     report("Foreign valno in live segment", MF, LR, Reg, LaneMask);
1541     errs() << S << " has a bad valno\n";
1542   }
1543
1544   if (VNI->isUnused()) {
1545     report("Live segment valno is marked unused", MF, LR, Reg, LaneMask);
1546     errs() << S << '\n';
1547   }
1548
1549   const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(S.start);
1550   if (!MBB) {
1551     report("Bad start of live segment, no basic block", MF, LR, Reg, LaneMask);
1552     errs() << S << '\n';
1553     return;
1554   }
1555   SlotIndex MBBStartIdx = LiveInts->getMBBStartIdx(MBB);
1556   if (S.start != MBBStartIdx && S.start != VNI->def) {
1557     report("Live segment must begin at MBB entry or valno def", MBB, LR, Reg,
1558            LaneMask);
1559     errs() << S << '\n';
1560   }
1561
1562   const MachineBasicBlock *EndMBB =
1563     LiveInts->getMBBFromIndex(S.end.getPrevSlot());
1564   if (!EndMBB) {
1565     report("Bad end of live segment, no basic block", MF, LR, Reg, LaneMask);
1566     errs() << S << '\n';
1567     return;
1568   }
1569
1570   // No more checks for live-out segments.
1571   if (S.end == LiveInts->getMBBEndIdx(EndMBB))
1572     return;
1573
1574   // RegUnit intervals are allowed dead phis.
1575   if (!TargetRegisterInfo::isVirtualRegister(Reg) && VNI->isPHIDef() &&
1576       S.start == VNI->def && S.end == VNI->def.getDeadSlot())
1577     return;
1578
1579   // The live segment is ending inside EndMBB
1580   const MachineInstr *MI =
1581     LiveInts->getInstructionFromIndex(S.end.getPrevSlot());
1582   if (!MI) {
1583     report("Live segment doesn't end at a valid instruction", EndMBB, LR, Reg,
1584            LaneMask);
1585     errs() << S << '\n';
1586     return;
1587   }
1588
1589   // The block slot must refer to a basic block boundary.
1590   if (S.end.isBlock()) {
1591     report("Live segment ends at B slot of an instruction", EndMBB, LR, Reg,
1592            LaneMask);
1593     errs() << S << '\n';
1594   }
1595
1596   if (S.end.isDead()) {
1597     // Segment ends on the dead slot.
1598     // That means there must be a dead def.
1599     if (!SlotIndex::isSameInstr(S.start, S.end)) {
1600       report("Live segment ending at dead slot spans instructions", EndMBB, LR,
1601              Reg, LaneMask);
1602       errs() << S << '\n';
1603     }
1604   }
1605
1606   // A live segment can only end at an early-clobber slot if it is being
1607   // redefined by an early-clobber def.
1608   if (S.end.isEarlyClobber()) {
1609     if (I+1 == LR.end() || (I+1)->start != S.end) {
1610       report("Live segment ending at early clobber slot must be "
1611              "redefined by an EC def in the same instruction", EndMBB, LR, Reg,
1612              LaneMask);
1613       errs() << S << '\n';
1614     }
1615   }
1616
1617   // The following checks only apply to virtual registers. Physreg liveness
1618   // is too weird to check.
1619   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1620     // A live segment can end with either a redefinition, a kill flag on a
1621     // use, or a dead flag on a def.
1622     bool hasRead = false;
1623     bool hasSubRegDef = false;
1624     for (ConstMIBundleOperands MOI(MI); MOI.isValid(); ++MOI) {
1625       if (!MOI->isReg() || MOI->getReg() != Reg)
1626         continue;
1627       if (LaneMask != 0 &&
1628           (LaneMask & TRI->getSubRegIndexLaneMask(MOI->getSubReg())) == 0)
1629         continue;
1630       if (MOI->isDef() && MOI->getSubReg() != 0)
1631         hasSubRegDef = true;
1632       if (MOI->readsReg())
1633         hasRead = true;
1634     }
1635     if (!S.end.isDead()) {
1636       if (!hasRead) {
1637         // When tracking subregister liveness, the main range must start new
1638         // values on partial register writes, even if there is no read.
1639         if (!MRI->shouldTrackSubRegLiveness(Reg) || LaneMask != 0 ||
1640             !hasSubRegDef) {
1641           report("Instruction ending live segment doesn't read the register",
1642                  MI);
1643           errs() << S << " in " << LR << '\n';
1644         }
1645       }
1646     }
1647   }
1648
1649   // Now check all the basic blocks in this live segment.
1650   MachineFunction::const_iterator MFI = MBB->getIterator();
1651   // Is this live segment the beginning of a non-PHIDef VN?
1652   if (S.start == VNI->def && !VNI->isPHIDef()) {
1653     // Not live-in to any blocks.
1654     if (MBB == EndMBB)
1655       return;
1656     // Skip this block.
1657     ++MFI;
1658   }
1659   for (;;) {
1660     assert(LiveInts->isLiveInToMBB(LR, &*MFI));
1661     // We don't know how to track physregs into a landing pad.
1662     if (!TargetRegisterInfo::isVirtualRegister(Reg) &&
1663         MFI->isEHPad()) {
1664       if (&*MFI == EndMBB)
1665         break;
1666       ++MFI;
1667       continue;
1668     }
1669
1670     // Is VNI a PHI-def in the current block?
1671     bool IsPHI = VNI->isPHIDef() &&
1672       VNI->def == LiveInts->getMBBStartIdx(&*MFI);
1673
1674     // Check that VNI is live-out of all predecessors.
1675     for (MachineBasicBlock::const_pred_iterator PI = MFI->pred_begin(),
1676          PE = MFI->pred_end(); PI != PE; ++PI) {
1677       SlotIndex PEnd = LiveInts->getMBBEndIdx(*PI);
1678       const VNInfo *PVNI = LR.getVNInfoBefore(PEnd);
1679
1680       // All predecessors must have a live-out value.
1681       if (!PVNI) {
1682         report("Register not marked live out of predecessor", *PI, LR, Reg,
1683                LaneMask);
1684         errs() << "Valno #" << VNI->id << " live into BB#" << MFI->getNumber()
1685                << '@' << LiveInts->getMBBStartIdx(&*MFI) << ", not live before "
1686                << PEnd << '\n';
1687         continue;
1688       }
1689
1690       // Only PHI-defs can take different predecessor values.
1691       if (!IsPHI && PVNI != VNI) {
1692         report("Different value live out of predecessor", *PI, LR, Reg,
1693                LaneMask);
1694         errs() << "Valno #" << PVNI->id << " live out of BB#"
1695                << (*PI)->getNumber() << '@' << PEnd << "\nValno #" << VNI->id
1696                << " live into BB#" << MFI->getNumber() << '@'
1697                << LiveInts->getMBBStartIdx(&*MFI) << '\n';
1698       }
1699     }
1700     if (&*MFI == EndMBB)
1701       break;
1702     ++MFI;
1703   }
1704 }
1705
1706 void MachineVerifier::verifyLiveRange(const LiveRange &LR, unsigned Reg,
1707                                       LaneBitmask LaneMask) {
1708   for (const VNInfo *VNI : LR.valnos)
1709     verifyLiveRangeValue(LR, VNI, Reg, LaneMask);
1710
1711   for (LiveRange::const_iterator I = LR.begin(), E = LR.end(); I != E; ++I)
1712     verifyLiveRangeSegment(LR, I, Reg, LaneMask);
1713 }
1714
1715 void MachineVerifier::verifyLiveInterval(const LiveInterval &LI) {
1716   unsigned Reg = LI.reg;
1717   assert(TargetRegisterInfo::isVirtualRegister(Reg));
1718   verifyLiveRange(LI, Reg);
1719
1720   LaneBitmask Mask = 0;
1721   LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(Reg);
1722   for (const LiveInterval::SubRange &SR : LI.subranges()) {
1723     if ((Mask & SR.LaneMask) != 0)
1724       report("Lane masks of sub ranges overlap in live interval", MF, LI);
1725     if ((SR.LaneMask & ~MaxMask) != 0)
1726       report("Subrange lanemask is invalid", MF, LI);
1727     if (SR.empty())
1728       report("Subrange must not be empty", MF, SR, LI.reg, SR.LaneMask);
1729     Mask |= SR.LaneMask;
1730     verifyLiveRange(SR, LI.reg, SR.LaneMask);
1731     if (!LI.covers(SR))
1732       report("A Subrange is not covered by the main range", MF, LI);
1733   }
1734
1735   // Check the LI only has one connected component.
1736   ConnectedVNInfoEqClasses ConEQ(*LiveInts);
1737   unsigned NumComp = ConEQ.Classify(&LI);
1738   if (NumComp > 1) {
1739     report("Multiple connected components in live interval", MF, LI);
1740     for (unsigned comp = 0; comp != NumComp; ++comp) {
1741       errs() << comp << ": valnos";
1742       for (LiveInterval::const_vni_iterator I = LI.vni_begin(),
1743            E = LI.vni_end(); I!=E; ++I)
1744         if (comp == ConEQ.getEqClass(*I))
1745           errs() << ' ' << (*I)->id;
1746       errs() << '\n';
1747     }
1748   }
1749 }
1750
1751 namespace {
1752   // FrameSetup and FrameDestroy can have zero adjustment, so using a single
1753   // integer, we can't tell whether it is a FrameSetup or FrameDestroy if the
1754   // value is zero.
1755   // We use a bool plus an integer to capture the stack state.
1756   struct StackStateOfBB {
1757     StackStateOfBB() : EntryValue(0), ExitValue(0), EntryIsSetup(false),
1758       ExitIsSetup(false) { }
1759     StackStateOfBB(int EntryVal, int ExitVal, bool EntrySetup, bool ExitSetup) :
1760       EntryValue(EntryVal), ExitValue(ExitVal), EntryIsSetup(EntrySetup),
1761       ExitIsSetup(ExitSetup) { }
1762     // Can be negative, which means we are setting up a frame.
1763     int EntryValue;
1764     int ExitValue;
1765     bool EntryIsSetup;
1766     bool ExitIsSetup;
1767   };
1768 }
1769
1770 /// Make sure on every path through the CFG, a FrameSetup <n> is always followed
1771 /// by a FrameDestroy <n>, stack adjustments are identical on all
1772 /// CFG edges to a merge point, and frame is destroyed at end of a return block.
1773 void MachineVerifier::verifyStackFrame() {
1774   unsigned FrameSetupOpcode   = TII->getCallFrameSetupOpcode();
1775   unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
1776
1777   SmallVector<StackStateOfBB, 8> SPState;
1778   SPState.resize(MF->getNumBlockIDs());
1779   SmallPtrSet<const MachineBasicBlock*, 8> Reachable;
1780
1781   // Visit the MBBs in DFS order.
1782   for (df_ext_iterator<const MachineFunction*,
1783                        SmallPtrSet<const MachineBasicBlock*, 8> >
1784        DFI = df_ext_begin(MF, Reachable), DFE = df_ext_end(MF, Reachable);
1785        DFI != DFE; ++DFI) {
1786     const MachineBasicBlock *MBB = *DFI;
1787
1788     StackStateOfBB BBState;
1789     // Check the exit state of the DFS stack predecessor.
1790     if (DFI.getPathLength() >= 2) {
1791       const MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
1792       assert(Reachable.count(StackPred) &&
1793              "DFS stack predecessor is already visited.\n");
1794       BBState.EntryValue = SPState[StackPred->getNumber()].ExitValue;
1795       BBState.EntryIsSetup = SPState[StackPred->getNumber()].ExitIsSetup;
1796       BBState.ExitValue = BBState.EntryValue;
1797       BBState.ExitIsSetup = BBState.EntryIsSetup;
1798     }
1799
1800     // Update stack state by checking contents of MBB.
1801     for (const auto &I : *MBB) {
1802       if (I.getOpcode() == FrameSetupOpcode) {
1803         // The first operand of a FrameOpcode should be i32.
1804         int Size = I.getOperand(0).getImm();
1805         assert(Size >= 0 &&
1806           "Value should be non-negative in FrameSetup and FrameDestroy.\n");
1807
1808         if (BBState.ExitIsSetup)
1809           report("FrameSetup is after another FrameSetup", &I);
1810         BBState.ExitValue -= Size;
1811         BBState.ExitIsSetup = true;
1812       }
1813
1814       if (I.getOpcode() == FrameDestroyOpcode) {
1815         // The first operand of a FrameOpcode should be i32.
1816         int Size = I.getOperand(0).getImm();
1817         assert(Size >= 0 &&
1818           "Value should be non-negative in FrameSetup and FrameDestroy.\n");
1819
1820         if (!BBState.ExitIsSetup)
1821           report("FrameDestroy is not after a FrameSetup", &I);
1822         int AbsSPAdj = BBState.ExitValue < 0 ? -BBState.ExitValue :
1823                                                BBState.ExitValue;
1824         if (BBState.ExitIsSetup && AbsSPAdj != Size) {
1825           report("FrameDestroy <n> is after FrameSetup <m>", &I);
1826           errs() << "FrameDestroy <" << Size << "> is after FrameSetup <"
1827               << AbsSPAdj << ">.\n";
1828         }
1829         BBState.ExitValue += Size;
1830         BBState.ExitIsSetup = false;
1831       }
1832     }
1833     SPState[MBB->getNumber()] = BBState;
1834
1835     // Make sure the exit state of any predecessor is consistent with the entry
1836     // state.
1837     for (MachineBasicBlock::const_pred_iterator I = MBB->pred_begin(),
1838          E = MBB->pred_end(); I != E; ++I) {
1839       if (Reachable.count(*I) &&
1840           (SPState[(*I)->getNumber()].ExitValue != BBState.EntryValue ||
1841            SPState[(*I)->getNumber()].ExitIsSetup != BBState.EntryIsSetup)) {
1842         report("The exit stack state of a predecessor is inconsistent.", MBB);
1843         errs() << "Predecessor BB#" << (*I)->getNumber() << " has exit state ("
1844             << SPState[(*I)->getNumber()].ExitValue << ", "
1845             << SPState[(*I)->getNumber()].ExitIsSetup
1846             << "), while BB#" << MBB->getNumber() << " has entry state ("
1847             << BBState.EntryValue << ", " << BBState.EntryIsSetup << ").\n";
1848       }
1849     }
1850
1851     // Make sure the entry state of any successor is consistent with the exit
1852     // state.
1853     for (MachineBasicBlock::const_succ_iterator I = MBB->succ_begin(),
1854          E = MBB->succ_end(); I != E; ++I) {
1855       if (Reachable.count(*I) &&
1856           (SPState[(*I)->getNumber()].EntryValue != BBState.ExitValue ||
1857            SPState[(*I)->getNumber()].EntryIsSetup != BBState.ExitIsSetup)) {
1858         report("The entry stack state of a successor is inconsistent.", MBB);
1859         errs() << "Successor BB#" << (*I)->getNumber() << " has entry state ("
1860             << SPState[(*I)->getNumber()].EntryValue << ", "
1861             << SPState[(*I)->getNumber()].EntryIsSetup
1862             << "), while BB#" << MBB->getNumber() << " has exit state ("
1863             << BBState.ExitValue << ", " << BBState.ExitIsSetup << ").\n";
1864       }
1865     }
1866
1867     // Make sure a basic block with return ends with zero stack adjustment.
1868     if (!MBB->empty() && MBB->back().isReturn()) {
1869       if (BBState.ExitIsSetup)
1870         report("A return block ends with a FrameSetup.", MBB);
1871       if (BBState.ExitValue)
1872         report("A return block ends with a nonzero stack adjustment.", MBB);
1873     }
1874   }
1875 }