MachineVerifier.cpp 125 KB

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