MachineFunction.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  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/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/CodeGen/PseudoSourceValue.h"
  29. #include "llvm/CodeGen/WinEHFuncInfo.h"
  30. #include "llvm/IR/DataLayout.h"
  31. #include "llvm/IR/DebugInfo.h"
  32. #include "llvm/IR/Function.h"
  33. #include "llvm/IR/Module.h"
  34. #include "llvm/IR/ModuleSlotTracker.h"
  35. #include "llvm/MC/MCAsmInfo.h"
  36. #include "llvm/MC/MCContext.h"
  37. #include "llvm/Support/Debug.h"
  38. #include "llvm/Support/GraphWriter.h"
  39. #include "llvm/Support/raw_ostream.h"
  40. #include "llvm/Target/TargetFrameLowering.h"
  41. #include "llvm/Target/TargetLowering.h"
  42. #include "llvm/Target/TargetMachine.h"
  43. #include "llvm/Target/TargetSubtargetInfo.h"
  44. using namespace llvm;
  45. #define DEBUG_TYPE "codegen"
  46. static cl::opt<unsigned>
  47. AlignAllFunctions("align-all-functions",
  48. cl::desc("Force the alignment of all functions."),
  49. cl::init(0), cl::Hidden);
  50. static const char *getPropertyName(MachineFunctionProperties::Property Prop) {
  51. typedef MachineFunctionProperties::Property P;
  52. switch(Prop) {
  53. case P::FailedISel: return "FailedISel";
  54. case P::IsSSA: return "IsSSA";
  55. case P::Legalized: return "Legalized";
  56. case P::NoPHIs: return "NoPHIs";
  57. case P::NoVRegs: return "NoVRegs";
  58. case P::RegBankSelected: return "RegBankSelected";
  59. case P::Selected: return "Selected";
  60. case P::TracksLiveness: return "TracksLiveness";
  61. }
  62. llvm_unreachable("Invalid machine function property");
  63. }
  64. void MachineFunctionProperties::print(raw_ostream &OS) const {
  65. const char *Separator = "";
  66. for (BitVector::size_type I = 0; I < Properties.size(); ++I) {
  67. if (!Properties[I])
  68. continue;
  69. OS << Separator << getPropertyName(static_cast<Property>(I));
  70. Separator = ", ";
  71. }
  72. }
  73. //===----------------------------------------------------------------------===//
  74. // MachineFunction implementation
  75. //===----------------------------------------------------------------------===//
  76. // Out-of-line virtual method.
  77. MachineFunctionInfo::~MachineFunctionInfo() {}
  78. void ilist_alloc_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
  79. MBB->getParent()->DeleteMachineBasicBlock(MBB);
  80. }
  81. static inline unsigned getFnStackAlignment(const TargetSubtargetInfo *STI,
  82. const Function *Fn) {
  83. if (Fn->hasFnAttribute(Attribute::StackAlignment))
  84. return Fn->getFnStackAlignment();
  85. return STI->getFrameLowering()->getStackAlignment();
  86. }
  87. MachineFunction::MachineFunction(const Function *F, const TargetMachine &TM,
  88. unsigned FunctionNum, MachineModuleInfo &mmi)
  89. : Fn(F), Target(TM), STI(TM.getSubtargetImpl(*F)), Ctx(mmi.getContext()),
  90. MMI(mmi) {
  91. FunctionNumber = FunctionNum;
  92. init();
  93. }
  94. void MachineFunction::init() {
  95. // Assume the function starts in SSA form with correct liveness.
  96. Properties.set(MachineFunctionProperties::Property::IsSSA);
  97. Properties.set(MachineFunctionProperties::Property::TracksLiveness);
  98. if (STI->getRegisterInfo())
  99. RegInfo = new (Allocator) MachineRegisterInfo(this);
  100. else
  101. RegInfo = nullptr;
  102. MFInfo = nullptr;
  103. // We can realign the stack if the target supports it and the user hasn't
  104. // explicitly asked us not to.
  105. bool CanRealignSP = STI->getFrameLowering()->isStackRealignable() &&
  106. !Fn->hasFnAttribute("no-realign-stack");
  107. FrameInfo = new (Allocator) MachineFrameInfo(
  108. getFnStackAlignment(STI, Fn), /*StackRealignable=*/CanRealignSP,
  109. /*ForceRealign=*/CanRealignSP &&
  110. Fn->hasFnAttribute(Attribute::StackAlignment));
  111. if (Fn->hasFnAttribute(Attribute::StackAlignment))
  112. FrameInfo->ensureMaxAlignment(Fn->getFnStackAlignment());
  113. ConstantPool = new (Allocator) MachineConstantPool(getDataLayout());
  114. Alignment = STI->getTargetLowering()->getMinFunctionAlignment();
  115. // FIXME: Shouldn't use pref alignment if explicit alignment is set on Fn.
  116. // FIXME: Use Function::optForSize().
  117. if (!Fn->hasFnAttribute(Attribute::OptimizeForSize))
  118. Alignment = std::max(Alignment,
  119. STI->getTargetLowering()->getPrefFunctionAlignment());
  120. if (AlignAllFunctions)
  121. Alignment = AlignAllFunctions;
  122. JumpTableInfo = nullptr;
  123. if (isFuncletEHPersonality(classifyEHPersonality(
  124. Fn->hasPersonalityFn() ? Fn->getPersonalityFn() : nullptr))) {
  125. WinEHInfo = new (Allocator) WinEHFuncInfo();
  126. }
  127. assert(Target.isCompatibleDataLayout(getDataLayout()) &&
  128. "Can't create a MachineFunction using a Module with a "
  129. "Target-incompatible DataLayout attached\n");
  130. PSVManager = llvm::make_unique<PseudoSourceValueManager>();
  131. }
  132. MachineFunction::~MachineFunction() {
  133. clear();
  134. }
  135. void MachineFunction::clear() {
  136. Properties.reset();
  137. // Don't call destructors on MachineInstr and MachineOperand. All of their
  138. // memory comes from the BumpPtrAllocator which is about to be purged.
  139. //
  140. // Do call MachineBasicBlock destructors, it contains std::vectors.
  141. for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
  142. I->Insts.clearAndLeakNodesUnsafely();
  143. InstructionRecycler.clear(Allocator);
  144. OperandRecycler.clear(Allocator);
  145. BasicBlockRecycler.clear(Allocator);
  146. VariableDbgInfos.clear();
  147. if (RegInfo) {
  148. RegInfo->~MachineRegisterInfo();
  149. Allocator.Deallocate(RegInfo);
  150. }
  151. if (MFInfo) {
  152. MFInfo->~MachineFunctionInfo();
  153. Allocator.Deallocate(MFInfo);
  154. }
  155. FrameInfo->~MachineFrameInfo();
  156. Allocator.Deallocate(FrameInfo);
  157. ConstantPool->~MachineConstantPool();
  158. Allocator.Deallocate(ConstantPool);
  159. if (JumpTableInfo) {
  160. JumpTableInfo->~MachineJumpTableInfo();
  161. Allocator.Deallocate(JumpTableInfo);
  162. }
  163. if (WinEHInfo) {
  164. WinEHInfo->~WinEHFuncInfo();
  165. Allocator.Deallocate(WinEHInfo);
  166. }
  167. }
  168. const DataLayout &MachineFunction::getDataLayout() const {
  169. return Fn->getParent()->getDataLayout();
  170. }
  171. /// Get the JumpTableInfo for this function.
  172. /// If it does not already exist, allocate one.
  173. MachineJumpTableInfo *MachineFunction::
  174. getOrCreateJumpTableInfo(unsigned EntryKind) {
  175. if (JumpTableInfo) return JumpTableInfo;
  176. JumpTableInfo = new (Allocator)
  177. MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
  178. return JumpTableInfo;
  179. }
  180. /// Should we be emitting segmented stack stuff for the function
  181. bool MachineFunction::shouldSplitStack() const {
  182. return getFunction()->hasFnAttribute("split-stack");
  183. }
  184. /// This discards all of the MachineBasicBlock numbers and recomputes them.
  185. /// This guarantees that the MBB numbers are sequential, dense, and match the
  186. /// ordering of the blocks within the function. If a specific MachineBasicBlock
  187. /// is specified, only that block and those after it are renumbered.
  188. void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
  189. if (empty()) { MBBNumbering.clear(); return; }
  190. MachineFunction::iterator MBBI, E = end();
  191. if (MBB == nullptr)
  192. MBBI = begin();
  193. else
  194. MBBI = MBB->getIterator();
  195. // Figure out the block number this should have.
  196. unsigned BlockNo = 0;
  197. if (MBBI != begin())
  198. BlockNo = std::prev(MBBI)->getNumber() + 1;
  199. for (; MBBI != E; ++MBBI, ++BlockNo) {
  200. if (MBBI->getNumber() != (int)BlockNo) {
  201. // Remove use of the old number.
  202. if (MBBI->getNumber() != -1) {
  203. assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
  204. "MBB number mismatch!");
  205. MBBNumbering[MBBI->getNumber()] = nullptr;
  206. }
  207. // If BlockNo is already taken, set that block's number to -1.
  208. if (MBBNumbering[BlockNo])
  209. MBBNumbering[BlockNo]->setNumber(-1);
  210. MBBNumbering[BlockNo] = &*MBBI;
  211. MBBI->setNumber(BlockNo);
  212. }
  213. }
  214. // Okay, all the blocks are renumbered. If we have compactified the block
  215. // numbering, shrink MBBNumbering now.
  216. assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
  217. MBBNumbering.resize(BlockNo);
  218. }
  219. /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'.
  220. MachineInstr *MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
  221. const DebugLoc &DL,
  222. bool NoImp) {
  223. return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
  224. MachineInstr(*this, MCID, DL, NoImp);
  225. }
  226. /// Create a new MachineInstr which is a copy of the 'Orig' instruction,
  227. /// identical in all ways except the instruction has no parent, prev, or next.
  228. MachineInstr *
  229. MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
  230. return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
  231. MachineInstr(*this, *Orig);
  232. }
  233. MachineInstr &MachineFunction::CloneMachineInstrBundle(MachineBasicBlock &MBB,
  234. MachineBasicBlock::iterator InsertBefore, const MachineInstr &Orig) {
  235. MachineInstr *FirstClone = nullptr;
  236. MachineBasicBlock::const_instr_iterator I = Orig.getIterator();
  237. for (;;) {
  238. MachineInstr *Cloned = CloneMachineInstr(&*I);
  239. MBB.insert(InsertBefore, Cloned);
  240. if (FirstClone == nullptr) {
  241. FirstClone = Cloned;
  242. } else {
  243. Cloned->bundleWithPred();
  244. }
  245. if (!I->isBundledWithSucc())
  246. break;
  247. ++I;
  248. }
  249. return *FirstClone;
  250. }
  251. /// Delete the given MachineInstr.
  252. ///
  253. /// This function also serves as the MachineInstr destructor - the real
  254. /// ~MachineInstr() destructor must be empty.
  255. void
  256. MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
  257. // Strip it for parts. The operand array and the MI object itself are
  258. // independently recyclable.
  259. if (MI->Operands)
  260. deallocateOperandArray(MI->CapOperands, MI->Operands);
  261. // Don't call ~MachineInstr() which must be trivial anyway because
  262. // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
  263. // destructors.
  264. InstructionRecycler.Deallocate(Allocator, MI);
  265. }
  266. /// Allocate a new MachineBasicBlock. Use this instead of
  267. /// `new MachineBasicBlock'.
  268. MachineBasicBlock *
  269. MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
  270. return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
  271. MachineBasicBlock(*this, bb);
  272. }
  273. /// Delete the given MachineBasicBlock.
  274. void
  275. MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
  276. assert(MBB->getParent() == this && "MBB parent mismatch!");
  277. MBB->~MachineBasicBlock();
  278. BasicBlockRecycler.Deallocate(Allocator, MBB);
  279. }
  280. MachineMemOperand *MachineFunction::getMachineMemOperand(
  281. MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s,
  282. unsigned base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges,
  283. SyncScope::ID SSID, AtomicOrdering Ordering,
  284. AtomicOrdering FailureOrdering) {
  285. return new (Allocator)
  286. MachineMemOperand(PtrInfo, f, s, base_alignment, AAInfo, Ranges,
  287. SSID, Ordering, FailureOrdering);
  288. }
  289. MachineMemOperand *
  290. MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
  291. int64_t Offset, uint64_t Size) {
  292. if (MMO->getValue())
  293. return new (Allocator)
  294. MachineMemOperand(MachinePointerInfo(MMO->getValue(),
  295. MMO->getOffset()+Offset),
  296. MMO->getFlags(), Size, MMO->getBaseAlignment(),
  297. AAMDNodes(), nullptr, MMO->getSyncScopeID(),
  298. MMO->getOrdering(), MMO->getFailureOrdering());
  299. return new (Allocator)
  300. MachineMemOperand(MachinePointerInfo(MMO->getPseudoValue(),
  301. MMO->getOffset()+Offset),
  302. MMO->getFlags(), Size, MMO->getBaseAlignment(),
  303. AAMDNodes(), nullptr, MMO->getSyncScopeID(),
  304. MMO->getOrdering(), MMO->getFailureOrdering());
  305. }
  306. MachineMemOperand *
  307. MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
  308. const AAMDNodes &AAInfo) {
  309. MachinePointerInfo MPI = MMO->getValue() ?
  310. MachinePointerInfo(MMO->getValue(), MMO->getOffset()) :
  311. MachinePointerInfo(MMO->getPseudoValue(), MMO->getOffset());
  312. return new (Allocator)
  313. MachineMemOperand(MPI, MMO->getFlags(), MMO->getSize(),
  314. MMO->getBaseAlignment(), AAInfo,
  315. MMO->getRanges(), MMO->getSyncScopeID(),
  316. MMO->getOrdering(), MMO->getFailureOrdering());
  317. }
  318. MachineInstr::mmo_iterator
  319. MachineFunction::allocateMemRefsArray(unsigned long Num) {
  320. return Allocator.Allocate<MachineMemOperand *>(Num);
  321. }
  322. std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
  323. MachineFunction::extractLoadMemRefs(MachineInstr::mmo_iterator Begin,
  324. MachineInstr::mmo_iterator End) {
  325. // Count the number of load mem refs.
  326. unsigned Num = 0;
  327. for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
  328. if ((*I)->isLoad())
  329. ++Num;
  330. // Allocate a new array and populate it with the load information.
  331. MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
  332. unsigned Index = 0;
  333. for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
  334. if ((*I)->isLoad()) {
  335. if (!(*I)->isStore())
  336. // Reuse the MMO.
  337. Result[Index] = *I;
  338. else {
  339. // Clone the MMO and unset the store flag.
  340. MachineMemOperand *JustLoad =
  341. getMachineMemOperand((*I)->getPointerInfo(),
  342. (*I)->getFlags() & ~MachineMemOperand::MOStore,
  343. (*I)->getSize(), (*I)->getBaseAlignment(),
  344. (*I)->getAAInfo(), nullptr,
  345. (*I)->getSyncScopeID(), (*I)->getOrdering(),
  346. (*I)->getFailureOrdering());
  347. Result[Index] = JustLoad;
  348. }
  349. ++Index;
  350. }
  351. }
  352. return std::make_pair(Result, Result + Num);
  353. }
  354. std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
  355. MachineFunction::extractStoreMemRefs(MachineInstr::mmo_iterator Begin,
  356. MachineInstr::mmo_iterator End) {
  357. // Count the number of load mem refs.
  358. unsigned Num = 0;
  359. for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
  360. if ((*I)->isStore())
  361. ++Num;
  362. // Allocate a new array and populate it with the store information.
  363. MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
  364. unsigned Index = 0;
  365. for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
  366. if ((*I)->isStore()) {
  367. if (!(*I)->isLoad())
  368. // Reuse the MMO.
  369. Result[Index] = *I;
  370. else {
  371. // Clone the MMO and unset the load flag.
  372. MachineMemOperand *JustStore =
  373. getMachineMemOperand((*I)->getPointerInfo(),
  374. (*I)->getFlags() & ~MachineMemOperand::MOLoad,
  375. (*I)->getSize(), (*I)->getBaseAlignment(),
  376. (*I)->getAAInfo(), nullptr,
  377. (*I)->getSyncScopeID(), (*I)->getOrdering(),
  378. (*I)->getFailureOrdering());
  379. Result[Index] = JustStore;
  380. }
  381. ++Index;
  382. }
  383. }
  384. return std::make_pair(Result, Result + Num);
  385. }
  386. const char *MachineFunction::createExternalSymbolName(StringRef Name) {
  387. char *Dest = Allocator.Allocate<char>(Name.size() + 1);
  388. std::copy(Name.begin(), Name.end(), Dest);
  389. Dest[Name.size()] = 0;
  390. return Dest;
  391. }
  392. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  393. LLVM_DUMP_METHOD void MachineFunction::dump() const {
  394. print(dbgs());
  395. }
  396. #endif
  397. StringRef MachineFunction::getName() const {
  398. assert(getFunction() && "No function!");
  399. return getFunction()->getName();
  400. }
  401. void MachineFunction::print(raw_ostream &OS, const SlotIndexes *Indexes) const {
  402. OS << "# Machine code for function " << getName() << ": ";
  403. getProperties().print(OS);
  404. OS << '\n';
  405. // Print Frame Information
  406. FrameInfo->print(*this, OS);
  407. // Print JumpTable Information
  408. if (JumpTableInfo)
  409. JumpTableInfo->print(OS);
  410. // Print Constant Pool
  411. ConstantPool->print(OS);
  412. const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo();
  413. if (RegInfo && !RegInfo->livein_empty()) {
  414. OS << "Function Live Ins: ";
  415. for (MachineRegisterInfo::livein_iterator
  416. I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
  417. OS << PrintReg(I->first, TRI);
  418. if (I->second)
  419. OS << " in " << PrintReg(I->second, TRI);
  420. if (std::next(I) != E)
  421. OS << ", ";
  422. }
  423. OS << '\n';
  424. }
  425. ModuleSlotTracker MST(getFunction()->getParent());
  426. MST.incorporateFunction(*getFunction());
  427. for (const auto &BB : *this) {
  428. OS << '\n';
  429. BB.print(OS, MST, Indexes);
  430. }
  431. OS << "\n# End machine code for function " << getName() << ".\n\n";
  432. }
  433. namespace llvm {
  434. template<>
  435. struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
  436. DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
  437. static std::string getGraphName(const MachineFunction *F) {
  438. return ("CFG for '" + F->getName() + "' function").str();
  439. }
  440. std::string getNodeLabel(const MachineBasicBlock *Node,
  441. const MachineFunction *Graph) {
  442. std::string OutStr;
  443. {
  444. raw_string_ostream OSS(OutStr);
  445. if (isSimple()) {
  446. OSS << "BB#" << Node->getNumber();
  447. if (const BasicBlock *BB = Node->getBasicBlock())
  448. OSS << ": " << BB->getName();
  449. } else
  450. Node->print(OSS);
  451. }
  452. if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
  453. // Process string output to make it nicer...
  454. for (unsigned i = 0; i != OutStr.length(); ++i)
  455. if (OutStr[i] == '\n') { // Left justify
  456. OutStr[i] = '\\';
  457. OutStr.insert(OutStr.begin()+i+1, 'l');
  458. }
  459. return OutStr;
  460. }
  461. };
  462. }
  463. void MachineFunction::viewCFG() const
  464. {
  465. #ifndef NDEBUG
  466. ViewGraph(this, "mf" + getName());
  467. #else
  468. errs() << "MachineFunction::viewCFG is only available in debug builds on "
  469. << "systems with Graphviz or gv!\n";
  470. #endif // NDEBUG
  471. }
  472. void MachineFunction::viewCFGOnly() const
  473. {
  474. #ifndef NDEBUG
  475. ViewGraph(this, "mf" + getName(), true);
  476. #else
  477. errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
  478. << "systems with Graphviz or gv!\n";
  479. #endif // NDEBUG
  480. }
  481. /// Add the specified physical register as a live-in value and
  482. /// create a corresponding virtual register for it.
  483. unsigned MachineFunction::addLiveIn(unsigned PReg,
  484. const TargetRegisterClass *RC) {
  485. MachineRegisterInfo &MRI = getRegInfo();
  486. unsigned VReg = MRI.getLiveInVirtReg(PReg);
  487. if (VReg) {
  488. const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
  489. (void)VRegRC;
  490. // A physical register can be added several times.
  491. // Between two calls, the register class of the related virtual register
  492. // may have been constrained to match some operation constraints.
  493. // In that case, check that the current register class includes the
  494. // physical register and is a sub class of the specified RC.
  495. assert((VRegRC == RC || (VRegRC->contains(PReg) &&
  496. RC->hasSubClassEq(VRegRC))) &&
  497. "Register class mismatch!");
  498. return VReg;
  499. }
  500. VReg = MRI.createVirtualRegister(RC);
  501. MRI.addLiveIn(PReg, VReg);
  502. return VReg;
  503. }
  504. /// Return the MCSymbol for the specified non-empty jump table.
  505. /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
  506. /// normal 'L' label is returned.
  507. MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
  508. bool isLinkerPrivate) const {
  509. const DataLayout &DL = getDataLayout();
  510. assert(JumpTableInfo && "No jump tables");
  511. assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
  512. StringRef Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix()
  513. : DL.getPrivateGlobalPrefix();
  514. SmallString<60> Name;
  515. raw_svector_ostream(Name)
  516. << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
  517. return Ctx.getOrCreateSymbol(Name);
  518. }
  519. /// Return a function-local symbol to represent the PIC base.
  520. MCSymbol *MachineFunction::getPICBaseSymbol() const {
  521. const DataLayout &DL = getDataLayout();
  522. return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
  523. Twine(getFunctionNumber()) + "$pb");
  524. }
  525. /// \name Exception Handling
  526. /// \{
  527. LandingPadInfo &
  528. MachineFunction::getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad) {
  529. unsigned N = LandingPads.size();
  530. for (unsigned i = 0; i < N; ++i) {
  531. LandingPadInfo &LP = LandingPads[i];
  532. if (LP.LandingPadBlock == LandingPad)
  533. return LP;
  534. }
  535. LandingPads.push_back(LandingPadInfo(LandingPad));
  536. return LandingPads[N];
  537. }
  538. void MachineFunction::addInvoke(MachineBasicBlock *LandingPad,
  539. MCSymbol *BeginLabel, MCSymbol *EndLabel) {
  540. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  541. LP.BeginLabels.push_back(BeginLabel);
  542. LP.EndLabels.push_back(EndLabel);
  543. }
  544. MCSymbol *MachineFunction::addLandingPad(MachineBasicBlock *LandingPad) {
  545. MCSymbol *LandingPadLabel = Ctx.createTempSymbol();
  546. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  547. LP.LandingPadLabel = LandingPadLabel;
  548. return LandingPadLabel;
  549. }
  550. void MachineFunction::addCatchTypeInfo(MachineBasicBlock *LandingPad,
  551. ArrayRef<const GlobalValue *> TyInfo) {
  552. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  553. for (unsigned N = TyInfo.size(); N; --N)
  554. LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1]));
  555. }
  556. void MachineFunction::addFilterTypeInfo(MachineBasicBlock *LandingPad,
  557. ArrayRef<const GlobalValue *> TyInfo) {
  558. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  559. std::vector<unsigned> IdsInFilter(TyInfo.size());
  560. for (unsigned I = 0, E = TyInfo.size(); I != E; ++I)
  561. IdsInFilter[I] = getTypeIDFor(TyInfo[I]);
  562. LP.TypeIds.push_back(getFilterIDFor(IdsInFilter));
  563. }
  564. void MachineFunction::tidyLandingPads(DenseMap<MCSymbol*, uintptr_t> *LPMap) {
  565. for (unsigned i = 0; i != LandingPads.size(); ) {
  566. LandingPadInfo &LandingPad = LandingPads[i];
  567. if (LandingPad.LandingPadLabel &&
  568. !LandingPad.LandingPadLabel->isDefined() &&
  569. (!LPMap || (*LPMap)[LandingPad.LandingPadLabel] == 0))
  570. LandingPad.LandingPadLabel = nullptr;
  571. // Special case: we *should* emit LPs with null LP MBB. This indicates
  572. // "nounwind" case.
  573. if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) {
  574. LandingPads.erase(LandingPads.begin() + i);
  575. continue;
  576. }
  577. for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) {
  578. MCSymbol *BeginLabel = LandingPad.BeginLabels[j];
  579. MCSymbol *EndLabel = LandingPad.EndLabels[j];
  580. if ((BeginLabel->isDefined() ||
  581. (LPMap && (*LPMap)[BeginLabel] != 0)) &&
  582. (EndLabel->isDefined() ||
  583. (LPMap && (*LPMap)[EndLabel] != 0))) continue;
  584. LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j);
  585. LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j);
  586. --j;
  587. --e;
  588. }
  589. // Remove landing pads with no try-ranges.
  590. if (LandingPads[i].BeginLabels.empty()) {
  591. LandingPads.erase(LandingPads.begin() + i);
  592. continue;
  593. }
  594. // If there is no landing pad, ensure that the list of typeids is empty.
  595. // If the only typeid is a cleanup, this is the same as having no typeids.
  596. if (!LandingPad.LandingPadBlock ||
  597. (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0]))
  598. LandingPad.TypeIds.clear();
  599. ++i;
  600. }
  601. }
  602. void MachineFunction::addCleanup(MachineBasicBlock *LandingPad) {
  603. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  604. LP.TypeIds.push_back(0);
  605. }
  606. void MachineFunction::addSEHCatchHandler(MachineBasicBlock *LandingPad,
  607. const Function *Filter,
  608. const BlockAddress *RecoverBA) {
  609. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  610. SEHHandler Handler;
  611. Handler.FilterOrFinally = Filter;
  612. Handler.RecoverBA = RecoverBA;
  613. LP.SEHHandlers.push_back(Handler);
  614. }
  615. void MachineFunction::addSEHCleanupHandler(MachineBasicBlock *LandingPad,
  616. const Function *Cleanup) {
  617. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  618. SEHHandler Handler;
  619. Handler.FilterOrFinally = Cleanup;
  620. Handler.RecoverBA = nullptr;
  621. LP.SEHHandlers.push_back(Handler);
  622. }
  623. void MachineFunction::setCallSiteLandingPad(MCSymbol *Sym,
  624. ArrayRef<unsigned> Sites) {
  625. LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end());
  626. }
  627. unsigned MachineFunction::getTypeIDFor(const GlobalValue *TI) {
  628. for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
  629. if (TypeInfos[i] == TI) return i + 1;
  630. TypeInfos.push_back(TI);
  631. return TypeInfos.size();
  632. }
  633. int MachineFunction::getFilterIDFor(std::vector<unsigned> &TyIds) {
  634. // If the new filter coincides with the tail of an existing filter, then
  635. // re-use the existing filter. Folding filters more than this requires
  636. // re-ordering filters and/or their elements - probably not worth it.
  637. for (std::vector<unsigned>::iterator I = FilterEnds.begin(),
  638. E = FilterEnds.end(); I != E; ++I) {
  639. unsigned i = *I, j = TyIds.size();
  640. while (i && j)
  641. if (FilterIds[--i] != TyIds[--j])
  642. goto try_next;
  643. if (!j)
  644. // The new filter coincides with range [i, end) of the existing filter.
  645. return -(1 + i);
  646. try_next:;
  647. }
  648. // Add the new filter.
  649. int FilterID = -(1 + FilterIds.size());
  650. FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
  651. FilterIds.insert(FilterIds.end(), TyIds.begin(), TyIds.end());
  652. FilterEnds.push_back(FilterIds.size());
  653. FilterIds.push_back(0); // terminator
  654. return FilterID;
  655. }
  656. void llvm::addLandingPadInfo(const LandingPadInst &I, MachineBasicBlock &MBB) {
  657. MachineFunction &MF = *MBB.getParent();
  658. if (const auto *PF = dyn_cast<Function>(
  659. I.getParent()->getParent()->getPersonalityFn()->stripPointerCasts()))
  660. MF.getMMI().addPersonality(PF);
  661. if (I.isCleanup())
  662. MF.addCleanup(&MBB);
  663. // FIXME: New EH - Add the clauses in reverse order. This isn't 100% correct,
  664. // but we need to do it this way because of how the DWARF EH emitter
  665. // processes the clauses.
  666. for (unsigned i = I.getNumClauses(); i != 0; --i) {
  667. Value *Val = I.getClause(i - 1);
  668. if (I.isCatch(i - 1)) {
  669. MF.addCatchTypeInfo(&MBB,
  670. dyn_cast<GlobalValue>(Val->stripPointerCasts()));
  671. } else {
  672. // Add filters in a list.
  673. Constant *CVal = cast<Constant>(Val);
  674. SmallVector<const GlobalValue *, 4> FilterList;
  675. for (User::op_iterator II = CVal->op_begin(), IE = CVal->op_end();
  676. II != IE; ++II)
  677. FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts()));
  678. MF.addFilterTypeInfo(&MBB, FilterList);
  679. }
  680. }
  681. }
  682. /// \}
  683. //===----------------------------------------------------------------------===//
  684. // MachineJumpTableInfo implementation
  685. //===----------------------------------------------------------------------===//
  686. /// Return the size of each entry in the jump table.
  687. unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
  688. // The size of a jump table entry is 4 bytes unless the entry is just the
  689. // address of a block, in which case it is the pointer size.
  690. switch (getEntryKind()) {
  691. case MachineJumpTableInfo::EK_BlockAddress:
  692. return TD.getPointerSize();
  693. case MachineJumpTableInfo::EK_GPRel64BlockAddress:
  694. return 8;
  695. case MachineJumpTableInfo::EK_GPRel32BlockAddress:
  696. case MachineJumpTableInfo::EK_LabelDifference32:
  697. case MachineJumpTableInfo::EK_Custom32:
  698. return 4;
  699. case MachineJumpTableInfo::EK_Inline:
  700. return 0;
  701. }
  702. llvm_unreachable("Unknown jump table encoding!");
  703. }
  704. /// Return the alignment of each entry in the jump table.
  705. unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
  706. // The alignment of a jump table entry is the alignment of int32 unless the
  707. // entry is just the address of a block, in which case it is the pointer
  708. // alignment.
  709. switch (getEntryKind()) {
  710. case MachineJumpTableInfo::EK_BlockAddress:
  711. return TD.getPointerABIAlignment();
  712. case MachineJumpTableInfo::EK_GPRel64BlockAddress:
  713. return TD.getABIIntegerTypeAlignment(64);
  714. case MachineJumpTableInfo::EK_GPRel32BlockAddress:
  715. case MachineJumpTableInfo::EK_LabelDifference32:
  716. case MachineJumpTableInfo::EK_Custom32:
  717. return TD.getABIIntegerTypeAlignment(32);
  718. case MachineJumpTableInfo::EK_Inline:
  719. return 1;
  720. }
  721. llvm_unreachable("Unknown jump table encoding!");
  722. }
  723. /// Create a new jump table entry in the jump table info.
  724. unsigned MachineJumpTableInfo::createJumpTableIndex(
  725. const std::vector<MachineBasicBlock*> &DestBBs) {
  726. assert(!DestBBs.empty() && "Cannot create an empty jump table!");
  727. JumpTables.push_back(MachineJumpTableEntry(DestBBs));
  728. return JumpTables.size()-1;
  729. }
  730. /// If Old is the target of any jump tables, update the jump tables to branch
  731. /// to New instead.
  732. bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
  733. MachineBasicBlock *New) {
  734. assert(Old != New && "Not making a change?");
  735. bool MadeChange = false;
  736. for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
  737. ReplaceMBBInJumpTable(i, Old, New);
  738. return MadeChange;
  739. }
  740. /// If Old is a target of the jump tables, update the jump table to branch to
  741. /// New instead.
  742. bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
  743. MachineBasicBlock *Old,
  744. MachineBasicBlock *New) {
  745. assert(Old != New && "Not making a change?");
  746. bool MadeChange = false;
  747. MachineJumpTableEntry &JTE = JumpTables[Idx];
  748. for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
  749. if (JTE.MBBs[j] == Old) {
  750. JTE.MBBs[j] = New;
  751. MadeChange = true;
  752. }
  753. return MadeChange;
  754. }
  755. void MachineJumpTableInfo::print(raw_ostream &OS) const {
  756. if (JumpTables.empty()) return;
  757. OS << "Jump Tables:\n";
  758. for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
  759. OS << " jt#" << i << ": ";
  760. for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
  761. OS << " BB#" << JumpTables[i].MBBs[j]->getNumber();
  762. }
  763. OS << '\n';
  764. }
  765. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  766. LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); }
  767. #endif
  768. //===----------------------------------------------------------------------===//
  769. // MachineConstantPool implementation
  770. //===----------------------------------------------------------------------===//
  771. void MachineConstantPoolValue::anchor() { }
  772. Type *MachineConstantPoolEntry::getType() const {
  773. if (isMachineConstantPoolEntry())
  774. return Val.MachineCPVal->getType();
  775. return Val.ConstVal->getType();
  776. }
  777. bool MachineConstantPoolEntry::needsRelocation() const {
  778. if (isMachineConstantPoolEntry())
  779. return true;
  780. return Val.ConstVal->needsRelocation();
  781. }
  782. SectionKind
  783. MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
  784. if (needsRelocation())
  785. return SectionKind::getReadOnlyWithRel();
  786. switch (DL->getTypeAllocSize(getType())) {
  787. case 4:
  788. return SectionKind::getMergeableConst4();
  789. case 8:
  790. return SectionKind::getMergeableConst8();
  791. case 16:
  792. return SectionKind::getMergeableConst16();
  793. case 32:
  794. return SectionKind::getMergeableConst32();
  795. default:
  796. return SectionKind::getReadOnly();
  797. }
  798. }
  799. MachineConstantPool::~MachineConstantPool() {
  800. // A constant may be a member of both Constants and MachineCPVsSharingEntries,
  801. // so keep track of which we've deleted to avoid double deletions.
  802. DenseSet<MachineConstantPoolValue*> Deleted;
  803. for (unsigned i = 0, e = Constants.size(); i != e; ++i)
  804. if (Constants[i].isMachineConstantPoolEntry()) {
  805. Deleted.insert(Constants[i].Val.MachineCPVal);
  806. delete Constants[i].Val.MachineCPVal;
  807. }
  808. for (DenseSet<MachineConstantPoolValue*>::iterator I =
  809. MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
  810. I != E; ++I) {
  811. if (Deleted.count(*I) == 0)
  812. delete *I;
  813. }
  814. }
  815. /// Test whether the given two constants can be allocated the same constant pool
  816. /// entry.
  817. static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
  818. const DataLayout &DL) {
  819. // Handle the trivial case quickly.
  820. if (A == B) return true;
  821. // If they have the same type but weren't the same constant, quickly
  822. // reject them.
  823. if (A->getType() == B->getType()) return false;
  824. // We can't handle structs or arrays.
  825. if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
  826. isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
  827. return false;
  828. // For now, only support constants with the same size.
  829. uint64_t StoreSize = DL.getTypeStoreSize(A->getType());
  830. if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128)
  831. return false;
  832. Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
  833. // Try constant folding a bitcast of both instructions to an integer. If we
  834. // get two identical ConstantInt's, then we are good to share them. We use
  835. // the constant folding APIs to do this so that we get the benefit of
  836. // DataLayout.
  837. if (isa<PointerType>(A->getType()))
  838. A = ConstantFoldCastOperand(Instruction::PtrToInt,
  839. const_cast<Constant *>(A), IntTy, DL);
  840. else if (A->getType() != IntTy)
  841. A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A),
  842. IntTy, DL);
  843. if (isa<PointerType>(B->getType()))
  844. B = ConstantFoldCastOperand(Instruction::PtrToInt,
  845. const_cast<Constant *>(B), IntTy, DL);
  846. else if (B->getType() != IntTy)
  847. B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B),
  848. IntTy, DL);
  849. return A == B;
  850. }
  851. /// Create a new entry in the constant pool or return an existing one.
  852. /// User must specify the log2 of the minimum required alignment for the object.
  853. unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
  854. unsigned Alignment) {
  855. assert(Alignment && "Alignment must be specified!");
  856. if (Alignment > PoolAlignment) PoolAlignment = Alignment;
  857. // Check to see if we already have this constant.
  858. //
  859. // FIXME, this could be made much more efficient for large constant pools.
  860. for (unsigned i = 0, e = Constants.size(); i != e; ++i)
  861. if (!Constants[i].isMachineConstantPoolEntry() &&
  862. CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) {
  863. if ((unsigned)Constants[i].getAlignment() < Alignment)
  864. Constants[i].Alignment = Alignment;
  865. return i;
  866. }
  867. Constants.push_back(MachineConstantPoolEntry(C, Alignment));
  868. return Constants.size()-1;
  869. }
  870. unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
  871. unsigned Alignment) {
  872. assert(Alignment && "Alignment must be specified!");
  873. if (Alignment > PoolAlignment) PoolAlignment = Alignment;
  874. // Check to see if we already have this constant.
  875. //
  876. // FIXME, this could be made much more efficient for large constant pools.
  877. int Idx = V->getExistingMachineCPValue(this, Alignment);
  878. if (Idx != -1) {
  879. MachineCPVsSharingEntries.insert(V);
  880. return (unsigned)Idx;
  881. }
  882. Constants.push_back(MachineConstantPoolEntry(V, Alignment));
  883. return Constants.size()-1;
  884. }
  885. void MachineConstantPool::print(raw_ostream &OS) const {
  886. if (Constants.empty()) return;
  887. OS << "Constant Pool:\n";
  888. for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
  889. OS << " cp#" << i << ": ";
  890. if (Constants[i].isMachineConstantPoolEntry())
  891. Constants[i].Val.MachineCPVal->print(OS);
  892. else
  893. Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
  894. OS << ", align=" << Constants[i].getAlignment();
  895. OS << "\n";
  896. }
  897. }
  898. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  899. LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); }
  900. #endif