MachineFunction.cpp 18 KB

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