MachineFunction.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  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. // Don't call destructors on MachineInstr and MachineOperand. All of their
  74. // memory comes from the BumpPtrAllocator which is about to be purged.
  75. //
  76. // Do call MachineBasicBlock destructors, it contains std::vectors.
  77. for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
  78. I->Insts.clearAndLeakNodesUnsafely();
  79. InstructionRecycler.clear(Allocator);
  80. OperandRecycler.clear(Allocator);
  81. BasicBlockRecycler.clear(Allocator);
  82. if (RegInfo) {
  83. RegInfo->~MachineRegisterInfo();
  84. Allocator.Deallocate(RegInfo);
  85. }
  86. if (MFInfo) {
  87. MFInfo->~MachineFunctionInfo();
  88. Allocator.Deallocate(MFInfo);
  89. }
  90. FrameInfo->~MachineFrameInfo();
  91. Allocator.Deallocate(FrameInfo);
  92. ConstantPool->~MachineConstantPool();
  93. Allocator.Deallocate(ConstantPool);
  94. if (JumpTableInfo) {
  95. JumpTableInfo->~MachineJumpTableInfo();
  96. Allocator.Deallocate(JumpTableInfo);
  97. }
  98. }
  99. /// getOrCreateJumpTableInfo - Get the JumpTableInfo for this function, if it
  100. /// does already exist, allocate one.
  101. MachineJumpTableInfo *MachineFunction::
  102. getOrCreateJumpTableInfo(unsigned EntryKind) {
  103. if (JumpTableInfo) return JumpTableInfo;
  104. JumpTableInfo = new (Allocator)
  105. MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
  106. return JumpTableInfo;
  107. }
  108. /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
  109. /// recomputes them. This guarantees that the MBB numbers are sequential,
  110. /// dense, and match the ordering of the blocks within the function. If a
  111. /// specific MachineBasicBlock is specified, only that block and those after
  112. /// it are renumbered.
  113. void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
  114. if (empty()) { MBBNumbering.clear(); return; }
  115. MachineFunction::iterator MBBI, E = end();
  116. if (MBB == 0)
  117. MBBI = begin();
  118. else
  119. MBBI = MBB;
  120. // Figure out the block number this should have.
  121. unsigned BlockNo = 0;
  122. if (MBBI != begin())
  123. BlockNo = prior(MBBI)->getNumber()+1;
  124. for (; MBBI != E; ++MBBI, ++BlockNo) {
  125. if (MBBI->getNumber() != (int)BlockNo) {
  126. // Remove use of the old number.
  127. if (MBBI->getNumber() != -1) {
  128. assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
  129. "MBB number mismatch!");
  130. MBBNumbering[MBBI->getNumber()] = 0;
  131. }
  132. // If BlockNo is already taken, set that block's number to -1.
  133. if (MBBNumbering[BlockNo])
  134. MBBNumbering[BlockNo]->setNumber(-1);
  135. MBBNumbering[BlockNo] = MBBI;
  136. MBBI->setNumber(BlockNo);
  137. }
  138. }
  139. // Okay, all the blocks are renumbered. If we have compactified the block
  140. // numbering, shrink MBBNumbering now.
  141. assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
  142. MBBNumbering.resize(BlockNo);
  143. }
  144. /// CreateMachineInstr - Allocate a new MachineInstr. Use this instead
  145. /// of `new MachineInstr'.
  146. ///
  147. MachineInstr *
  148. MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
  149. DebugLoc DL, bool NoImp) {
  150. return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
  151. MachineInstr(*this, MCID, DL, NoImp);
  152. }
  153. /// CloneMachineInstr - Create a new MachineInstr which is a copy of the
  154. /// 'Orig' instruction, identical in all ways except the instruction
  155. /// has no parent, prev, or next.
  156. ///
  157. MachineInstr *
  158. MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
  159. return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
  160. MachineInstr(*this, *Orig);
  161. }
  162. /// DeleteMachineInstr - Delete the given MachineInstr.
  163. ///
  164. /// This function also serves as the MachineInstr destructor - the real
  165. /// ~MachineInstr() destructor must be empty.
  166. void
  167. MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
  168. // Strip it for parts. The operand array and the MI object itself are
  169. // independently recyclable.
  170. if (MI->Operands)
  171. deallocateOperandArray(MI->CapOperands, MI->Operands);
  172. // Don't call ~MachineInstr() which must be trivial anyway because
  173. // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
  174. // destructors.
  175. InstructionRecycler.Deallocate(Allocator, MI);
  176. }
  177. /// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this
  178. /// instead of `new MachineBasicBlock'.
  179. ///
  180. MachineBasicBlock *
  181. MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
  182. return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
  183. MachineBasicBlock(*this, bb);
  184. }
  185. /// DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
  186. ///
  187. void
  188. MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
  189. assert(MBB->getParent() == this && "MBB parent mismatch!");
  190. MBB->~MachineBasicBlock();
  191. BasicBlockRecycler.Deallocate(Allocator, MBB);
  192. }
  193. MachineMemOperand *
  194. MachineFunction::getMachineMemOperand(MachinePointerInfo PtrInfo, unsigned f,
  195. uint64_t s, unsigned base_alignment,
  196. const MDNode *TBAAInfo,
  197. const MDNode *Ranges) {
  198. return new (Allocator) MachineMemOperand(PtrInfo, f, s, base_alignment,
  199. TBAAInfo, Ranges);
  200. }
  201. MachineMemOperand *
  202. MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
  203. int64_t Offset, uint64_t Size) {
  204. return new (Allocator)
  205. MachineMemOperand(MachinePointerInfo(MMO->getValue(),
  206. MMO->getOffset()+Offset),
  207. MMO->getFlags(), Size,
  208. MMO->getBaseAlignment(), 0);
  209. }
  210. MachineInstr::mmo_iterator
  211. MachineFunction::allocateMemRefsArray(unsigned long Num) {
  212. return Allocator.Allocate<MachineMemOperand *>(Num);
  213. }
  214. std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
  215. MachineFunction::extractLoadMemRefs(MachineInstr::mmo_iterator Begin,
  216. MachineInstr::mmo_iterator End) {
  217. // Count the number of load mem refs.
  218. unsigned Num = 0;
  219. for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
  220. if ((*I)->isLoad())
  221. ++Num;
  222. // Allocate a new array and populate it with the load information.
  223. MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
  224. unsigned Index = 0;
  225. for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
  226. if ((*I)->isLoad()) {
  227. if (!(*I)->isStore())
  228. // Reuse the MMO.
  229. Result[Index] = *I;
  230. else {
  231. // Clone the MMO and unset the store flag.
  232. MachineMemOperand *JustLoad =
  233. getMachineMemOperand((*I)->getPointerInfo(),
  234. (*I)->getFlags() & ~MachineMemOperand::MOStore,
  235. (*I)->getSize(), (*I)->getBaseAlignment(),
  236. (*I)->getTBAAInfo());
  237. Result[Index] = JustLoad;
  238. }
  239. ++Index;
  240. }
  241. }
  242. return std::make_pair(Result, Result + Num);
  243. }
  244. std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
  245. MachineFunction::extractStoreMemRefs(MachineInstr::mmo_iterator Begin,
  246. MachineInstr::mmo_iterator End) {
  247. // Count the number of load mem refs.
  248. unsigned Num = 0;
  249. for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
  250. if ((*I)->isStore())
  251. ++Num;
  252. // Allocate a new array and populate it with the store information.
  253. MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
  254. unsigned Index = 0;
  255. for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
  256. if ((*I)->isStore()) {
  257. if (!(*I)->isLoad())
  258. // Reuse the MMO.
  259. Result[Index] = *I;
  260. else {
  261. // Clone the MMO and unset the load flag.
  262. MachineMemOperand *JustStore =
  263. getMachineMemOperand((*I)->getPointerInfo(),
  264. (*I)->getFlags() & ~MachineMemOperand::MOLoad,
  265. (*I)->getSize(), (*I)->getBaseAlignment(),
  266. (*I)->getTBAAInfo());
  267. Result[Index] = JustStore;
  268. }
  269. ++Index;
  270. }
  271. }
  272. return std::make_pair(Result, Result + Num);
  273. }
  274. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  275. void MachineFunction::dump() const {
  276. print(dbgs());
  277. }
  278. #endif
  279. StringRef MachineFunction::getName() const {
  280. assert(getFunction() && "No function!");
  281. return getFunction()->getName();
  282. }
  283. void MachineFunction::print(raw_ostream &OS, SlotIndexes *Indexes) const {
  284. OS << "# Machine code for function " << getName() << ": ";
  285. if (RegInfo) {
  286. OS << (RegInfo->isSSA() ? "SSA" : "Post SSA");
  287. if (!RegInfo->tracksLiveness())
  288. OS << ", not tracking liveness";
  289. }
  290. OS << '\n';
  291. // Print Frame Information
  292. FrameInfo->print(*this, OS);
  293. // Print JumpTable Information
  294. if (JumpTableInfo)
  295. JumpTableInfo->print(OS);
  296. // Print Constant Pool
  297. ConstantPool->print(OS);
  298. const TargetRegisterInfo *TRI = getTarget().getRegisterInfo();
  299. if (RegInfo && !RegInfo->livein_empty()) {
  300. OS << "Function Live Ins: ";
  301. for (MachineRegisterInfo::livein_iterator
  302. I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
  303. OS << PrintReg(I->first, TRI);
  304. if (I->second)
  305. OS << " in " << PrintReg(I->second, TRI);
  306. if (llvm::next(I) != E)
  307. OS << ", ";
  308. }
  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 PrefAlign,
  414. unsigned MinAlign, unsigned StackAlign,
  415. const AllocaInst *Alloca = 0) {
  416. if (!ShouldClamp || PrefAlign <= StackAlign)
  417. return PrefAlign;
  418. if (Alloca && MinAlign > StackAlign)
  419. Alloca->getParent()->getContext().emitWarning(Alloca,
  420. "Requested alignment exceeds the stack alignment!");
  421. else
  422. assert(MinAlign <= StackAlign &&
  423. "Requested alignment exceeds the stack alignment!");
  424. return StackAlign;
  425. }
  426. /// CreateStackObjectWithMinAlign - Create a new statically sized stack
  427. /// object, returning a nonnegative identifier to represent it. This function
  428. /// takes a preferred alignment and a minimal alignment.
  429. ///
  430. int MachineFrameInfo::CreateStackObjectWithMinAlign(uint64_t Size,
  431. unsigned PrefAlignment, unsigned MinAlignment,
  432. bool isSS, bool MayNeedSP, const AllocaInst *Alloca) {
  433. assert(Size != 0 && "Cannot allocate zero size stack objects!");
  434. unsigned Alignment = clampStackAlignment(
  435. !TFI.isStackRealignable() || !RealignOption,
  436. PrefAlignment, MinAlignment,
  437. TFI.getStackAlignment(), Alloca);
  438. Objects.push_back(StackObject(Size, Alignment, 0, false, isSS, MayNeedSP,
  439. Alloca));
  440. int Index = (int)Objects.size() - NumFixedObjects - 1;
  441. assert(Index >= 0 && "Bad frame index!");
  442. ensureMaxAlignment(Alignment);
  443. return Index;
  444. }
  445. /// CreateSpillStackObject - Create a new statically sized stack object that
  446. /// represents a spill slot, returning a nonnegative identifier to represent
  447. /// it.
  448. ///
  449. int MachineFrameInfo::CreateSpillStackObject(uint64_t Size,
  450. unsigned Alignment) {
  451. Alignment = clampStackAlignment(!TFI.isStackRealignable() || !RealignOption,
  452. Alignment, 0,
  453. TFI.getStackAlignment());
  454. CreateStackObject(Size, Alignment, true, false);
  455. int Index = (int)Objects.size() - NumFixedObjects - 1;
  456. ensureMaxAlignment(Alignment);
  457. return Index;
  458. }
  459. /// CreateVariableSizedObject - Notify the MachineFrameInfo object that a
  460. /// variable sized object has been created. This must be created whenever a
  461. /// variable sized object is created, whether or not the index returned is
  462. /// actually used.
  463. ///
  464. int MachineFrameInfo::CreateVariableSizedObject(unsigned PrefAlignment,
  465. unsigned MinAlignment, const AllocaInst *Alloca) {
  466. HasVarSizedObjects = true;
  467. unsigned Alignment = clampStackAlignment(
  468. !TFI.isStackRealignable() || !RealignOption,
  469. PrefAlignment, MinAlignment,
  470. TFI.getStackAlignment(), Alloca);
  471. Objects.push_back(StackObject(0, Alignment, 0, false, false, true, 0));
  472. ensureMaxAlignment(Alignment);
  473. return (int)Objects.size()-NumFixedObjects-1;
  474. }
  475. /// CreateFixedObject - Create a new object at a fixed location on the stack.
  476. /// All fixed objects should be created before other objects are created for
  477. /// efficiency. By default, fixed objects are immutable. This returns an
  478. /// index with a negative value.
  479. ///
  480. int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
  481. bool Immutable) {
  482. assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
  483. // The alignment of the frame index can be determined from its offset from
  484. // the incoming frame position. If the frame object is at offset 32 and
  485. // the stack is guaranteed to be 16-byte aligned, then we know that the
  486. // object is 16-byte aligned.
  487. unsigned StackAlign = TFI.getStackAlignment();
  488. unsigned Align = MinAlign(SPOffset, StackAlign);
  489. Align = clampStackAlignment(!TFI.isStackRealignable() || !RealignOption,
  490. Align, 0, TFI.getStackAlignment());
  491. Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset, Immutable,
  492. /*isSS*/ false,
  493. /*NeedSP*/ false,
  494. /*Alloca*/ 0));
  495. return -++NumFixedObjects;
  496. }
  497. BitVector
  498. MachineFrameInfo::getPristineRegs(const MachineBasicBlock *MBB) const {
  499. assert(MBB && "MBB must be valid");
  500. const MachineFunction *MF = MBB->getParent();
  501. assert(MF && "MBB must be part of a MachineFunction");
  502. const TargetMachine &TM = MF->getTarget();
  503. const TargetRegisterInfo *TRI = TM.getRegisterInfo();
  504. BitVector BV(TRI->getNumRegs());
  505. // Before CSI is calculated, no registers are considered pristine. They can be
  506. // freely used and PEI will make sure they are saved.
  507. if (!isCalleeSavedInfoValid())
  508. return BV;
  509. for (const uint16_t *CSR = TRI->getCalleeSavedRegs(MF); CSR && *CSR; ++CSR)
  510. BV.set(*CSR);
  511. // The entry MBB always has all CSRs pristine.
  512. if (MBB == &MF->front())
  513. return BV;
  514. // On other MBBs the saved CSRs are not pristine.
  515. const std::vector<CalleeSavedInfo> &CSI = getCalleeSavedInfo();
  516. for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
  517. E = CSI.end(); I != E; ++I)
  518. BV.reset(I->getReg());
  519. return BV;
  520. }
  521. void MachineFrameInfo::print(const MachineFunction &MF, raw_ostream &OS) const{
  522. if (Objects.empty()) return;
  523. const TargetFrameLowering *FI = MF.getTarget().getFrameLowering();
  524. int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0);
  525. OS << "Frame Objects:\n";
  526. for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
  527. const StackObject &SO = Objects[i];
  528. OS << " fi#" << (int)(i-NumFixedObjects) << ": ";
  529. if (SO.Size == ~0ULL) {
  530. OS << "dead\n";
  531. continue;
  532. }
  533. if (SO.Size == 0)
  534. OS << "variable sized";
  535. else
  536. OS << "size=" << SO.Size;
  537. OS << ", align=" << SO.Alignment;
  538. if (i < NumFixedObjects)
  539. OS << ", fixed";
  540. if (i < NumFixedObjects || SO.SPOffset != -1) {
  541. int64_t Off = SO.SPOffset - ValOffset;
  542. OS << ", at location [SP";
  543. if (Off > 0)
  544. OS << "+" << Off;
  545. else if (Off < 0)
  546. OS << Off;
  547. OS << "]";
  548. }
  549. OS << "\n";
  550. }
  551. }
  552. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  553. void MachineFrameInfo::dump(const MachineFunction &MF) const {
  554. print(MF, dbgs());
  555. }
  556. #endif
  557. //===----------------------------------------------------------------------===//
  558. // MachineJumpTableInfo implementation
  559. //===----------------------------------------------------------------------===//
  560. /// getEntrySize - Return the size of each entry in the jump table.
  561. unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
  562. // The size of a jump table entry is 4 bytes unless the entry is just the
  563. // address of a block, in which case it is the pointer size.
  564. switch (getEntryKind()) {
  565. case MachineJumpTableInfo::EK_BlockAddress:
  566. return TD.getPointerSize();
  567. case MachineJumpTableInfo::EK_GPRel64BlockAddress:
  568. return 8;
  569. case MachineJumpTableInfo::EK_GPRel32BlockAddress:
  570. case MachineJumpTableInfo::EK_LabelDifference32:
  571. case MachineJumpTableInfo::EK_Custom32:
  572. return 4;
  573. case MachineJumpTableInfo::EK_Inline:
  574. return 0;
  575. }
  576. llvm_unreachable("Unknown jump table encoding!");
  577. }
  578. /// getEntryAlignment - Return the alignment of each entry in the jump table.
  579. unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
  580. // The alignment of a jump table entry is the alignment of int32 unless the
  581. // entry is just the address of a block, in which case it is the pointer
  582. // alignment.
  583. switch (getEntryKind()) {
  584. case MachineJumpTableInfo::EK_BlockAddress:
  585. return TD.getPointerABIAlignment();
  586. case MachineJumpTableInfo::EK_GPRel64BlockAddress:
  587. return TD.getABIIntegerTypeAlignment(64);
  588. case MachineJumpTableInfo::EK_GPRel32BlockAddress:
  589. case MachineJumpTableInfo::EK_LabelDifference32:
  590. case MachineJumpTableInfo::EK_Custom32:
  591. return TD.getABIIntegerTypeAlignment(32);
  592. case MachineJumpTableInfo::EK_Inline:
  593. return 1;
  594. }
  595. llvm_unreachable("Unknown jump table encoding!");
  596. }
  597. /// createJumpTableIndex - Create a new jump table entry in the jump table info.
  598. ///
  599. unsigned MachineJumpTableInfo::createJumpTableIndex(
  600. const std::vector<MachineBasicBlock*> &DestBBs) {
  601. assert(!DestBBs.empty() && "Cannot create an empty jump table!");
  602. JumpTables.push_back(MachineJumpTableEntry(DestBBs));
  603. return JumpTables.size()-1;
  604. }
  605. /// ReplaceMBBInJumpTables - If Old is the target of any jump tables, update
  606. /// the jump tables to branch to New instead.
  607. bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
  608. MachineBasicBlock *New) {
  609. assert(Old != New && "Not making a change?");
  610. bool MadeChange = false;
  611. for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
  612. ReplaceMBBInJumpTable(i, Old, New);
  613. return MadeChange;
  614. }
  615. /// ReplaceMBBInJumpTable - If Old is a target of the jump tables, update
  616. /// the jump table to branch to New instead.
  617. bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
  618. MachineBasicBlock *Old,
  619. MachineBasicBlock *New) {
  620. assert(Old != New && "Not making a change?");
  621. bool MadeChange = false;
  622. MachineJumpTableEntry &JTE = JumpTables[Idx];
  623. for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
  624. if (JTE.MBBs[j] == Old) {
  625. JTE.MBBs[j] = New;
  626. MadeChange = true;
  627. }
  628. return MadeChange;
  629. }
  630. void MachineJumpTableInfo::print(raw_ostream &OS) const {
  631. if (JumpTables.empty()) return;
  632. OS << "Jump Tables:\n";
  633. for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
  634. OS << " jt#" << i << ": ";
  635. for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
  636. OS << " BB#" << JumpTables[i].MBBs[j]->getNumber();
  637. }
  638. OS << '\n';
  639. }
  640. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  641. void MachineJumpTableInfo::dump() const { print(dbgs()); }
  642. #endif
  643. //===----------------------------------------------------------------------===//
  644. // MachineConstantPool implementation
  645. //===----------------------------------------------------------------------===//
  646. void MachineConstantPoolValue::anchor() { }
  647. Type *MachineConstantPoolEntry::getType() const {
  648. if (isMachineConstantPoolEntry())
  649. return Val.MachineCPVal->getType();
  650. return Val.ConstVal->getType();
  651. }
  652. unsigned MachineConstantPoolEntry::getRelocationInfo() const {
  653. if (isMachineConstantPoolEntry())
  654. return Val.MachineCPVal->getRelocationInfo();
  655. return Val.ConstVal->getRelocationInfo();
  656. }
  657. MachineConstantPool::~MachineConstantPool() {
  658. for (unsigned i = 0, e = Constants.size(); i != e; ++i)
  659. if (Constants[i].isMachineConstantPoolEntry())
  660. delete Constants[i].Val.MachineCPVal;
  661. for (DenseSet<MachineConstantPoolValue*>::iterator I =
  662. MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
  663. I != E; ++I)
  664. delete *I;
  665. }
  666. /// CanShareConstantPoolEntry - Test whether the given two constants
  667. /// can be allocated the same constant pool entry.
  668. static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
  669. const DataLayout *TD) {
  670. // Handle the trivial case quickly.
  671. if (A == B) return true;
  672. // If they have the same type but weren't the same constant, quickly
  673. // reject them.
  674. if (A->getType() == B->getType()) return false;
  675. // We can't handle structs or arrays.
  676. if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
  677. isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
  678. return false;
  679. // For now, only support constants with the same size.
  680. uint64_t StoreSize = TD->getTypeStoreSize(A->getType());
  681. if (StoreSize != TD->getTypeStoreSize(B->getType()) ||
  682. StoreSize > 128)
  683. return false;
  684. Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
  685. // Try constant folding a bitcast of both instructions to an integer. If we
  686. // get two identical ConstantInt's, then we are good to share them. We use
  687. // the constant folding APIs to do this so that we get the benefit of
  688. // DataLayout.
  689. if (isa<PointerType>(A->getType()))
  690. A = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
  691. const_cast<Constant*>(A), TD);
  692. else if (A->getType() != IntTy)
  693. A = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
  694. const_cast<Constant*>(A), TD);
  695. if (isa<PointerType>(B->getType()))
  696. B = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
  697. const_cast<Constant*>(B), TD);
  698. else if (B->getType() != IntTy)
  699. B = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
  700. const_cast<Constant*>(B), TD);
  701. return A == B;
  702. }
  703. /// getConstantPoolIndex - Create a new entry in the constant pool or return
  704. /// an existing one. User must specify the log2 of the minimum required
  705. /// alignment for the object.
  706. ///
  707. unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
  708. unsigned Alignment) {
  709. assert(Alignment && "Alignment must be specified!");
  710. if (Alignment > PoolAlignment) PoolAlignment = Alignment;
  711. // Check to see if we already have this constant.
  712. //
  713. // FIXME, this could be made much more efficient for large constant pools.
  714. for (unsigned i = 0, e = Constants.size(); i != e; ++i)
  715. if (!Constants[i].isMachineConstantPoolEntry() &&
  716. CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, TD)) {
  717. if ((unsigned)Constants[i].getAlignment() < Alignment)
  718. Constants[i].Alignment = Alignment;
  719. return i;
  720. }
  721. Constants.push_back(MachineConstantPoolEntry(C, Alignment));
  722. return Constants.size()-1;
  723. }
  724. unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
  725. unsigned Alignment) {
  726. assert(Alignment && "Alignment must be specified!");
  727. if (Alignment > PoolAlignment) PoolAlignment = Alignment;
  728. // Check to see if we already have this constant.
  729. //
  730. // FIXME, this could be made much more efficient for large constant pools.
  731. int Idx = V->getExistingMachineCPValue(this, Alignment);
  732. if (Idx != -1) {
  733. MachineCPVsSharingEntries.insert(V);
  734. return (unsigned)Idx;
  735. }
  736. Constants.push_back(MachineConstantPoolEntry(V, Alignment));
  737. return Constants.size()-1;
  738. }
  739. void MachineConstantPool::print(raw_ostream &OS) const {
  740. if (Constants.empty()) return;
  741. OS << "Constant Pool:\n";
  742. for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
  743. OS << " cp#" << i << ": ";
  744. if (Constants[i].isMachineConstantPoolEntry())
  745. Constants[i].Val.MachineCPVal->print(OS);
  746. else
  747. OS << *(const Value*)Constants[i].Val.ConstVal;
  748. OS << ", align=" << Constants[i].getAlignment();
  749. OS << "\n";
  750. }
  751. }
  752. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  753. void MachineConstantPool::dump() const { print(dbgs()); }
  754. #endif