1 //===-- MachineFunction.cpp -----------------------------------------------===// 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 // Collect native machine code information for a function. This allows 11 // target-specific information about the generated code to be stored with each 12 // function. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "llvm/DerivedTypes.h" 17 #include "llvm/Function.h" 18 #include "llvm/Instructions.h" 19 #include "llvm/ADT/STLExtras.h" 20 #include "llvm/Config/config.h" 21 #include "llvm/CodeGen/MachineConstantPool.h" 22 #include "llvm/CodeGen/MachineFunctionPass.h" 23 #include "llvm/CodeGen/MachineFrameInfo.h" 24 #include "llvm/CodeGen/MachineInstr.h" 25 #include "llvm/CodeGen/MachineJumpTableInfo.h" 26 #include "llvm/CodeGen/MachineRegisterInfo.h" 27 #include "llvm/CodeGen/Passes.h" 28 #include "llvm/Target/TargetData.h" 29 #include "llvm/Target/TargetLowering.h" 30 #include "llvm/Target/TargetMachine.h" 31 #include "llvm/Target/TargetFrameInfo.h" 32 #include "llvm/Support/Compiler.h" 33 #include "llvm/Support/GraphWriter.h" 34 #include "llvm/Support/raw_ostream.h" 35 #include <fstream> 36 #include <sstream> 37 using namespace llvm; 38 39 bool MachineFunctionPass::runOnFunction(Function &F) { 40 // Do not codegen any 'available_externally' functions at all, they have 41 // definitions outside the translation unit. 42 if (F.hasAvailableExternallyLinkage()) 43 return false; 44 45 return runOnMachineFunction(MachineFunction::get(&F)); 46 } 47 48 namespace { 49 struct VISIBILITY_HIDDEN Printer : public MachineFunctionPass { 50 static char ID; 51 52 std::ostream *OS; 53 const std::string Banner; 54 55 Printer (std::ostream *os, const std::string &banner) 56 : MachineFunctionPass(&ID), OS(os), Banner(banner) {} 57 58 const char *getPassName() const { return "MachineFunction Printer"; } 59 60 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 61 AU.setPreservesAll(); 62 } 63 64 bool runOnMachineFunction(MachineFunction &MF) { 65 (*OS) << Banner; 66 MF.print (*OS); 67 return false; 68 } 69 }; 70 char Printer::ID = 0; 71 } 72 73 /// Returns a newly-created MachineFunction Printer pass. The default output 74 /// stream is std::cerr; the default banner is empty. 75 /// 76 FunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS, 77 const std::string &Banner){ 78 return new Printer(OS, Banner); 79 } 80 81 namespace { 82 struct VISIBILITY_HIDDEN Deleter : public MachineFunctionPass { 83 static char ID; 84 Deleter() : MachineFunctionPass(&ID) {} 85 86 const char *getPassName() const { return "Machine Code Deleter"; } 87 88 bool runOnMachineFunction(MachineFunction &MF) { 89 // Delete the annotation from the function now. 90 MachineFunction::destruct(MF.getFunction()); 91 return true; 92 } 93 }; 94 char Deleter::ID = 0; 95 } 96 97 /// MachineCodeDeletion Pass - This pass deletes all of the machine code for 98 /// the current function, which should happen after the function has been 99 /// emitted to a .s file or to memory. 100 FunctionPass *llvm::createMachineCodeDeleter() { 101 return new Deleter(); 102 } 103 104 105 106 //===---------------------------------------------------------------------===// 107 // MachineFunction implementation 108 //===---------------------------------------------------------------------===// 109 110 void ilist_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) { 111 MBB->getParent()->DeleteMachineBasicBlock(MBB); 112 } 113 114 MachineFunction::MachineFunction(const Function *F, 115 const TargetMachine &TM) 116 : Annotation(AnnotationManager::getID("CodeGen::MachineCodeForFunction")), 117 Fn(F), Target(TM) { 118 if (TM.getRegisterInfo()) 119 RegInfo = new (Allocator.Allocate<MachineRegisterInfo>()) 120 MachineRegisterInfo(*TM.getRegisterInfo()); 121 else 122 RegInfo = 0; 123 MFInfo = 0; 124 FrameInfo = new (Allocator.Allocate<MachineFrameInfo>()) 125 MachineFrameInfo(*TM.getFrameInfo()); 126 ConstantPool = new (Allocator.Allocate<MachineConstantPool>()) 127 MachineConstantPool(TM.getTargetData()); 128 Alignment = TM.getTargetLowering()->getFunctionAlignment(F); 129 130 // Set up jump table. 131 const TargetData &TD = *TM.getTargetData(); 132 bool IsPic = TM.getRelocationModel() == Reloc::PIC_; 133 unsigned EntrySize = IsPic ? 4 : TD.getPointerSize(); 134 unsigned TyAlignment = IsPic ? TD.getABITypeAlignment(Type::Int32Ty) 135 : TD.getPointerABIAlignment(); 136 JumpTableInfo = new (Allocator.Allocate<MachineJumpTableInfo>()) 137 MachineJumpTableInfo(EntrySize, TyAlignment); 138 } 139 140 MachineFunction::~MachineFunction() { 141 BasicBlocks.clear(); 142 InstructionRecycler.clear(Allocator); 143 BasicBlockRecycler.clear(Allocator); 144 if (RegInfo) { 145 RegInfo->~MachineRegisterInfo(); 146 Allocator.Deallocate(RegInfo); 147 } 148 if (MFInfo) { 149 MFInfo->~MachineFunctionInfo(); 150 Allocator.Deallocate(MFInfo); 151 } 152 FrameInfo->~MachineFrameInfo(); Allocator.Deallocate(FrameInfo); 153 ConstantPool->~MachineConstantPool(); Allocator.Deallocate(ConstantPool); 154 JumpTableInfo->~MachineJumpTableInfo(); Allocator.Deallocate(JumpTableInfo); 155 } 156 157 158 /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and 159 /// recomputes them. This guarantees that the MBB numbers are sequential, 160 /// dense, and match the ordering of the blocks within the function. If a 161 /// specific MachineBasicBlock is specified, only that block and those after 162 /// it are renumbered. 163 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) { 164 if (empty()) { MBBNumbering.clear(); return; } 165 MachineFunction::iterator MBBI, E = end(); 166 if (MBB == 0) 167 MBBI = begin(); 168 else 169 MBBI = MBB; 170 171 // Figure out the block number this should have. 172 unsigned BlockNo = 0; 173 if (MBBI != begin()) 174 BlockNo = prior(MBBI)->getNumber()+1; 175 176 for (; MBBI != E; ++MBBI, ++BlockNo) { 177 if (MBBI->getNumber() != (int)BlockNo) { 178 // Remove use of the old number. 179 if (MBBI->getNumber() != -1) { 180 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI && 181 "MBB number mismatch!"); 182 MBBNumbering[MBBI->getNumber()] = 0; 183 } 184 185 // If BlockNo is already taken, set that block's number to -1. 186 if (MBBNumbering[BlockNo]) 187 MBBNumbering[BlockNo]->setNumber(-1); 188 189 MBBNumbering[BlockNo] = MBBI; 190 MBBI->setNumber(BlockNo); 191 } 192 } 193 194 // Okay, all the blocks are renumbered. If we have compactified the block 195 // numbering, shrink MBBNumbering now. 196 assert(BlockNo <= MBBNumbering.size() && "Mismatch!"); 197 MBBNumbering.resize(BlockNo); 198 } 199 200 /// CreateMachineInstr - Allocate a new MachineInstr. Use this instead 201 /// of `new MachineInstr'. 202 /// 203 MachineInstr * 204 MachineFunction::CreateMachineInstr(const TargetInstrDesc &TID, 205 DebugLoc DL, bool NoImp) { 206 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator)) 207 MachineInstr(TID, DL, NoImp); 208 } 209 210 /// CloneMachineInstr - Create a new MachineInstr which is a copy of the 211 /// 'Orig' instruction, identical in all ways except the the instruction 212 /// has no parent, prev, or next. 213 /// 214 MachineInstr * 215 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) { 216 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator)) 217 MachineInstr(*this, *Orig); 218 } 219 220 /// DeleteMachineInstr - Delete the given MachineInstr. 221 /// 222 void 223 MachineFunction::DeleteMachineInstr(MachineInstr *MI) { 224 // Clear the instructions memoperands. This must be done manually because 225 // the instruction's parent pointer is now null, so it can't properly 226 // deallocate them on its own. 227 MI->clearMemOperands(*this); 228 229 MI->~MachineInstr(); 230 InstructionRecycler.Deallocate(Allocator, MI); 231 } 232 233 /// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this 234 /// instead of `new MachineBasicBlock'. 235 /// 236 MachineBasicBlock * 237 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) { 238 return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator)) 239 MachineBasicBlock(*this, bb); 240 } 241 242 /// DeleteMachineBasicBlock - Delete the given MachineBasicBlock. 243 /// 244 void 245 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) { 246 assert(MBB->getParent() == this && "MBB parent mismatch!"); 247 MBB->~MachineBasicBlock(); 248 BasicBlockRecycler.Deallocate(Allocator, MBB); 249 } 250 251 void MachineFunction::dump() const { 252 print(*cerr.stream()); 253 } 254 255 void MachineFunction::print(std::ostream &OS, 256 const PrefixPrinter &prefix) const { 257 OS << "# Machine code for " << Fn->getName () << "():\n"; 258 259 // Print Frame Information 260 FrameInfo->print(*this, OS); 261 262 // Print JumpTable Information 263 JumpTableInfo->print(OS); 264 265 // Print Constant Pool 266 { 267 raw_os_ostream OSS(OS); 268 ConstantPool->print(OSS); 269 } 270 271 const TargetRegisterInfo *TRI = getTarget().getRegisterInfo(); 272 273 if (RegInfo && !RegInfo->livein_empty()) { 274 OS << "Live Ins:"; 275 for (MachineRegisterInfo::livein_iterator 276 I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) { 277 if (TRI) 278 OS << " " << TRI->getName(I->first); 279 else 280 OS << " Reg #" << I->first; 281 282 if (I->second) 283 OS << " in VR#" << I->second << " "; 284 } 285 OS << "\n"; 286 } 287 if (RegInfo && !RegInfo->liveout_empty()) { 288 OS << "Live Outs:"; 289 for (MachineRegisterInfo::liveout_iterator 290 I = RegInfo->liveout_begin(), E = RegInfo->liveout_end(); I != E; ++I) 291 if (TRI) 292 OS << " " << TRI->getName(*I); 293 else 294 OS << " Reg #" << *I; 295 OS << "\n"; 296 } 297 298 for (const_iterator BB = begin(); BB != end(); ++BB) { 299 OS << prefix(*BB); 300 BB->print(OS, prefix); 301 } 302 303 OS << "\n# End machine code for " << Fn->getName () << "().\n\n"; 304 } 305 306 namespace llvm { 307 template<> 308 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits { 309 static std::string getGraphName(const MachineFunction *F) { 310 return "CFG for '" + F->getFunction()->getName() + "' function"; 311 } 312 313 static std::string getNodeLabel(const MachineBasicBlock *Node, 314 const MachineFunction *Graph, 315 bool ShortNames) { 316 if (ShortNames && Node->getBasicBlock() && 317 !Node->getBasicBlock()->getName().empty()) 318 return Node->getBasicBlock()->getName() + ":"; 319 320 std::ostringstream Out; 321 if (ShortNames) { 322 Out << Node->getNumber() << ':'; 323 return Out.str(); 324 } 325 326 Node->print(Out); 327 328 std::string OutStr = Out.str(); 329 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin()); 330 331 // Process string output to make it nicer... 332 for (unsigned i = 0; i != OutStr.length(); ++i) 333 if (OutStr[i] == '\n') { // Left justify 334 OutStr[i] = '\\'; 335 OutStr.insert(OutStr.begin()+i+1, 'l'); 336 } 337 return OutStr; 338 } 339 }; 340 } 341 342 void MachineFunction::viewCFG() const 343 { 344 #ifndef NDEBUG 345 ViewGraph(this, "mf" + getFunction()->getName()); 346 #else 347 cerr << "SelectionDAG::viewGraph is only available in debug builds on " 348 << "systems with Graphviz or gv!\n"; 349 #endif // NDEBUG 350 } 351 352 void MachineFunction::viewCFGOnly() const 353 { 354 #ifndef NDEBUG 355 ViewGraph(this, "mf" + getFunction()->getName(), true); 356 #else 357 cerr << "SelectionDAG::viewGraph is only available in debug builds on " 358 << "systems with Graphviz or gv!\n"; 359 #endif // NDEBUG 360 } 361 362 // The next two methods are used to construct and to retrieve 363 // the MachineCodeForFunction object for the given function. 364 // construct() -- Allocates and initializes for a given function and target 365 // get() -- Returns a handle to the object. 366 // This should not be called before "construct()" 367 // for a given Function. 368 // 369 MachineFunction& 370 MachineFunction::construct(const Function *Fn, const TargetMachine &Tar) 371 { 372 AnnotationID MF_AID = 373 AnnotationManager::getID("CodeGen::MachineCodeForFunction"); 374 assert(Fn->getAnnotation(MF_AID) == 0 && 375 "Object already exists for this function!"); 376 MachineFunction* mcInfo = new MachineFunction(Fn, Tar); 377 Fn->addAnnotation(mcInfo); 378 return *mcInfo; 379 } 380 381 void MachineFunction::destruct(const Function *Fn) { 382 AnnotationID MF_AID = 383 AnnotationManager::getID("CodeGen::MachineCodeForFunction"); 384 bool Deleted = Fn->deleteAnnotation(MF_AID); 385 assert(Deleted && "Machine code did not exist for function!"); 386 Deleted = Deleted; // silence warning when no assertions. 387 } 388 389 MachineFunction& MachineFunction::get(const Function *F) 390 { 391 AnnotationID MF_AID = 392 AnnotationManager::getID("CodeGen::MachineCodeForFunction"); 393 MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID); 394 assert(mc && "Call construct() method first to allocate the object"); 395 return *mc; 396 } 397 398 /// addLiveIn - Add the specified physical register as a live-in value and 399 /// create a corresponding virtual register for it. 400 unsigned MachineFunction::addLiveIn(unsigned PReg, 401 const TargetRegisterClass *RC) { 402 assert(RC->contains(PReg) && "Not the correct regclass!"); 403 unsigned VReg = getRegInfo().createVirtualRegister(RC); 404 getRegInfo().addLiveIn(PReg, VReg); 405 return VReg; 406 } 407 408 /// getOrCreateDebugLocID - Look up the DebugLocTuple index with the given 409 /// source file, line, and column. If none currently exists, create a new 410 /// DebugLocTuple, and insert it into the DebugIdMap. 411 unsigned MachineFunction::getOrCreateDebugLocID(GlobalVariable *CompileUnit, 412 unsigned Line, unsigned Col) { 413 DebugLocTuple Tuple(CompileUnit, Line, Col); 414 DenseMap<DebugLocTuple, unsigned>::iterator II 415 = DebugLocInfo.DebugIdMap.find(Tuple); 416 if (II != DebugLocInfo.DebugIdMap.end()) 417 return II->second; 418 // Add a new tuple. 419 unsigned Id = DebugLocInfo.DebugLocations.size(); 420 DebugLocInfo.DebugLocations.push_back(Tuple); 421 DebugLocInfo.DebugIdMap[Tuple] = Id; 422 return Id; 423 } 424 425 /// getDebugLocTuple - Get the DebugLocTuple for a given DebugLoc object. 426 DebugLocTuple MachineFunction::getDebugLocTuple(DebugLoc DL) const { 427 unsigned Idx = DL.getIndex(); 428 assert(Idx < DebugLocInfo.DebugLocations.size() && 429 "Invalid index into debug locations!"); 430 return DebugLocInfo.DebugLocations[Idx]; 431 } 432 433 //===----------------------------------------------------------------------===// 434 // MachineFrameInfo implementation 435 //===----------------------------------------------------------------------===// 436 437 /// CreateFixedObject - Create a new object at a fixed location on the stack. 438 /// All fixed objects should be created before other objects are created for 439 /// efficiency. By default, fixed objects are immutable. This returns an 440 /// index with a negative value. 441 /// 442 int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset, 443 bool Immutable) { 444 assert(Size != 0 && "Cannot allocate zero size fixed stack objects!"); 445 Objects.insert(Objects.begin(), StackObject(Size, 1, SPOffset, Immutable)); 446 return -++NumFixedObjects; 447 } 448 449 450 void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{ 451 const TargetFrameInfo *FI = MF.getTarget().getFrameInfo(); 452 int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0); 453 454 for (unsigned i = 0, e = Objects.size(); i != e; ++i) { 455 const StackObject &SO = Objects[i]; 456 OS << " <fi#" << (int)(i-NumFixedObjects) << ">: "; 457 if (SO.Size == ~0ULL) { 458 OS << "dead\n"; 459 continue; 460 } 461 if (SO.Size == 0) 462 OS << "variable sized"; 463 else 464 OS << "size is " << SO.Size << " byte" << (SO.Size != 1 ? "s," : ","); 465 OS << " alignment is " << SO.Alignment << " byte" 466 << (SO.Alignment != 1 ? "s," : ","); 467 468 if (i < NumFixedObjects) 469 OS << " fixed"; 470 if (i < NumFixedObjects || SO.SPOffset != -1) { 471 int64_t Off = SO.SPOffset - ValOffset; 472 OS << " at location [SP"; 473 if (Off > 0) 474 OS << "+" << Off; 475 else if (Off < 0) 476 OS << Off; 477 OS << "]"; 478 } 479 OS << "\n"; 480 } 481 482 if (HasVarSizedObjects) 483 OS << " Stack frame contains variable sized objects\n"; 484 } 485 486 void MachineFrameInfo::dump(const MachineFunction &MF) const { 487 print(MF, *cerr.stream()); 488 } 489 490 491 //===----------------------------------------------------------------------===// 492 // MachineJumpTableInfo implementation 493 //===----------------------------------------------------------------------===// 494 495 /// getJumpTableIndex - Create a new jump table entry in the jump table info 496 /// or return an existing one. 497 /// 498 unsigned MachineJumpTableInfo::getJumpTableIndex( 499 const std::vector<MachineBasicBlock*> &DestBBs) { 500 assert(!DestBBs.empty() && "Cannot create an empty jump table!"); 501 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) 502 if (JumpTables[i].MBBs == DestBBs) 503 return i; 504 505 JumpTables.push_back(MachineJumpTableEntry(DestBBs)); 506 return JumpTables.size()-1; 507 } 508 509 /// ReplaceMBBInJumpTables - If Old is the target of any jump tables, update 510 /// the jump tables to branch to New instead. 511 bool 512 MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old, 513 MachineBasicBlock *New) { 514 assert(Old != New && "Not making a change?"); 515 bool MadeChange = false; 516 for (size_t i = 0, e = JumpTables.size(); i != e; ++i) { 517 MachineJumpTableEntry &JTE = JumpTables[i]; 518 for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j) 519 if (JTE.MBBs[j] == Old) { 520 JTE.MBBs[j] = New; 521 MadeChange = true; 522 } 523 } 524 return MadeChange; 525 } 526 527 void MachineJumpTableInfo::print(std::ostream &OS) const { 528 // FIXME: this is lame, maybe we could print out the MBB numbers or something 529 // like {1, 2, 4, 5, 3, 0} 530 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) { 531 OS << " <jt#" << i << "> has " << JumpTables[i].MBBs.size() 532 << " entries\n"; 533 } 534 } 535 536 void MachineJumpTableInfo::dump() const { print(*cerr.stream()); } 537 538 539 //===----------------------------------------------------------------------===// 540 // MachineConstantPool implementation 541 //===----------------------------------------------------------------------===// 542 543 const Type *MachineConstantPoolEntry::getType() const { 544 if (isMachineConstantPoolEntry()) 545 return Val.MachineCPVal->getType(); 546 return Val.ConstVal->getType(); 547 } 548 549 MachineConstantPool::~MachineConstantPool() { 550 for (unsigned i = 0, e = Constants.size(); i != e; ++i) 551 if (Constants[i].isMachineConstantPoolEntry()) 552 delete Constants[i].Val.MachineCPVal; 553 } 554 555 /// getConstantPoolIndex - Create a new entry in the constant pool or return 556 /// an existing one. User must specify the log2 of the minimum required 557 /// alignment for the object. 558 /// 559 unsigned MachineConstantPool::getConstantPoolIndex(Constant *C, 560 unsigned Alignment) { 561 assert(Alignment && "Alignment must be specified!"); 562 if (Alignment > PoolAlignment) PoolAlignment = Alignment; 563 564 // Check to see if we already have this constant. 565 // 566 // FIXME, this could be made much more efficient for large constant pools. 567 for (unsigned i = 0, e = Constants.size(); i != e; ++i) 568 if (Constants[i].Val.ConstVal == C && 569 (Constants[i].getAlignment() & (Alignment - 1)) == 0) 570 return i; 571 572 Constants.push_back(MachineConstantPoolEntry(C, Alignment)); 573 return Constants.size()-1; 574 } 575 576 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V, 577 unsigned Alignment) { 578 assert(Alignment && "Alignment must be specified!"); 579 if (Alignment > PoolAlignment) PoolAlignment = Alignment; 580 581 // Check to see if we already have this constant. 582 // 583 // FIXME, this could be made much more efficient for large constant pools. 584 int Idx = V->getExistingMachineCPValue(this, Alignment); 585 if (Idx != -1) 586 return (unsigned)Idx; 587 588 Constants.push_back(MachineConstantPoolEntry(V, Alignment)); 589 return Constants.size()-1; 590 } 591 592 void MachineConstantPool::print(raw_ostream &OS) const { 593 for (unsigned i = 0, e = Constants.size(); i != e; ++i) { 594 OS << " <cp#" << i << "> is"; 595 if (Constants[i].isMachineConstantPoolEntry()) 596 Constants[i].Val.MachineCPVal->print(OS); 597 else 598 OS << *(Value*)Constants[i].Val.ConstVal; 599 OS << " , alignment=" << Constants[i].getAlignment(); 600 OS << "\n"; 601 } 602 } 603 604 void MachineConstantPool::dump() const { print(errs()); } 605