MachineFunction.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  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. LLVM_NODISCARD unsigned
  238. MachineFunction::addFrameInst(const MCCFIInstruction &Inst) {
  239. FrameInstructions.push_back(Inst);
  240. return FrameInstructions.size() - 1;
  241. }
  242. /// This discards all of the MachineBasicBlock numbers and recomputes them.
  243. /// This guarantees that the MBB numbers are sequential, dense, and match the
  244. /// ordering of the blocks within the function. If a specific MachineBasicBlock
  245. /// is specified, only that block and those after it are renumbered.
  246. void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
  247. if (empty()) { MBBNumbering.clear(); return; }
  248. MachineFunction::iterator MBBI, E = end();
  249. if (MBB == nullptr)
  250. MBBI = begin();
  251. else
  252. MBBI = MBB->getIterator();
  253. // Figure out the block number this should have.
  254. unsigned BlockNo = 0;
  255. if (MBBI != begin())
  256. BlockNo = std::prev(MBBI)->getNumber() + 1;
  257. for (; MBBI != E; ++MBBI, ++BlockNo) {
  258. if (MBBI->getNumber() != (int)BlockNo) {
  259. // Remove use of the old number.
  260. if (MBBI->getNumber() != -1) {
  261. assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
  262. "MBB number mismatch!");
  263. MBBNumbering[MBBI->getNumber()] = nullptr;
  264. }
  265. // If BlockNo is already taken, set that block's number to -1.
  266. if (MBBNumbering[BlockNo])
  267. MBBNumbering[BlockNo]->setNumber(-1);
  268. MBBNumbering[BlockNo] = &*MBBI;
  269. MBBI->setNumber(BlockNo);
  270. }
  271. }
  272. // Okay, all the blocks are renumbered. If we have compactified the block
  273. // numbering, shrink MBBNumbering now.
  274. assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
  275. MBBNumbering.resize(BlockNo);
  276. }
  277. /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'.
  278. MachineInstr *MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
  279. const DebugLoc &DL,
  280. bool NoImp) {
  281. return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
  282. MachineInstr(*this, MCID, DL, NoImp);
  283. }
  284. /// Create a new MachineInstr which is a copy of the 'Orig' instruction,
  285. /// identical in all ways except the instruction has no parent, prev, or next.
  286. MachineInstr *
  287. MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
  288. return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
  289. MachineInstr(*this, *Orig);
  290. }
  291. MachineInstr &MachineFunction::CloneMachineInstrBundle(MachineBasicBlock &MBB,
  292. MachineBasicBlock::iterator InsertBefore, const MachineInstr &Orig) {
  293. MachineInstr *FirstClone = nullptr;
  294. MachineBasicBlock::const_instr_iterator I = Orig.getIterator();
  295. while (true) {
  296. MachineInstr *Cloned = CloneMachineInstr(&*I);
  297. MBB.insert(InsertBefore, Cloned);
  298. if (FirstClone == nullptr) {
  299. FirstClone = Cloned;
  300. } else {
  301. Cloned->bundleWithPred();
  302. }
  303. if (!I->isBundledWithSucc())
  304. break;
  305. ++I;
  306. }
  307. return *FirstClone;
  308. }
  309. /// Delete the given MachineInstr.
  310. ///
  311. /// This function also serves as the MachineInstr destructor - the real
  312. /// ~MachineInstr() destructor must be empty.
  313. void
  314. MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
  315. // Strip it for parts. The operand array and the MI object itself are
  316. // independently recyclable.
  317. if (MI->Operands)
  318. deallocateOperandArray(MI->CapOperands, MI->Operands);
  319. // Don't call ~MachineInstr() which must be trivial anyway because
  320. // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
  321. // destructors.
  322. InstructionRecycler.Deallocate(Allocator, MI);
  323. }
  324. /// Allocate a new MachineBasicBlock. Use this instead of
  325. /// `new MachineBasicBlock'.
  326. MachineBasicBlock *
  327. MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
  328. return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
  329. MachineBasicBlock(*this, bb);
  330. }
  331. /// Delete the given MachineBasicBlock.
  332. void
  333. MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
  334. assert(MBB->getParent() == this && "MBB parent mismatch!");
  335. MBB->~MachineBasicBlock();
  336. BasicBlockRecycler.Deallocate(Allocator, MBB);
  337. }
  338. MachineMemOperand *MachineFunction::getMachineMemOperand(
  339. MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s,
  340. unsigned base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges,
  341. SyncScope::ID SSID, AtomicOrdering Ordering,
  342. AtomicOrdering FailureOrdering) {
  343. return new (Allocator)
  344. MachineMemOperand(PtrInfo, f, s, base_alignment, AAInfo, Ranges,
  345. SSID, Ordering, FailureOrdering);
  346. }
  347. MachineMemOperand *
  348. MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
  349. int64_t Offset, uint64_t Size) {
  350. const MachinePointerInfo &PtrInfo = MMO->getPointerInfo();
  351. // If there is no pointer value, the offset isn't tracked so we need to adjust
  352. // the base alignment.
  353. unsigned Align = PtrInfo.V.isNull()
  354. ? MinAlign(MMO->getBaseAlignment(), Offset)
  355. : MMO->getBaseAlignment();
  356. return new (Allocator)
  357. MachineMemOperand(PtrInfo.getWithOffset(Offset), MMO->getFlags(), Size,
  358. Align, AAMDNodes(), nullptr, MMO->getSyncScopeID(),
  359. MMO->getOrdering(), MMO->getFailureOrdering());
  360. }
  361. MachineMemOperand *
  362. MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
  363. const AAMDNodes &AAInfo) {
  364. MachinePointerInfo MPI = MMO->getValue() ?
  365. MachinePointerInfo(MMO->getValue(), MMO->getOffset()) :
  366. MachinePointerInfo(MMO->getPseudoValue(), MMO->getOffset());
  367. return new (Allocator)
  368. MachineMemOperand(MPI, MMO->getFlags(), MMO->getSize(),
  369. MMO->getBaseAlignment(), AAInfo,
  370. MMO->getRanges(), MMO->getSyncScopeID(),
  371. MMO->getOrdering(), MMO->getFailureOrdering());
  372. }
  373. MachineInstr::ExtraInfo *
  374. MachineFunction::createMIExtraInfo(ArrayRef<MachineMemOperand *> MMOs,
  375. MCSymbol *PreInstrSymbol,
  376. MCSymbol *PostInstrSymbol) {
  377. return MachineInstr::ExtraInfo::create(Allocator, MMOs, PreInstrSymbol,
  378. PostInstrSymbol);
  379. }
  380. const char *MachineFunction::createExternalSymbolName(StringRef Name) {
  381. char *Dest = Allocator.Allocate<char>(Name.size() + 1);
  382. llvm::copy(Name, Dest);
  383. Dest[Name.size()] = 0;
  384. return Dest;
  385. }
  386. uint32_t *MachineFunction::allocateRegMask() {
  387. unsigned NumRegs = getSubtarget().getRegisterInfo()->getNumRegs();
  388. unsigned Size = MachineOperand::getRegMaskSize(NumRegs);
  389. uint32_t *Mask = Allocator.Allocate<uint32_t>(Size);
  390. memset(Mask, 0, Size * sizeof(Mask[0]));
  391. return Mask;
  392. }
  393. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  394. LLVM_DUMP_METHOD void MachineFunction::dump() const {
  395. print(dbgs());
  396. }
  397. #endif
  398. StringRef MachineFunction::getName() const {
  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. // If we print the whole function, print it at its most verbose level.
  430. BB.print(OS, MST, Indexes, /*IsStandalone=*/true);
  431. }
  432. OS << "\n# End machine code for function " << getName() << ".\n\n";
  433. }
  434. namespace llvm {
  435. template<>
  436. struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
  437. DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
  438. static std::string getGraphName(const MachineFunction *F) {
  439. return ("CFG for '" + F->getName() + "' function").str();
  440. }
  441. std::string getNodeLabel(const MachineBasicBlock *Node,
  442. const MachineFunction *Graph) {
  443. std::string OutStr;
  444. {
  445. raw_string_ostream OSS(OutStr);
  446. if (isSimple()) {
  447. OSS << printMBBReference(*Node);
  448. if (const BasicBlock *BB = Node->getBasicBlock())
  449. OSS << ": " << BB->getName();
  450. } else
  451. Node->print(OSS);
  452. }
  453. if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
  454. // Process string output to make it nicer...
  455. for (unsigned i = 0; i != OutStr.length(); ++i)
  456. if (OutStr[i] == '\n') { // Left justify
  457. OutStr[i] = '\\';
  458. OutStr.insert(OutStr.begin()+i+1, 'l');
  459. }
  460. return OutStr;
  461. }
  462. };
  463. } // end namespace llvm
  464. void MachineFunction::viewCFG() const
  465. {
  466. #ifndef NDEBUG
  467. ViewGraph(this, "mf" + getName());
  468. #else
  469. errs() << "MachineFunction::viewCFG is only available in debug builds on "
  470. << "systems with Graphviz or gv!\n";
  471. #endif // NDEBUG
  472. }
  473. void MachineFunction::viewCFGOnly() const
  474. {
  475. #ifndef NDEBUG
  476. ViewGraph(this, "mf" + getName(), true);
  477. #else
  478. errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
  479. << "systems with Graphviz or gv!\n";
  480. #endif // NDEBUG
  481. }
  482. /// Add the specified physical register as a live-in value and
  483. /// create a corresponding virtual register for it.
  484. unsigned MachineFunction::addLiveIn(unsigned PReg,
  485. const TargetRegisterClass *RC) {
  486. MachineRegisterInfo &MRI = getRegInfo();
  487. unsigned VReg = MRI.getLiveInVirtReg(PReg);
  488. if (VReg) {
  489. const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
  490. (void)VRegRC;
  491. // A physical register can be added several times.
  492. // Between two calls, the register class of the related virtual register
  493. // may have been constrained to match some operation constraints.
  494. // In that case, check that the current register class includes the
  495. // physical register and is a sub class of the specified RC.
  496. assert((VRegRC == RC || (VRegRC->contains(PReg) &&
  497. RC->hasSubClassEq(VRegRC))) &&
  498. "Register class mismatch!");
  499. return VReg;
  500. }
  501. VReg = MRI.createVirtualRegister(RC);
  502. MRI.addLiveIn(PReg, VReg);
  503. return VReg;
  504. }
  505. /// Return the MCSymbol for the specified non-empty jump table.
  506. /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
  507. /// normal 'L' label is returned.
  508. MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
  509. bool isLinkerPrivate) const {
  510. const DataLayout &DL = getDataLayout();
  511. assert(JumpTableInfo && "No jump tables");
  512. assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
  513. StringRef Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix()
  514. : DL.getPrivateGlobalPrefix();
  515. SmallString<60> Name;
  516. raw_svector_ostream(Name)
  517. << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
  518. return Ctx.getOrCreateSymbol(Name);
  519. }
  520. /// Return a function-local symbol to represent the PIC base.
  521. MCSymbol *MachineFunction::getPICBaseSymbol() const {
  522. const DataLayout &DL = getDataLayout();
  523. return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
  524. Twine(getFunctionNumber()) + "$pb");
  525. }
  526. /// \name Exception Handling
  527. /// \{
  528. LandingPadInfo &
  529. MachineFunction::getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad) {
  530. unsigned N = LandingPads.size();
  531. for (unsigned i = 0; i < N; ++i) {
  532. LandingPadInfo &LP = LandingPads[i];
  533. if (LP.LandingPadBlock == LandingPad)
  534. return LP;
  535. }
  536. LandingPads.push_back(LandingPadInfo(LandingPad));
  537. return LandingPads[N];
  538. }
  539. void MachineFunction::addInvoke(MachineBasicBlock *LandingPad,
  540. MCSymbol *BeginLabel, MCSymbol *EndLabel) {
  541. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  542. LP.BeginLabels.push_back(BeginLabel);
  543. LP.EndLabels.push_back(EndLabel);
  544. }
  545. MCSymbol *MachineFunction::addLandingPad(MachineBasicBlock *LandingPad) {
  546. MCSymbol *LandingPadLabel = Ctx.createTempSymbol();
  547. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  548. LP.LandingPadLabel = LandingPadLabel;
  549. const Instruction *FirstI = LandingPad->getBasicBlock()->getFirstNonPHI();
  550. if (const auto *LPI = dyn_cast<LandingPadInst>(FirstI)) {
  551. if (const auto *PF =
  552. dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts()))
  553. getMMI().addPersonality(PF);
  554. if (LPI->isCleanup())
  555. addCleanup(LandingPad);
  556. // FIXME: New EH - Add the clauses in reverse order. This isn't 100%
  557. // correct, but we need to do it this way because of how the DWARF EH
  558. // emitter processes the clauses.
  559. for (unsigned I = LPI->getNumClauses(); I != 0; --I) {
  560. Value *Val = LPI->getClause(I - 1);
  561. if (LPI->isCatch(I - 1)) {
  562. addCatchTypeInfo(LandingPad,
  563. dyn_cast<GlobalValue>(Val->stripPointerCasts()));
  564. } else {
  565. // Add filters in a list.
  566. auto *CVal = cast<Constant>(Val);
  567. SmallVector<const GlobalValue *, 4> FilterList;
  568. for (User::op_iterator II = CVal->op_begin(), IE = CVal->op_end();
  569. II != IE; ++II)
  570. FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts()));
  571. addFilterTypeInfo(LandingPad, FilterList);
  572. }
  573. }
  574. } else if (const auto *CPI = dyn_cast<CatchPadInst>(FirstI)) {
  575. for (unsigned I = CPI->getNumArgOperands(); I != 0; --I) {
  576. Value *TypeInfo = CPI->getArgOperand(I - 1)->stripPointerCasts();
  577. addCatchTypeInfo(LandingPad, dyn_cast<GlobalValue>(TypeInfo));
  578. }
  579. } else {
  580. assert(isa<CleanupPadInst>(FirstI) && "Invalid landingpad!");
  581. }
  582. return LandingPadLabel;
  583. }
  584. void MachineFunction::addCatchTypeInfo(MachineBasicBlock *LandingPad,
  585. ArrayRef<const GlobalValue *> TyInfo) {
  586. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  587. for (unsigned N = TyInfo.size(); N; --N)
  588. LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1]));
  589. }
  590. void MachineFunction::addFilterTypeInfo(MachineBasicBlock *LandingPad,
  591. ArrayRef<const GlobalValue *> TyInfo) {
  592. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  593. std::vector<unsigned> IdsInFilter(TyInfo.size());
  594. for (unsigned I = 0, E = TyInfo.size(); I != E; ++I)
  595. IdsInFilter[I] = getTypeIDFor(TyInfo[I]);
  596. LP.TypeIds.push_back(getFilterIDFor(IdsInFilter));
  597. }
  598. void MachineFunction::tidyLandingPads(DenseMap<MCSymbol *, uintptr_t> *LPMap,
  599. bool TidyIfNoBeginLabels) {
  600. for (unsigned i = 0; i != LandingPads.size(); ) {
  601. LandingPadInfo &LandingPad = LandingPads[i];
  602. if (LandingPad.LandingPadLabel &&
  603. !LandingPad.LandingPadLabel->isDefined() &&
  604. (!LPMap || (*LPMap)[LandingPad.LandingPadLabel] == 0))
  605. LandingPad.LandingPadLabel = nullptr;
  606. // Special case: we *should* emit LPs with null LP MBB. This indicates
  607. // "nounwind" case.
  608. if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) {
  609. LandingPads.erase(LandingPads.begin() + i);
  610. continue;
  611. }
  612. if (TidyIfNoBeginLabels) {
  613. for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) {
  614. MCSymbol *BeginLabel = LandingPad.BeginLabels[j];
  615. MCSymbol *EndLabel = LandingPad.EndLabels[j];
  616. if ((BeginLabel->isDefined() || (LPMap && (*LPMap)[BeginLabel] != 0)) &&
  617. (EndLabel->isDefined() || (LPMap && (*LPMap)[EndLabel] != 0)))
  618. continue;
  619. LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j);
  620. LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j);
  621. --j;
  622. --e;
  623. }
  624. // Remove landing pads with no try-ranges.
  625. if (LandingPads[i].BeginLabels.empty()) {
  626. LandingPads.erase(LandingPads.begin() + i);
  627. continue;
  628. }
  629. }
  630. // If there is no landing pad, ensure that the list of typeids is empty.
  631. // If the only typeid is a cleanup, this is the same as having no typeids.
  632. if (!LandingPad.LandingPadBlock ||
  633. (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0]))
  634. LandingPad.TypeIds.clear();
  635. ++i;
  636. }
  637. }
  638. void MachineFunction::addCleanup(MachineBasicBlock *LandingPad) {
  639. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  640. LP.TypeIds.push_back(0);
  641. }
  642. void MachineFunction::addSEHCatchHandler(MachineBasicBlock *LandingPad,
  643. const Function *Filter,
  644. const BlockAddress *RecoverBA) {
  645. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  646. SEHHandler Handler;
  647. Handler.FilterOrFinally = Filter;
  648. Handler.RecoverBA = RecoverBA;
  649. LP.SEHHandlers.push_back(Handler);
  650. }
  651. void MachineFunction::addSEHCleanupHandler(MachineBasicBlock *LandingPad,
  652. const Function *Cleanup) {
  653. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  654. SEHHandler Handler;
  655. Handler.FilterOrFinally = Cleanup;
  656. Handler.RecoverBA = nullptr;
  657. LP.SEHHandlers.push_back(Handler);
  658. }
  659. void MachineFunction::setCallSiteLandingPad(MCSymbol *Sym,
  660. ArrayRef<unsigned> Sites) {
  661. LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end());
  662. }
  663. unsigned MachineFunction::getTypeIDFor(const GlobalValue *TI) {
  664. for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
  665. if (TypeInfos[i] == TI) return i + 1;
  666. TypeInfos.push_back(TI);
  667. return TypeInfos.size();
  668. }
  669. int MachineFunction::getFilterIDFor(std::vector<unsigned> &TyIds) {
  670. // If the new filter coincides with the tail of an existing filter, then
  671. // re-use the existing filter. Folding filters more than this requires
  672. // re-ordering filters and/or their elements - probably not worth it.
  673. for (std::vector<unsigned>::iterator I = FilterEnds.begin(),
  674. E = FilterEnds.end(); I != E; ++I) {
  675. unsigned i = *I, j = TyIds.size();
  676. while (i && j)
  677. if (FilterIds[--i] != TyIds[--j])
  678. goto try_next;
  679. if (!j)
  680. // The new filter coincides with range [i, end) of the existing filter.
  681. return -(1 + i);
  682. try_next:;
  683. }
  684. // Add the new filter.
  685. int FilterID = -(1 + FilterIds.size());
  686. FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
  687. FilterIds.insert(FilterIds.end(), TyIds.begin(), TyIds.end());
  688. FilterEnds.push_back(FilterIds.size());
  689. FilterIds.push_back(0); // terminator
  690. return FilterID;
  691. }
  692. /// \}
  693. //===----------------------------------------------------------------------===//
  694. // MachineJumpTableInfo implementation
  695. //===----------------------------------------------------------------------===//
  696. /// Return the size of each entry in the jump table.
  697. unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
  698. // The size of a jump table entry is 4 bytes unless the entry is just the
  699. // address of a block, in which case it is the pointer size.
  700. switch (getEntryKind()) {
  701. case MachineJumpTableInfo::EK_BlockAddress:
  702. return TD.getPointerSize();
  703. case MachineJumpTableInfo::EK_GPRel64BlockAddress:
  704. return 8;
  705. case MachineJumpTableInfo::EK_GPRel32BlockAddress:
  706. case MachineJumpTableInfo::EK_LabelDifference32:
  707. case MachineJumpTableInfo::EK_Custom32:
  708. return 4;
  709. case MachineJumpTableInfo::EK_Inline:
  710. return 0;
  711. }
  712. llvm_unreachable("Unknown jump table encoding!");
  713. }
  714. /// Return the alignment of each entry in the jump table.
  715. unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
  716. // The alignment of a jump table entry is the alignment of int32 unless the
  717. // entry is just the address of a block, in which case it is the pointer
  718. // alignment.
  719. switch (getEntryKind()) {
  720. case MachineJumpTableInfo::EK_BlockAddress:
  721. return TD.getPointerABIAlignment(0);
  722. case MachineJumpTableInfo::EK_GPRel64BlockAddress:
  723. return TD.getABIIntegerTypeAlignment(64);
  724. case MachineJumpTableInfo::EK_GPRel32BlockAddress:
  725. case MachineJumpTableInfo::EK_LabelDifference32:
  726. case MachineJumpTableInfo::EK_Custom32:
  727. return TD.getABIIntegerTypeAlignment(32);
  728. case MachineJumpTableInfo::EK_Inline:
  729. return 1;
  730. }
  731. llvm_unreachable("Unknown jump table encoding!");
  732. }
  733. /// Create a new jump table entry in the jump table info.
  734. unsigned MachineJumpTableInfo::createJumpTableIndex(
  735. const std::vector<MachineBasicBlock*> &DestBBs) {
  736. assert(!DestBBs.empty() && "Cannot create an empty jump table!");
  737. JumpTables.push_back(MachineJumpTableEntry(DestBBs));
  738. return JumpTables.size()-1;
  739. }
  740. /// If Old is the target of any jump tables, update the jump tables to branch
  741. /// to New instead.
  742. bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
  743. MachineBasicBlock *New) {
  744. assert(Old != New && "Not making a change?");
  745. bool MadeChange = false;
  746. for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
  747. ReplaceMBBInJumpTable(i, Old, New);
  748. return MadeChange;
  749. }
  750. /// If Old is a target of the jump tables, update the jump table to branch to
  751. /// New instead.
  752. bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
  753. MachineBasicBlock *Old,
  754. MachineBasicBlock *New) {
  755. assert(Old != New && "Not making a change?");
  756. bool MadeChange = false;
  757. MachineJumpTableEntry &JTE = JumpTables[Idx];
  758. for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
  759. if (JTE.MBBs[j] == Old) {
  760. JTE.MBBs[j] = New;
  761. MadeChange = true;
  762. }
  763. return MadeChange;
  764. }
  765. void MachineJumpTableInfo::print(raw_ostream &OS) const {
  766. if (JumpTables.empty()) return;
  767. OS << "Jump Tables:\n";
  768. for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
  769. OS << printJumpTableEntryReference(i) << ": ";
  770. for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
  771. OS << ' ' << printMBBReference(*JumpTables[i].MBBs[j]);
  772. }
  773. OS << '\n';
  774. }
  775. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  776. LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); }
  777. #endif
  778. Printable llvm::printJumpTableEntryReference(unsigned Idx) {
  779. return Printable([Idx](raw_ostream &OS) { OS << "%jump-table." << Idx; });
  780. }
  781. //===----------------------------------------------------------------------===//
  782. // MachineConstantPool implementation
  783. //===----------------------------------------------------------------------===//
  784. void MachineConstantPoolValue::anchor() {}
  785. Type *MachineConstantPoolEntry::getType() const {
  786. if (isMachineConstantPoolEntry())
  787. return Val.MachineCPVal->getType();
  788. return Val.ConstVal->getType();
  789. }
  790. bool MachineConstantPoolEntry::needsRelocation() const {
  791. if (isMachineConstantPoolEntry())
  792. return true;
  793. return Val.ConstVal->needsRelocation();
  794. }
  795. SectionKind
  796. MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
  797. if (needsRelocation())
  798. return SectionKind::getReadOnlyWithRel();
  799. switch (DL->getTypeAllocSize(getType())) {
  800. case 4:
  801. return SectionKind::getMergeableConst4();
  802. case 8:
  803. return SectionKind::getMergeableConst8();
  804. case 16:
  805. return SectionKind::getMergeableConst16();
  806. case 32:
  807. return SectionKind::getMergeableConst32();
  808. default:
  809. return SectionKind::getReadOnly();
  810. }
  811. }
  812. MachineConstantPool::~MachineConstantPool() {
  813. // A constant may be a member of both Constants and MachineCPVsSharingEntries,
  814. // so keep track of which we've deleted to avoid double deletions.
  815. DenseSet<MachineConstantPoolValue*> Deleted;
  816. for (unsigned i = 0, e = Constants.size(); i != e; ++i)
  817. if (Constants[i].isMachineConstantPoolEntry()) {
  818. Deleted.insert(Constants[i].Val.MachineCPVal);
  819. delete Constants[i].Val.MachineCPVal;
  820. }
  821. for (DenseSet<MachineConstantPoolValue*>::iterator I =
  822. MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
  823. I != E; ++I) {
  824. if (Deleted.count(*I) == 0)
  825. delete *I;
  826. }
  827. }
  828. /// Test whether the given two constants can be allocated the same constant pool
  829. /// entry.
  830. static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
  831. const DataLayout &DL) {
  832. // Handle the trivial case quickly.
  833. if (A == B) return true;
  834. // If they have the same type but weren't the same constant, quickly
  835. // reject them.
  836. if (A->getType() == B->getType()) return false;
  837. // We can't handle structs or arrays.
  838. if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
  839. isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
  840. return false;
  841. // For now, only support constants with the same size.
  842. uint64_t StoreSize = DL.getTypeStoreSize(A->getType());
  843. if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128)
  844. return false;
  845. Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
  846. // Try constant folding a bitcast of both instructions to an integer. If we
  847. // get two identical ConstantInt's, then we are good to share them. We use
  848. // the constant folding APIs to do this so that we get the benefit of
  849. // DataLayout.
  850. if (isa<PointerType>(A->getType()))
  851. A = ConstantFoldCastOperand(Instruction::PtrToInt,
  852. const_cast<Constant *>(A), IntTy, DL);
  853. else if (A->getType() != IntTy)
  854. A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A),
  855. IntTy, DL);
  856. if (isa<PointerType>(B->getType()))
  857. B = ConstantFoldCastOperand(Instruction::PtrToInt,
  858. const_cast<Constant *>(B), IntTy, DL);
  859. else if (B->getType() != IntTy)
  860. B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B),
  861. IntTy, DL);
  862. return A == B;
  863. }
  864. /// Create a new entry in the constant pool or return an existing one.
  865. /// User must specify the log2 of the minimum required alignment for the object.
  866. unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
  867. unsigned Alignment) {
  868. assert(Alignment && "Alignment must be specified!");
  869. if (Alignment > PoolAlignment) PoolAlignment = Alignment;
  870. // Check to see if we already have this constant.
  871. //
  872. // FIXME, this could be made much more efficient for large constant pools.
  873. for (unsigned i = 0, e = Constants.size(); i != e; ++i)
  874. if (!Constants[i].isMachineConstantPoolEntry() &&
  875. CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) {
  876. if ((unsigned)Constants[i].getAlignment() < Alignment)
  877. Constants[i].Alignment = Alignment;
  878. return i;
  879. }
  880. Constants.push_back(MachineConstantPoolEntry(C, Alignment));
  881. return Constants.size()-1;
  882. }
  883. unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
  884. unsigned Alignment) {
  885. assert(Alignment && "Alignment must be specified!");
  886. if (Alignment > PoolAlignment) PoolAlignment = Alignment;
  887. // Check to see if we already have this constant.
  888. //
  889. // FIXME, this could be made much more efficient for large constant pools.
  890. int Idx = V->getExistingMachineCPValue(this, Alignment);
  891. if (Idx != -1) {
  892. MachineCPVsSharingEntries.insert(V);
  893. return (unsigned)Idx;
  894. }
  895. Constants.push_back(MachineConstantPoolEntry(V, Alignment));
  896. return Constants.size()-1;
  897. }
  898. void MachineConstantPool::print(raw_ostream &OS) const {
  899. if (Constants.empty()) return;
  900. OS << "Constant Pool:\n";
  901. for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
  902. OS << " cp#" << i << ": ";
  903. if (Constants[i].isMachineConstantPoolEntry())
  904. Constants[i].Val.MachineCPVal->print(OS);
  905. else
  906. Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
  907. OS << ", align=" << Constants[i].getAlignment();
  908. OS << "\n";
  909. }
  910. }
  911. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  912. LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); }
  913. #endif