MachineFunction.cpp 35 KB

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