MachineFunction.cpp 39 KB

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