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