MachineFunction.cpp 33 KB

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