MachineVerifier.cpp 91 KB

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