MachineFunction.cpp 37 KB

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