MachineVerifier.cpp 66 KB

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