MachineVerifier.cpp 85 KB

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