MachineFunction.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  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/Config/config.h"
  19. #include "llvm/CodeGen/MachineConstantPool.h"
  20. #include "llvm/CodeGen/MachineFunction.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/MachineModuleInfo.h"
  26. #include "llvm/CodeGen/MachineRegisterInfo.h"
  27. #include "llvm/CodeGen/Passes.h"
  28. #include "llvm/MC/MCAsmInfo.h"
  29. #include "llvm/MC/MCContext.h"
  30. #include "llvm/Analysis/DebugInfo.h"
  31. #include "llvm/Support/Debug.h"
  32. #include "llvm/Target/TargetData.h"
  33. #include "llvm/Target/TargetLowering.h"
  34. #include "llvm/Target/TargetMachine.h"
  35. #include "llvm/Target/TargetFrameLowering.h"
  36. #include "llvm/ADT/SmallString.h"
  37. #include "llvm/ADT/STLExtras.h"
  38. #include "llvm/Support/GraphWriter.h"
  39. #include "llvm/Support/raw_ostream.h"
  40. using namespace llvm;
  41. //===----------------------------------------------------------------------===//
  42. // MachineFunction implementation
  43. //===----------------------------------------------------------------------===//
  44. // Out of line virtual method.
  45. MachineFunctionInfo::~MachineFunctionInfo() {}
  46. void ilist_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
  47. MBB->getParent()->DeleteMachineBasicBlock(MBB);
  48. }
  49. MachineFunction::MachineFunction(const Function *F, const TargetMachine &TM,
  50. unsigned FunctionNum, MachineModuleInfo &mmi,
  51. GCModuleInfo* gmi)
  52. : Fn(F), Target(TM), Ctx(mmi.getContext()), MMI(mmi), GMI(gmi) {
  53. if (TM.getRegisterInfo())
  54. RegInfo = new (Allocator) MachineRegisterInfo(*TM.getRegisterInfo());
  55. else
  56. RegInfo = 0;
  57. MFInfo = 0;
  58. FrameInfo = new (Allocator) MachineFrameInfo(*TM.getFrameLowering());
  59. if (Fn->hasFnAttr(Attribute::StackAlignment))
  60. FrameInfo->setMaxAlignment(Attribute::getStackAlignmentFromAttrs(
  61. Fn->getAttributes().getFnAttributes()));
  62. ConstantPool = new (Allocator) MachineConstantPool(TM.getTargetData());
  63. Alignment = TM.getTargetLowering()->getMinFunctionAlignment();
  64. // FIXME: Shouldn't use pref alignment if explicit alignment is set on Fn.
  65. if (!Fn->hasFnAttr(Attribute::OptimizeForSize))
  66. Alignment = std::max(Alignment,
  67. TM.getTargetLowering()->getPrefFunctionAlignment());
  68. FunctionNumber = FunctionNum;
  69. JumpTableInfo = 0;
  70. }
  71. MachineFunction::~MachineFunction() {
  72. BasicBlocks.clear();
  73. InstructionRecycler.clear(Allocator);
  74. BasicBlockRecycler.clear(Allocator);
  75. if (RegInfo) {
  76. RegInfo->~MachineRegisterInfo();
  77. Allocator.Deallocate(RegInfo);
  78. }
  79. if (MFInfo) {
  80. MFInfo->~MachineFunctionInfo();
  81. Allocator.Deallocate(MFInfo);
  82. }
  83. FrameInfo->~MachineFrameInfo(); Allocator.Deallocate(FrameInfo);
  84. ConstantPool->~MachineConstantPool(); Allocator.Deallocate(ConstantPool);
  85. if (JumpTableInfo) {
  86. JumpTableInfo->~MachineJumpTableInfo();
  87. Allocator.Deallocate(JumpTableInfo);
  88. }
  89. }
  90. /// getOrCreateJumpTableInfo - Get the JumpTableInfo for this function, if it
  91. /// does already exist, allocate one.
  92. MachineJumpTableInfo *MachineFunction::
  93. getOrCreateJumpTableInfo(unsigned EntryKind) {
  94. if (JumpTableInfo) return JumpTableInfo;
  95. JumpTableInfo = new (Allocator)
  96. MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
  97. return JumpTableInfo;
  98. }
  99. /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
  100. /// recomputes them. This guarantees that the MBB numbers are sequential,
  101. /// dense, and match the ordering of the blocks within the function. If a
  102. /// specific MachineBasicBlock is specified, only that block and those after
  103. /// it are renumbered.
  104. void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
  105. if (empty()) { MBBNumbering.clear(); return; }
  106. MachineFunction::iterator MBBI, E = end();
  107. if (MBB == 0)
  108. MBBI = begin();
  109. else
  110. MBBI = MBB;
  111. // Figure out the block number this should have.
  112. unsigned BlockNo = 0;
  113. if (MBBI != begin())
  114. BlockNo = prior(MBBI)->getNumber()+1;
  115. for (; MBBI != E; ++MBBI, ++BlockNo) {
  116. if (MBBI->getNumber() != (int)BlockNo) {
  117. // Remove use of the old number.
  118. if (MBBI->getNumber() != -1) {
  119. assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
  120. "MBB number mismatch!");
  121. MBBNumbering[MBBI->getNumber()] = 0;
  122. }
  123. // If BlockNo is already taken, set that block's number to -1.
  124. if (MBBNumbering[BlockNo])
  125. MBBNumbering[BlockNo]->setNumber(-1);
  126. MBBNumbering[BlockNo] = MBBI;
  127. MBBI->setNumber(BlockNo);
  128. }
  129. }
  130. // Okay, all the blocks are renumbered. If we have compactified the block
  131. // numbering, shrink MBBNumbering now.
  132. assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
  133. MBBNumbering.resize(BlockNo);
  134. }
  135. /// CreateMachineInstr - Allocate a new MachineInstr. Use this instead
  136. /// of `new MachineInstr'.
  137. ///
  138. MachineInstr *
  139. MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
  140. DebugLoc DL, bool NoImp) {
  141. return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
  142. MachineInstr(MCID, DL, NoImp);
  143. }
  144. /// CloneMachineInstr - Create a new MachineInstr which is a copy of the
  145. /// 'Orig' instruction, identical in all ways except the instruction
  146. /// has no parent, prev, or next.
  147. ///
  148. MachineInstr *
  149. MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
  150. return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
  151. MachineInstr(*this, *Orig);
  152. }
  153. /// DeleteMachineInstr - Delete the given MachineInstr.
  154. ///
  155. void
  156. MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
  157. MI->~MachineInstr();
  158. InstructionRecycler.Deallocate(Allocator, MI);
  159. }
  160. /// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this
  161. /// instead of `new MachineBasicBlock'.
  162. ///
  163. MachineBasicBlock *
  164. MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
  165. return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
  166. MachineBasicBlock(*this, bb);
  167. }
  168. /// DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
  169. ///
  170. void
  171. MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
  172. assert(MBB->getParent() == this && "MBB parent mismatch!");
  173. MBB->~MachineBasicBlock();
  174. BasicBlockRecycler.Deallocate(Allocator, MBB);
  175. }
  176. MachineMemOperand *
  177. MachineFunction::getMachineMemOperand(MachinePointerInfo PtrInfo, unsigned f,
  178. uint64_t s, unsigned base_alignment,
  179. const MDNode *TBAAInfo) {
  180. return new (Allocator) MachineMemOperand(PtrInfo, f, s, base_alignment,
  181. TBAAInfo);
  182. }
  183. MachineMemOperand *
  184. MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
  185. int64_t Offset, uint64_t Size) {
  186. return new (Allocator)
  187. MachineMemOperand(MachinePointerInfo(MMO->getValue(),
  188. MMO->getOffset()+Offset),
  189. MMO->getFlags(), Size,
  190. MMO->getBaseAlignment(), 0);
  191. }
  192. MachineInstr::mmo_iterator
  193. MachineFunction::allocateMemRefsArray(unsigned long Num) {
  194. return Allocator.Allocate<MachineMemOperand *>(Num);
  195. }
  196. std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
  197. MachineFunction::extractLoadMemRefs(MachineInstr::mmo_iterator Begin,
  198. MachineInstr::mmo_iterator End) {
  199. // Count the number of load mem refs.
  200. unsigned Num = 0;
  201. for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
  202. if ((*I)->isLoad())
  203. ++Num;
  204. // Allocate a new array and populate it with the load information.
  205. MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
  206. unsigned Index = 0;
  207. for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
  208. if ((*I)->isLoad()) {
  209. if (!(*I)->isStore())
  210. // Reuse the MMO.
  211. Result[Index] = *I;
  212. else {
  213. // Clone the MMO and unset the store flag.
  214. MachineMemOperand *JustLoad =
  215. getMachineMemOperand((*I)->getPointerInfo(),
  216. (*I)->getFlags() & ~MachineMemOperand::MOStore,
  217. (*I)->getSize(), (*I)->getBaseAlignment(),
  218. (*I)->getTBAAInfo());
  219. Result[Index] = JustLoad;
  220. }
  221. ++Index;
  222. }
  223. }
  224. return std::make_pair(Result, Result + Num);
  225. }
  226. std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
  227. MachineFunction::extractStoreMemRefs(MachineInstr::mmo_iterator Begin,
  228. MachineInstr::mmo_iterator End) {
  229. // Count the number of load mem refs.
  230. unsigned Num = 0;
  231. for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
  232. if ((*I)->isStore())
  233. ++Num;
  234. // Allocate a new array and populate it with the store information.
  235. MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
  236. unsigned Index = 0;
  237. for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
  238. if ((*I)->isStore()) {
  239. if (!(*I)->isLoad())
  240. // Reuse the MMO.
  241. Result[Index] = *I;
  242. else {
  243. // Clone the MMO and unset the load flag.
  244. MachineMemOperand *JustStore =
  245. getMachineMemOperand((*I)->getPointerInfo(),
  246. (*I)->getFlags() & ~MachineMemOperand::MOLoad,
  247. (*I)->getSize(), (*I)->getBaseAlignment(),
  248. (*I)->getTBAAInfo());
  249. Result[Index] = JustStore;
  250. }
  251. ++Index;
  252. }
  253. }
  254. return std::make_pair(Result, Result + Num);
  255. }
  256. void MachineFunction::dump() const {
  257. print(dbgs());
  258. }
  259. void MachineFunction::print(raw_ostream &OS, SlotIndexes *Indexes) const {
  260. OS << "# Machine code for function " << Fn->getName() << ":\n";
  261. // Print Frame Information
  262. FrameInfo->print(*this, OS);
  263. // Print JumpTable Information
  264. if (JumpTableInfo)
  265. JumpTableInfo->print(OS);
  266. // Print Constant Pool
  267. ConstantPool->print(OS);
  268. const TargetRegisterInfo *TRI = getTarget().getRegisterInfo();
  269. if (RegInfo && !RegInfo->livein_empty()) {
  270. OS << "Function Live Ins: ";
  271. for (MachineRegisterInfo::livein_iterator
  272. I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
  273. OS << PrintReg(I->first, TRI);
  274. if (I->second)
  275. OS << " in " << PrintReg(I->second, TRI);
  276. if (llvm::next(I) != E)
  277. OS << ", ";
  278. }
  279. OS << '\n';
  280. }
  281. if (RegInfo && !RegInfo->liveout_empty()) {
  282. OS << "Function Live Outs:";
  283. for (MachineRegisterInfo::liveout_iterator
  284. I = RegInfo->liveout_begin(), E = RegInfo->liveout_end(); I != E; ++I)
  285. OS << ' ' << PrintReg(*I, TRI);
  286. OS << '\n';
  287. }
  288. for (const_iterator BB = begin(), E = end(); BB != E; ++BB) {
  289. OS << '\n';
  290. BB->print(OS, Indexes);
  291. }
  292. OS << "\n# End machine code for function " << Fn->getName() << ".\n\n";
  293. }
  294. namespace llvm {
  295. template<>
  296. struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
  297. DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
  298. static std::string getGraphName(const MachineFunction *F) {
  299. return "CFG for '" + F->getFunction()->getNameStr() + "' function";
  300. }
  301. std::string getNodeLabel(const MachineBasicBlock *Node,
  302. const MachineFunction *Graph) {
  303. std::string OutStr;
  304. {
  305. raw_string_ostream OSS(OutStr);
  306. if (isSimple()) {
  307. OSS << "BB#" << Node->getNumber();
  308. if (const BasicBlock *BB = Node->getBasicBlock())
  309. OSS << ": " << BB->getName();
  310. } else
  311. Node->print(OSS);
  312. }
  313. if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
  314. // Process string output to make it nicer...
  315. for (unsigned i = 0; i != OutStr.length(); ++i)
  316. if (OutStr[i] == '\n') { // Left justify
  317. OutStr[i] = '\\';
  318. OutStr.insert(OutStr.begin()+i+1, 'l');
  319. }
  320. return OutStr;
  321. }
  322. };
  323. }
  324. void MachineFunction::viewCFG() const
  325. {
  326. #ifndef NDEBUG
  327. ViewGraph(this, "mf" + getFunction()->getNameStr());
  328. #else
  329. errs() << "MachineFunction::viewCFG is only available in debug builds on "
  330. << "systems with Graphviz or gv!\n";
  331. #endif // NDEBUG
  332. }
  333. void MachineFunction::viewCFGOnly() const
  334. {
  335. #ifndef NDEBUG
  336. ViewGraph(this, "mf" + getFunction()->getNameStr(), true);
  337. #else
  338. errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
  339. << "systems with Graphviz or gv!\n";
  340. #endif // NDEBUG
  341. }
  342. /// addLiveIn - Add the specified physical register as a live-in value and
  343. /// create a corresponding virtual register for it.
  344. unsigned MachineFunction::addLiveIn(unsigned PReg,
  345. const TargetRegisterClass *RC) {
  346. MachineRegisterInfo &MRI = getRegInfo();
  347. unsigned VReg = MRI.getLiveInVirtReg(PReg);
  348. if (VReg) {
  349. assert(MRI.getRegClass(VReg) == RC && "Register class mismatch!");
  350. return VReg;
  351. }
  352. VReg = MRI.createVirtualRegister(RC);
  353. MRI.addLiveIn(PReg, VReg);
  354. return VReg;
  355. }
  356. /// getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
  357. /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
  358. /// normal 'L' label is returned.
  359. MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
  360. bool isLinkerPrivate) const {
  361. assert(JumpTableInfo && "No jump tables");
  362. assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
  363. const MCAsmInfo &MAI = *getTarget().getMCAsmInfo();
  364. const char *Prefix = isLinkerPrivate ? MAI.getLinkerPrivateGlobalPrefix() :
  365. MAI.getPrivateGlobalPrefix();
  366. SmallString<60> Name;
  367. raw_svector_ostream(Name)
  368. << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
  369. return Ctx.GetOrCreateSymbol(Name.str());
  370. }
  371. /// getPICBaseSymbol - Return a function-local symbol to represent the PIC
  372. /// base.
  373. MCSymbol *MachineFunction::getPICBaseSymbol() const {
  374. const MCAsmInfo &MAI = *Target.getMCAsmInfo();
  375. return Ctx.GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix())+
  376. Twine(getFunctionNumber())+"$pb");
  377. }
  378. //===----------------------------------------------------------------------===//
  379. // MachineFrameInfo implementation
  380. //===----------------------------------------------------------------------===//
  381. /// CreateFixedObject - Create a new object at a fixed location on the stack.
  382. /// All fixed objects should be created before other objects are created for
  383. /// efficiency. By default, fixed objects are immutable. This returns an
  384. /// index with a negative value.
  385. ///
  386. int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
  387. bool Immutable) {
  388. assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
  389. // The alignment of the frame index can be determined from its offset from
  390. // the incoming frame position. If the frame object is at offset 32 and
  391. // the stack is guaranteed to be 16-byte aligned, then we know that the
  392. // object is 16-byte aligned.
  393. unsigned StackAlign = TFI.getStackAlignment();
  394. unsigned Align = MinAlign(SPOffset, StackAlign);
  395. Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset, Immutable,
  396. /*isSS*/false, false));
  397. return -++NumFixedObjects;
  398. }
  399. BitVector
  400. MachineFrameInfo::getPristineRegs(const MachineBasicBlock *MBB) const {
  401. assert(MBB && "MBB must be valid");
  402. const MachineFunction *MF = MBB->getParent();
  403. assert(MF && "MBB must be part of a MachineFunction");
  404. const TargetMachine &TM = MF->getTarget();
  405. const TargetRegisterInfo *TRI = TM.getRegisterInfo();
  406. BitVector BV(TRI->getNumRegs());
  407. // Before CSI is calculated, no registers are considered pristine. They can be
  408. // freely used and PEI will make sure they are saved.
  409. if (!isCalleeSavedInfoValid())
  410. return BV;
  411. for (const unsigned *CSR = TRI->getCalleeSavedRegs(MF); CSR && *CSR; ++CSR)
  412. BV.set(*CSR);
  413. // The entry MBB always has all CSRs pristine.
  414. if (MBB == &MF->front())
  415. return BV;
  416. // On other MBBs the saved CSRs are not pristine.
  417. const std::vector<CalleeSavedInfo> &CSI = getCalleeSavedInfo();
  418. for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
  419. E = CSI.end(); I != E; ++I)
  420. BV.reset(I->getReg());
  421. return BV;
  422. }
  423. void MachineFrameInfo::print(const MachineFunction &MF, raw_ostream &OS) const{
  424. if (Objects.empty()) return;
  425. const TargetFrameLowering *FI = MF.getTarget().getFrameLowering();
  426. int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0);
  427. OS << "Frame Objects:\n";
  428. for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
  429. const StackObject &SO = Objects[i];
  430. OS << " fi#" << (int)(i-NumFixedObjects) << ": ";
  431. if (SO.Size == ~0ULL) {
  432. OS << "dead\n";
  433. continue;
  434. }
  435. if (SO.Size == 0)
  436. OS << "variable sized";
  437. else
  438. OS << "size=" << SO.Size;
  439. OS << ", align=" << SO.Alignment;
  440. if (i < NumFixedObjects)
  441. OS << ", fixed";
  442. if (i < NumFixedObjects || SO.SPOffset != -1) {
  443. int64_t Off = SO.SPOffset - ValOffset;
  444. OS << ", at location [SP";
  445. if (Off > 0)
  446. OS << "+" << Off;
  447. else if (Off < 0)
  448. OS << Off;
  449. OS << "]";
  450. }
  451. OS << "\n";
  452. }
  453. }
  454. void MachineFrameInfo::dump(const MachineFunction &MF) const {
  455. print(MF, dbgs());
  456. }
  457. //===----------------------------------------------------------------------===//
  458. // MachineJumpTableInfo implementation
  459. //===----------------------------------------------------------------------===//
  460. /// getEntrySize - Return the size of each entry in the jump table.
  461. unsigned MachineJumpTableInfo::getEntrySize(const TargetData &TD) const {
  462. // The size of a jump table entry is 4 bytes unless the entry is just the
  463. // address of a block, in which case it is the pointer size.
  464. switch (getEntryKind()) {
  465. case MachineJumpTableInfo::EK_BlockAddress:
  466. return TD.getPointerSize();
  467. case MachineJumpTableInfo::EK_GPRel32BlockAddress:
  468. case MachineJumpTableInfo::EK_LabelDifference32:
  469. case MachineJumpTableInfo::EK_Custom32:
  470. return 4;
  471. case MachineJumpTableInfo::EK_Inline:
  472. return 0;
  473. }
  474. assert(0 && "Unknown jump table encoding!");
  475. return ~0;
  476. }
  477. /// getEntryAlignment - Return the alignment of each entry in the jump table.
  478. unsigned MachineJumpTableInfo::getEntryAlignment(const TargetData &TD) const {
  479. // The alignment of a jump table entry is the alignment of int32 unless the
  480. // entry is just the address of a block, in which case it is the pointer
  481. // alignment.
  482. switch (getEntryKind()) {
  483. case MachineJumpTableInfo::EK_BlockAddress:
  484. return TD.getPointerABIAlignment();
  485. case MachineJumpTableInfo::EK_GPRel32BlockAddress:
  486. case MachineJumpTableInfo::EK_LabelDifference32:
  487. case MachineJumpTableInfo::EK_Custom32:
  488. return TD.getABIIntegerTypeAlignment(32);
  489. case MachineJumpTableInfo::EK_Inline:
  490. return 1;
  491. }
  492. assert(0 && "Unknown jump table encoding!");
  493. return ~0;
  494. }
  495. /// createJumpTableIndex - Create a new jump table entry in the jump table info.
  496. ///
  497. unsigned MachineJumpTableInfo::createJumpTableIndex(
  498. const std::vector<MachineBasicBlock*> &DestBBs) {
  499. assert(!DestBBs.empty() && "Cannot create an empty jump table!");
  500. JumpTables.push_back(MachineJumpTableEntry(DestBBs));
  501. return JumpTables.size()-1;
  502. }
  503. /// ReplaceMBBInJumpTables - If Old is the target of any jump tables, update
  504. /// the jump tables to branch to New instead.
  505. bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
  506. MachineBasicBlock *New) {
  507. assert(Old != New && "Not making a change?");
  508. bool MadeChange = false;
  509. for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
  510. ReplaceMBBInJumpTable(i, Old, New);
  511. return MadeChange;
  512. }
  513. /// ReplaceMBBInJumpTable - If Old is a target of the jump tables, update
  514. /// the jump table to branch to New instead.
  515. bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
  516. MachineBasicBlock *Old,
  517. MachineBasicBlock *New) {
  518. assert(Old != New && "Not making a change?");
  519. bool MadeChange = false;
  520. MachineJumpTableEntry &JTE = JumpTables[Idx];
  521. for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
  522. if (JTE.MBBs[j] == Old) {
  523. JTE.MBBs[j] = New;
  524. MadeChange = true;
  525. }
  526. return MadeChange;
  527. }
  528. void MachineJumpTableInfo::print(raw_ostream &OS) const {
  529. if (JumpTables.empty()) return;
  530. OS << "Jump Tables:\n";
  531. for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
  532. OS << " jt#" << i << ": ";
  533. for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
  534. OS << " BB#" << JumpTables[i].MBBs[j]->getNumber();
  535. }
  536. OS << '\n';
  537. }
  538. void MachineJumpTableInfo::dump() const { print(dbgs()); }
  539. //===----------------------------------------------------------------------===//
  540. // MachineConstantPool implementation
  541. //===----------------------------------------------------------------------===//
  542. const Type *MachineConstantPoolEntry::getType() const {
  543. if (isMachineConstantPoolEntry())
  544. return Val.MachineCPVal->getType();
  545. return Val.ConstVal->getType();
  546. }
  547. unsigned MachineConstantPoolEntry::getRelocationInfo() const {
  548. if (isMachineConstantPoolEntry())
  549. return Val.MachineCPVal->getRelocationInfo();
  550. return Val.ConstVal->getRelocationInfo();
  551. }
  552. MachineConstantPool::~MachineConstantPool() {
  553. for (unsigned i = 0, e = Constants.size(); i != e; ++i)
  554. if (Constants[i].isMachineConstantPoolEntry())
  555. delete Constants[i].Val.MachineCPVal;
  556. for (DenseSet<MachineConstantPoolValue*>::iterator I =
  557. MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
  558. I != E; ++I)
  559. delete *I;
  560. }
  561. /// CanShareConstantPoolEntry - Test whether the given two constants
  562. /// can be allocated the same constant pool entry.
  563. static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
  564. const TargetData *TD) {
  565. // Handle the trivial case quickly.
  566. if (A == B) return true;
  567. // If they have the same type but weren't the same constant, quickly
  568. // reject them.
  569. if (A->getType() == B->getType()) return false;
  570. // For now, only support constants with the same size.
  571. if (TD->getTypeStoreSize(A->getType()) != TD->getTypeStoreSize(B->getType()))
  572. return false;
  573. // If a floating-point value and an integer value have the same encoding,
  574. // they can share a constant-pool entry.
  575. if (const ConstantFP *AFP = dyn_cast<ConstantFP>(A))
  576. if (const ConstantInt *BI = dyn_cast<ConstantInt>(B))
  577. return AFP->getValueAPF().bitcastToAPInt() == BI->getValue();
  578. if (const ConstantFP *BFP = dyn_cast<ConstantFP>(B))
  579. if (const ConstantInt *AI = dyn_cast<ConstantInt>(A))
  580. return BFP->getValueAPF().bitcastToAPInt() == AI->getValue();
  581. // Two vectors can share an entry if each pair of corresponding
  582. // elements could.
  583. if (const ConstantVector *AV = dyn_cast<ConstantVector>(A))
  584. if (const ConstantVector *BV = dyn_cast<ConstantVector>(B)) {
  585. if (AV->getType()->getNumElements() != BV->getType()->getNumElements())
  586. return false;
  587. for (unsigned i = 0, e = AV->getType()->getNumElements(); i != e; ++i)
  588. if (!CanShareConstantPoolEntry(AV->getOperand(i),
  589. BV->getOperand(i), TD))
  590. return false;
  591. return true;
  592. }
  593. // TODO: Handle other cases.
  594. return false;
  595. }
  596. /// getConstantPoolIndex - Create a new entry in the constant pool or return
  597. /// an existing one. User must specify the log2 of the minimum required
  598. /// alignment for the object.
  599. ///
  600. unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
  601. unsigned Alignment) {
  602. assert(Alignment && "Alignment must be specified!");
  603. if (Alignment > PoolAlignment) PoolAlignment = Alignment;
  604. // Check to see if we already have this constant.
  605. //
  606. // FIXME, this could be made much more efficient for large constant pools.
  607. for (unsigned i = 0, e = Constants.size(); i != e; ++i)
  608. if (!Constants[i].isMachineConstantPoolEntry() &&
  609. CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, TD)) {
  610. if ((unsigned)Constants[i].getAlignment() < Alignment)
  611. Constants[i].Alignment = Alignment;
  612. return i;
  613. }
  614. Constants.push_back(MachineConstantPoolEntry(C, Alignment));
  615. return Constants.size()-1;
  616. }
  617. unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
  618. unsigned Alignment) {
  619. assert(Alignment && "Alignment must be specified!");
  620. if (Alignment > PoolAlignment) PoolAlignment = Alignment;
  621. // Check to see if we already have this constant.
  622. //
  623. // FIXME, this could be made much more efficient for large constant pools.
  624. int Idx = V->getExistingMachineCPValue(this, Alignment);
  625. if (Idx != -1) {
  626. MachineCPVsSharingEntries.insert(V);
  627. return (unsigned)Idx;
  628. }
  629. Constants.push_back(MachineConstantPoolEntry(V, Alignment));
  630. return Constants.size()-1;
  631. }
  632. void MachineConstantPool::print(raw_ostream &OS) const {
  633. if (Constants.empty()) return;
  634. OS << "Constant Pool:\n";
  635. for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
  636. OS << " cp#" << i << ": ";
  637. if (Constants[i].isMachineConstantPoolEntry())
  638. Constants[i].Val.MachineCPVal->print(OS);
  639. else
  640. OS << *(Value*)Constants[i].Val.ConstVal;
  641. OS << ", align=" << Constants[i].getAlignment();
  642. OS << "\n";
  643. }
  644. }
  645. void MachineConstantPool::dump() const { print(dbgs()); }