MachineFunction.cpp 30 KB

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