1 //===-- MachineFunction.cpp -----------------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file was developed by the LLVM research group and is distributed under 6 // the University of Illinois Open Source 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/CodeGen/MachineFunctionPass.h" 17 #include "llvm/CodeGen/MachineInstr.h" 18 #include "llvm/CodeGen/SSARegMap.h" 19 #include "llvm/CodeGen/MachineFrameInfo.h" 20 #include "llvm/CodeGen/MachineConstantPool.h" 21 #include "llvm/CodeGen/MachineJumpTableInfo.h" 22 #include "llvm/CodeGen/Passes.h" 23 #include "llvm/Target/TargetData.h" 24 #include "llvm/Target/TargetMachine.h" 25 #include "llvm/Target/TargetFrameInfo.h" 26 #include "llvm/Function.h" 27 #include "llvm/Instructions.h" 28 #include "llvm/Support/LeakDetector.h" 29 #include "llvm/Support/GraphWriter.h" 30 #include "llvm/System/Path.h" 31 #include "llvm/System/Program.h" 32 #include "llvm/Config/config.h" 33 #include <fstream> 34 #include <iostream> 35 #include <sstream> 36 37 using namespace llvm; 38 39 static AnnotationID MF_AID( 40 AnnotationManager::getID("CodeGen::MachineCodeForFunction")); 41 42 43 namespace { 44 struct Printer : public MachineFunctionPass { 45 std::ostream *OS; 46 const std::string Banner; 47 48 Printer (std::ostream *_OS, const std::string &_Banner) : 49 OS (_OS), Banner (_Banner) { } 50 51 const char *getPassName() const { return "MachineFunction Printer"; } 52 53 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 54 AU.setPreservesAll(); 55 } 56 57 bool runOnMachineFunction(MachineFunction &MF) { 58 (*OS) << Banner; 59 MF.print (*OS); 60 return false; 61 } 62 }; 63 } 64 65 /// Returns a newly-created MachineFunction Printer pass. The default output 66 /// stream is std::cerr; the default banner is empty. 67 /// 68 FunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS, 69 const std::string &Banner){ 70 return new Printer(OS, Banner); 71 } 72 73 namespace { 74 struct Deleter : public MachineFunctionPass { 75 const char *getPassName() const { return "Machine Code Deleter"; } 76 77 bool runOnMachineFunction(MachineFunction &MF) { 78 // Delete the annotation from the function now. 79 MachineFunction::destruct(MF.getFunction()); 80 return true; 81 } 82 }; 83 } 84 85 /// MachineCodeDeletion Pass - This pass deletes all of the machine code for 86 /// the current function, which should happen after the function has been 87 /// emitted to a .s file or to memory. 88 FunctionPass *llvm::createMachineCodeDeleter() { 89 return new Deleter(); 90 } 91 92 93 94 //===---------------------------------------------------------------------===// 95 // MachineFunction implementation 96 //===---------------------------------------------------------------------===// 97 98 MachineBasicBlock* ilist_traits<MachineBasicBlock>::createSentinel() { 99 MachineBasicBlock* dummy = new MachineBasicBlock(); 100 LeakDetector::removeGarbageObject(dummy); 101 return dummy; 102 } 103 104 void ilist_traits<MachineBasicBlock>::transferNodesFromList( 105 iplist<MachineBasicBlock, ilist_traits<MachineBasicBlock> >& toList, 106 ilist_iterator<MachineBasicBlock> first, 107 ilist_iterator<MachineBasicBlock> last) { 108 if (Parent != toList.Parent) 109 for (; first != last; ++first) 110 first->Parent = toList.Parent; 111 } 112 113 MachineFunction::MachineFunction(const Function *F, 114 const TargetMachine &TM) 115 : Annotation(MF_AID), Fn(F), Target(TM), UsedPhysRegs(0) { 116 SSARegMapping = new SSARegMap(); 117 MFInfo = 0; 118 FrameInfo = new MachineFrameInfo(); 119 ConstantPool = new MachineConstantPool(TM.getTargetData()); 120 JumpTableInfo = new MachineJumpTableInfo(TM.getTargetData()); 121 BasicBlocks.Parent = this; 122 } 123 124 MachineFunction::~MachineFunction() { 125 BasicBlocks.clear(); 126 delete SSARegMapping; 127 delete MFInfo; 128 delete FrameInfo; 129 delete ConstantPool; 130 delete JumpTableInfo; 131 delete[] UsedPhysRegs; 132 } 133 134 void MachineFunction::dump() const { print(std::cerr); } 135 136 void MachineFunction::print(std::ostream &OS) const { 137 OS << "# Machine code for " << Fn->getName () << "():\n"; 138 139 // Print Frame Information 140 getFrameInfo()->print(*this, OS); 141 142 // Print JumpTable Information 143 getJumpTableInfo()->print(OS); 144 145 // Print Constant Pool 146 getConstantPool()->print(OS); 147 148 const MRegisterInfo *MRI = getTarget().getRegisterInfo(); 149 150 if (livein_begin() != livein_end()) { 151 OS << "Live Ins:"; 152 for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I) { 153 if (MRI) 154 OS << " " << MRI->getName(I->first); 155 else 156 OS << " Reg #" << I->first; 157 158 if (I->second) 159 OS << " in VR#" << I->second << " "; 160 } 161 OS << "\n"; 162 } 163 if (liveout_begin() != liveout_end()) { 164 OS << "Live Outs:"; 165 for (liveout_iterator I = liveout_begin(), E = liveout_end(); I != E; ++I) 166 if (MRI) 167 OS << " " << MRI->getName(*I); 168 else 169 OS << " Reg #" << *I; 170 OS << "\n"; 171 } 172 173 for (const_iterator BB = begin(); BB != end(); ++BB) 174 BB->print(OS); 175 176 OS << "\n# End machine code for " << Fn->getName () << "().\n\n"; 177 } 178 179 /// CFGOnly flag - This is used to control whether or not the CFG graph printer 180 /// prints out the contents of basic blocks or not. This is acceptable because 181 /// this code is only really used for debugging purposes. 182 /// 183 static bool CFGOnly = false; 184 185 namespace llvm { 186 template<> 187 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits { 188 static std::string getGraphName(const MachineFunction *F) { 189 return "CFG for '" + F->getFunction()->getName() + "' function"; 190 } 191 192 static std::string getNodeLabel(const MachineBasicBlock *Node, 193 const MachineFunction *Graph) { 194 if (CFGOnly && Node->getBasicBlock() && 195 !Node->getBasicBlock()->getName().empty()) 196 return Node->getBasicBlock()->getName() + ":"; 197 198 std::ostringstream Out; 199 if (CFGOnly) { 200 Out << Node->getNumber() << ':'; 201 return Out.str(); 202 } 203 204 Node->print(Out); 205 206 std::string OutStr = Out.str(); 207 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin()); 208 209 // Process string output to make it nicer... 210 for (unsigned i = 0; i != OutStr.length(); ++i) 211 if (OutStr[i] == '\n') { // Left justify 212 OutStr[i] = '\\'; 213 OutStr.insert(OutStr.begin()+i+1, 'l'); 214 } 215 return OutStr; 216 } 217 }; 218 } 219 220 void MachineFunction::viewCFG() const 221 { 222 #ifndef NDEBUG 223 char pathsuff[9]; 224 225 sprintf(pathsuff, "%06u", unsigned(rand())); 226 227 sys::Path TempDir = sys::Path::GetTemporaryDirectory(); 228 sys::Path Filename = TempDir; 229 Filename.appendComponent("mf" + getFunction()->getName() + "." + pathsuff + ".dot"); 230 std::cerr << "Writing '" << Filename << "'... "; 231 std::ofstream F(Filename.c_str()); 232 233 if (!F) { 234 std::cerr << " error opening file for writing!\n"; 235 return; 236 } 237 238 WriteGraph(F, this); 239 F.close(); 240 std::cerr << "\n"; 241 242 #if HAVE_GRAPHVIZ 243 sys::Path Graphviz(LLVM_PATH_GRAPHVIZ); 244 std::vector<const char*> args; 245 args.push_back(Graphviz.c_str()); 246 args.push_back(Filename.c_str()); 247 args.push_back(0); 248 249 std::cerr << "Running 'Graphviz' program... " << std::flush; 250 if (sys::Program::ExecuteAndWait(Graphviz, &args[0])) { 251 std::cerr << "Error viewing graph: 'Graphviz' not in path?\n"; 252 } else { 253 Filename.eraseFromDisk(); 254 return; 255 } 256 #elif (HAVE_GV && HAVE_DOT) 257 sys::Path PSFilename = TempDir; 258 PSFilename.appendComponent(std::string("mf.tempgraph") + "." + pathsuff + ".ps"); 259 260 sys::Path dot(LLVM_PATH_DOT); 261 std::vector<const char*> args; 262 args.push_back(dot.c_str()); 263 args.push_back("-Tps"); 264 args.push_back("-Nfontname=Courier"); 265 args.push_back("-Gsize=7.5,10"); 266 args.push_back(Filename.c_str()); 267 args.push_back("-o"); 268 args.push_back(PSFilename.c_str()); 269 args.push_back(0); 270 271 std::cerr << "Running 'dot' program... " << std::flush; 272 if (sys::Program::ExecuteAndWait(dot, &args[0])) { 273 std::cerr << "Error viewing graph: 'dot' not in path?\n"; 274 } else { 275 std::cerr << "\n"; 276 277 sys::Path gv(LLVM_PATH_GV); 278 args.clear(); 279 args.push_back(gv.c_str()); 280 args.push_back(PSFilename.c_str()); 281 args.push_back(0); 282 283 sys::Program::ExecuteAndWait(gv, &args[0]); 284 } 285 Filename.eraseFromDisk(); 286 PSFilename.eraseFromDisk(); 287 return; 288 #elif HAVE_DOTTY 289 sys::Path dotty(LLVM_PATH_DOTTY); 290 std::vector<const char*> args; 291 args.push_back(dotty.c_str()); 292 args.push_back(Filename.c_str()); 293 args.push_back(0); 294 295 std::cerr << "Running 'dotty' program... " << std::flush; 296 if (sys::Program::ExecuteAndWait(dotty, &args[0])) { 297 std::cerr << "Error viewing graph: 'dotty' not in path?\n"; 298 } else { 299 #ifndef __MINGW32__ // Dotty spawns another app and doesn't wait until it returns 300 Filename.eraseFromDisk(); 301 #endif 302 return; 303 } 304 #endif 305 306 #endif // NDEBUG 307 std::cerr << "MachineFunction::viewCFG is only available in debug builds on " 308 << "systems with Graphviz or gv!\n"; 309 310 #ifndef NDEBUG 311 Filename.eraseFromDisk(); 312 TempDir.eraseFromDisk(true); 313 #endif 314 } 315 316 void MachineFunction::viewCFGOnly() const 317 { 318 CFGOnly = true; 319 viewCFG(); 320 CFGOnly = false; 321 } 322 323 // The next two methods are used to construct and to retrieve 324 // the MachineCodeForFunction object for the given function. 325 // construct() -- Allocates and initializes for a given function and target 326 // get() -- Returns a handle to the object. 327 // This should not be called before "construct()" 328 // for a given Function. 329 // 330 MachineFunction& 331 MachineFunction::construct(const Function *Fn, const TargetMachine &Tar) 332 { 333 assert(Fn->getAnnotation(MF_AID) == 0 && 334 "Object already exists for this function!"); 335 MachineFunction* mcInfo = new MachineFunction(Fn, Tar); 336 Fn->addAnnotation(mcInfo); 337 return *mcInfo; 338 } 339 340 void MachineFunction::destruct(const Function *Fn) { 341 bool Deleted = Fn->deleteAnnotation(MF_AID); 342 assert(Deleted && "Machine code did not exist for function!"); 343 } 344 345 MachineFunction& MachineFunction::get(const Function *F) 346 { 347 MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID); 348 assert(mc && "Call construct() method first to allocate the object"); 349 return *mc; 350 } 351 352 void MachineFunction::clearSSARegMap() { 353 delete SSARegMapping; 354 SSARegMapping = 0; 355 } 356 357 //===----------------------------------------------------------------------===// 358 // MachineFrameInfo implementation 359 //===----------------------------------------------------------------------===// 360 361 void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{ 362 int ValOffset = MF.getTarget().getFrameInfo()->getOffsetOfLocalArea(); 363 364 for (unsigned i = 0, e = Objects.size(); i != e; ++i) { 365 const StackObject &SO = Objects[i]; 366 OS << " <fi #" << (int)(i-NumFixedObjects) << ">: "; 367 if (SO.Size == 0) 368 OS << "variable sized"; 369 else 370 OS << "size is " << SO.Size << " byte" << (SO.Size != 1 ? "s," : ","); 371 OS << " alignment is " << SO.Alignment << " byte" 372 << (SO.Alignment != 1 ? "s," : ","); 373 374 if (i < NumFixedObjects) 375 OS << " fixed"; 376 if (i < NumFixedObjects || SO.SPOffset != -1) { 377 int Off = SO.SPOffset - ValOffset; 378 OS << " at location [SP"; 379 if (Off > 0) 380 OS << "+" << Off; 381 else if (Off < 0) 382 OS << Off; 383 OS << "]"; 384 } 385 OS << "\n"; 386 } 387 388 if (HasVarSizedObjects) 389 OS << " Stack frame contains variable sized objects\n"; 390 } 391 392 void MachineFrameInfo::dump(const MachineFunction &MF) const { 393 print(MF, std::cerr); 394 } 395 396 397 //===----------------------------------------------------------------------===// 398 // MachineJumpTableInfo implementation 399 //===----------------------------------------------------------------------===// 400 401 /// getJumpTableIndex - Create a new jump table entry in the jump table info 402 /// or return an existing one. 403 /// 404 unsigned MachineJumpTableInfo::getJumpTableIndex( 405 std::vector<MachineBasicBlock*> &DestBBs) { 406 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) 407 if (JumpTables[i].MBBs == DestBBs) 408 return i; 409 410 JumpTables.push_back(MachineJumpTableEntry(DestBBs)); 411 return JumpTables.size()-1; 412 } 413 414 415 void MachineJumpTableInfo::print(std::ostream &OS) const { 416 // FIXME: this is lame, maybe we could print out the MBB numbers or something 417 // like {1, 2, 4, 5, 3, 0} 418 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) { 419 OS << " <jt #" << i << "> has " << JumpTables[i].MBBs.size() 420 << " entries\n"; 421 } 422 } 423 424 unsigned MachineJumpTableInfo::getEntrySize() const { 425 return TD->getPointerSize(); 426 } 427 428 unsigned MachineJumpTableInfo::getAlignment() const { 429 return TD->getPointerAlignment(); 430 } 431 432 void MachineJumpTableInfo::dump() const { print(std::cerr); } 433 434 435 //===----------------------------------------------------------------------===// 436 // MachineConstantPool implementation 437 //===----------------------------------------------------------------------===// 438 439 /// getConstantPoolIndex - Create a new entry in the constant pool or return 440 /// an existing one. User must specify an alignment in bytes for the object. 441 /// 442 unsigned MachineConstantPool::getConstantPoolIndex(Constant *C, 443 unsigned Alignment) { 444 assert(Alignment && "Alignment must be specified!"); 445 if (Alignment > PoolAlignment) PoolAlignment = Alignment; 446 447 // Check to see if we already have this constant. 448 // 449 // FIXME, this could be made much more efficient for large constant pools. 450 unsigned AlignMask = (1 << Alignment)-1; 451 for (unsigned i = 0, e = Constants.size(); i != e; ++i) 452 if (Constants[i].Val == C && (Constants[i].Offset & AlignMask) == 0) 453 return i; 454 455 unsigned Offset = 0; 456 if (!Constants.empty()) { 457 Offset = Constants.back().Offset; 458 Offset += TD->getTypeSize(Constants.back().Val->getType()); 459 Offset = (Offset+AlignMask)&~AlignMask; 460 } 461 462 Constants.push_back(MachineConstantPoolEntry(C, Offset)); 463 return Constants.size()-1; 464 } 465 466 467 void MachineConstantPool::print(std::ostream &OS) const { 468 for (unsigned i = 0, e = Constants.size(); i != e; ++i) { 469 OS << " <cp #" << i << "> is" << *(Value*)Constants[i].Val; 470 OS << " , offset=" << Constants[i].Offset; 471 OS << "\n"; 472 } 473 } 474 475 void MachineConstantPool::dump() const { print(std::cerr); } 476