MachineVerifier.cpp 63 KB

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