MachineVerifier.cpp 119 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287
  1. //===- MachineVerifier.cpp - Machine Code Verifier ------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Pass to verify generated machine code. The following is checked:
  10. //
  11. // Operand counts: All explicit operands must be present.
  12. //
  13. // Register classes: All physical and virtual register operands must be
  14. // compatible with the register class required by the instruction descriptor.
  15. //
  16. // Register live intervals: Registers must be defined only once, and must be
  17. // defined before use.
  18. //
  19. // The machine code verifier is enabled with the command-line option
  20. // -verify-machineinstrs.
  21. //===----------------------------------------------------------------------===//
  22. #include "llvm/ADT/BitVector.h"
  23. #include "llvm/ADT/DenseMap.h"
  24. #include "llvm/ADT/DenseSet.h"
  25. #include "llvm/ADT/DepthFirstIterator.h"
  26. #include "llvm/ADT/PostOrderIterator.h"
  27. #include "llvm/ADT/STLExtras.h"
  28. #include "llvm/ADT/SetOperations.h"
  29. #include "llvm/ADT/SmallPtrSet.h"
  30. #include "llvm/ADT/SmallVector.h"
  31. #include "llvm/ADT/StringRef.h"
  32. #include "llvm/ADT/Twine.h"
  33. #include "llvm/Analysis/EHPersonalities.h"
  34. #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
  35. #include "llvm/CodeGen/LiveInterval.h"
  36. #include "llvm/CodeGen/LiveIntervalCalc.h"
  37. #include "llvm/CodeGen/LiveIntervals.h"
  38. #include "llvm/CodeGen/LiveStacks.h"
  39. #include "llvm/CodeGen/LiveVariables.h"
  40. #include "llvm/CodeGen/MachineBasicBlock.h"
  41. #include "llvm/CodeGen/MachineFrameInfo.h"
  42. #include "llvm/CodeGen/MachineFunction.h"
  43. #include "llvm/CodeGen/MachineFunctionPass.h"
  44. #include "llvm/CodeGen/MachineInstr.h"
  45. #include "llvm/CodeGen/MachineInstrBundle.h"
  46. #include "llvm/CodeGen/MachineMemOperand.h"
  47. #include "llvm/CodeGen/MachineOperand.h"
  48. #include "llvm/CodeGen/MachineRegisterInfo.h"
  49. #include "llvm/CodeGen/PseudoSourceValue.h"
  50. #include "llvm/CodeGen/SlotIndexes.h"
  51. #include "llvm/CodeGen/StackMaps.h"
  52. #include "llvm/CodeGen/TargetInstrInfo.h"
  53. #include "llvm/CodeGen/TargetOpcodes.h"
  54. #include "llvm/CodeGen/TargetRegisterInfo.h"
  55. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  56. #include "llvm/IR/BasicBlock.h"
  57. #include "llvm/IR/Function.h"
  58. #include "llvm/IR/InlineAsm.h"
  59. #include "llvm/IR/Instructions.h"
  60. #include "llvm/InitializePasses.h"
  61. #include "llvm/MC/LaneBitmask.h"
  62. #include "llvm/MC/MCAsmInfo.h"
  63. #include "llvm/MC/MCInstrDesc.h"
  64. #include "llvm/MC/MCRegisterInfo.h"
  65. #include "llvm/MC/MCTargetOptions.h"
  66. #include "llvm/Pass.h"
  67. #include "llvm/Support/Casting.h"
  68. #include "llvm/Support/ErrorHandling.h"
  69. #include "llvm/Support/LowLevelTypeImpl.h"
  70. #include "llvm/Support/MathExtras.h"
  71. #include "llvm/Support/raw_ostream.h"
  72. #include "llvm/Target/TargetMachine.h"
  73. #include <algorithm>
  74. #include <cassert>
  75. #include <cstddef>
  76. #include <cstdint>
  77. #include <iterator>
  78. #include <string>
  79. #include <utility>
  80. using namespace llvm;
  81. namespace {
  82. struct MachineVerifier {
  83. MachineVerifier(Pass *pass, const char *b) : PASS(pass), Banner(b) {}
  84. unsigned verify(const MachineFunction &MF);
  85. Pass *const PASS;
  86. const char *Banner;
  87. const MachineFunction *MF;
  88. const TargetMachine *TM;
  89. const TargetInstrInfo *TII;
  90. const TargetRegisterInfo *TRI;
  91. const MachineRegisterInfo *MRI;
  92. unsigned foundErrors;
  93. // Avoid querying the MachineFunctionProperties for each operand.
  94. bool isFunctionRegBankSelected;
  95. bool isFunctionSelected;
  96. bool isFunctionTracksDebugUserValues;
  97. using RegVector = SmallVector<Register, 16>;
  98. using RegMaskVector = SmallVector<const uint32_t *, 4>;
  99. using RegSet = DenseSet<Register>;
  100. using RegMap = DenseMap<Register, 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, Register Reg) {
  112. RV.push_back(Reg);
  113. if (Reg.isPhysical())
  114. append_range(RV, TRI->subregs(Reg.asMCReg()));
  115. }
  116. struct BBInfo {
  117. // Is this MBB reachable from the MF entry point?
  118. bool reachable = false;
  119. // Vregs that must be live in because they are used without being
  120. // defined. Map value is the user. vregsLiveIn doesn't include regs
  121. // that only are used by PHI nodes.
  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 vregsRequired if it belongs there. Return true if
  139. // anything changed.
  140. bool addRequired(Register Reg) {
  141. if (!Reg.isVirtual())
  142. return false;
  143. if (regsLiveOut.count(Reg))
  144. return false;
  145. return vregsRequired.insert(Reg).second;
  146. }
  147. // Same for a full set.
  148. bool addRequired(const RegSet &RS) {
  149. bool Changed = false;
  150. for (Register Reg : RS)
  151. Changed |= addRequired(Reg);
  152. return Changed;
  153. }
  154. // Same for a full map.
  155. bool addRequired(const RegMap &RM) {
  156. bool Changed = false;
  157. for (const auto &I : RM)
  158. Changed |= addRequired(I.first);
  159. return Changed;
  160. }
  161. // Live-out registers are either in regsLiveOut or vregsPassed.
  162. bool isLiveOut(Register Reg) const {
  163. return regsLiveOut.count(Reg) || vregsPassed.count(Reg);
  164. }
  165. };
  166. // Extra register info per MBB.
  167. DenseMap<const MachineBasicBlock*, BBInfo> MBBInfoMap;
  168. bool isReserved(Register Reg) {
  169. return Reg.id() < regsReserved.size() && regsReserved.test(Reg.id());
  170. }
  171. bool isAllocatable(Register Reg) const {
  172. return Reg.id() < TRI->getNumRegs() && TRI->isInAllocatableClass(Reg) &&
  173. !regsReserved.test(Reg.id());
  174. }
  175. // Analysis information if available
  176. LiveVariables *LiveVars;
  177. LiveIntervals *LiveInts;
  178. LiveStacks *LiveStks;
  179. SlotIndexes *Indexes;
  180. void visitMachineFunctionBefore();
  181. void visitMachineBasicBlockBefore(const MachineBasicBlock *MBB);
  182. void visitMachineBundleBefore(const MachineInstr *MI);
  183. /// Verify that all of \p MI's virtual register operands are scalars.
  184. /// \returns True if all virtual register operands are scalar. False
  185. /// otherwise.
  186. bool verifyAllRegOpsScalar(const MachineInstr &MI,
  187. const MachineRegisterInfo &MRI);
  188. bool verifyVectorElementMatch(LLT Ty0, LLT Ty1, const MachineInstr *MI);
  189. void verifyPreISelGenericInstruction(const MachineInstr *MI);
  190. void visitMachineInstrBefore(const MachineInstr *MI);
  191. void visitMachineOperand(const MachineOperand *MO, unsigned MONum);
  192. void visitMachineBundleAfter(const MachineInstr *MI);
  193. void visitMachineBasicBlockAfter(const MachineBasicBlock *MBB);
  194. void visitMachineFunctionAfter();
  195. void report(const char *msg, const MachineFunction *MF);
  196. void report(const char *msg, const MachineBasicBlock *MBB);
  197. void report(const char *msg, const MachineInstr *MI);
  198. void report(const char *msg, const MachineOperand *MO, unsigned MONum,
  199. LLT MOVRegType = LLT{});
  200. void report(const Twine &Msg, const MachineInstr *MI);
  201. void report_context(const LiveInterval &LI) const;
  202. void report_context(const LiveRange &LR, Register VRegUnit,
  203. LaneBitmask LaneMask) const;
  204. void report_context(const LiveRange::Segment &S) const;
  205. void report_context(const VNInfo &VNI) const;
  206. void report_context(SlotIndex Pos) const;
  207. void report_context(MCPhysReg PhysReg) const;
  208. void report_context_liverange(const LiveRange &LR) const;
  209. void report_context_lanemask(LaneBitmask LaneMask) const;
  210. void report_context_vreg(Register VReg) const;
  211. void report_context_vreg_regunit(Register VRegOrUnit) const;
  212. void verifyInlineAsm(const MachineInstr *MI);
  213. void checkLiveness(const MachineOperand *MO, unsigned MONum);
  214. void checkLivenessAtUse(const MachineOperand *MO, unsigned MONum,
  215. SlotIndex UseIdx, const LiveRange &LR,
  216. Register VRegOrUnit,
  217. LaneBitmask LaneMask = LaneBitmask::getNone());
  218. void checkLivenessAtDef(const MachineOperand *MO, unsigned MONum,
  219. SlotIndex DefIdx, const LiveRange &LR,
  220. Register VRegOrUnit, bool SubRangeCheck = false,
  221. LaneBitmask LaneMask = LaneBitmask::getNone());
  222. void markReachable(const MachineBasicBlock *MBB);
  223. void calcRegsPassed();
  224. void checkPHIOps(const MachineBasicBlock &MBB);
  225. void calcRegsRequired();
  226. void verifyLiveVariables();
  227. void verifyLiveIntervals();
  228. void verifyLiveInterval(const LiveInterval&);
  229. void verifyLiveRangeValue(const LiveRange &, const VNInfo *, Register,
  230. LaneBitmask);
  231. void verifyLiveRangeSegment(const LiveRange &,
  232. const LiveRange::const_iterator I, Register,
  233. LaneBitmask);
  234. void verifyLiveRange(const LiveRange &, Register,
  235. LaneBitmask LaneMask = LaneBitmask::getNone());
  236. void verifyStackFrame();
  237. void verifySlotIndexes() const;
  238. void verifyProperties(const MachineFunction &MF);
  239. };
  240. struct MachineVerifierPass : public MachineFunctionPass {
  241. static char ID; // Pass ID, replacement for typeid
  242. const std::string Banner;
  243. MachineVerifierPass(std::string banner = std::string())
  244. : MachineFunctionPass(ID), Banner(std::move(banner)) {
  245. initializeMachineVerifierPassPass(*PassRegistry::getPassRegistry());
  246. }
  247. void getAnalysisUsage(AnalysisUsage &AU) const override {
  248. AU.setPreservesAll();
  249. MachineFunctionPass::getAnalysisUsage(AU);
  250. }
  251. bool runOnMachineFunction(MachineFunction &MF) override {
  252. // Skip functions that have known verification problems.
  253. // FIXME: Remove this mechanism when all problematic passes have been
  254. // fixed.
  255. if (MF.getProperties().hasProperty(
  256. MachineFunctionProperties::Property::FailsVerification))
  257. return false;
  258. unsigned FoundErrors = MachineVerifier(this, Banner.c_str()).verify(MF);
  259. if (FoundErrors)
  260. report_fatal_error("Found "+Twine(FoundErrors)+" machine code errors.");
  261. return false;
  262. }
  263. };
  264. } // end anonymous namespace
  265. char MachineVerifierPass::ID = 0;
  266. INITIALIZE_PASS(MachineVerifierPass, "machineverifier",
  267. "Verify generated machine code", false, false)
  268. FunctionPass *llvm::createMachineVerifierPass(const std::string &Banner) {
  269. return new MachineVerifierPass(Banner);
  270. }
  271. void llvm::verifyMachineFunction(MachineFunctionAnalysisManager *,
  272. const std::string &Banner,
  273. const MachineFunction &MF) {
  274. // TODO: Use MFAM after porting below analyses.
  275. // LiveVariables *LiveVars;
  276. // LiveIntervals *LiveInts;
  277. // LiveStacks *LiveStks;
  278. // SlotIndexes *Indexes;
  279. unsigned FoundErrors = MachineVerifier(nullptr, Banner.c_str()).verify(MF);
  280. if (FoundErrors)
  281. report_fatal_error("Found " + Twine(FoundErrors) + " machine code errors.");
  282. }
  283. bool MachineFunction::verify(Pass *p, const char *Banner, bool AbortOnErrors)
  284. const {
  285. MachineFunction &MF = const_cast<MachineFunction&>(*this);
  286. unsigned FoundErrors = MachineVerifier(p, Banner).verify(MF);
  287. if (AbortOnErrors && FoundErrors)
  288. report_fatal_error("Found "+Twine(FoundErrors)+" machine code errors.");
  289. return FoundErrors == 0;
  290. }
  291. void MachineVerifier::verifySlotIndexes() const {
  292. if (Indexes == nullptr)
  293. return;
  294. // Ensure the IdxMBB list is sorted by slot indexes.
  295. SlotIndex Last;
  296. for (SlotIndexes::MBBIndexIterator I = Indexes->MBBIndexBegin(),
  297. E = Indexes->MBBIndexEnd(); I != E; ++I) {
  298. assert(!Last.isValid() || I->first > Last);
  299. Last = I->first;
  300. }
  301. }
  302. void MachineVerifier::verifyProperties(const MachineFunction &MF) {
  303. // If a pass has introduced virtual registers without clearing the
  304. // NoVRegs property (or set it without allocating the vregs)
  305. // then report an error.
  306. if (MF.getProperties().hasProperty(
  307. MachineFunctionProperties::Property::NoVRegs) &&
  308. MRI->getNumVirtRegs())
  309. report("Function has NoVRegs property but there are VReg operands", &MF);
  310. }
  311. unsigned MachineVerifier::verify(const MachineFunction &MF) {
  312. foundErrors = 0;
  313. this->MF = &MF;
  314. TM = &MF.getTarget();
  315. TII = MF.getSubtarget().getInstrInfo();
  316. TRI = MF.getSubtarget().getRegisterInfo();
  317. MRI = &MF.getRegInfo();
  318. const bool isFunctionFailedISel = MF.getProperties().hasProperty(
  319. MachineFunctionProperties::Property::FailedISel);
  320. // If we're mid-GlobalISel and we already triggered the fallback path then
  321. // it's expected that the MIR is somewhat broken but that's ok since we'll
  322. // reset it and clear the FailedISel attribute in ResetMachineFunctions.
  323. if (isFunctionFailedISel)
  324. return foundErrors;
  325. isFunctionRegBankSelected = MF.getProperties().hasProperty(
  326. MachineFunctionProperties::Property::RegBankSelected);
  327. isFunctionSelected = MF.getProperties().hasProperty(
  328. MachineFunctionProperties::Property::Selected);
  329. isFunctionTracksDebugUserValues = MF.getProperties().hasProperty(
  330. MachineFunctionProperties::Property::TracksDebugUserValues);
  331. LiveVars = nullptr;
  332. LiveInts = nullptr;
  333. LiveStks = nullptr;
  334. Indexes = nullptr;
  335. if (PASS) {
  336. LiveInts = PASS->getAnalysisIfAvailable<LiveIntervals>();
  337. // We don't want to verify LiveVariables if LiveIntervals is available.
  338. if (!LiveInts)
  339. LiveVars = PASS->getAnalysisIfAvailable<LiveVariables>();
  340. LiveStks = PASS->getAnalysisIfAvailable<LiveStacks>();
  341. Indexes = PASS->getAnalysisIfAvailable<SlotIndexes>();
  342. }
  343. verifySlotIndexes();
  344. verifyProperties(MF);
  345. visitMachineFunctionBefore();
  346. for (const MachineBasicBlock &MBB : MF) {
  347. visitMachineBasicBlockBefore(&MBB);
  348. // Keep track of the current bundle header.
  349. const MachineInstr *CurBundle = nullptr;
  350. // Do we expect the next instruction to be part of the same bundle?
  351. bool InBundle = false;
  352. for (const MachineInstr &MI : MBB.instrs()) {
  353. if (MI.getParent() != &MBB) {
  354. report("Bad instruction parent pointer", &MBB);
  355. errs() << "Instruction: " << MI;
  356. continue;
  357. }
  358. // Check for consistent bundle flags.
  359. if (InBundle && !MI.isBundledWithPred())
  360. report("Missing BundledPred flag, "
  361. "BundledSucc was set on predecessor",
  362. &MI);
  363. if (!InBundle && MI.isBundledWithPred())
  364. report("BundledPred flag is set, "
  365. "but BundledSucc not set on predecessor",
  366. &MI);
  367. // Is this a bundle header?
  368. if (!MI.isInsideBundle()) {
  369. if (CurBundle)
  370. visitMachineBundleAfter(CurBundle);
  371. CurBundle = &MI;
  372. visitMachineBundleBefore(CurBundle);
  373. } else if (!CurBundle)
  374. report("No bundle header", &MI);
  375. visitMachineInstrBefore(&MI);
  376. for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
  377. const MachineOperand &Op = MI.getOperand(I);
  378. if (Op.getParent() != &MI) {
  379. // Make sure to use correct addOperand / RemoveOperand / ChangeTo
  380. // functions when replacing operands of a MachineInstr.
  381. report("Instruction has operand with wrong parent set", &MI);
  382. }
  383. visitMachineOperand(&Op, I);
  384. }
  385. // Was this the last bundled instruction?
  386. InBundle = MI.isBundledWithSucc();
  387. }
  388. if (CurBundle)
  389. visitMachineBundleAfter(CurBundle);
  390. if (InBundle)
  391. report("BundledSucc flag set on last instruction in block", &MBB.back());
  392. visitMachineBasicBlockAfter(&MBB);
  393. }
  394. visitMachineFunctionAfter();
  395. // Clean up.
  396. regsLive.clear();
  397. regsDefined.clear();
  398. regsDead.clear();
  399. regsKilled.clear();
  400. regMasks.clear();
  401. MBBInfoMap.clear();
  402. return foundErrors;
  403. }
  404. void MachineVerifier::report(const char *msg, const MachineFunction *MF) {
  405. assert(MF);
  406. errs() << '\n';
  407. if (!foundErrors++) {
  408. if (Banner)
  409. errs() << "# " << Banner << '\n';
  410. if (LiveInts != nullptr)
  411. LiveInts->print(errs());
  412. else
  413. MF->print(errs(), Indexes);
  414. }
  415. errs() << "*** Bad machine code: " << msg << " ***\n"
  416. << "- function: " << MF->getName() << "\n";
  417. }
  418. void MachineVerifier::report(const char *msg, const MachineBasicBlock *MBB) {
  419. assert(MBB);
  420. report(msg, MBB->getParent());
  421. errs() << "- basic block: " << printMBBReference(*MBB) << ' '
  422. << MBB->getName() << " (" << (const void *)MBB << ')';
  423. if (Indexes)
  424. errs() << " [" << Indexes->getMBBStartIdx(MBB)
  425. << ';' << Indexes->getMBBEndIdx(MBB) << ')';
  426. errs() << '\n';
  427. }
  428. void MachineVerifier::report(const char *msg, const MachineInstr *MI) {
  429. assert(MI);
  430. report(msg, MI->getParent());
  431. errs() << "- instruction: ";
  432. if (Indexes && Indexes->hasIndex(*MI))
  433. errs() << Indexes->getInstructionIndex(*MI) << '\t';
  434. MI->print(errs(), /*IsStandalone=*/true);
  435. }
  436. void MachineVerifier::report(const char *msg, const MachineOperand *MO,
  437. unsigned MONum, LLT MOVRegType) {
  438. assert(MO);
  439. report(msg, MO->getParent());
  440. errs() << "- operand " << MONum << ": ";
  441. MO->print(errs(), MOVRegType, TRI);
  442. errs() << "\n";
  443. }
  444. void MachineVerifier::report(const Twine &Msg, const MachineInstr *MI) {
  445. report(Msg.str().c_str(), MI);
  446. }
  447. void MachineVerifier::report_context(SlotIndex Pos) const {
  448. errs() << "- at: " << Pos << '\n';
  449. }
  450. void MachineVerifier::report_context(const LiveInterval &LI) const {
  451. errs() << "- interval: " << LI << '\n';
  452. }
  453. void MachineVerifier::report_context(const LiveRange &LR, Register VRegUnit,
  454. LaneBitmask LaneMask) const {
  455. report_context_liverange(LR);
  456. report_context_vreg_regunit(VRegUnit);
  457. if (LaneMask.any())
  458. report_context_lanemask(LaneMask);
  459. }
  460. void MachineVerifier::report_context(const LiveRange::Segment &S) const {
  461. errs() << "- segment: " << S << '\n';
  462. }
  463. void MachineVerifier::report_context(const VNInfo &VNI) const {
  464. errs() << "- ValNo: " << VNI.id << " (def " << VNI.def << ")\n";
  465. }
  466. void MachineVerifier::report_context_liverange(const LiveRange &LR) const {
  467. errs() << "- liverange: " << LR << '\n';
  468. }
  469. void MachineVerifier::report_context(MCPhysReg PReg) const {
  470. errs() << "- p. register: " << printReg(PReg, TRI) << '\n';
  471. }
  472. void MachineVerifier::report_context_vreg(Register VReg) const {
  473. errs() << "- v. register: " << printReg(VReg, TRI) << '\n';
  474. }
  475. void MachineVerifier::report_context_vreg_regunit(Register VRegOrUnit) const {
  476. if (Register::isVirtualRegister(VRegOrUnit)) {
  477. report_context_vreg(VRegOrUnit);
  478. } else {
  479. errs() << "- regunit: " << printRegUnit(VRegOrUnit, TRI) << '\n';
  480. }
  481. }
  482. void MachineVerifier::report_context_lanemask(LaneBitmask LaneMask) const {
  483. errs() << "- lanemask: " << PrintLaneMask(LaneMask) << '\n';
  484. }
  485. void MachineVerifier::markReachable(const MachineBasicBlock *MBB) {
  486. BBInfo &MInfo = MBBInfoMap[MBB];
  487. if (!MInfo.reachable) {
  488. MInfo.reachable = true;
  489. for (const MachineBasicBlock *Succ : MBB->successors())
  490. markReachable(Succ);
  491. }
  492. }
  493. void MachineVerifier::visitMachineFunctionBefore() {
  494. lastIndex = SlotIndex();
  495. regsReserved = MRI->reservedRegsFrozen() ? MRI->getReservedRegs()
  496. : TRI->getReservedRegs(*MF);
  497. if (!MF->empty())
  498. markReachable(&MF->front());
  499. // Build a set of the basic blocks in the function.
  500. FunctionBlocks.clear();
  501. for (const auto &MBB : *MF) {
  502. FunctionBlocks.insert(&MBB);
  503. BBInfo &MInfo = MBBInfoMap[&MBB];
  504. MInfo.Preds.insert(MBB.pred_begin(), MBB.pred_end());
  505. if (MInfo.Preds.size() != MBB.pred_size())
  506. report("MBB has duplicate entries in its predecessor list.", &MBB);
  507. MInfo.Succs.insert(MBB.succ_begin(), MBB.succ_end());
  508. if (MInfo.Succs.size() != MBB.succ_size())
  509. report("MBB has duplicate entries in its successor list.", &MBB);
  510. }
  511. // Check that the register use lists are sane.
  512. MRI->verifyUseLists();
  513. if (!MF->empty())
  514. verifyStackFrame();
  515. }
  516. void
  517. MachineVerifier::visitMachineBasicBlockBefore(const MachineBasicBlock *MBB) {
  518. FirstTerminator = nullptr;
  519. FirstNonPHI = nullptr;
  520. if (!MF->getProperties().hasProperty(
  521. MachineFunctionProperties::Property::NoPHIs) && MRI->tracksLiveness()) {
  522. // If this block has allocatable physical registers live-in, check that
  523. // it is an entry block or landing pad.
  524. for (const auto &LI : MBB->liveins()) {
  525. if (isAllocatable(LI.PhysReg) && !MBB->isEHPad() &&
  526. MBB->getIterator() != MBB->getParent()->begin()) {
  527. report("MBB has allocatable live-in, but isn't entry or landing-pad.", MBB);
  528. report_context(LI.PhysReg);
  529. }
  530. }
  531. }
  532. // Count the number of landing pad successors.
  533. SmallPtrSet<const MachineBasicBlock*, 4> LandingPadSuccs;
  534. for (const auto *succ : MBB->successors()) {
  535. if (succ->isEHPad())
  536. LandingPadSuccs.insert(succ);
  537. if (!FunctionBlocks.count(succ))
  538. report("MBB has successor that isn't part of the function.", MBB);
  539. if (!MBBInfoMap[succ].Preds.count(MBB)) {
  540. report("Inconsistent CFG", MBB);
  541. errs() << "MBB is not in the predecessor list of the successor "
  542. << printMBBReference(*succ) << ".\n";
  543. }
  544. }
  545. // Check the predecessor list.
  546. for (const MachineBasicBlock *Pred : MBB->predecessors()) {
  547. if (!FunctionBlocks.count(Pred))
  548. report("MBB has predecessor that isn't part of the function.", MBB);
  549. if (!MBBInfoMap[Pred].Succs.count(MBB)) {
  550. report("Inconsistent CFG", MBB);
  551. errs() << "MBB is not in the successor list of the predecessor "
  552. << printMBBReference(*Pred) << ".\n";
  553. }
  554. }
  555. const MCAsmInfo *AsmInfo = TM->getMCAsmInfo();
  556. const BasicBlock *BB = MBB->getBasicBlock();
  557. const Function &F = MF->getFunction();
  558. if (LandingPadSuccs.size() > 1 &&
  559. !(AsmInfo &&
  560. AsmInfo->getExceptionHandlingType() == ExceptionHandling::SjLj &&
  561. BB && isa<SwitchInst>(BB->getTerminator())) &&
  562. !isScopedEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
  563. report("MBB has more than one landing pad successor", MBB);
  564. // Call analyzeBranch. If it succeeds, there several more conditions to check.
  565. MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
  566. SmallVector<MachineOperand, 4> Cond;
  567. if (!TII->analyzeBranch(*const_cast<MachineBasicBlock *>(MBB), TBB, FBB,
  568. Cond)) {
  569. // Ok, analyzeBranch thinks it knows what's going on with this block. Let's
  570. // check whether its answers match up with reality.
  571. if (!TBB && !FBB) {
  572. // Block falls through to its successor.
  573. if (!MBB->empty() && MBB->back().isBarrier() &&
  574. !TII->isPredicated(MBB->back())) {
  575. report("MBB exits via unconditional fall-through but ends with a "
  576. "barrier instruction!", MBB);
  577. }
  578. if (!Cond.empty()) {
  579. report("MBB exits via unconditional fall-through but has a condition!",
  580. MBB);
  581. }
  582. } else if (TBB && !FBB && Cond.empty()) {
  583. // Block unconditionally branches somewhere.
  584. if (MBB->empty()) {
  585. report("MBB exits via unconditional branch but doesn't contain "
  586. "any instructions!", MBB);
  587. } else if (!MBB->back().isBarrier()) {
  588. report("MBB exits via unconditional branch but doesn't end with a "
  589. "barrier instruction!", MBB);
  590. } else if (!MBB->back().isTerminator()) {
  591. report("MBB exits via unconditional branch but the branch isn't a "
  592. "terminator instruction!", MBB);
  593. }
  594. } else if (TBB && !FBB && !Cond.empty()) {
  595. // Block conditionally branches somewhere, otherwise falls through.
  596. if (MBB->empty()) {
  597. report("MBB exits via conditional branch/fall-through but doesn't "
  598. "contain any instructions!", MBB);
  599. } else if (MBB->back().isBarrier()) {
  600. report("MBB exits via conditional branch/fall-through but ends with a "
  601. "barrier instruction!", MBB);
  602. } else if (!MBB->back().isTerminator()) {
  603. report("MBB exits via conditional branch/fall-through but the branch "
  604. "isn't a terminator instruction!", MBB);
  605. }
  606. } else if (TBB && FBB) {
  607. // Block conditionally branches somewhere, otherwise branches
  608. // somewhere else.
  609. if (MBB->empty()) {
  610. report("MBB exits via conditional branch/branch but doesn't "
  611. "contain any instructions!", MBB);
  612. } else if (!MBB->back().isBarrier()) {
  613. report("MBB exits via conditional branch/branch but doesn't end with a "
  614. "barrier instruction!", MBB);
  615. } else if (!MBB->back().isTerminator()) {
  616. report("MBB exits via conditional branch/branch but the branch "
  617. "isn't a terminator instruction!", MBB);
  618. }
  619. if (Cond.empty()) {
  620. report("MBB exits via conditional branch/branch but there's no "
  621. "condition!", MBB);
  622. }
  623. } else {
  624. report("analyzeBranch returned invalid data!", MBB);
  625. }
  626. // Now check that the successors match up with the answers reported by
  627. // analyzeBranch.
  628. if (TBB && !MBB->isSuccessor(TBB))
  629. report("MBB exits via jump or conditional branch, but its target isn't a "
  630. "CFG successor!",
  631. MBB);
  632. if (FBB && !MBB->isSuccessor(FBB))
  633. report("MBB exits via conditional branch, but its target isn't a CFG "
  634. "successor!",
  635. MBB);
  636. // There might be a fallthrough to the next block if there's either no
  637. // unconditional true branch, or if there's a condition, and one of the
  638. // branches is missing.
  639. bool Fallthrough = !TBB || (!Cond.empty() && !FBB);
  640. // A conditional fallthrough must be an actual CFG successor, not
  641. // unreachable. (Conversely, an unconditional fallthrough might not really
  642. // be a successor, because the block might end in unreachable.)
  643. if (!Cond.empty() && !FBB) {
  644. MachineFunction::const_iterator MBBI = std::next(MBB->getIterator());
  645. if (MBBI == MF->end()) {
  646. report("MBB conditionally falls through out of function!", MBB);
  647. } else if (!MBB->isSuccessor(&*MBBI))
  648. report("MBB exits via conditional branch/fall-through but the CFG "
  649. "successors don't match the actual successors!",
  650. MBB);
  651. }
  652. // Verify that there aren't any extra un-accounted-for successors.
  653. for (const MachineBasicBlock *SuccMBB : MBB->successors()) {
  654. // If this successor is one of the branch targets, it's okay.
  655. if (SuccMBB == TBB || SuccMBB == FBB)
  656. continue;
  657. // If we might have a fallthrough, and the successor is the fallthrough
  658. // block, that's also ok.
  659. if (Fallthrough && SuccMBB == MBB->getNextNode())
  660. continue;
  661. // Also accept successors which are for exception-handling or might be
  662. // inlineasm_br targets.
  663. if (SuccMBB->isEHPad() || SuccMBB->isInlineAsmBrIndirectTarget())
  664. continue;
  665. report("MBB has unexpected successors which are not branch targets, "
  666. "fallthrough, EHPads, or inlineasm_br targets.",
  667. MBB);
  668. }
  669. }
  670. regsLive.clear();
  671. if (MRI->tracksLiveness()) {
  672. for (const auto &LI : MBB->liveins()) {
  673. if (!Register::isPhysicalRegister(LI.PhysReg)) {
  674. report("MBB live-in list contains non-physical register", MBB);
  675. continue;
  676. }
  677. for (const MCPhysReg &SubReg : TRI->subregs_inclusive(LI.PhysReg))
  678. regsLive.insert(SubReg);
  679. }
  680. }
  681. const MachineFrameInfo &MFI = MF->getFrameInfo();
  682. BitVector PR = MFI.getPristineRegs(*MF);
  683. for (unsigned I : PR.set_bits()) {
  684. for (const MCPhysReg &SubReg : TRI->subregs_inclusive(I))
  685. regsLive.insert(SubReg);
  686. }
  687. regsKilled.clear();
  688. regsDefined.clear();
  689. if (Indexes)
  690. lastIndex = Indexes->getMBBStartIdx(MBB);
  691. }
  692. // This function gets called for all bundle headers, including normal
  693. // stand-alone unbundled instructions.
  694. void MachineVerifier::visitMachineBundleBefore(const MachineInstr *MI) {
  695. if (Indexes && Indexes->hasIndex(*MI)) {
  696. SlotIndex idx = Indexes->getInstructionIndex(*MI);
  697. if (!(idx > lastIndex)) {
  698. report("Instruction index out of order", MI);
  699. errs() << "Last instruction was at " << lastIndex << '\n';
  700. }
  701. lastIndex = idx;
  702. }
  703. // Ensure non-terminators don't follow terminators.
  704. if (MI->isTerminator()) {
  705. if (!FirstTerminator)
  706. FirstTerminator = MI;
  707. } else if (FirstTerminator) {
  708. report("Non-terminator instruction after the first terminator", MI);
  709. errs() << "First terminator was:\t" << *FirstTerminator;
  710. }
  711. }
  712. // The operands on an INLINEASM instruction must follow a template.
  713. // Verify that the flag operands make sense.
  714. void MachineVerifier::verifyInlineAsm(const MachineInstr *MI) {
  715. // The first two operands on INLINEASM are the asm string and global flags.
  716. if (MI->getNumOperands() < 2) {
  717. report("Too few operands on inline asm", MI);
  718. return;
  719. }
  720. if (!MI->getOperand(0).isSymbol())
  721. report("Asm string must be an external symbol", MI);
  722. if (!MI->getOperand(1).isImm())
  723. report("Asm flags must be an immediate", MI);
  724. // Allowed flags are Extra_HasSideEffects = 1, Extra_IsAlignStack = 2,
  725. // Extra_AsmDialect = 4, Extra_MayLoad = 8, and Extra_MayStore = 16,
  726. // and Extra_IsConvergent = 32.
  727. if (!isUInt<6>(MI->getOperand(1).getImm()))
  728. report("Unknown asm flags", &MI->getOperand(1), 1);
  729. static_assert(InlineAsm::MIOp_FirstOperand == 2, "Asm format changed");
  730. unsigned OpNo = InlineAsm::MIOp_FirstOperand;
  731. unsigned NumOps;
  732. for (unsigned e = MI->getNumOperands(); OpNo < e; OpNo += NumOps) {
  733. const MachineOperand &MO = MI->getOperand(OpNo);
  734. // There may be implicit ops after the fixed operands.
  735. if (!MO.isImm())
  736. break;
  737. NumOps = 1 + InlineAsm::getNumOperandRegisters(MO.getImm());
  738. }
  739. if (OpNo > MI->getNumOperands())
  740. report("Missing operands in last group", MI);
  741. // An optional MDNode follows the groups.
  742. if (OpNo < MI->getNumOperands() && MI->getOperand(OpNo).isMetadata())
  743. ++OpNo;
  744. // All trailing operands must be implicit registers.
  745. for (unsigned e = MI->getNumOperands(); OpNo < e; ++OpNo) {
  746. const MachineOperand &MO = MI->getOperand(OpNo);
  747. if (!MO.isReg() || !MO.isImplicit())
  748. report("Expected implicit register after groups", &MO, OpNo);
  749. }
  750. }
  751. bool MachineVerifier::verifyAllRegOpsScalar(const MachineInstr &MI,
  752. const MachineRegisterInfo &MRI) {
  753. if (none_of(MI.explicit_operands(), [&MRI](const MachineOperand &Op) {
  754. if (!Op.isReg())
  755. return false;
  756. const auto Reg = Op.getReg();
  757. if (Reg.isPhysical())
  758. return false;
  759. return !MRI.getType(Reg).isScalar();
  760. }))
  761. return true;
  762. report("All register operands must have scalar types", &MI);
  763. return false;
  764. }
  765. /// Check that types are consistent when two operands need to have the same
  766. /// number of vector elements.
  767. /// \return true if the types are valid.
  768. bool MachineVerifier::verifyVectorElementMatch(LLT Ty0, LLT Ty1,
  769. const MachineInstr *MI) {
  770. if (Ty0.isVector() != Ty1.isVector()) {
  771. report("operand types must be all-vector or all-scalar", MI);
  772. // Generally we try to report as many issues as possible at once, but in
  773. // this case it's not clear what should we be comparing the size of the
  774. // scalar with: the size of the whole vector or its lane. Instead of
  775. // making an arbitrary choice and emitting not so helpful message, let's
  776. // avoid the extra noise and stop here.
  777. return false;
  778. }
  779. if (Ty0.isVector() && Ty0.getNumElements() != Ty1.getNumElements()) {
  780. report("operand types must preserve number of vector elements", MI);
  781. return false;
  782. }
  783. return true;
  784. }
  785. void MachineVerifier::verifyPreISelGenericInstruction(const MachineInstr *MI) {
  786. if (isFunctionSelected)
  787. report("Unexpected generic instruction in a Selected function", MI);
  788. const MCInstrDesc &MCID = MI->getDesc();
  789. unsigned NumOps = MI->getNumOperands();
  790. // Branches must reference a basic block if they are not indirect
  791. if (MI->isBranch() && !MI->isIndirectBranch()) {
  792. bool HasMBB = false;
  793. for (const MachineOperand &Op : MI->operands()) {
  794. if (Op.isMBB()) {
  795. HasMBB = true;
  796. break;
  797. }
  798. }
  799. if (!HasMBB) {
  800. report("Branch instruction is missing a basic block operand or "
  801. "isIndirectBranch property",
  802. MI);
  803. }
  804. }
  805. // Check types.
  806. SmallVector<LLT, 4> Types;
  807. for (unsigned I = 0, E = std::min(MCID.getNumOperands(), NumOps);
  808. I != E; ++I) {
  809. if (!MCID.OpInfo[I].isGenericType())
  810. continue;
  811. // Generic instructions specify type equality constraints between some of
  812. // their operands. Make sure these are consistent.
  813. size_t TypeIdx = MCID.OpInfo[I].getGenericTypeIndex();
  814. Types.resize(std::max(TypeIdx + 1, Types.size()));
  815. const MachineOperand *MO = &MI->getOperand(I);
  816. if (!MO->isReg()) {
  817. report("generic instruction must use register operands", MI);
  818. continue;
  819. }
  820. LLT OpTy = MRI->getType(MO->getReg());
  821. // Don't report a type mismatch if there is no actual mismatch, only a
  822. // type missing, to reduce noise:
  823. if (OpTy.isValid()) {
  824. // Only the first valid type for a type index will be printed: don't
  825. // overwrite it later so it's always clear which type was expected:
  826. if (!Types[TypeIdx].isValid())
  827. Types[TypeIdx] = OpTy;
  828. else if (Types[TypeIdx] != OpTy)
  829. report("Type mismatch in generic instruction", MO, I, OpTy);
  830. } else {
  831. // Generic instructions must have types attached to their operands.
  832. report("Generic instruction is missing a virtual register type", MO, I);
  833. }
  834. }
  835. // Generic opcodes must not have physical register operands.
  836. for (unsigned I = 0; I < MI->getNumOperands(); ++I) {
  837. const MachineOperand *MO = &MI->getOperand(I);
  838. if (MO->isReg() && Register::isPhysicalRegister(MO->getReg()))
  839. report("Generic instruction cannot have physical register", MO, I);
  840. }
  841. // Avoid out of bounds in checks below. This was already reported earlier.
  842. if (MI->getNumOperands() < MCID.getNumOperands())
  843. return;
  844. StringRef ErrorInfo;
  845. if (!TII->verifyInstruction(*MI, ErrorInfo))
  846. report(ErrorInfo.data(), MI);
  847. // Verify properties of various specific instruction types
  848. unsigned Opc = MI->getOpcode();
  849. switch (Opc) {
  850. case TargetOpcode::G_ASSERT_SEXT:
  851. case TargetOpcode::G_ASSERT_ZEXT: {
  852. std::string OpcName =
  853. Opc == TargetOpcode::G_ASSERT_ZEXT ? "G_ASSERT_ZEXT" : "G_ASSERT_SEXT";
  854. if (!MI->getOperand(2).isImm()) {
  855. report(Twine(OpcName, " expects an immediate operand #2"), MI);
  856. break;
  857. }
  858. Register Dst = MI->getOperand(0).getReg();
  859. Register Src = MI->getOperand(1).getReg();
  860. LLT SrcTy = MRI->getType(Src);
  861. int64_t Imm = MI->getOperand(2).getImm();
  862. if (Imm <= 0) {
  863. report(Twine(OpcName, " size must be >= 1"), MI);
  864. break;
  865. }
  866. if (Imm >= SrcTy.getScalarSizeInBits()) {
  867. report(Twine(OpcName, " size must be less than source bit width"), MI);
  868. break;
  869. }
  870. if (MRI->getRegBankOrNull(Src) != MRI->getRegBankOrNull(Dst)) {
  871. report(
  872. Twine(OpcName, " source and destination register banks must match"),
  873. MI);
  874. break;
  875. }
  876. if (MRI->getRegClassOrNull(Src) != MRI->getRegClassOrNull(Dst))
  877. report(
  878. Twine(OpcName, " source and destination register classes must match"),
  879. MI);
  880. break;
  881. }
  882. case TargetOpcode::G_CONSTANT:
  883. case TargetOpcode::G_FCONSTANT: {
  884. LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
  885. if (DstTy.isVector())
  886. report("Instruction cannot use a vector result type", MI);
  887. if (MI->getOpcode() == TargetOpcode::G_CONSTANT) {
  888. if (!MI->getOperand(1).isCImm()) {
  889. report("G_CONSTANT operand must be cimm", MI);
  890. break;
  891. }
  892. const ConstantInt *CI = MI->getOperand(1).getCImm();
  893. if (CI->getBitWidth() != DstTy.getSizeInBits())
  894. report("inconsistent constant size", MI);
  895. } else {
  896. if (!MI->getOperand(1).isFPImm()) {
  897. report("G_FCONSTANT operand must be fpimm", MI);
  898. break;
  899. }
  900. const ConstantFP *CF = MI->getOperand(1).getFPImm();
  901. if (APFloat::getSizeInBits(CF->getValueAPF().getSemantics()) !=
  902. DstTy.getSizeInBits()) {
  903. report("inconsistent constant size", MI);
  904. }
  905. }
  906. break;
  907. }
  908. case TargetOpcode::G_LOAD:
  909. case TargetOpcode::G_STORE:
  910. case TargetOpcode::G_ZEXTLOAD:
  911. case TargetOpcode::G_SEXTLOAD: {
  912. LLT ValTy = MRI->getType(MI->getOperand(0).getReg());
  913. LLT PtrTy = MRI->getType(MI->getOperand(1).getReg());
  914. if (!PtrTy.isPointer())
  915. report("Generic memory instruction must access a pointer", MI);
  916. // Generic loads and stores must have a single MachineMemOperand
  917. // describing that access.
  918. if (!MI->hasOneMemOperand()) {
  919. report("Generic instruction accessing memory must have one mem operand",
  920. MI);
  921. } else {
  922. const MachineMemOperand &MMO = **MI->memoperands_begin();
  923. if (MI->getOpcode() == TargetOpcode::G_ZEXTLOAD ||
  924. MI->getOpcode() == TargetOpcode::G_SEXTLOAD) {
  925. if (MMO.getSizeInBits() >= ValTy.getSizeInBits())
  926. report("Generic extload must have a narrower memory type", MI);
  927. } else if (MI->getOpcode() == TargetOpcode::G_LOAD) {
  928. if (MMO.getSize() > ValTy.getSizeInBytes())
  929. report("load memory size cannot exceed result size", MI);
  930. } else if (MI->getOpcode() == TargetOpcode::G_STORE) {
  931. if (ValTy.getSizeInBytes() < MMO.getSize())
  932. report("store memory size cannot exceed value size", MI);
  933. }
  934. }
  935. break;
  936. }
  937. case TargetOpcode::G_PHI: {
  938. LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
  939. if (!DstTy.isValid() || !all_of(drop_begin(MI->operands()),
  940. [this, &DstTy](const MachineOperand &MO) {
  941. if (!MO.isReg())
  942. return true;
  943. LLT Ty = MRI->getType(MO.getReg());
  944. if (!Ty.isValid() || (Ty != DstTy))
  945. return false;
  946. return true;
  947. }))
  948. report("Generic Instruction G_PHI has operands with incompatible/missing "
  949. "types",
  950. MI);
  951. break;
  952. }
  953. case TargetOpcode::G_BITCAST: {
  954. LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
  955. LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
  956. if (!DstTy.isValid() || !SrcTy.isValid())
  957. break;
  958. if (SrcTy.isPointer() != DstTy.isPointer())
  959. report("bitcast cannot convert between pointers and other types", MI);
  960. if (SrcTy.getSizeInBits() != DstTy.getSizeInBits())
  961. report("bitcast sizes must match", MI);
  962. if (SrcTy == DstTy)
  963. report("bitcast must change the type", MI);
  964. break;
  965. }
  966. case TargetOpcode::G_INTTOPTR:
  967. case TargetOpcode::G_PTRTOINT:
  968. case TargetOpcode::G_ADDRSPACE_CAST: {
  969. LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
  970. LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
  971. if (!DstTy.isValid() || !SrcTy.isValid())
  972. break;
  973. verifyVectorElementMatch(DstTy, SrcTy, MI);
  974. DstTy = DstTy.getScalarType();
  975. SrcTy = SrcTy.getScalarType();
  976. if (MI->getOpcode() == TargetOpcode::G_INTTOPTR) {
  977. if (!DstTy.isPointer())
  978. report("inttoptr result type must be a pointer", MI);
  979. if (SrcTy.isPointer())
  980. report("inttoptr source type must not be a pointer", MI);
  981. } else if (MI->getOpcode() == TargetOpcode::G_PTRTOINT) {
  982. if (!SrcTy.isPointer())
  983. report("ptrtoint source type must be a pointer", MI);
  984. if (DstTy.isPointer())
  985. report("ptrtoint result type must not be a pointer", MI);
  986. } else {
  987. assert(MI->getOpcode() == TargetOpcode::G_ADDRSPACE_CAST);
  988. if (!SrcTy.isPointer() || !DstTy.isPointer())
  989. report("addrspacecast types must be pointers", MI);
  990. else {
  991. if (SrcTy.getAddressSpace() == DstTy.getAddressSpace())
  992. report("addrspacecast must convert different address spaces", MI);
  993. }
  994. }
  995. break;
  996. }
  997. case TargetOpcode::G_PTR_ADD: {
  998. LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
  999. LLT PtrTy = MRI->getType(MI->getOperand(1).getReg());
  1000. LLT OffsetTy = MRI->getType(MI->getOperand(2).getReg());
  1001. if (!DstTy.isValid() || !PtrTy.isValid() || !OffsetTy.isValid())
  1002. break;
  1003. if (!PtrTy.getScalarType().isPointer())
  1004. report("gep first operand must be a pointer", MI);
  1005. if (OffsetTy.getScalarType().isPointer())
  1006. report("gep offset operand must not be a pointer", MI);
  1007. // TODO: Is the offset allowed to be a scalar with a vector?
  1008. break;
  1009. }
  1010. case TargetOpcode::G_PTRMASK: {
  1011. LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
  1012. LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
  1013. LLT MaskTy = MRI->getType(MI->getOperand(2).getReg());
  1014. if (!DstTy.isValid() || !SrcTy.isValid() || !MaskTy.isValid())
  1015. break;
  1016. if (!DstTy.getScalarType().isPointer())
  1017. report("ptrmask result type must be a pointer", MI);
  1018. if (!MaskTy.getScalarType().isScalar())
  1019. report("ptrmask mask type must be an integer", MI);
  1020. verifyVectorElementMatch(DstTy, MaskTy, MI);
  1021. break;
  1022. }
  1023. case TargetOpcode::G_SEXT:
  1024. case TargetOpcode::G_ZEXT:
  1025. case TargetOpcode::G_ANYEXT:
  1026. case TargetOpcode::G_TRUNC:
  1027. case TargetOpcode::G_FPEXT:
  1028. case TargetOpcode::G_FPTRUNC: {
  1029. // Number of operands and presense of types is already checked (and
  1030. // reported in case of any issues), so no need to report them again. As
  1031. // we're trying to report as many issues as possible at once, however, the
  1032. // instructions aren't guaranteed to have the right number of operands or
  1033. // types attached to them at this point
  1034. assert(MCID.getNumOperands() == 2 && "Expected 2 operands G_*{EXT,TRUNC}");
  1035. LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
  1036. LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
  1037. if (!DstTy.isValid() || !SrcTy.isValid())
  1038. break;
  1039. LLT DstElTy = DstTy.getScalarType();
  1040. LLT SrcElTy = SrcTy.getScalarType();
  1041. if (DstElTy.isPointer() || SrcElTy.isPointer())
  1042. report("Generic extend/truncate can not operate on pointers", MI);
  1043. verifyVectorElementMatch(DstTy, SrcTy, MI);
  1044. unsigned DstSize = DstElTy.getSizeInBits();
  1045. unsigned SrcSize = SrcElTy.getSizeInBits();
  1046. switch (MI->getOpcode()) {
  1047. default:
  1048. if (DstSize <= SrcSize)
  1049. report("Generic extend has destination type no larger than source", MI);
  1050. break;
  1051. case TargetOpcode::G_TRUNC:
  1052. case TargetOpcode::G_FPTRUNC:
  1053. if (DstSize >= SrcSize)
  1054. report("Generic truncate has destination type no smaller than source",
  1055. MI);
  1056. break;
  1057. }
  1058. break;
  1059. }
  1060. case TargetOpcode::G_SELECT: {
  1061. LLT SelTy = MRI->getType(MI->getOperand(0).getReg());
  1062. LLT CondTy = MRI->getType(MI->getOperand(1).getReg());
  1063. if (!SelTy.isValid() || !CondTy.isValid())
  1064. break;
  1065. // Scalar condition select on a vector is valid.
  1066. if (CondTy.isVector())
  1067. verifyVectorElementMatch(SelTy, CondTy, MI);
  1068. break;
  1069. }
  1070. case TargetOpcode::G_MERGE_VALUES: {
  1071. // G_MERGE_VALUES should only be used to merge scalars into a larger scalar,
  1072. // e.g. s2N = MERGE sN, sN
  1073. // Merging multiple scalars into a vector is not allowed, should use
  1074. // G_BUILD_VECTOR for that.
  1075. LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
  1076. LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
  1077. if (DstTy.isVector() || SrcTy.isVector())
  1078. report("G_MERGE_VALUES cannot operate on vectors", MI);
  1079. const unsigned NumOps = MI->getNumOperands();
  1080. if (DstTy.getSizeInBits() != SrcTy.getSizeInBits() * (NumOps - 1))
  1081. report("G_MERGE_VALUES result size is inconsistent", MI);
  1082. for (unsigned I = 2; I != NumOps; ++I) {
  1083. if (MRI->getType(MI->getOperand(I).getReg()) != SrcTy)
  1084. report("G_MERGE_VALUES source types do not match", MI);
  1085. }
  1086. break;
  1087. }
  1088. case TargetOpcode::G_UNMERGE_VALUES: {
  1089. LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
  1090. LLT SrcTy = MRI->getType(MI->getOperand(MI->getNumOperands()-1).getReg());
  1091. // For now G_UNMERGE can split vectors.
  1092. for (unsigned i = 0; i < MI->getNumOperands()-1; ++i) {
  1093. if (MRI->getType(MI->getOperand(i).getReg()) != DstTy)
  1094. report("G_UNMERGE_VALUES destination types do not match", MI);
  1095. }
  1096. if (SrcTy.getSizeInBits() !=
  1097. (DstTy.getSizeInBits() * (MI->getNumOperands() - 1))) {
  1098. report("G_UNMERGE_VALUES source operand does not cover dest operands",
  1099. MI);
  1100. }
  1101. break;
  1102. }
  1103. case TargetOpcode::G_BUILD_VECTOR: {
  1104. // Source types must be scalars, dest type a vector. Total size of scalars
  1105. // must match the dest vector size.
  1106. LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
  1107. LLT SrcEltTy = MRI->getType(MI->getOperand(1).getReg());
  1108. if (!DstTy.isVector() || SrcEltTy.isVector()) {
  1109. report("G_BUILD_VECTOR must produce a vector from scalar operands", MI);
  1110. break;
  1111. }
  1112. if (DstTy.getElementType() != SrcEltTy)
  1113. report("G_BUILD_VECTOR result element type must match source type", MI);
  1114. if (DstTy.getNumElements() != MI->getNumOperands() - 1)
  1115. report("G_BUILD_VECTOR must have an operand for each elemement", MI);
  1116. for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), 2))
  1117. if (MRI->getType(MI->getOperand(1).getReg()) != MRI->getType(MO.getReg()))
  1118. report("G_BUILD_VECTOR source operand types are not homogeneous", MI);
  1119. break;
  1120. }
  1121. case TargetOpcode::G_BUILD_VECTOR_TRUNC: {
  1122. // Source types must be scalars, dest type a vector. Scalar types must be
  1123. // larger than the dest vector elt type, as this is a truncating operation.
  1124. LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
  1125. LLT SrcEltTy = MRI->getType(MI->getOperand(1).getReg());
  1126. if (!DstTy.isVector() || SrcEltTy.isVector())
  1127. report("G_BUILD_VECTOR_TRUNC must produce a vector from scalar operands",
  1128. MI);
  1129. for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), 2))
  1130. if (MRI->getType(MI->getOperand(1).getReg()) != MRI->getType(MO.getReg()))
  1131. report("G_BUILD_VECTOR_TRUNC source operand types are not homogeneous",
  1132. MI);
  1133. if (SrcEltTy.getSizeInBits() <= DstTy.getElementType().getSizeInBits())
  1134. report("G_BUILD_VECTOR_TRUNC source operand types are not larger than "
  1135. "dest elt type",
  1136. MI);
  1137. break;
  1138. }
  1139. case TargetOpcode::G_CONCAT_VECTORS: {
  1140. // Source types should be vectors, and total size should match the dest
  1141. // vector size.
  1142. LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
  1143. LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
  1144. if (!DstTy.isVector() || !SrcTy.isVector())
  1145. report("G_CONCAT_VECTOR requires vector source and destination operands",
  1146. MI);
  1147. if (MI->getNumOperands() < 3)
  1148. report("G_CONCAT_VECTOR requires at least 2 source operands", MI);
  1149. for (const MachineOperand &MO : llvm::drop_begin(MI->operands(), 2))
  1150. if (MRI->getType(MI->getOperand(1).getReg()) != MRI->getType(MO.getReg()))
  1151. report("G_CONCAT_VECTOR source operand types are not homogeneous", MI);
  1152. if (DstTy.getNumElements() !=
  1153. SrcTy.getNumElements() * (MI->getNumOperands() - 1))
  1154. report("G_CONCAT_VECTOR num dest and source elements should match", MI);
  1155. break;
  1156. }
  1157. case TargetOpcode::G_ICMP:
  1158. case TargetOpcode::G_FCMP: {
  1159. LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
  1160. LLT SrcTy = MRI->getType(MI->getOperand(2).getReg());
  1161. if ((DstTy.isVector() != SrcTy.isVector()) ||
  1162. (DstTy.isVector() && DstTy.getNumElements() != SrcTy.getNumElements()))
  1163. report("Generic vector icmp/fcmp must preserve number of lanes", MI);
  1164. break;
  1165. }
  1166. case TargetOpcode::G_EXTRACT: {
  1167. const MachineOperand &SrcOp = MI->getOperand(1);
  1168. if (!SrcOp.isReg()) {
  1169. report("extract source must be a register", MI);
  1170. break;
  1171. }
  1172. const MachineOperand &OffsetOp = MI->getOperand(2);
  1173. if (!OffsetOp.isImm()) {
  1174. report("extract offset must be a constant", MI);
  1175. break;
  1176. }
  1177. unsigned DstSize = MRI->getType(MI->getOperand(0).getReg()).getSizeInBits();
  1178. unsigned SrcSize = MRI->getType(SrcOp.getReg()).getSizeInBits();
  1179. if (SrcSize == DstSize)
  1180. report("extract source must be larger than result", MI);
  1181. if (DstSize + OffsetOp.getImm() > SrcSize)
  1182. report("extract reads past end of register", MI);
  1183. break;
  1184. }
  1185. case TargetOpcode::G_INSERT: {
  1186. const MachineOperand &SrcOp = MI->getOperand(2);
  1187. if (!SrcOp.isReg()) {
  1188. report("insert source must be a register", MI);
  1189. break;
  1190. }
  1191. const MachineOperand &OffsetOp = MI->getOperand(3);
  1192. if (!OffsetOp.isImm()) {
  1193. report("insert offset must be a constant", MI);
  1194. break;
  1195. }
  1196. unsigned DstSize = MRI->getType(MI->getOperand(0).getReg()).getSizeInBits();
  1197. unsigned SrcSize = MRI->getType(SrcOp.getReg()).getSizeInBits();
  1198. if (DstSize <= SrcSize)
  1199. report("inserted size must be smaller than total register", MI);
  1200. if (SrcSize + OffsetOp.getImm() > DstSize)
  1201. report("insert writes past end of register", MI);
  1202. break;
  1203. }
  1204. case TargetOpcode::G_JUMP_TABLE: {
  1205. if (!MI->getOperand(1).isJTI())
  1206. report("G_JUMP_TABLE source operand must be a jump table index", MI);
  1207. LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
  1208. if (!DstTy.isPointer())
  1209. report("G_JUMP_TABLE dest operand must have a pointer type", MI);
  1210. break;
  1211. }
  1212. case TargetOpcode::G_BRJT: {
  1213. if (!MRI->getType(MI->getOperand(0).getReg()).isPointer())
  1214. report("G_BRJT src operand 0 must be a pointer type", MI);
  1215. if (!MI->getOperand(1).isJTI())
  1216. report("G_BRJT src operand 1 must be a jump table index", MI);
  1217. const auto &IdxOp = MI->getOperand(2);
  1218. if (!IdxOp.isReg() || MRI->getType(IdxOp.getReg()).isPointer())
  1219. report("G_BRJT src operand 2 must be a scalar reg type", MI);
  1220. break;
  1221. }
  1222. case TargetOpcode::G_INTRINSIC:
  1223. case TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS: {
  1224. // TODO: Should verify number of def and use operands, but the current
  1225. // interface requires passing in IR types for mangling.
  1226. const MachineOperand &IntrIDOp = MI->getOperand(MI->getNumExplicitDefs());
  1227. if (!IntrIDOp.isIntrinsicID()) {
  1228. report("G_INTRINSIC first src operand must be an intrinsic ID", MI);
  1229. break;
  1230. }
  1231. bool NoSideEffects = MI->getOpcode() == TargetOpcode::G_INTRINSIC;
  1232. unsigned IntrID = IntrIDOp.getIntrinsicID();
  1233. if (IntrID != 0 && IntrID < Intrinsic::num_intrinsics) {
  1234. AttributeList Attrs
  1235. = Intrinsic::getAttributes(MF->getFunction().getContext(),
  1236. static_cast<Intrinsic::ID>(IntrID));
  1237. bool DeclHasSideEffects = !Attrs.hasFnAttr(Attribute::ReadNone);
  1238. if (NoSideEffects && DeclHasSideEffects) {
  1239. report("G_INTRINSIC used with intrinsic that accesses memory", MI);
  1240. break;
  1241. }
  1242. if (!NoSideEffects && !DeclHasSideEffects) {
  1243. report("G_INTRINSIC_W_SIDE_EFFECTS used with readnone intrinsic", MI);
  1244. break;
  1245. }
  1246. }
  1247. break;
  1248. }
  1249. case TargetOpcode::G_SEXT_INREG: {
  1250. if (!MI->getOperand(2).isImm()) {
  1251. report("G_SEXT_INREG expects an immediate operand #2", MI);
  1252. break;
  1253. }
  1254. LLT SrcTy = MRI->getType(MI->getOperand(1).getReg());
  1255. int64_t Imm = MI->getOperand(2).getImm();
  1256. if (Imm <= 0)
  1257. report("G_SEXT_INREG size must be >= 1", MI);
  1258. if (Imm >= SrcTy.getScalarSizeInBits())
  1259. report("G_SEXT_INREG size must be less than source bit width", MI);
  1260. break;
  1261. }
  1262. case TargetOpcode::G_SHUFFLE_VECTOR: {
  1263. const MachineOperand &MaskOp = MI->getOperand(3);
  1264. if (!MaskOp.isShuffleMask()) {
  1265. report("Incorrect mask operand type for G_SHUFFLE_VECTOR", MI);
  1266. break;
  1267. }
  1268. LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
  1269. LLT Src0Ty = MRI->getType(MI->getOperand(1).getReg());
  1270. LLT Src1Ty = MRI->getType(MI->getOperand(2).getReg());
  1271. if (Src0Ty != Src1Ty)
  1272. report("Source operands must be the same type", MI);
  1273. if (Src0Ty.getScalarType() != DstTy.getScalarType())
  1274. report("G_SHUFFLE_VECTOR cannot change element type", MI);
  1275. // Don't check that all operands are vector because scalars are used in
  1276. // place of 1 element vectors.
  1277. int SrcNumElts = Src0Ty.isVector() ? Src0Ty.getNumElements() : 1;
  1278. int DstNumElts = DstTy.isVector() ? DstTy.getNumElements() : 1;
  1279. ArrayRef<int> MaskIdxes = MaskOp.getShuffleMask();
  1280. if (static_cast<int>(MaskIdxes.size()) != DstNumElts)
  1281. report("Wrong result type for shufflemask", MI);
  1282. for (int Idx : MaskIdxes) {
  1283. if (Idx < 0)
  1284. continue;
  1285. if (Idx >= 2 * SrcNumElts)
  1286. report("Out of bounds shuffle index", MI);
  1287. }
  1288. break;
  1289. }
  1290. case TargetOpcode::G_DYN_STACKALLOC: {
  1291. const MachineOperand &DstOp = MI->getOperand(0);
  1292. const MachineOperand &AllocOp = MI->getOperand(1);
  1293. const MachineOperand &AlignOp = MI->getOperand(2);
  1294. if (!DstOp.isReg() || !MRI->getType(DstOp.getReg()).isPointer()) {
  1295. report("dst operand 0 must be a pointer type", MI);
  1296. break;
  1297. }
  1298. if (!AllocOp.isReg() || !MRI->getType(AllocOp.getReg()).isScalar()) {
  1299. report("src operand 1 must be a scalar reg type", MI);
  1300. break;
  1301. }
  1302. if (!AlignOp.isImm()) {
  1303. report("src operand 2 must be an immediate type", MI);
  1304. break;
  1305. }
  1306. break;
  1307. }
  1308. case TargetOpcode::G_MEMCPY_INLINE:
  1309. case TargetOpcode::G_MEMCPY:
  1310. case TargetOpcode::G_MEMMOVE: {
  1311. ArrayRef<MachineMemOperand *> MMOs = MI->memoperands();
  1312. if (MMOs.size() != 2) {
  1313. report("memcpy/memmove must have 2 memory operands", MI);
  1314. break;
  1315. }
  1316. if ((!MMOs[0]->isStore() || MMOs[0]->isLoad()) ||
  1317. (MMOs[1]->isStore() || !MMOs[1]->isLoad())) {
  1318. report("wrong memory operand types", MI);
  1319. break;
  1320. }
  1321. if (MMOs[0]->getSize() != MMOs[1]->getSize())
  1322. report("inconsistent memory operand sizes", MI);
  1323. LLT DstPtrTy = MRI->getType(MI->getOperand(0).getReg());
  1324. LLT SrcPtrTy = MRI->getType(MI->getOperand(1).getReg());
  1325. if (!DstPtrTy.isPointer() || !SrcPtrTy.isPointer()) {
  1326. report("memory instruction operand must be a pointer", MI);
  1327. break;
  1328. }
  1329. if (DstPtrTy.getAddressSpace() != MMOs[0]->getAddrSpace())
  1330. report("inconsistent store address space", MI);
  1331. if (SrcPtrTy.getAddressSpace() != MMOs[1]->getAddrSpace())
  1332. report("inconsistent load address space", MI);
  1333. if (Opc != TargetOpcode::G_MEMCPY_INLINE)
  1334. if (!MI->getOperand(3).isImm() || (MI->getOperand(3).getImm() & ~1LL))
  1335. report("'tail' flag (operand 3) must be an immediate 0 or 1", MI);
  1336. break;
  1337. }
  1338. case TargetOpcode::G_BZERO:
  1339. case TargetOpcode::G_MEMSET: {
  1340. ArrayRef<MachineMemOperand *> MMOs = MI->memoperands();
  1341. std::string Name = Opc == TargetOpcode::G_MEMSET ? "memset" : "bzero";
  1342. if (MMOs.size() != 1) {
  1343. report(Twine(Name, " must have 1 memory operand"), MI);
  1344. break;
  1345. }
  1346. if ((!MMOs[0]->isStore() || MMOs[0]->isLoad())) {
  1347. report(Twine(Name, " memory operand must be a store"), MI);
  1348. break;
  1349. }
  1350. LLT DstPtrTy = MRI->getType(MI->getOperand(0).getReg());
  1351. if (!DstPtrTy.isPointer()) {
  1352. report(Twine(Name, " operand must be a pointer"), MI);
  1353. break;
  1354. }
  1355. if (DstPtrTy.getAddressSpace() != MMOs[0]->getAddrSpace())
  1356. report("inconsistent " + Twine(Name, " address space"), MI);
  1357. if (!MI->getOperand(MI->getNumOperands() - 1).isImm() ||
  1358. (MI->getOperand(MI->getNumOperands() - 1).getImm() & ~1LL))
  1359. report("'tail' flag (last operand) must be an immediate 0 or 1", MI);
  1360. break;
  1361. }
  1362. case TargetOpcode::G_VECREDUCE_SEQ_FADD:
  1363. case TargetOpcode::G_VECREDUCE_SEQ_FMUL: {
  1364. LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
  1365. LLT Src1Ty = MRI->getType(MI->getOperand(1).getReg());
  1366. LLT Src2Ty = MRI->getType(MI->getOperand(2).getReg());
  1367. if (!DstTy.isScalar())
  1368. report("Vector reduction requires a scalar destination type", MI);
  1369. if (!Src1Ty.isScalar())
  1370. report("Sequential FADD/FMUL vector reduction requires a scalar 1st operand", MI);
  1371. if (!Src2Ty.isVector())
  1372. report("Sequential FADD/FMUL vector reduction must have a vector 2nd operand", MI);
  1373. break;
  1374. }
  1375. case TargetOpcode::G_VECREDUCE_FADD:
  1376. case TargetOpcode::G_VECREDUCE_FMUL:
  1377. case TargetOpcode::G_VECREDUCE_FMAX:
  1378. case TargetOpcode::G_VECREDUCE_FMIN:
  1379. case TargetOpcode::G_VECREDUCE_ADD:
  1380. case TargetOpcode::G_VECREDUCE_MUL:
  1381. case TargetOpcode::G_VECREDUCE_AND:
  1382. case TargetOpcode::G_VECREDUCE_OR:
  1383. case TargetOpcode::G_VECREDUCE_XOR:
  1384. case TargetOpcode::G_VECREDUCE_SMAX:
  1385. case TargetOpcode::G_VECREDUCE_SMIN:
  1386. case TargetOpcode::G_VECREDUCE_UMAX:
  1387. case TargetOpcode::G_VECREDUCE_UMIN: {
  1388. LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
  1389. if (!DstTy.isScalar())
  1390. report("Vector reduction requires a scalar destination type", MI);
  1391. break;
  1392. }
  1393. case TargetOpcode::G_SBFX:
  1394. case TargetOpcode::G_UBFX: {
  1395. LLT DstTy = MRI->getType(MI->getOperand(0).getReg());
  1396. if (DstTy.isVector()) {
  1397. report("Bitfield extraction is not supported on vectors", MI);
  1398. break;
  1399. }
  1400. break;
  1401. }
  1402. case TargetOpcode::G_SHL:
  1403. case TargetOpcode::G_LSHR:
  1404. case TargetOpcode::G_ASHR:
  1405. case TargetOpcode::G_ROTR:
  1406. case TargetOpcode::G_ROTL: {
  1407. LLT Src1Ty = MRI->getType(MI->getOperand(1).getReg());
  1408. LLT Src2Ty = MRI->getType(MI->getOperand(2).getReg());
  1409. if (Src1Ty.isVector() != Src2Ty.isVector()) {
  1410. report("Shifts and rotates require operands to be either all scalars or "
  1411. "all vectors",
  1412. MI);
  1413. break;
  1414. }
  1415. break;
  1416. }
  1417. case TargetOpcode::G_LLROUND:
  1418. case TargetOpcode::G_LROUND: {
  1419. verifyAllRegOpsScalar(*MI, *MRI);
  1420. break;
  1421. }
  1422. default:
  1423. break;
  1424. }
  1425. }
  1426. void MachineVerifier::visitMachineInstrBefore(const MachineInstr *MI) {
  1427. const MCInstrDesc &MCID = MI->getDesc();
  1428. if (MI->getNumOperands() < MCID.getNumOperands()) {
  1429. report("Too few operands", MI);
  1430. errs() << MCID.getNumOperands() << " operands expected, but "
  1431. << MI->getNumOperands() << " given.\n";
  1432. }
  1433. if (MI->isPHI()) {
  1434. if (MF->getProperties().hasProperty(
  1435. MachineFunctionProperties::Property::NoPHIs))
  1436. report("Found PHI instruction with NoPHIs property set", MI);
  1437. if (FirstNonPHI)
  1438. report("Found PHI instruction after non-PHI", MI);
  1439. } else if (FirstNonPHI == nullptr)
  1440. FirstNonPHI = MI;
  1441. // Check the tied operands.
  1442. if (MI->isInlineAsm())
  1443. verifyInlineAsm(MI);
  1444. // Check that unspillable terminators define a reg and have at most one use.
  1445. if (TII->isUnspillableTerminator(MI)) {
  1446. if (!MI->getOperand(0).isReg() || !MI->getOperand(0).isDef())
  1447. report("Unspillable Terminator does not define a reg", MI);
  1448. Register Def = MI->getOperand(0).getReg();
  1449. if (Def.isVirtual() &&
  1450. !MF->getProperties().hasProperty(
  1451. MachineFunctionProperties::Property::NoPHIs) &&
  1452. std::distance(MRI->use_nodbg_begin(Def), MRI->use_nodbg_end()) > 1)
  1453. report("Unspillable Terminator expected to have at most one use!", MI);
  1454. }
  1455. // A fully-formed DBG_VALUE must have a location. Ignore partially formed
  1456. // DBG_VALUEs: these are convenient to use in tests, but should never get
  1457. // generated.
  1458. if (MI->isDebugValue() && MI->getNumOperands() == 4)
  1459. if (!MI->getDebugLoc())
  1460. report("Missing DebugLoc for debug instruction", MI);
  1461. // Meta instructions should never be the subject of debug value tracking,
  1462. // they don't create a value in the output program at all.
  1463. if (MI->isMetaInstruction() && MI->peekDebugInstrNum())
  1464. report("Metadata instruction should not have a value tracking number", MI);
  1465. // Check the MachineMemOperands for basic consistency.
  1466. for (MachineMemOperand *Op : MI->memoperands()) {
  1467. if (Op->isLoad() && !MI->mayLoad())
  1468. report("Missing mayLoad flag", MI);
  1469. if (Op->isStore() && !MI->mayStore())
  1470. report("Missing mayStore flag", MI);
  1471. }
  1472. // Debug values must not have a slot index.
  1473. // Other instructions must have one, unless they are inside a bundle.
  1474. if (LiveInts) {
  1475. bool mapped = !LiveInts->isNotInMIMap(*MI);
  1476. if (MI->isDebugOrPseudoInstr()) {
  1477. if (mapped)
  1478. report("Debug instruction has a slot index", MI);
  1479. } else if (MI->isInsideBundle()) {
  1480. if (mapped)
  1481. report("Instruction inside bundle has a slot index", MI);
  1482. } else {
  1483. if (!mapped)
  1484. report("Missing slot index", MI);
  1485. }
  1486. }
  1487. unsigned Opc = MCID.getOpcode();
  1488. if (isPreISelGenericOpcode(Opc) || isPreISelGenericOptimizationHint(Opc)) {
  1489. verifyPreISelGenericInstruction(MI);
  1490. return;
  1491. }
  1492. StringRef ErrorInfo;
  1493. if (!TII->verifyInstruction(*MI, ErrorInfo))
  1494. report(ErrorInfo.data(), MI);
  1495. // Verify properties of various specific instruction types
  1496. switch (MI->getOpcode()) {
  1497. case TargetOpcode::COPY: {
  1498. const MachineOperand &DstOp = MI->getOperand(0);
  1499. const MachineOperand &SrcOp = MI->getOperand(1);
  1500. const Register SrcReg = SrcOp.getReg();
  1501. const Register DstReg = DstOp.getReg();
  1502. LLT DstTy = MRI->getType(DstReg);
  1503. LLT SrcTy = MRI->getType(SrcReg);
  1504. if (SrcTy.isValid() && DstTy.isValid()) {
  1505. // If both types are valid, check that the types are the same.
  1506. if (SrcTy != DstTy) {
  1507. report("Copy Instruction is illegal with mismatching types", MI);
  1508. errs() << "Def = " << DstTy << ", Src = " << SrcTy << "\n";
  1509. }
  1510. break;
  1511. }
  1512. if (!SrcTy.isValid() && !DstTy.isValid())
  1513. break;
  1514. // If we have only one valid type, this is likely a copy between a virtual
  1515. // and physical register.
  1516. unsigned SrcSize = 0;
  1517. unsigned DstSize = 0;
  1518. if (SrcReg.isPhysical() && DstTy.isValid()) {
  1519. const TargetRegisterClass *SrcRC =
  1520. TRI->getMinimalPhysRegClassLLT(SrcReg, DstTy);
  1521. if (SrcRC)
  1522. SrcSize = TRI->getRegSizeInBits(*SrcRC);
  1523. }
  1524. if (SrcSize == 0)
  1525. SrcSize = TRI->getRegSizeInBits(SrcReg, *MRI);
  1526. if (DstReg.isPhysical() && SrcTy.isValid()) {
  1527. const TargetRegisterClass *DstRC =
  1528. TRI->getMinimalPhysRegClassLLT(DstReg, SrcTy);
  1529. if (DstRC)
  1530. DstSize = TRI->getRegSizeInBits(*DstRC);
  1531. }
  1532. if (DstSize == 0)
  1533. DstSize = TRI->getRegSizeInBits(DstReg, *MRI);
  1534. if (SrcSize != 0 && DstSize != 0 && SrcSize != DstSize) {
  1535. if (!DstOp.getSubReg() && !SrcOp.getSubReg()) {
  1536. report("Copy Instruction is illegal with mismatching sizes", MI);
  1537. errs() << "Def Size = " << DstSize << ", Src Size = " << SrcSize
  1538. << "\n";
  1539. }
  1540. }
  1541. break;
  1542. }
  1543. case TargetOpcode::STATEPOINT: {
  1544. StatepointOpers SO(MI);
  1545. if (!MI->getOperand(SO.getIDPos()).isImm() ||
  1546. !MI->getOperand(SO.getNBytesPos()).isImm() ||
  1547. !MI->getOperand(SO.getNCallArgsPos()).isImm()) {
  1548. report("meta operands to STATEPOINT not constant!", MI);
  1549. break;
  1550. }
  1551. auto VerifyStackMapConstant = [&](unsigned Offset) {
  1552. if (Offset >= MI->getNumOperands()) {
  1553. report("stack map constant to STATEPOINT is out of range!", MI);
  1554. return;
  1555. }
  1556. if (!MI->getOperand(Offset - 1).isImm() ||
  1557. MI->getOperand(Offset - 1).getImm() != StackMaps::ConstantOp ||
  1558. !MI->getOperand(Offset).isImm())
  1559. report("stack map constant to STATEPOINT not well formed!", MI);
  1560. };
  1561. VerifyStackMapConstant(SO.getCCIdx());
  1562. VerifyStackMapConstant(SO.getFlagsIdx());
  1563. VerifyStackMapConstant(SO.getNumDeoptArgsIdx());
  1564. VerifyStackMapConstant(SO.getNumGCPtrIdx());
  1565. VerifyStackMapConstant(SO.getNumAllocaIdx());
  1566. VerifyStackMapConstant(SO.getNumGcMapEntriesIdx());
  1567. // Verify that all explicit statepoint defs are tied to gc operands as
  1568. // they are expected to be a relocation of gc operands.
  1569. unsigned FirstGCPtrIdx = SO.getFirstGCPtrIdx();
  1570. unsigned LastGCPtrIdx = SO.getNumAllocaIdx() - 2;
  1571. for (unsigned Idx = 0; Idx < MI->getNumDefs(); Idx++) {
  1572. unsigned UseOpIdx;
  1573. if (!MI->isRegTiedToUseOperand(Idx, &UseOpIdx)) {
  1574. report("STATEPOINT defs expected to be tied", MI);
  1575. break;
  1576. }
  1577. if (UseOpIdx < FirstGCPtrIdx || UseOpIdx > LastGCPtrIdx) {
  1578. report("STATEPOINT def tied to non-gc operand", MI);
  1579. break;
  1580. }
  1581. }
  1582. // TODO: verify we have properly encoded deopt arguments
  1583. } break;
  1584. case TargetOpcode::INSERT_SUBREG: {
  1585. unsigned InsertedSize;
  1586. if (unsigned SubIdx = MI->getOperand(2).getSubReg())
  1587. InsertedSize = TRI->getSubRegIdxSize(SubIdx);
  1588. else
  1589. InsertedSize = TRI->getRegSizeInBits(MI->getOperand(2).getReg(), *MRI);
  1590. unsigned SubRegSize = TRI->getSubRegIdxSize(MI->getOperand(3).getImm());
  1591. if (SubRegSize < InsertedSize) {
  1592. report("INSERT_SUBREG expected inserted value to have equal or lesser "
  1593. "size than the subreg it was inserted into", MI);
  1594. break;
  1595. }
  1596. } break;
  1597. }
  1598. }
  1599. void
  1600. MachineVerifier::visitMachineOperand(const MachineOperand *MO, unsigned MONum) {
  1601. const MachineInstr *MI = MO->getParent();
  1602. const MCInstrDesc &MCID = MI->getDesc();
  1603. unsigned NumDefs = MCID.getNumDefs();
  1604. if (MCID.getOpcode() == TargetOpcode::PATCHPOINT)
  1605. NumDefs = (MONum == 0 && MO->isReg()) ? NumDefs : 0;
  1606. // The first MCID.NumDefs operands must be explicit register defines
  1607. if (MONum < NumDefs) {
  1608. const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
  1609. if (!MO->isReg())
  1610. report("Explicit definition must be a register", MO, MONum);
  1611. else if (!MO->isDef() && !MCOI.isOptionalDef())
  1612. report("Explicit definition marked as use", MO, MONum);
  1613. else if (MO->isImplicit())
  1614. report("Explicit definition marked as implicit", MO, MONum);
  1615. } else if (MONum < MCID.getNumOperands()) {
  1616. const MCOperandInfo &MCOI = MCID.OpInfo[MONum];
  1617. // Don't check if it's the last operand in a variadic instruction. See,
  1618. // e.g., LDM_RET in the arm back end. Check non-variadic operands only.
  1619. bool IsOptional = MI->isVariadic() && MONum == MCID.getNumOperands() - 1;
  1620. if (!IsOptional) {
  1621. if (MO->isReg()) {
  1622. if (MO->isDef() && !MCOI.isOptionalDef() && !MCID.variadicOpsAreDefs())
  1623. report("Explicit operand marked as def", MO, MONum);
  1624. if (MO->isImplicit())
  1625. report("Explicit operand marked as implicit", MO, MONum);
  1626. }
  1627. // Check that an instruction has register operands only as expected.
  1628. if (MCOI.OperandType == MCOI::OPERAND_REGISTER &&
  1629. !MO->isReg() && !MO->isFI())
  1630. report("Expected a register operand.", MO, MONum);
  1631. if (MO->isReg()) {
  1632. if (MCOI.OperandType == MCOI::OPERAND_IMMEDIATE ||
  1633. (MCOI.OperandType == MCOI::OPERAND_PCREL &&
  1634. !TII->isPCRelRegisterOperandLegal(*MO)))
  1635. report("Expected a non-register operand.", MO, MONum);
  1636. }
  1637. }
  1638. int TiedTo = MCID.getOperandConstraint(MONum, MCOI::TIED_TO);
  1639. if (TiedTo != -1) {
  1640. if (!MO->isReg())
  1641. report("Tied use must be a register", MO, MONum);
  1642. else if (!MO->isTied())
  1643. report("Operand should be tied", MO, MONum);
  1644. else if (unsigned(TiedTo) != MI->findTiedOperandIdx(MONum))
  1645. report("Tied def doesn't match MCInstrDesc", MO, MONum);
  1646. else if (Register::isPhysicalRegister(MO->getReg())) {
  1647. const MachineOperand &MOTied = MI->getOperand(TiedTo);
  1648. if (!MOTied.isReg())
  1649. report("Tied counterpart must be a register", &MOTied, TiedTo);
  1650. else if (Register::isPhysicalRegister(MOTied.getReg()) &&
  1651. MO->getReg() != MOTied.getReg())
  1652. report("Tied physical registers must match.", &MOTied, TiedTo);
  1653. }
  1654. } else if (MO->isReg() && MO->isTied())
  1655. report("Explicit operand should not be tied", MO, MONum);
  1656. } else {
  1657. // ARM adds %reg0 operands to indicate predicates. We'll allow that.
  1658. if (MO->isReg() && !MO->isImplicit() && !MI->isVariadic() && MO->getReg())
  1659. report("Extra explicit operand on non-variadic instruction", MO, MONum);
  1660. }
  1661. switch (MO->getType()) {
  1662. case MachineOperand::MO_Register: {
  1663. // Verify debug flag on debug instructions. Check this first because reg0
  1664. // indicates an undefined debug value.
  1665. if (MI->isDebugInstr() && MO->isUse()) {
  1666. if (!MO->isDebug())
  1667. report("Register operand must be marked debug", MO, MONum);
  1668. } else if (MO->isDebug()) {
  1669. report("Register operand must not be marked debug", MO, MONum);
  1670. }
  1671. const Register Reg = MO->getReg();
  1672. if (!Reg)
  1673. return;
  1674. if (MRI->tracksLiveness() && !MI->isDebugInstr())
  1675. checkLiveness(MO, MONum);
  1676. // Verify the consistency of tied operands.
  1677. if (MO->isTied()) {
  1678. unsigned OtherIdx = MI->findTiedOperandIdx(MONum);
  1679. const MachineOperand &OtherMO = MI->getOperand(OtherIdx);
  1680. if (!OtherMO.isReg())
  1681. report("Must be tied to a register", MO, MONum);
  1682. if (!OtherMO.isTied())
  1683. report("Missing tie flags on tied operand", MO, MONum);
  1684. if (MI->findTiedOperandIdx(OtherIdx) != MONum)
  1685. report("Inconsistent tie links", MO, MONum);
  1686. if (MONum < MCID.getNumDefs()) {
  1687. if (OtherIdx < MCID.getNumOperands()) {
  1688. if (-1 == MCID.getOperandConstraint(OtherIdx, MCOI::TIED_TO))
  1689. report("Explicit def tied to explicit use without tie constraint",
  1690. MO, MONum);
  1691. } else {
  1692. if (!OtherMO.isImplicit())
  1693. report("Explicit def should be tied to implicit use", MO, MONum);
  1694. }
  1695. }
  1696. }
  1697. // Verify two-address constraints after the twoaddressinstruction pass.
  1698. // Both twoaddressinstruction pass and phi-node-elimination pass call
  1699. // MRI->leaveSSA() to set MF as NoSSA, we should do the verification after
  1700. // twoaddressinstruction pass not after phi-node-elimination pass. So we
  1701. // shouldn't use the NoSSA as the condition, we should based on
  1702. // TiedOpsRewritten property to verify two-address constraints, this
  1703. // property will be set in twoaddressinstruction pass.
  1704. unsigned DefIdx;
  1705. if (MF->getProperties().hasProperty(
  1706. MachineFunctionProperties::Property::TiedOpsRewritten) &&
  1707. MO->isUse() && MI->isRegTiedToDefOperand(MONum, &DefIdx) &&
  1708. Reg != MI->getOperand(DefIdx).getReg())
  1709. report("Two-address instruction operands must be identical", MO, MONum);
  1710. // Check register classes.
  1711. unsigned SubIdx = MO->getSubReg();
  1712. if (Register::isPhysicalRegister(Reg)) {
  1713. if (SubIdx) {
  1714. report("Illegal subregister index for physical register", MO, MONum);
  1715. return;
  1716. }
  1717. if (MONum < MCID.getNumOperands()) {
  1718. if (const TargetRegisterClass *DRC =
  1719. TII->getRegClass(MCID, MONum, TRI, *MF)) {
  1720. if (!DRC->contains(Reg)) {
  1721. report("Illegal physical register for instruction", MO, MONum);
  1722. errs() << printReg(Reg, TRI) << " is not a "
  1723. << TRI->getRegClassName(DRC) << " register.\n";
  1724. }
  1725. }
  1726. }
  1727. if (MO->isRenamable()) {
  1728. if (MRI->isReserved(Reg)) {
  1729. report("isRenamable set on reserved register", MO, MONum);
  1730. return;
  1731. }
  1732. }
  1733. } else {
  1734. // Virtual register.
  1735. const TargetRegisterClass *RC = MRI->getRegClassOrNull(Reg);
  1736. if (!RC) {
  1737. // This is a generic virtual register.
  1738. // Do not allow undef uses for generic virtual registers. This ensures
  1739. // getVRegDef can never fail and return null on a generic register.
  1740. //
  1741. // FIXME: This restriction should probably be broadened to all SSA
  1742. // MIR. However, DetectDeadLanes/ProcessImplicitDefs technically still
  1743. // run on the SSA function just before phi elimination.
  1744. if (MO->isUndef())
  1745. report("Generic virtual register use cannot be undef", MO, MONum);
  1746. // Debug value instruction is permitted to use undefined vregs.
  1747. // This is a performance measure to skip the overhead of immediately
  1748. // pruning unused debug operands. The final undef substitution occurs
  1749. // when debug values are allocated in LDVImpl::handleDebugValue, so
  1750. // these verifications always apply after this pass.
  1751. if (isFunctionTracksDebugUserValues || !MO->isUse() ||
  1752. !MI->isDebugValue() || !MRI->def_empty(Reg)) {
  1753. // If we're post-Select, we can't have gvregs anymore.
  1754. if (isFunctionSelected) {
  1755. report("Generic virtual register invalid in a Selected function",
  1756. MO, MONum);
  1757. return;
  1758. }
  1759. // The gvreg must have a type and it must not have a SubIdx.
  1760. LLT Ty = MRI->getType(Reg);
  1761. if (!Ty.isValid()) {
  1762. report("Generic virtual register must have a valid type", MO,
  1763. MONum);
  1764. return;
  1765. }
  1766. const RegisterBank *RegBank = MRI->getRegBankOrNull(Reg);
  1767. // If we're post-RegBankSelect, the gvreg must have a bank.
  1768. if (!RegBank && isFunctionRegBankSelected) {
  1769. report("Generic virtual register must have a bank in a "
  1770. "RegBankSelected function",
  1771. MO, MONum);
  1772. return;
  1773. }
  1774. // Make sure the register fits into its register bank if any.
  1775. if (RegBank && Ty.isValid() &&
  1776. RegBank->getSize() < Ty.getSizeInBits()) {
  1777. report("Register bank is too small for virtual register", MO,
  1778. MONum);
  1779. errs() << "Register bank " << RegBank->getName() << " too small("
  1780. << RegBank->getSize() << ") to fit " << Ty.getSizeInBits()
  1781. << "-bits\n";
  1782. return;
  1783. }
  1784. }
  1785. if (SubIdx) {
  1786. report("Generic virtual register does not allow subregister index", MO,
  1787. MONum);
  1788. return;
  1789. }
  1790. // If this is a target specific instruction and this operand
  1791. // has register class constraint, the virtual register must
  1792. // comply to it.
  1793. if (!isPreISelGenericOpcode(MCID.getOpcode()) &&
  1794. MONum < MCID.getNumOperands() &&
  1795. TII->getRegClass(MCID, MONum, TRI, *MF)) {
  1796. report("Virtual register does not match instruction constraint", MO,
  1797. MONum);
  1798. errs() << "Expect register class "
  1799. << TRI->getRegClassName(
  1800. TII->getRegClass(MCID, MONum, TRI, *MF))
  1801. << " but got nothing\n";
  1802. return;
  1803. }
  1804. break;
  1805. }
  1806. if (SubIdx) {
  1807. const TargetRegisterClass *SRC =
  1808. TRI->getSubClassWithSubReg(RC, SubIdx);
  1809. if (!SRC) {
  1810. report("Invalid subregister index for virtual register", MO, MONum);
  1811. errs() << "Register class " << TRI->getRegClassName(RC)
  1812. << " does not support subreg index " << SubIdx << "\n";
  1813. return;
  1814. }
  1815. if (RC != SRC) {
  1816. report("Invalid register class for subregister index", MO, MONum);
  1817. errs() << "Register class " << TRI->getRegClassName(RC)
  1818. << " does not fully support subreg index " << SubIdx << "\n";
  1819. return;
  1820. }
  1821. }
  1822. if (MONum < MCID.getNumOperands()) {
  1823. if (const TargetRegisterClass *DRC =
  1824. TII->getRegClass(MCID, MONum, TRI, *MF)) {
  1825. if (SubIdx) {
  1826. const TargetRegisterClass *SuperRC =
  1827. TRI->getLargestLegalSuperClass(RC, *MF);
  1828. if (!SuperRC) {
  1829. report("No largest legal super class exists.", MO, MONum);
  1830. return;
  1831. }
  1832. DRC = TRI->getMatchingSuperRegClass(SuperRC, DRC, SubIdx);
  1833. if (!DRC) {
  1834. report("No matching super-reg register class.", MO, MONum);
  1835. return;
  1836. }
  1837. }
  1838. if (!RC->hasSuperClassEq(DRC)) {
  1839. report("Illegal virtual register for instruction", MO, MONum);
  1840. errs() << "Expected a " << TRI->getRegClassName(DRC)
  1841. << " register, but got a " << TRI->getRegClassName(RC)
  1842. << " register\n";
  1843. }
  1844. }
  1845. }
  1846. }
  1847. break;
  1848. }
  1849. case MachineOperand::MO_RegisterMask:
  1850. regMasks.push_back(MO->getRegMask());
  1851. break;
  1852. case MachineOperand::MO_MachineBasicBlock:
  1853. if (MI->isPHI() && !MO->getMBB()->isSuccessor(MI->getParent()))
  1854. report("PHI operand is not in the CFG", MO, MONum);
  1855. break;
  1856. case MachineOperand::MO_FrameIndex:
  1857. if (LiveStks && LiveStks->hasInterval(MO->getIndex()) &&
  1858. LiveInts && !LiveInts->isNotInMIMap(*MI)) {
  1859. int FI = MO->getIndex();
  1860. LiveInterval &LI = LiveStks->getInterval(FI);
  1861. SlotIndex Idx = LiveInts->getInstructionIndex(*MI);
  1862. bool stores = MI->mayStore();
  1863. bool loads = MI->mayLoad();
  1864. // For a memory-to-memory move, we need to check if the frame
  1865. // index is used for storing or loading, by inspecting the
  1866. // memory operands.
  1867. if (stores && loads) {
  1868. for (auto *MMO : MI->memoperands()) {
  1869. const PseudoSourceValue *PSV = MMO->getPseudoValue();
  1870. if (PSV == nullptr) continue;
  1871. const FixedStackPseudoSourceValue *Value =
  1872. dyn_cast<FixedStackPseudoSourceValue>(PSV);
  1873. if (Value == nullptr) continue;
  1874. if (Value->getFrameIndex() != FI) continue;
  1875. if (MMO->isStore())
  1876. loads = false;
  1877. else
  1878. stores = false;
  1879. break;
  1880. }
  1881. if (loads == stores)
  1882. report("Missing fixed stack memoperand.", MI);
  1883. }
  1884. if (loads && !LI.liveAt(Idx.getRegSlot(true))) {
  1885. report("Instruction loads from dead spill slot", MO, MONum);
  1886. errs() << "Live stack: " << LI << '\n';
  1887. }
  1888. if (stores && !LI.liveAt(Idx.getRegSlot())) {
  1889. report("Instruction stores to dead spill slot", MO, MONum);
  1890. errs() << "Live stack: " << LI << '\n';
  1891. }
  1892. }
  1893. break;
  1894. default:
  1895. break;
  1896. }
  1897. }
  1898. void MachineVerifier::checkLivenessAtUse(const MachineOperand *MO,
  1899. unsigned MONum, SlotIndex UseIdx,
  1900. const LiveRange &LR,
  1901. Register VRegOrUnit,
  1902. LaneBitmask LaneMask) {
  1903. LiveQueryResult LRQ = LR.Query(UseIdx);
  1904. // Check if we have a segment at the use, note however that we only need one
  1905. // live subregister range, the others may be dead.
  1906. if (!LRQ.valueIn() && LaneMask.none()) {
  1907. report("No live segment at use", MO, MONum);
  1908. report_context_liverange(LR);
  1909. report_context_vreg_regunit(VRegOrUnit);
  1910. report_context(UseIdx);
  1911. }
  1912. if (MO->isKill() && !LRQ.isKill()) {
  1913. report("Live range continues after kill flag", MO, MONum);
  1914. report_context_liverange(LR);
  1915. report_context_vreg_regunit(VRegOrUnit);
  1916. if (LaneMask.any())
  1917. report_context_lanemask(LaneMask);
  1918. report_context(UseIdx);
  1919. }
  1920. }
  1921. void MachineVerifier::checkLivenessAtDef(const MachineOperand *MO,
  1922. unsigned MONum, SlotIndex DefIdx,
  1923. const LiveRange &LR,
  1924. Register VRegOrUnit,
  1925. bool SubRangeCheck,
  1926. LaneBitmask LaneMask) {
  1927. if (const VNInfo *VNI = LR.getVNInfoAt(DefIdx)) {
  1928. assert(VNI && "NULL valno is not allowed");
  1929. if (VNI->def != DefIdx) {
  1930. report("Inconsistent valno->def", MO, MONum);
  1931. report_context_liverange(LR);
  1932. report_context_vreg_regunit(VRegOrUnit);
  1933. if (LaneMask.any())
  1934. report_context_lanemask(LaneMask);
  1935. report_context(*VNI);
  1936. report_context(DefIdx);
  1937. }
  1938. } else {
  1939. report("No live segment at def", MO, MONum);
  1940. report_context_liverange(LR);
  1941. report_context_vreg_regunit(VRegOrUnit);
  1942. if (LaneMask.any())
  1943. report_context_lanemask(LaneMask);
  1944. report_context(DefIdx);
  1945. }
  1946. // Check that, if the dead def flag is present, LiveInts agree.
  1947. if (MO->isDead()) {
  1948. LiveQueryResult LRQ = LR.Query(DefIdx);
  1949. if (!LRQ.isDeadDef()) {
  1950. assert(Register::isVirtualRegister(VRegOrUnit) &&
  1951. "Expecting a virtual register.");
  1952. // A dead subreg def only tells us that the specific subreg is dead. There
  1953. // could be other non-dead defs of other subregs, or we could have other
  1954. // parts of the register being live through the instruction. So unless we
  1955. // are checking liveness for a subrange it is ok for the live range to
  1956. // continue, given that we have a dead def of a subregister.
  1957. if (SubRangeCheck || MO->getSubReg() == 0) {
  1958. report("Live range continues after dead def flag", MO, MONum);
  1959. report_context_liverange(LR);
  1960. report_context_vreg_regunit(VRegOrUnit);
  1961. if (LaneMask.any())
  1962. report_context_lanemask(LaneMask);
  1963. }
  1964. }
  1965. }
  1966. }
  1967. void MachineVerifier::checkLiveness(const MachineOperand *MO, unsigned MONum) {
  1968. const MachineInstr *MI = MO->getParent();
  1969. const Register Reg = MO->getReg();
  1970. const unsigned SubRegIdx = MO->getSubReg();
  1971. const LiveInterval *LI = nullptr;
  1972. if (LiveInts && Reg.isVirtual()) {
  1973. if (LiveInts->hasInterval(Reg)) {
  1974. LI = &LiveInts->getInterval(Reg);
  1975. if (SubRegIdx != 0 && (MO->isDef() || !MO->isUndef()) && !LI->empty() &&
  1976. !LI->hasSubRanges() && MRI->shouldTrackSubRegLiveness(Reg))
  1977. report("Live interval for subreg operand has no subranges", MO, MONum);
  1978. } else {
  1979. report("Virtual register has no live interval", MO, MONum);
  1980. }
  1981. }
  1982. // Both use and def operands can read a register.
  1983. if (MO->readsReg()) {
  1984. if (MO->isKill())
  1985. addRegWithSubRegs(regsKilled, Reg);
  1986. // Check that LiveVars knows this kill (unless we are inside a bundle, in
  1987. // which case we have already checked that LiveVars knows any kills on the
  1988. // bundle header instead).
  1989. if (LiveVars && Reg.isVirtual() && MO->isKill() &&
  1990. !MI->isBundledWithPred()) {
  1991. LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
  1992. if (!is_contained(VI.Kills, MI))
  1993. report("Kill missing from LiveVariables", MO, MONum);
  1994. }
  1995. // Check LiveInts liveness and kill.
  1996. if (LiveInts && !LiveInts->isNotInMIMap(*MI)) {
  1997. SlotIndex UseIdx = LiveInts->getInstructionIndex(*MI);
  1998. // Check the cached regunit intervals.
  1999. if (Reg.isPhysical() && !isReserved(Reg)) {
  2000. for (MCRegUnitIterator Units(Reg.asMCReg(), TRI); Units.isValid();
  2001. ++Units) {
  2002. if (MRI->isReservedRegUnit(*Units))
  2003. continue;
  2004. if (const LiveRange *LR = LiveInts->getCachedRegUnit(*Units))
  2005. checkLivenessAtUse(MO, MONum, UseIdx, *LR, *Units);
  2006. }
  2007. }
  2008. if (Reg.isVirtual()) {
  2009. // This is a virtual register interval.
  2010. checkLivenessAtUse(MO, MONum, UseIdx, *LI, Reg);
  2011. if (LI->hasSubRanges() && !MO->isDef()) {
  2012. LaneBitmask MOMask = SubRegIdx != 0
  2013. ? TRI->getSubRegIndexLaneMask(SubRegIdx)
  2014. : MRI->getMaxLaneMaskForVReg(Reg);
  2015. LaneBitmask LiveInMask;
  2016. for (const LiveInterval::SubRange &SR : LI->subranges()) {
  2017. if ((MOMask & SR.LaneMask).none())
  2018. continue;
  2019. checkLivenessAtUse(MO, MONum, UseIdx, SR, Reg, SR.LaneMask);
  2020. LiveQueryResult LRQ = SR.Query(UseIdx);
  2021. if (LRQ.valueIn())
  2022. LiveInMask |= SR.LaneMask;
  2023. }
  2024. // At least parts of the register has to be live at the use.
  2025. if ((LiveInMask & MOMask).none()) {
  2026. report("No live subrange at use", MO, MONum);
  2027. report_context(*LI);
  2028. report_context(UseIdx);
  2029. }
  2030. }
  2031. }
  2032. }
  2033. // Use of a dead register.
  2034. if (!regsLive.count(Reg)) {
  2035. if (Reg.isPhysical()) {
  2036. // Reserved registers may be used even when 'dead'.
  2037. bool Bad = !isReserved(Reg);
  2038. // We are fine if just any subregister has a defined value.
  2039. if (Bad) {
  2040. for (const MCPhysReg &SubReg : TRI->subregs(Reg)) {
  2041. if (regsLive.count(SubReg)) {
  2042. Bad = false;
  2043. break;
  2044. }
  2045. }
  2046. }
  2047. // If there is an additional implicit-use of a super register we stop
  2048. // here. By definition we are fine if the super register is not
  2049. // (completely) dead, if the complete super register is dead we will
  2050. // get a report for its operand.
  2051. if (Bad) {
  2052. for (const MachineOperand &MOP : MI->uses()) {
  2053. if (!MOP.isReg() || !MOP.isImplicit())
  2054. continue;
  2055. if (!MOP.getReg().isPhysical())
  2056. continue;
  2057. if (llvm::is_contained(TRI->subregs(MOP.getReg()), Reg))
  2058. Bad = false;
  2059. }
  2060. }
  2061. if (Bad)
  2062. report("Using an undefined physical register", MO, MONum);
  2063. } else if (MRI->def_empty(Reg)) {
  2064. report("Reading virtual register without a def", MO, MONum);
  2065. } else {
  2066. BBInfo &MInfo = MBBInfoMap[MI->getParent()];
  2067. // We don't know which virtual registers are live in, so only complain
  2068. // if vreg was killed in this MBB. Otherwise keep track of vregs that
  2069. // must be live in. PHI instructions are handled separately.
  2070. if (MInfo.regsKilled.count(Reg))
  2071. report("Using a killed virtual register", MO, MONum);
  2072. else if (!MI->isPHI())
  2073. MInfo.vregsLiveIn.insert(std::make_pair(Reg, MI));
  2074. }
  2075. }
  2076. }
  2077. if (MO->isDef()) {
  2078. // Register defined.
  2079. // TODO: verify that earlyclobber ops are not used.
  2080. if (MO->isDead())
  2081. addRegWithSubRegs(regsDead, Reg);
  2082. else
  2083. addRegWithSubRegs(regsDefined, Reg);
  2084. // Verify SSA form.
  2085. if (MRI->isSSA() && Reg.isVirtual() &&
  2086. std::next(MRI->def_begin(Reg)) != MRI->def_end())
  2087. report("Multiple virtual register defs in SSA form", MO, MONum);
  2088. // Check LiveInts for a live segment, but only for virtual registers.
  2089. if (LiveInts && !LiveInts->isNotInMIMap(*MI)) {
  2090. SlotIndex DefIdx = LiveInts->getInstructionIndex(*MI);
  2091. DefIdx = DefIdx.getRegSlot(MO->isEarlyClobber());
  2092. if (Reg.isVirtual()) {
  2093. checkLivenessAtDef(MO, MONum, DefIdx, *LI, Reg);
  2094. if (LI->hasSubRanges()) {
  2095. LaneBitmask MOMask = SubRegIdx != 0
  2096. ? TRI->getSubRegIndexLaneMask(SubRegIdx)
  2097. : MRI->getMaxLaneMaskForVReg(Reg);
  2098. for (const LiveInterval::SubRange &SR : LI->subranges()) {
  2099. if ((SR.LaneMask & MOMask).none())
  2100. continue;
  2101. checkLivenessAtDef(MO, MONum, DefIdx, SR, Reg, true, SR.LaneMask);
  2102. }
  2103. }
  2104. }
  2105. }
  2106. }
  2107. }
  2108. // This function gets called after visiting all instructions in a bundle. The
  2109. // argument points to the bundle header.
  2110. // Normal stand-alone instructions are also considered 'bundles', and this
  2111. // function is called for all of them.
  2112. void MachineVerifier::visitMachineBundleAfter(const MachineInstr *MI) {
  2113. BBInfo &MInfo = MBBInfoMap[MI->getParent()];
  2114. set_union(MInfo.regsKilled, regsKilled);
  2115. set_subtract(regsLive, regsKilled); regsKilled.clear();
  2116. // Kill any masked registers.
  2117. while (!regMasks.empty()) {
  2118. const uint32_t *Mask = regMasks.pop_back_val();
  2119. for (Register Reg : regsLive)
  2120. if (Reg.isPhysical() &&
  2121. MachineOperand::clobbersPhysReg(Mask, Reg.asMCReg()))
  2122. regsDead.push_back(Reg);
  2123. }
  2124. set_subtract(regsLive, regsDead); regsDead.clear();
  2125. set_union(regsLive, regsDefined); regsDefined.clear();
  2126. }
  2127. void
  2128. MachineVerifier::visitMachineBasicBlockAfter(const MachineBasicBlock *MBB) {
  2129. MBBInfoMap[MBB].regsLiveOut = regsLive;
  2130. regsLive.clear();
  2131. if (Indexes) {
  2132. SlotIndex stop = Indexes->getMBBEndIdx(MBB);
  2133. if (!(stop > lastIndex)) {
  2134. report("Block ends before last instruction index", MBB);
  2135. errs() << "Block ends at " << stop
  2136. << " last instruction was at " << lastIndex << '\n';
  2137. }
  2138. lastIndex = stop;
  2139. }
  2140. }
  2141. namespace {
  2142. // This implements a set of registers that serves as a filter: can filter other
  2143. // sets by passing through elements not in the filter and blocking those that
  2144. // are. Any filter implicitly includes the full set of physical registers upon
  2145. // creation, thus filtering them all out. The filter itself as a set only grows,
  2146. // and needs to be as efficient as possible.
  2147. struct VRegFilter {
  2148. // Add elements to the filter itself. \pre Input set \p FromRegSet must have
  2149. // no duplicates. Both virtual and physical registers are fine.
  2150. template <typename RegSetT> void add(const RegSetT &FromRegSet) {
  2151. SmallVector<Register, 0> VRegsBuffer;
  2152. filterAndAdd(FromRegSet, VRegsBuffer);
  2153. }
  2154. // Filter \p FromRegSet through the filter and append passed elements into \p
  2155. // ToVRegs. All elements appended are then added to the filter itself.
  2156. // \returns true if anything changed.
  2157. template <typename RegSetT>
  2158. bool filterAndAdd(const RegSetT &FromRegSet,
  2159. SmallVectorImpl<Register> &ToVRegs) {
  2160. unsigned SparseUniverse = Sparse.size();
  2161. unsigned NewSparseUniverse = SparseUniverse;
  2162. unsigned NewDenseSize = Dense.size();
  2163. size_t Begin = ToVRegs.size();
  2164. for (Register Reg : FromRegSet) {
  2165. if (!Reg.isVirtual())
  2166. continue;
  2167. unsigned Index = Register::virtReg2Index(Reg);
  2168. if (Index < SparseUniverseMax) {
  2169. if (Index < SparseUniverse && Sparse.test(Index))
  2170. continue;
  2171. NewSparseUniverse = std::max(NewSparseUniverse, Index + 1);
  2172. } else {
  2173. if (Dense.count(Reg))
  2174. continue;
  2175. ++NewDenseSize;
  2176. }
  2177. ToVRegs.push_back(Reg);
  2178. }
  2179. size_t End = ToVRegs.size();
  2180. if (Begin == End)
  2181. return false;
  2182. // Reserving space in sets once performs better than doing so continuously
  2183. // and pays easily for double look-ups (even in Dense with SparseUniverseMax
  2184. // tuned all the way down) and double iteration (the second one is over a
  2185. // SmallVector, which is a lot cheaper compared to DenseSet or BitVector).
  2186. Sparse.resize(NewSparseUniverse);
  2187. Dense.reserve(NewDenseSize);
  2188. for (unsigned I = Begin; I < End; ++I) {
  2189. Register Reg = ToVRegs[I];
  2190. unsigned Index = Register::virtReg2Index(Reg);
  2191. if (Index < SparseUniverseMax)
  2192. Sparse.set(Index);
  2193. else
  2194. Dense.insert(Reg);
  2195. }
  2196. return true;
  2197. }
  2198. private:
  2199. static constexpr unsigned SparseUniverseMax = 10 * 1024 * 8;
  2200. // VRegs indexed within SparseUniverseMax are tracked by Sparse, those beyound
  2201. // are tracked by Dense. The only purpose of the threashold and the Dense set
  2202. // is to have a reasonably growing memory usage in pathological cases (large
  2203. // number of very sparse VRegFilter instances live at the same time). In
  2204. // practice even in the worst-by-execution time cases having all elements
  2205. // tracked by Sparse (very large SparseUniverseMax scenario) tends to be more
  2206. // space efficient than if tracked by Dense. The threashold is set to keep the
  2207. // worst-case memory usage within 2x of figures determined empirically for
  2208. // "all Dense" scenario in such worst-by-execution-time cases.
  2209. BitVector Sparse;
  2210. DenseSet<unsigned> Dense;
  2211. };
  2212. // Implements both a transfer function and a (binary, in-place) join operator
  2213. // for a dataflow over register sets with set union join and filtering transfer
  2214. // (out_b = in_b \ filter_b). filter_b is expected to be set-up ahead of time.
  2215. // Maintains out_b as its state, allowing for O(n) iteration over it at any
  2216. // time, where n is the size of the set (as opposed to O(U) where U is the
  2217. // universe). filter_b implicitly contains all physical registers at all times.
  2218. class FilteringVRegSet {
  2219. VRegFilter Filter;
  2220. SmallVector<Register, 0> VRegs;
  2221. public:
  2222. // Set-up the filter_b. \pre Input register set \p RS must have no duplicates.
  2223. // Both virtual and physical registers are fine.
  2224. template <typename RegSetT> void addToFilter(const RegSetT &RS) {
  2225. Filter.add(RS);
  2226. }
  2227. // Passes \p RS through the filter_b (transfer function) and adds what's left
  2228. // to itself (out_b).
  2229. template <typename RegSetT> bool add(const RegSetT &RS) {
  2230. // Double-duty the Filter: to maintain VRegs a set (and the join operation
  2231. // a set union) just add everything being added here to the Filter as well.
  2232. return Filter.filterAndAdd(RS, VRegs);
  2233. }
  2234. using const_iterator = decltype(VRegs)::const_iterator;
  2235. const_iterator begin() const { return VRegs.begin(); }
  2236. const_iterator end() const { return VRegs.end(); }
  2237. size_t size() const { return VRegs.size(); }
  2238. };
  2239. } // namespace
  2240. // Calculate the largest possible vregsPassed sets. These are the registers that
  2241. // can pass through an MBB live, but may not be live every time. It is assumed
  2242. // that all vregsPassed sets are empty before the call.
  2243. void MachineVerifier::calcRegsPassed() {
  2244. if (MF->empty())
  2245. // ReversePostOrderTraversal doesn't handle empty functions.
  2246. return;
  2247. for (const MachineBasicBlock *MB :
  2248. ReversePostOrderTraversal<const MachineFunction *>(MF)) {
  2249. FilteringVRegSet VRegs;
  2250. BBInfo &Info = MBBInfoMap[MB];
  2251. assert(Info.reachable);
  2252. VRegs.addToFilter(Info.regsKilled);
  2253. VRegs.addToFilter(Info.regsLiveOut);
  2254. for (const MachineBasicBlock *Pred : MB->predecessors()) {
  2255. const BBInfo &PredInfo = MBBInfoMap[Pred];
  2256. if (!PredInfo.reachable)
  2257. continue;
  2258. VRegs.add(PredInfo.regsLiveOut);
  2259. VRegs.add(PredInfo.vregsPassed);
  2260. }
  2261. Info.vregsPassed.reserve(VRegs.size());
  2262. Info.vregsPassed.insert(VRegs.begin(), VRegs.end());
  2263. }
  2264. }
  2265. // Calculate the set of virtual registers that must be passed through each basic
  2266. // block in order to satisfy the requirements of successor blocks. This is very
  2267. // similar to calcRegsPassed, only backwards.
  2268. void MachineVerifier::calcRegsRequired() {
  2269. // First push live-in regs to predecessors' vregsRequired.
  2270. SmallPtrSet<const MachineBasicBlock*, 8> todo;
  2271. for (const auto &MBB : *MF) {
  2272. BBInfo &MInfo = MBBInfoMap[&MBB];
  2273. for (const MachineBasicBlock *Pred : MBB.predecessors()) {
  2274. BBInfo &PInfo = MBBInfoMap[Pred];
  2275. if (PInfo.addRequired(MInfo.vregsLiveIn))
  2276. todo.insert(Pred);
  2277. }
  2278. // Handle the PHI node.
  2279. for (const MachineInstr &MI : MBB.phis()) {
  2280. for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
  2281. // Skip those Operands which are undef regs or not regs.
  2282. if (!MI.getOperand(i).isReg() || !MI.getOperand(i).readsReg())
  2283. continue;
  2284. // Get register and predecessor for one PHI edge.
  2285. Register Reg = MI.getOperand(i).getReg();
  2286. const MachineBasicBlock *Pred = MI.getOperand(i + 1).getMBB();
  2287. BBInfo &PInfo = MBBInfoMap[Pred];
  2288. if (PInfo.addRequired(Reg))
  2289. todo.insert(Pred);
  2290. }
  2291. }
  2292. }
  2293. // Iteratively push vregsRequired to predecessors. This will converge to the
  2294. // same final state regardless of DenseSet iteration order.
  2295. while (!todo.empty()) {
  2296. const MachineBasicBlock *MBB = *todo.begin();
  2297. todo.erase(MBB);
  2298. BBInfo &MInfo = MBBInfoMap[MBB];
  2299. for (const MachineBasicBlock *Pred : MBB->predecessors()) {
  2300. if (Pred == MBB)
  2301. continue;
  2302. BBInfo &SInfo = MBBInfoMap[Pred];
  2303. if (SInfo.addRequired(MInfo.vregsRequired))
  2304. todo.insert(Pred);
  2305. }
  2306. }
  2307. }
  2308. // Check PHI instructions at the beginning of MBB. It is assumed that
  2309. // calcRegsPassed has been run so BBInfo::isLiveOut is valid.
  2310. void MachineVerifier::checkPHIOps(const MachineBasicBlock &MBB) {
  2311. BBInfo &MInfo = MBBInfoMap[&MBB];
  2312. SmallPtrSet<const MachineBasicBlock*, 8> seen;
  2313. for (const MachineInstr &Phi : MBB) {
  2314. if (!Phi.isPHI())
  2315. break;
  2316. seen.clear();
  2317. const MachineOperand &MODef = Phi.getOperand(0);
  2318. if (!MODef.isReg() || !MODef.isDef()) {
  2319. report("Expected first PHI operand to be a register def", &MODef, 0);
  2320. continue;
  2321. }
  2322. if (MODef.isTied() || MODef.isImplicit() || MODef.isInternalRead() ||
  2323. MODef.isEarlyClobber() || MODef.isDebug())
  2324. report("Unexpected flag on PHI operand", &MODef, 0);
  2325. Register DefReg = MODef.getReg();
  2326. if (!Register::isVirtualRegister(DefReg))
  2327. report("Expected first PHI operand to be a virtual register", &MODef, 0);
  2328. for (unsigned I = 1, E = Phi.getNumOperands(); I != E; I += 2) {
  2329. const MachineOperand &MO0 = Phi.getOperand(I);
  2330. if (!MO0.isReg()) {
  2331. report("Expected PHI operand to be a register", &MO0, I);
  2332. continue;
  2333. }
  2334. if (MO0.isImplicit() || MO0.isInternalRead() || MO0.isEarlyClobber() ||
  2335. MO0.isDebug() || MO0.isTied())
  2336. report("Unexpected flag on PHI operand", &MO0, I);
  2337. const MachineOperand &MO1 = Phi.getOperand(I + 1);
  2338. if (!MO1.isMBB()) {
  2339. report("Expected PHI operand to be a basic block", &MO1, I + 1);
  2340. continue;
  2341. }
  2342. const MachineBasicBlock &Pre = *MO1.getMBB();
  2343. if (!Pre.isSuccessor(&MBB)) {
  2344. report("PHI input is not a predecessor block", &MO1, I + 1);
  2345. continue;
  2346. }
  2347. if (MInfo.reachable) {
  2348. seen.insert(&Pre);
  2349. BBInfo &PrInfo = MBBInfoMap[&Pre];
  2350. if (!MO0.isUndef() && PrInfo.reachable &&
  2351. !PrInfo.isLiveOut(MO0.getReg()))
  2352. report("PHI operand is not live-out from predecessor", &MO0, I);
  2353. }
  2354. }
  2355. // Did we see all predecessors?
  2356. if (MInfo.reachable) {
  2357. for (MachineBasicBlock *Pred : MBB.predecessors()) {
  2358. if (!seen.count(Pred)) {
  2359. report("Missing PHI operand", &Phi);
  2360. errs() << printMBBReference(*Pred)
  2361. << " is a predecessor according to the CFG.\n";
  2362. }
  2363. }
  2364. }
  2365. }
  2366. }
  2367. void MachineVerifier::visitMachineFunctionAfter() {
  2368. calcRegsPassed();
  2369. for (const MachineBasicBlock &MBB : *MF)
  2370. checkPHIOps(MBB);
  2371. // Now check liveness info if available
  2372. calcRegsRequired();
  2373. // Check for killed virtual registers that should be live out.
  2374. for (const auto &MBB : *MF) {
  2375. BBInfo &MInfo = MBBInfoMap[&MBB];
  2376. for (Register VReg : MInfo.vregsRequired)
  2377. if (MInfo.regsKilled.count(VReg)) {
  2378. report("Virtual register killed in block, but needed live out.", &MBB);
  2379. errs() << "Virtual register " << printReg(VReg)
  2380. << " is used after the block.\n";
  2381. }
  2382. }
  2383. if (!MF->empty()) {
  2384. BBInfo &MInfo = MBBInfoMap[&MF->front()];
  2385. for (Register VReg : MInfo.vregsRequired) {
  2386. report("Virtual register defs don't dominate all uses.", MF);
  2387. report_context_vreg(VReg);
  2388. }
  2389. }
  2390. if (LiveVars)
  2391. verifyLiveVariables();
  2392. if (LiveInts)
  2393. verifyLiveIntervals();
  2394. // Check live-in list of each MBB. If a register is live into MBB, check
  2395. // that the register is in regsLiveOut of each predecessor block. Since
  2396. // this must come from a definition in the predecesssor or its live-in
  2397. // list, this will catch a live-through case where the predecessor does not
  2398. // have the register in its live-in list. This currently only checks
  2399. // registers that have no aliases, are not allocatable and are not
  2400. // reserved, which could mean a condition code register for instance.
  2401. if (MRI->tracksLiveness())
  2402. for (const auto &MBB : *MF)
  2403. for (MachineBasicBlock::RegisterMaskPair P : MBB.liveins()) {
  2404. MCPhysReg LiveInReg = P.PhysReg;
  2405. bool hasAliases = MCRegAliasIterator(LiveInReg, TRI, false).isValid();
  2406. if (hasAliases || isAllocatable(LiveInReg) || isReserved(LiveInReg))
  2407. continue;
  2408. for (const MachineBasicBlock *Pred : MBB.predecessors()) {
  2409. BBInfo &PInfo = MBBInfoMap[Pred];
  2410. if (!PInfo.regsLiveOut.count(LiveInReg)) {
  2411. report("Live in register not found to be live out from predecessor.",
  2412. &MBB);
  2413. errs() << TRI->getName(LiveInReg)
  2414. << " not found to be live out from "
  2415. << printMBBReference(*Pred) << "\n";
  2416. }
  2417. }
  2418. }
  2419. for (auto CSInfo : MF->getCallSitesInfo())
  2420. if (!CSInfo.first->isCall())
  2421. report("Call site info referencing instruction that is not call", MF);
  2422. // If there's debug-info, check that we don't have any duplicate value
  2423. // tracking numbers.
  2424. if (MF->getFunction().getSubprogram()) {
  2425. DenseSet<unsigned> SeenNumbers;
  2426. for (auto &MBB : *MF) {
  2427. for (auto &MI : MBB) {
  2428. if (auto Num = MI.peekDebugInstrNum()) {
  2429. auto Result = SeenNumbers.insert((unsigned)Num);
  2430. if (!Result.second)
  2431. report("Instruction has a duplicated value tracking number", &MI);
  2432. }
  2433. }
  2434. }
  2435. }
  2436. }
  2437. void MachineVerifier::verifyLiveVariables() {
  2438. assert(LiveVars && "Don't call verifyLiveVariables without LiveVars");
  2439. for (unsigned I = 0, E = MRI->getNumVirtRegs(); I != E; ++I) {
  2440. Register Reg = Register::index2VirtReg(I);
  2441. LiveVariables::VarInfo &VI = LiveVars->getVarInfo(Reg);
  2442. for (const auto &MBB : *MF) {
  2443. BBInfo &MInfo = MBBInfoMap[&MBB];
  2444. // Our vregsRequired should be identical to LiveVariables' AliveBlocks
  2445. if (MInfo.vregsRequired.count(Reg)) {
  2446. if (!VI.AliveBlocks.test(MBB.getNumber())) {
  2447. report("LiveVariables: Block missing from AliveBlocks", &MBB);
  2448. errs() << "Virtual register " << printReg(Reg)
  2449. << " must be live through the block.\n";
  2450. }
  2451. } else {
  2452. if (VI.AliveBlocks.test(MBB.getNumber())) {
  2453. report("LiveVariables: Block should not be in AliveBlocks", &MBB);
  2454. errs() << "Virtual register " << printReg(Reg)
  2455. << " is not needed live through the block.\n";
  2456. }
  2457. }
  2458. }
  2459. }
  2460. }
  2461. void MachineVerifier::verifyLiveIntervals() {
  2462. assert(LiveInts && "Don't call verifyLiveIntervals without LiveInts");
  2463. for (unsigned I = 0, E = MRI->getNumVirtRegs(); I != E; ++I) {
  2464. Register Reg = Register::index2VirtReg(I);
  2465. // Spilling and splitting may leave unused registers around. Skip them.
  2466. if (MRI->reg_nodbg_empty(Reg))
  2467. continue;
  2468. if (!LiveInts->hasInterval(Reg)) {
  2469. report("Missing live interval for virtual register", MF);
  2470. errs() << printReg(Reg, TRI) << " still has defs or uses\n";
  2471. continue;
  2472. }
  2473. const LiveInterval &LI = LiveInts->getInterval(Reg);
  2474. assert(Reg == LI.reg() && "Invalid reg to interval mapping");
  2475. verifyLiveInterval(LI);
  2476. }
  2477. // Verify all the cached regunit intervals.
  2478. for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
  2479. if (const LiveRange *LR = LiveInts->getCachedRegUnit(i))
  2480. verifyLiveRange(*LR, i);
  2481. }
  2482. void MachineVerifier::verifyLiveRangeValue(const LiveRange &LR,
  2483. const VNInfo *VNI, Register Reg,
  2484. LaneBitmask LaneMask) {
  2485. if (VNI->isUnused())
  2486. return;
  2487. const VNInfo *DefVNI = LR.getVNInfoAt(VNI->def);
  2488. if (!DefVNI) {
  2489. report("Value not live at VNInfo def and not marked unused", MF);
  2490. report_context(LR, Reg, LaneMask);
  2491. report_context(*VNI);
  2492. return;
  2493. }
  2494. if (DefVNI != VNI) {
  2495. report("Live segment at def has different VNInfo", MF);
  2496. report_context(LR, Reg, LaneMask);
  2497. report_context(*VNI);
  2498. return;
  2499. }
  2500. const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(VNI->def);
  2501. if (!MBB) {
  2502. report("Invalid VNInfo definition index", MF);
  2503. report_context(LR, Reg, LaneMask);
  2504. report_context(*VNI);
  2505. return;
  2506. }
  2507. if (VNI->isPHIDef()) {
  2508. if (VNI->def != LiveInts->getMBBStartIdx(MBB)) {
  2509. report("PHIDef VNInfo is not defined at MBB start", MBB);
  2510. report_context(LR, Reg, LaneMask);
  2511. report_context(*VNI);
  2512. }
  2513. return;
  2514. }
  2515. // Non-PHI def.
  2516. const MachineInstr *MI = LiveInts->getInstructionFromIndex(VNI->def);
  2517. if (!MI) {
  2518. report("No instruction at VNInfo def index", MBB);
  2519. report_context(LR, Reg, LaneMask);
  2520. report_context(*VNI);
  2521. return;
  2522. }
  2523. if (Reg != 0) {
  2524. bool hasDef = false;
  2525. bool isEarlyClobber = false;
  2526. for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) {
  2527. if (!MOI->isReg() || !MOI->isDef())
  2528. continue;
  2529. if (Register::isVirtualRegister(Reg)) {
  2530. if (MOI->getReg() != Reg)
  2531. continue;
  2532. } else {
  2533. if (!Register::isPhysicalRegister(MOI->getReg()) ||
  2534. !TRI->hasRegUnit(MOI->getReg(), Reg))
  2535. continue;
  2536. }
  2537. if (LaneMask.any() &&
  2538. (TRI->getSubRegIndexLaneMask(MOI->getSubReg()) & LaneMask).none())
  2539. continue;
  2540. hasDef = true;
  2541. if (MOI->isEarlyClobber())
  2542. isEarlyClobber = true;
  2543. }
  2544. if (!hasDef) {
  2545. report("Defining instruction does not modify register", MI);
  2546. report_context(LR, Reg, LaneMask);
  2547. report_context(*VNI);
  2548. }
  2549. // Early clobber defs begin at USE slots, but other defs must begin at
  2550. // DEF slots.
  2551. if (isEarlyClobber) {
  2552. if (!VNI->def.isEarlyClobber()) {
  2553. report("Early clobber def must be at an early-clobber slot", MBB);
  2554. report_context(LR, Reg, LaneMask);
  2555. report_context(*VNI);
  2556. }
  2557. } else if (!VNI->def.isRegister()) {
  2558. report("Non-PHI, non-early clobber def must be at a register slot", MBB);
  2559. report_context(LR, Reg, LaneMask);
  2560. report_context(*VNI);
  2561. }
  2562. }
  2563. }
  2564. void MachineVerifier::verifyLiveRangeSegment(const LiveRange &LR,
  2565. const LiveRange::const_iterator I,
  2566. Register Reg,
  2567. LaneBitmask LaneMask) {
  2568. const LiveRange::Segment &S = *I;
  2569. const VNInfo *VNI = S.valno;
  2570. assert(VNI && "Live segment has no valno");
  2571. if (VNI->id >= LR.getNumValNums() || VNI != LR.getValNumInfo(VNI->id)) {
  2572. report("Foreign valno in live segment", MF);
  2573. report_context(LR, Reg, LaneMask);
  2574. report_context(S);
  2575. report_context(*VNI);
  2576. }
  2577. if (VNI->isUnused()) {
  2578. report("Live segment valno is marked unused", MF);
  2579. report_context(LR, Reg, LaneMask);
  2580. report_context(S);
  2581. }
  2582. const MachineBasicBlock *MBB = LiveInts->getMBBFromIndex(S.start);
  2583. if (!MBB) {
  2584. report("Bad start of live segment, no basic block", MF);
  2585. report_context(LR, Reg, LaneMask);
  2586. report_context(S);
  2587. return;
  2588. }
  2589. SlotIndex MBBStartIdx = LiveInts->getMBBStartIdx(MBB);
  2590. if (S.start != MBBStartIdx && S.start != VNI->def) {
  2591. report("Live segment must begin at MBB entry or valno def", MBB);
  2592. report_context(LR, Reg, LaneMask);
  2593. report_context(S);
  2594. }
  2595. const MachineBasicBlock *EndMBB =
  2596. LiveInts->getMBBFromIndex(S.end.getPrevSlot());
  2597. if (!EndMBB) {
  2598. report("Bad end of live segment, no basic block", MF);
  2599. report_context(LR, Reg, LaneMask);
  2600. report_context(S);
  2601. return;
  2602. }
  2603. // No more checks for live-out segments.
  2604. if (S.end == LiveInts->getMBBEndIdx(EndMBB))
  2605. return;
  2606. // RegUnit intervals are allowed dead phis.
  2607. if (!Register::isVirtualRegister(Reg) && VNI->isPHIDef() &&
  2608. S.start == VNI->def && S.end == VNI->def.getDeadSlot())
  2609. return;
  2610. // The live segment is ending inside EndMBB
  2611. const MachineInstr *MI =
  2612. LiveInts->getInstructionFromIndex(S.end.getPrevSlot());
  2613. if (!MI) {
  2614. report("Live segment doesn't end at a valid instruction", EndMBB);
  2615. report_context(LR, Reg, LaneMask);
  2616. report_context(S);
  2617. return;
  2618. }
  2619. // The block slot must refer to a basic block boundary.
  2620. if (S.end.isBlock()) {
  2621. report("Live segment ends at B slot of an instruction", EndMBB);
  2622. report_context(LR, Reg, LaneMask);
  2623. report_context(S);
  2624. }
  2625. if (S.end.isDead()) {
  2626. // Segment ends on the dead slot.
  2627. // That means there must be a dead def.
  2628. if (!SlotIndex::isSameInstr(S.start, S.end)) {
  2629. report("Live segment ending at dead slot spans instructions", EndMBB);
  2630. report_context(LR, Reg, LaneMask);
  2631. report_context(S);
  2632. }
  2633. }
  2634. // After tied operands are rewritten, a live segment can only end at an
  2635. // early-clobber slot if it is being redefined by an early-clobber def.
  2636. // TODO: Before tied operands are rewritten, a live segment can only end at an
  2637. // early-clobber slot if the last use is tied to an early-clobber def.
  2638. if (MF->getProperties().hasProperty(
  2639. MachineFunctionProperties::Property::TiedOpsRewritten) &&
  2640. S.end.isEarlyClobber()) {
  2641. if (I+1 == LR.end() || (I+1)->start != S.end) {
  2642. report("Live segment ending at early clobber slot must be "
  2643. "redefined by an EC def in the same instruction", EndMBB);
  2644. report_context(LR, Reg, LaneMask);
  2645. report_context(S);
  2646. }
  2647. }
  2648. // The following checks only apply to virtual registers. Physreg liveness
  2649. // is too weird to check.
  2650. if (Register::isVirtualRegister(Reg)) {
  2651. // A live segment can end with either a redefinition, a kill flag on a
  2652. // use, or a dead flag on a def.
  2653. bool hasRead = false;
  2654. bool hasSubRegDef = false;
  2655. bool hasDeadDef = false;
  2656. for (ConstMIBundleOperands MOI(*MI); MOI.isValid(); ++MOI) {
  2657. if (!MOI->isReg() || MOI->getReg() != Reg)
  2658. continue;
  2659. unsigned Sub = MOI->getSubReg();
  2660. LaneBitmask SLM = Sub != 0 ? TRI->getSubRegIndexLaneMask(Sub)
  2661. : LaneBitmask::getAll();
  2662. if (MOI->isDef()) {
  2663. if (Sub != 0) {
  2664. hasSubRegDef = true;
  2665. // An operand %0:sub0 reads %0:sub1..n. Invert the lane
  2666. // mask for subregister defs. Read-undef defs will be handled by
  2667. // readsReg below.
  2668. SLM = ~SLM;
  2669. }
  2670. if (MOI->isDead())
  2671. hasDeadDef = true;
  2672. }
  2673. if (LaneMask.any() && (LaneMask & SLM).none())
  2674. continue;
  2675. if (MOI->readsReg())
  2676. hasRead = true;
  2677. }
  2678. if (S.end.isDead()) {
  2679. // Make sure that the corresponding machine operand for a "dead" live
  2680. // range has the dead flag. We cannot perform this check for subregister
  2681. // liveranges as partially dead values are allowed.
  2682. if (LaneMask.none() && !hasDeadDef) {
  2683. report("Instruction ending live segment on dead slot has no dead flag",
  2684. MI);
  2685. report_context(LR, Reg, LaneMask);
  2686. report_context(S);
  2687. }
  2688. } else {
  2689. if (!hasRead) {
  2690. // When tracking subregister liveness, the main range must start new
  2691. // values on partial register writes, even if there is no read.
  2692. if (!MRI->shouldTrackSubRegLiveness(Reg) || LaneMask.any() ||
  2693. !hasSubRegDef) {
  2694. report("Instruction ending live segment doesn't read the register",
  2695. MI);
  2696. report_context(LR, Reg, LaneMask);
  2697. report_context(S);
  2698. }
  2699. }
  2700. }
  2701. }
  2702. // Now check all the basic blocks in this live segment.
  2703. MachineFunction::const_iterator MFI = MBB->getIterator();
  2704. // Is this live segment the beginning of a non-PHIDef VN?
  2705. if (S.start == VNI->def && !VNI->isPHIDef()) {
  2706. // Not live-in to any blocks.
  2707. if (MBB == EndMBB)
  2708. return;
  2709. // Skip this block.
  2710. ++MFI;
  2711. }
  2712. SmallVector<SlotIndex, 4> Undefs;
  2713. if (LaneMask.any()) {
  2714. LiveInterval &OwnerLI = LiveInts->getInterval(Reg);
  2715. OwnerLI.computeSubRangeUndefs(Undefs, LaneMask, *MRI, *Indexes);
  2716. }
  2717. while (true) {
  2718. assert(LiveInts->isLiveInToMBB(LR, &*MFI));
  2719. // We don't know how to track physregs into a landing pad.
  2720. if (!Register::isVirtualRegister(Reg) && MFI->isEHPad()) {
  2721. if (&*MFI == EndMBB)
  2722. break;
  2723. ++MFI;
  2724. continue;
  2725. }
  2726. // Is VNI a PHI-def in the current block?
  2727. bool IsPHI = VNI->isPHIDef() &&
  2728. VNI->def == LiveInts->getMBBStartIdx(&*MFI);
  2729. // Check that VNI is live-out of all predecessors.
  2730. for (const MachineBasicBlock *Pred : MFI->predecessors()) {
  2731. SlotIndex PEnd = LiveInts->getMBBEndIdx(Pred);
  2732. // Predecessor of landing pad live-out on last call.
  2733. if (MFI->isEHPad()) {
  2734. for (const MachineInstr &MI : llvm::reverse(*Pred)) {
  2735. if (MI.isCall()) {
  2736. PEnd = Indexes->getInstructionIndex(MI).getBoundaryIndex();
  2737. break;
  2738. }
  2739. }
  2740. }
  2741. const VNInfo *PVNI = LR.getVNInfoBefore(PEnd);
  2742. // All predecessors must have a live-out value. However for a phi
  2743. // instruction with subregister intervals
  2744. // only one of the subregisters (not necessarily the current one) needs to
  2745. // be defined.
  2746. if (!PVNI && (LaneMask.none() || !IsPHI)) {
  2747. if (LiveRangeCalc::isJointlyDominated(Pred, Undefs, *Indexes))
  2748. continue;
  2749. report("Register not marked live out of predecessor", Pred);
  2750. report_context(LR, Reg, LaneMask);
  2751. report_context(*VNI);
  2752. errs() << " live into " << printMBBReference(*MFI) << '@'
  2753. << LiveInts->getMBBStartIdx(&*MFI) << ", not live before "
  2754. << PEnd << '\n';
  2755. continue;
  2756. }
  2757. // Only PHI-defs can take different predecessor values.
  2758. if (!IsPHI && PVNI != VNI) {
  2759. report("Different value live out of predecessor", Pred);
  2760. report_context(LR, Reg, LaneMask);
  2761. errs() << "Valno #" << PVNI->id << " live out of "
  2762. << printMBBReference(*Pred) << '@' << PEnd << "\nValno #"
  2763. << VNI->id << " live into " << printMBBReference(*MFI) << '@'
  2764. << LiveInts->getMBBStartIdx(&*MFI) << '\n';
  2765. }
  2766. }
  2767. if (&*MFI == EndMBB)
  2768. break;
  2769. ++MFI;
  2770. }
  2771. }
  2772. void MachineVerifier::verifyLiveRange(const LiveRange &LR, Register Reg,
  2773. LaneBitmask LaneMask) {
  2774. for (const VNInfo *VNI : LR.valnos)
  2775. verifyLiveRangeValue(LR, VNI, Reg, LaneMask);
  2776. for (LiveRange::const_iterator I = LR.begin(), E = LR.end(); I != E; ++I)
  2777. verifyLiveRangeSegment(LR, I, Reg, LaneMask);
  2778. }
  2779. void MachineVerifier::verifyLiveInterval(const LiveInterval &LI) {
  2780. Register Reg = LI.reg();
  2781. assert(Register::isVirtualRegister(Reg));
  2782. verifyLiveRange(LI, Reg);
  2783. LaneBitmask Mask;
  2784. LaneBitmask MaxMask = MRI->getMaxLaneMaskForVReg(Reg);
  2785. for (const LiveInterval::SubRange &SR : LI.subranges()) {
  2786. if ((Mask & SR.LaneMask).any()) {
  2787. report("Lane masks of sub ranges overlap in live interval", MF);
  2788. report_context(LI);
  2789. }
  2790. if ((SR.LaneMask & ~MaxMask).any()) {
  2791. report("Subrange lanemask is invalid", MF);
  2792. report_context(LI);
  2793. }
  2794. if (SR.empty()) {
  2795. report("Subrange must not be empty", MF);
  2796. report_context(SR, LI.reg(), SR.LaneMask);
  2797. }
  2798. Mask |= SR.LaneMask;
  2799. verifyLiveRange(SR, LI.reg(), SR.LaneMask);
  2800. if (!LI.covers(SR)) {
  2801. report("A Subrange is not covered by the main range", MF);
  2802. report_context(LI);
  2803. }
  2804. }
  2805. // Check the LI only has one connected component.
  2806. ConnectedVNInfoEqClasses ConEQ(*LiveInts);
  2807. unsigned NumComp = ConEQ.Classify(LI);
  2808. if (NumComp > 1) {
  2809. report("Multiple connected components in live interval", MF);
  2810. report_context(LI);
  2811. for (unsigned comp = 0; comp != NumComp; ++comp) {
  2812. errs() << comp << ": valnos";
  2813. for (const VNInfo *I : LI.valnos)
  2814. if (comp == ConEQ.getEqClass(I))
  2815. errs() << ' ' << I->id;
  2816. errs() << '\n';
  2817. }
  2818. }
  2819. }
  2820. namespace {
  2821. // FrameSetup and FrameDestroy can have zero adjustment, so using a single
  2822. // integer, we can't tell whether it is a FrameSetup or FrameDestroy if the
  2823. // value is zero.
  2824. // We use a bool plus an integer to capture the stack state.
  2825. struct StackStateOfBB {
  2826. StackStateOfBB() = default;
  2827. StackStateOfBB(int EntryVal, int ExitVal, bool EntrySetup, bool ExitSetup) :
  2828. EntryValue(EntryVal), ExitValue(ExitVal), EntryIsSetup(EntrySetup),
  2829. ExitIsSetup(ExitSetup) {}
  2830. // Can be negative, which means we are setting up a frame.
  2831. int EntryValue = 0;
  2832. int ExitValue = 0;
  2833. bool EntryIsSetup = false;
  2834. bool ExitIsSetup = false;
  2835. };
  2836. } // end anonymous namespace
  2837. /// Make sure on every path through the CFG, a FrameSetup <n> is always followed
  2838. /// by a FrameDestroy <n>, stack adjustments are identical on all
  2839. /// CFG edges to a merge point, and frame is destroyed at end of a return block.
  2840. void MachineVerifier::verifyStackFrame() {
  2841. unsigned FrameSetupOpcode = TII->getCallFrameSetupOpcode();
  2842. unsigned FrameDestroyOpcode = TII->getCallFrameDestroyOpcode();
  2843. if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u)
  2844. return;
  2845. SmallVector<StackStateOfBB, 8> SPState;
  2846. SPState.resize(MF->getNumBlockIDs());
  2847. df_iterator_default_set<const MachineBasicBlock*> Reachable;
  2848. // Visit the MBBs in DFS order.
  2849. for (df_ext_iterator<const MachineFunction *,
  2850. df_iterator_default_set<const MachineBasicBlock *>>
  2851. DFI = df_ext_begin(MF, Reachable), DFE = df_ext_end(MF, Reachable);
  2852. DFI != DFE; ++DFI) {
  2853. const MachineBasicBlock *MBB = *DFI;
  2854. StackStateOfBB BBState;
  2855. // Check the exit state of the DFS stack predecessor.
  2856. if (DFI.getPathLength() >= 2) {
  2857. const MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
  2858. assert(Reachable.count(StackPred) &&
  2859. "DFS stack predecessor is already visited.\n");
  2860. BBState.EntryValue = SPState[StackPred->getNumber()].ExitValue;
  2861. BBState.EntryIsSetup = SPState[StackPred->getNumber()].ExitIsSetup;
  2862. BBState.ExitValue = BBState.EntryValue;
  2863. BBState.ExitIsSetup = BBState.EntryIsSetup;
  2864. }
  2865. // Update stack state by checking contents of MBB.
  2866. for (const auto &I : *MBB) {
  2867. if (I.getOpcode() == FrameSetupOpcode) {
  2868. if (BBState.ExitIsSetup)
  2869. report("FrameSetup is after another FrameSetup", &I);
  2870. BBState.ExitValue -= TII->getFrameTotalSize(I);
  2871. BBState.ExitIsSetup = true;
  2872. }
  2873. if (I.getOpcode() == FrameDestroyOpcode) {
  2874. int Size = TII->getFrameTotalSize(I);
  2875. if (!BBState.ExitIsSetup)
  2876. report("FrameDestroy is not after a FrameSetup", &I);
  2877. int AbsSPAdj = BBState.ExitValue < 0 ? -BBState.ExitValue :
  2878. BBState.ExitValue;
  2879. if (BBState.ExitIsSetup && AbsSPAdj != Size) {
  2880. report("FrameDestroy <n> is after FrameSetup <m>", &I);
  2881. errs() << "FrameDestroy <" << Size << "> is after FrameSetup <"
  2882. << AbsSPAdj << ">.\n";
  2883. }
  2884. BBState.ExitValue += Size;
  2885. BBState.ExitIsSetup = false;
  2886. }
  2887. }
  2888. SPState[MBB->getNumber()] = BBState;
  2889. // Make sure the exit state of any predecessor is consistent with the entry
  2890. // state.
  2891. for (const MachineBasicBlock *Pred : MBB->predecessors()) {
  2892. if (Reachable.count(Pred) &&
  2893. (SPState[Pred->getNumber()].ExitValue != BBState.EntryValue ||
  2894. SPState[Pred->getNumber()].ExitIsSetup != BBState.EntryIsSetup)) {
  2895. report("The exit stack state of a predecessor is inconsistent.", MBB);
  2896. errs() << "Predecessor " << printMBBReference(*Pred)
  2897. << " has exit state (" << SPState[Pred->getNumber()].ExitValue
  2898. << ", " << SPState[Pred->getNumber()].ExitIsSetup << "), while "
  2899. << printMBBReference(*MBB) << " has entry state ("
  2900. << BBState.EntryValue << ", " << BBState.EntryIsSetup << ").\n";
  2901. }
  2902. }
  2903. // Make sure the entry state of any successor is consistent with the exit
  2904. // state.
  2905. for (const MachineBasicBlock *Succ : MBB->successors()) {
  2906. if (Reachable.count(Succ) &&
  2907. (SPState[Succ->getNumber()].EntryValue != BBState.ExitValue ||
  2908. SPState[Succ->getNumber()].EntryIsSetup != BBState.ExitIsSetup)) {
  2909. report("The entry stack state of a successor is inconsistent.", MBB);
  2910. errs() << "Successor " << printMBBReference(*Succ)
  2911. << " has entry state (" << SPState[Succ->getNumber()].EntryValue
  2912. << ", " << SPState[Succ->getNumber()].EntryIsSetup << "), while "
  2913. << printMBBReference(*MBB) << " has exit state ("
  2914. << BBState.ExitValue << ", " << BBState.ExitIsSetup << ").\n";
  2915. }
  2916. }
  2917. // Make sure a basic block with return ends with zero stack adjustment.
  2918. if (!MBB->empty() && MBB->back().isReturn()) {
  2919. if (BBState.ExitIsSetup)
  2920. report("A return block ends with a FrameSetup.", MBB);
  2921. if (BBState.ExitValue)
  2922. report("A return block ends with a nonzero stack adjustment.", MBB);
  2923. }
  2924. }
  2925. }