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