MachineFunction.cpp 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495
  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/TargetInstrInfo.h"
  36. #include "llvm/CodeGen/TargetLowering.h"
  37. #include "llvm/CodeGen/TargetRegisterInfo.h"
  38. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  39. #include "llvm/CodeGen/WasmEHFuncInfo.h"
  40. #include "llvm/CodeGen/WinEHFuncInfo.h"
  41. #include "llvm/Config/llvm-config.h"
  42. #include "llvm/IR/Attributes.h"
  43. #include "llvm/IR/BasicBlock.h"
  44. #include "llvm/IR/Constant.h"
  45. #include "llvm/IR/DataLayout.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/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 <type_traits>
  73. #include <utility>
  74. #include <vector>
  75. #include "LiveDebugValues/LiveDebugValues.h"
  76. using namespace llvm;
  77. #define DEBUG_TYPE "codegen"
  78. static cl::opt<unsigned> AlignAllFunctions(
  79. "align-all-functions",
  80. cl::desc("Force the alignment of all functions in log2 format (e.g. 4 "
  81. "means align on 16B boundaries)."),
  82. cl::init(0), cl::Hidden);
  83. static const char *getPropertyName(MachineFunctionProperties::Property Prop) {
  84. using P = MachineFunctionProperties::Property;
  85. // clang-format off
  86. switch(Prop) {
  87. case P::FailedISel: return "FailedISel";
  88. case P::IsSSA: return "IsSSA";
  89. case P::Legalized: return "Legalized";
  90. case P::NoPHIs: return "NoPHIs";
  91. case P::NoVRegs: return "NoVRegs";
  92. case P::RegBankSelected: return "RegBankSelected";
  93. case P::Selected: return "Selected";
  94. case P::TracksLiveness: return "TracksLiveness";
  95. case P::TiedOpsRewritten: return "TiedOpsRewritten";
  96. case P::FailsVerification: return "FailsVerification";
  97. case P::TracksDebugUserValues: return "TracksDebugUserValues";
  98. }
  99. // clang-format on
  100. llvm_unreachable("Invalid machine function property");
  101. }
  102. void setUnsafeStackSize(const Function &F, MachineFrameInfo &FrameInfo) {
  103. if (!F.hasFnAttribute(Attribute::SafeStack))
  104. return;
  105. auto *Existing =
  106. dyn_cast_or_null<MDTuple>(F.getMetadata(LLVMContext::MD_annotation));
  107. if (!Existing || Existing->getNumOperands() != 2)
  108. return;
  109. auto *MetadataName = "unsafe-stack-size";
  110. if (auto &N = Existing->getOperand(0)) {
  111. if (cast<MDString>(N.get())->getString() == MetadataName) {
  112. if (auto &Op = Existing->getOperand(1)) {
  113. auto Val = mdconst::extract<ConstantInt>(Op)->getZExtValue();
  114. FrameInfo.setUnsafeStackSize(Val);
  115. }
  116. }
  117. }
  118. }
  119. // Pin the vtable to this file.
  120. void MachineFunction::Delegate::anchor() {}
  121. void MachineFunctionProperties::print(raw_ostream &OS) const {
  122. const char *Separator = "";
  123. for (BitVector::size_type I = 0; I < Properties.size(); ++I) {
  124. if (!Properties[I])
  125. continue;
  126. OS << Separator << getPropertyName(static_cast<Property>(I));
  127. Separator = ", ";
  128. }
  129. }
  130. //===----------------------------------------------------------------------===//
  131. // MachineFunction implementation
  132. //===----------------------------------------------------------------------===//
  133. // Out-of-line virtual method.
  134. MachineFunctionInfo::~MachineFunctionInfo() = default;
  135. void ilist_alloc_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
  136. MBB->getParent()->deleteMachineBasicBlock(MBB);
  137. }
  138. static inline Align getFnStackAlignment(const TargetSubtargetInfo *STI,
  139. const Function &F) {
  140. if (auto MA = F.getFnStackAlign())
  141. return *MA;
  142. return STI->getFrameLowering()->getStackAlign();
  143. }
  144. MachineFunction::MachineFunction(Function &F, const LLVMTargetMachine &Target,
  145. const TargetSubtargetInfo &STI,
  146. unsigned FunctionNum, MachineModuleInfo &mmi)
  147. : F(F), Target(Target), STI(&STI), Ctx(mmi.getContext()), MMI(mmi) {
  148. FunctionNumber = FunctionNum;
  149. init();
  150. }
  151. void MachineFunction::handleInsertion(MachineInstr &MI) {
  152. if (TheDelegate)
  153. TheDelegate->MF_HandleInsertion(MI);
  154. }
  155. void MachineFunction::handleRemoval(MachineInstr &MI) {
  156. if (TheDelegate)
  157. TheDelegate->MF_HandleRemoval(MI);
  158. }
  159. void MachineFunction::init() {
  160. // Assume the function starts in SSA form with correct liveness.
  161. Properties.set(MachineFunctionProperties::Property::IsSSA);
  162. Properties.set(MachineFunctionProperties::Property::TracksLiveness);
  163. if (STI->getRegisterInfo())
  164. RegInfo = new (Allocator) MachineRegisterInfo(this);
  165. else
  166. RegInfo = nullptr;
  167. MFInfo = nullptr;
  168. // We can realign the stack if the target supports it and the user hasn't
  169. // explicitly asked us not to.
  170. bool CanRealignSP = STI->getFrameLowering()->isStackRealignable() &&
  171. !F.hasFnAttribute("no-realign-stack");
  172. FrameInfo = new (Allocator) MachineFrameInfo(
  173. getFnStackAlignment(STI, F), /*StackRealignable=*/CanRealignSP,
  174. /*ForcedRealign=*/CanRealignSP &&
  175. F.hasFnAttribute(Attribute::StackAlignment));
  176. setUnsafeStackSize(F, *FrameInfo);
  177. if (F.hasFnAttribute(Attribute::StackAlignment))
  178. FrameInfo->ensureMaxAlignment(*F.getFnStackAlign());
  179. ConstantPool = new (Allocator) MachineConstantPool(getDataLayout());
  180. Alignment = STI->getTargetLowering()->getMinFunctionAlignment();
  181. // FIXME: Shouldn't use pref alignment if explicit alignment is set on F.
  182. // FIXME: Use Function::hasOptSize().
  183. if (!F.hasFnAttribute(Attribute::OptimizeForSize))
  184. Alignment = std::max(Alignment,
  185. STI->getTargetLowering()->getPrefFunctionAlignment());
  186. if (AlignAllFunctions)
  187. Alignment = Align(1ULL << AlignAllFunctions);
  188. JumpTableInfo = nullptr;
  189. if (isFuncletEHPersonality(classifyEHPersonality(
  190. F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
  191. WinEHInfo = new (Allocator) WinEHFuncInfo();
  192. }
  193. if (isScopedEHPersonality(classifyEHPersonality(
  194. F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
  195. WasmEHInfo = new (Allocator) WasmEHFuncInfo();
  196. }
  197. assert(Target.isCompatibleDataLayout(getDataLayout()) &&
  198. "Can't create a MachineFunction using a Module with a "
  199. "Target-incompatible DataLayout attached\n");
  200. PSVManager = std::make_unique<PseudoSourceValueManager>(getTarget());
  201. }
  202. void MachineFunction::initTargetMachineFunctionInfo(
  203. const TargetSubtargetInfo &STI) {
  204. assert(!MFInfo && "MachineFunctionInfo already set");
  205. MFInfo = Target.createMachineFunctionInfo(Allocator, F, &STI);
  206. }
  207. MachineFunction::~MachineFunction() {
  208. clear();
  209. }
  210. void MachineFunction::clear() {
  211. Properties.reset();
  212. // Don't call destructors on MachineInstr and MachineOperand. All of their
  213. // memory comes from the BumpPtrAllocator which is about to be purged.
  214. //
  215. // Do call MachineBasicBlock destructors, it contains std::vectors.
  216. for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
  217. I->Insts.clearAndLeakNodesUnsafely();
  218. MBBNumbering.clear();
  219. InstructionRecycler.clear(Allocator);
  220. OperandRecycler.clear(Allocator);
  221. BasicBlockRecycler.clear(Allocator);
  222. CodeViewAnnotations.clear();
  223. VariableDbgInfos.clear();
  224. if (RegInfo) {
  225. RegInfo->~MachineRegisterInfo();
  226. Allocator.Deallocate(RegInfo);
  227. }
  228. if (MFInfo) {
  229. MFInfo->~MachineFunctionInfo();
  230. Allocator.Deallocate(MFInfo);
  231. }
  232. FrameInfo->~MachineFrameInfo();
  233. Allocator.Deallocate(FrameInfo);
  234. ConstantPool->~MachineConstantPool();
  235. Allocator.Deallocate(ConstantPool);
  236. if (JumpTableInfo) {
  237. JumpTableInfo->~MachineJumpTableInfo();
  238. Allocator.Deallocate(JumpTableInfo);
  239. }
  240. if (WinEHInfo) {
  241. WinEHInfo->~WinEHFuncInfo();
  242. Allocator.Deallocate(WinEHInfo);
  243. }
  244. if (WasmEHInfo) {
  245. WasmEHInfo->~WasmEHFuncInfo();
  246. Allocator.Deallocate(WasmEHInfo);
  247. }
  248. }
  249. const DataLayout &MachineFunction::getDataLayout() const {
  250. return F.getParent()->getDataLayout();
  251. }
  252. /// Get the JumpTableInfo for this function.
  253. /// If it does not already exist, allocate one.
  254. MachineJumpTableInfo *MachineFunction::
  255. getOrCreateJumpTableInfo(unsigned EntryKind) {
  256. if (JumpTableInfo) return JumpTableInfo;
  257. JumpTableInfo = new (Allocator)
  258. MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
  259. return JumpTableInfo;
  260. }
  261. DenormalMode MachineFunction::getDenormalMode(const fltSemantics &FPType) const {
  262. return F.getDenormalMode(FPType);
  263. }
  264. /// Should we be emitting segmented stack stuff for the function
  265. bool MachineFunction::shouldSplitStack() const {
  266. return getFunction().hasFnAttribute("split-stack");
  267. }
  268. [[nodiscard]] unsigned
  269. MachineFunction::addFrameInst(const MCCFIInstruction &Inst) {
  270. FrameInstructions.push_back(Inst);
  271. return FrameInstructions.size() - 1;
  272. }
  273. /// This discards all of the MachineBasicBlock numbers and recomputes them.
  274. /// This guarantees that the MBB numbers are sequential, dense, and match the
  275. /// ordering of the blocks within the function. If a specific MachineBasicBlock
  276. /// is specified, only that block and those after it are renumbered.
  277. void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
  278. if (empty()) { MBBNumbering.clear(); return; }
  279. MachineFunction::iterator MBBI, E = end();
  280. if (MBB == nullptr)
  281. MBBI = begin();
  282. else
  283. MBBI = MBB->getIterator();
  284. // Figure out the block number this should have.
  285. unsigned BlockNo = 0;
  286. if (MBBI != begin())
  287. BlockNo = std::prev(MBBI)->getNumber() + 1;
  288. for (; MBBI != E; ++MBBI, ++BlockNo) {
  289. if (MBBI->getNumber() != (int)BlockNo) {
  290. // Remove use of the old number.
  291. if (MBBI->getNumber() != -1) {
  292. assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
  293. "MBB number mismatch!");
  294. MBBNumbering[MBBI->getNumber()] = nullptr;
  295. }
  296. // If BlockNo is already taken, set that block's number to -1.
  297. if (MBBNumbering[BlockNo])
  298. MBBNumbering[BlockNo]->setNumber(-1);
  299. MBBNumbering[BlockNo] = &*MBBI;
  300. MBBI->setNumber(BlockNo);
  301. }
  302. }
  303. // Okay, all the blocks are renumbered. If we have compactified the block
  304. // numbering, shrink MBBNumbering now.
  305. assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
  306. MBBNumbering.resize(BlockNo);
  307. }
  308. /// This method iterates over the basic blocks and assigns their IsBeginSection
  309. /// and IsEndSection fields. This must be called after MBB layout is finalized
  310. /// and the SectionID's are assigned to MBBs.
  311. void MachineFunction::assignBeginEndSections() {
  312. front().setIsBeginSection();
  313. auto CurrentSectionID = front().getSectionID();
  314. for (auto MBBI = std::next(begin()), E = end(); MBBI != E; ++MBBI) {
  315. if (MBBI->getSectionID() == CurrentSectionID)
  316. continue;
  317. MBBI->setIsBeginSection();
  318. std::prev(MBBI)->setIsEndSection();
  319. CurrentSectionID = MBBI->getSectionID();
  320. }
  321. back().setIsEndSection();
  322. }
  323. /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'.
  324. MachineInstr *MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
  325. DebugLoc DL,
  326. bool NoImplicit) {
  327. return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
  328. MachineInstr(*this, MCID, std::move(DL), NoImplicit);
  329. }
  330. /// Create a new MachineInstr which is a copy of the 'Orig' instruction,
  331. /// identical in all ways except the instruction has no parent, prev, or next.
  332. MachineInstr *
  333. MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
  334. return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
  335. MachineInstr(*this, *Orig);
  336. }
  337. MachineInstr &MachineFunction::cloneMachineInstrBundle(
  338. MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
  339. const MachineInstr &Orig) {
  340. MachineInstr *FirstClone = nullptr;
  341. MachineBasicBlock::const_instr_iterator I = Orig.getIterator();
  342. while (true) {
  343. MachineInstr *Cloned = CloneMachineInstr(&*I);
  344. MBB.insert(InsertBefore, Cloned);
  345. if (FirstClone == nullptr) {
  346. FirstClone = Cloned;
  347. } else {
  348. Cloned->bundleWithPred();
  349. }
  350. if (!I->isBundledWithSucc())
  351. break;
  352. ++I;
  353. }
  354. // Copy over call site info to the cloned instruction if needed. If Orig is in
  355. // a bundle, copyCallSiteInfo takes care of finding the call instruction in
  356. // the bundle.
  357. if (Orig.shouldUpdateCallSiteInfo())
  358. copyCallSiteInfo(&Orig, FirstClone);
  359. return *FirstClone;
  360. }
  361. /// Delete the given MachineInstr.
  362. ///
  363. /// This function also serves as the MachineInstr destructor - the real
  364. /// ~MachineInstr() destructor must be empty.
  365. void MachineFunction::deleteMachineInstr(MachineInstr *MI) {
  366. // Verify that a call site info is at valid state. This assertion should
  367. // be triggered during the implementation of support for the
  368. // call site info of a new architecture. If the assertion is triggered,
  369. // back trace will tell where to insert a call to updateCallSiteInfo().
  370. assert((!MI->isCandidateForCallSiteEntry() ||
  371. CallSitesInfo.find(MI) == CallSitesInfo.end()) &&
  372. "Call site info was not updated!");
  373. // Strip it for parts. The operand array and the MI object itself are
  374. // independently recyclable.
  375. if (MI->Operands)
  376. deallocateOperandArray(MI->CapOperands, MI->Operands);
  377. // Don't call ~MachineInstr() which must be trivial anyway because
  378. // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
  379. // destructors.
  380. InstructionRecycler.Deallocate(Allocator, MI);
  381. }
  382. /// Allocate a new MachineBasicBlock. Use this instead of
  383. /// `new MachineBasicBlock'.
  384. MachineBasicBlock *
  385. MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
  386. MachineBasicBlock *MBB =
  387. new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
  388. MachineBasicBlock(*this, bb);
  389. // Set BBID for `-basic-block=sections=labels` and
  390. // `-basic-block-sections=list` to allow robust mapping of profiles to basic
  391. // blocks.
  392. if (Target.getBBSectionsType() == BasicBlockSection::Labels ||
  393. Target.getBBSectionsType() == BasicBlockSection::List)
  394. MBB->setBBID(NextBBID++);
  395. return MBB;
  396. }
  397. /// Delete the given MachineBasicBlock.
  398. void MachineFunction::deleteMachineBasicBlock(MachineBasicBlock *MBB) {
  399. assert(MBB->getParent() == this && "MBB parent mismatch!");
  400. // Clean up any references to MBB in jump tables before deleting it.
  401. if (JumpTableInfo)
  402. JumpTableInfo->RemoveMBBFromJumpTables(MBB);
  403. MBB->~MachineBasicBlock();
  404. BasicBlockRecycler.Deallocate(Allocator, MBB);
  405. }
  406. MachineMemOperand *MachineFunction::getMachineMemOperand(
  407. MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s,
  408. Align base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges,
  409. SyncScope::ID SSID, AtomicOrdering Ordering,
  410. AtomicOrdering FailureOrdering) {
  411. return new (Allocator)
  412. MachineMemOperand(PtrInfo, f, s, base_alignment, AAInfo, Ranges,
  413. SSID, Ordering, FailureOrdering);
  414. }
  415. MachineMemOperand *MachineFunction::getMachineMemOperand(
  416. MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, LLT MemTy,
  417. Align base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges,
  418. SyncScope::ID SSID, AtomicOrdering Ordering,
  419. AtomicOrdering FailureOrdering) {
  420. return new (Allocator)
  421. MachineMemOperand(PtrInfo, f, MemTy, base_alignment, AAInfo, Ranges, SSID,
  422. Ordering, FailureOrdering);
  423. }
  424. MachineMemOperand *MachineFunction::getMachineMemOperand(
  425. const MachineMemOperand *MMO, const MachinePointerInfo &PtrInfo, uint64_t Size) {
  426. return new (Allocator)
  427. MachineMemOperand(PtrInfo, MMO->getFlags(), Size, MMO->getBaseAlign(),
  428. AAMDNodes(), nullptr, MMO->getSyncScopeID(),
  429. MMO->getSuccessOrdering(), MMO->getFailureOrdering());
  430. }
  431. MachineMemOperand *MachineFunction::getMachineMemOperand(
  432. const MachineMemOperand *MMO, const MachinePointerInfo &PtrInfo, LLT Ty) {
  433. return new (Allocator)
  434. MachineMemOperand(PtrInfo, MMO->getFlags(), Ty, MMO->getBaseAlign(),
  435. AAMDNodes(), nullptr, MMO->getSyncScopeID(),
  436. MMO->getSuccessOrdering(), MMO->getFailureOrdering());
  437. }
  438. MachineMemOperand *
  439. MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
  440. int64_t Offset, LLT Ty) {
  441. const MachinePointerInfo &PtrInfo = MMO->getPointerInfo();
  442. // If there is no pointer value, the offset isn't tracked so we need to adjust
  443. // the base alignment.
  444. Align Alignment = PtrInfo.V.isNull()
  445. ? commonAlignment(MMO->getBaseAlign(), Offset)
  446. : MMO->getBaseAlign();
  447. // Do not preserve ranges, since we don't necessarily know what the high bits
  448. // are anymore.
  449. return new (Allocator) MachineMemOperand(
  450. PtrInfo.getWithOffset(Offset), MMO->getFlags(), Ty, Alignment,
  451. MMO->getAAInfo(), nullptr, MMO->getSyncScopeID(),
  452. MMO->getSuccessOrdering(), MMO->getFailureOrdering());
  453. }
  454. MachineMemOperand *
  455. MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
  456. const AAMDNodes &AAInfo) {
  457. MachinePointerInfo MPI = MMO->getValue() ?
  458. MachinePointerInfo(MMO->getValue(), MMO->getOffset()) :
  459. MachinePointerInfo(MMO->getPseudoValue(), MMO->getOffset());
  460. return new (Allocator) MachineMemOperand(
  461. MPI, MMO->getFlags(), MMO->getSize(), MMO->getBaseAlign(), AAInfo,
  462. MMO->getRanges(), MMO->getSyncScopeID(), MMO->getSuccessOrdering(),
  463. MMO->getFailureOrdering());
  464. }
  465. MachineMemOperand *
  466. MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
  467. MachineMemOperand::Flags Flags) {
  468. return new (Allocator) MachineMemOperand(
  469. MMO->getPointerInfo(), Flags, MMO->getSize(), MMO->getBaseAlign(),
  470. MMO->getAAInfo(), MMO->getRanges(), MMO->getSyncScopeID(),
  471. MMO->getSuccessOrdering(), MMO->getFailureOrdering());
  472. }
  473. MachineInstr::ExtraInfo *MachineFunction::createMIExtraInfo(
  474. ArrayRef<MachineMemOperand *> MMOs, MCSymbol *PreInstrSymbol,
  475. MCSymbol *PostInstrSymbol, MDNode *HeapAllocMarker, MDNode *PCSections,
  476. uint32_t CFIType) {
  477. return MachineInstr::ExtraInfo::create(Allocator, MMOs, PreInstrSymbol,
  478. PostInstrSymbol, HeapAllocMarker,
  479. PCSections, CFIType);
  480. }
  481. const char *MachineFunction::createExternalSymbolName(StringRef Name) {
  482. char *Dest = Allocator.Allocate<char>(Name.size() + 1);
  483. llvm::copy(Name, Dest);
  484. Dest[Name.size()] = 0;
  485. return Dest;
  486. }
  487. uint32_t *MachineFunction::allocateRegMask() {
  488. unsigned NumRegs = getSubtarget().getRegisterInfo()->getNumRegs();
  489. unsigned Size = MachineOperand::getRegMaskSize(NumRegs);
  490. uint32_t *Mask = Allocator.Allocate<uint32_t>(Size);
  491. memset(Mask, 0, Size * sizeof(Mask[0]));
  492. return Mask;
  493. }
  494. ArrayRef<int> MachineFunction::allocateShuffleMask(ArrayRef<int> Mask) {
  495. int* AllocMask = Allocator.Allocate<int>(Mask.size());
  496. copy(Mask, AllocMask);
  497. return {AllocMask, Mask.size()};
  498. }
  499. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  500. LLVM_DUMP_METHOD void MachineFunction::dump() const {
  501. print(dbgs());
  502. }
  503. #endif
  504. StringRef MachineFunction::getName() const {
  505. return getFunction().getName();
  506. }
  507. void MachineFunction::print(raw_ostream &OS, const SlotIndexes *Indexes) const {
  508. OS << "# Machine code for function " << getName() << ": ";
  509. getProperties().print(OS);
  510. OS << '\n';
  511. // Print Frame Information
  512. FrameInfo->print(*this, OS);
  513. // Print JumpTable Information
  514. if (JumpTableInfo)
  515. JumpTableInfo->print(OS);
  516. // Print Constant Pool
  517. ConstantPool->print(OS);
  518. const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo();
  519. if (RegInfo && !RegInfo->livein_empty()) {
  520. OS << "Function Live Ins: ";
  521. for (MachineRegisterInfo::livein_iterator
  522. I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
  523. OS << printReg(I->first, TRI);
  524. if (I->second)
  525. OS << " in " << printReg(I->second, TRI);
  526. if (std::next(I) != E)
  527. OS << ", ";
  528. }
  529. OS << '\n';
  530. }
  531. ModuleSlotTracker MST(getFunction().getParent());
  532. MST.incorporateFunction(getFunction());
  533. for (const auto &BB : *this) {
  534. OS << '\n';
  535. // If we print the whole function, print it at its most verbose level.
  536. BB.print(OS, MST, Indexes, /*IsStandalone=*/true);
  537. }
  538. OS << "\n# End machine code for function " << getName() << ".\n\n";
  539. }
  540. /// True if this function needs frame moves for debug or exceptions.
  541. bool MachineFunction::needsFrameMoves() const {
  542. return getMMI().hasDebugInfo() ||
  543. getTarget().Options.ForceDwarfFrameSection ||
  544. F.needsUnwindTableEntry();
  545. }
  546. namespace llvm {
  547. template<>
  548. struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
  549. DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
  550. static std::string getGraphName(const MachineFunction *F) {
  551. return ("CFG for '" + F->getName() + "' function").str();
  552. }
  553. std::string getNodeLabel(const MachineBasicBlock *Node,
  554. const MachineFunction *Graph) {
  555. std::string OutStr;
  556. {
  557. raw_string_ostream OSS(OutStr);
  558. if (isSimple()) {
  559. OSS << printMBBReference(*Node);
  560. if (const BasicBlock *BB = Node->getBasicBlock())
  561. OSS << ": " << BB->getName();
  562. } else
  563. Node->print(OSS);
  564. }
  565. if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
  566. // Process string output to make it nicer...
  567. for (unsigned i = 0; i != OutStr.length(); ++i)
  568. if (OutStr[i] == '\n') { // Left justify
  569. OutStr[i] = '\\';
  570. OutStr.insert(OutStr.begin()+i+1, 'l');
  571. }
  572. return OutStr;
  573. }
  574. };
  575. } // end namespace llvm
  576. void MachineFunction::viewCFG() const
  577. {
  578. #ifndef NDEBUG
  579. ViewGraph(this, "mf" + getName());
  580. #else
  581. errs() << "MachineFunction::viewCFG is only available in debug builds on "
  582. << "systems with Graphviz or gv!\n";
  583. #endif // NDEBUG
  584. }
  585. void MachineFunction::viewCFGOnly() const
  586. {
  587. #ifndef NDEBUG
  588. ViewGraph(this, "mf" + getName(), true);
  589. #else
  590. errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
  591. << "systems with Graphviz or gv!\n";
  592. #endif // NDEBUG
  593. }
  594. /// Add the specified physical register as a live-in value and
  595. /// create a corresponding virtual register for it.
  596. Register MachineFunction::addLiveIn(MCRegister PReg,
  597. const TargetRegisterClass *RC) {
  598. MachineRegisterInfo &MRI = getRegInfo();
  599. Register VReg = MRI.getLiveInVirtReg(PReg);
  600. if (VReg) {
  601. const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
  602. (void)VRegRC;
  603. // A physical register can be added several times.
  604. // Between two calls, the register class of the related virtual register
  605. // may have been constrained to match some operation constraints.
  606. // In that case, check that the current register class includes the
  607. // physical register and is a sub class of the specified RC.
  608. assert((VRegRC == RC || (VRegRC->contains(PReg) &&
  609. RC->hasSubClassEq(VRegRC))) &&
  610. "Register class mismatch!");
  611. return VReg;
  612. }
  613. VReg = MRI.createVirtualRegister(RC);
  614. MRI.addLiveIn(PReg, VReg);
  615. return VReg;
  616. }
  617. /// Return the MCSymbol for the specified non-empty jump table.
  618. /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
  619. /// normal 'L' label is returned.
  620. MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
  621. bool isLinkerPrivate) const {
  622. const DataLayout &DL = getDataLayout();
  623. assert(JumpTableInfo && "No jump tables");
  624. assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
  625. StringRef Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix()
  626. : DL.getPrivateGlobalPrefix();
  627. SmallString<60> Name;
  628. raw_svector_ostream(Name)
  629. << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
  630. return Ctx.getOrCreateSymbol(Name);
  631. }
  632. /// Return a function-local symbol to represent the PIC base.
  633. MCSymbol *MachineFunction::getPICBaseSymbol() const {
  634. const DataLayout &DL = getDataLayout();
  635. return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
  636. Twine(getFunctionNumber()) + "$pb");
  637. }
  638. /// \name Exception Handling
  639. /// \{
  640. LandingPadInfo &
  641. MachineFunction::getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad) {
  642. unsigned N = LandingPads.size();
  643. for (unsigned i = 0; i < N; ++i) {
  644. LandingPadInfo &LP = LandingPads[i];
  645. if (LP.LandingPadBlock == LandingPad)
  646. return LP;
  647. }
  648. LandingPads.push_back(LandingPadInfo(LandingPad));
  649. return LandingPads[N];
  650. }
  651. void MachineFunction::addInvoke(MachineBasicBlock *LandingPad,
  652. MCSymbol *BeginLabel, MCSymbol *EndLabel) {
  653. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  654. LP.BeginLabels.push_back(BeginLabel);
  655. LP.EndLabels.push_back(EndLabel);
  656. }
  657. MCSymbol *MachineFunction::addLandingPad(MachineBasicBlock *LandingPad) {
  658. MCSymbol *LandingPadLabel = Ctx.createTempSymbol();
  659. LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
  660. LP.LandingPadLabel = LandingPadLabel;
  661. const Instruction *FirstI = LandingPad->getBasicBlock()->getFirstNonPHI();
  662. if (const auto *LPI = dyn_cast<LandingPadInst>(FirstI)) {
  663. // If there's no typeid list specified, then "cleanup" is implicit.
  664. // Otherwise, id 0 is reserved for the cleanup action.
  665. if (LPI->isCleanup() && LPI->getNumClauses() != 0)
  666. LP.TypeIds.push_back(0);
  667. // FIXME: New EH - Add the clauses in reverse order. This isn't 100%
  668. // correct, but we need to do it this way because of how the DWARF EH
  669. // emitter processes the clauses.
  670. for (unsigned I = LPI->getNumClauses(); I != 0; --I) {
  671. Value *Val = LPI->getClause(I - 1);
  672. if (LPI->isCatch(I - 1)) {
  673. LP.TypeIds.push_back(
  674. getTypeIDFor(dyn_cast<GlobalValue>(Val->stripPointerCasts())));
  675. } else {
  676. // Add filters in a list.
  677. auto *CVal = cast<Constant>(Val);
  678. SmallVector<unsigned, 4> FilterList;
  679. for (const Use &U : CVal->operands())
  680. FilterList.push_back(
  681. getTypeIDFor(cast<GlobalValue>(U->stripPointerCasts())));
  682. LP.TypeIds.push_back(getFilterIDFor(FilterList));
  683. }
  684. }
  685. } else if (const auto *CPI = dyn_cast<CatchPadInst>(FirstI)) {
  686. for (unsigned I = CPI->arg_size(); I != 0; --I) {
  687. auto *TypeInfo =
  688. dyn_cast<GlobalValue>(CPI->getArgOperand(I - 1)->stripPointerCasts());
  689. LP.TypeIds.push_back(getTypeIDFor(TypeInfo));
  690. }
  691. } else {
  692. assert(isa<CleanupPadInst>(FirstI) && "Invalid landingpad!");
  693. }
  694. return LandingPadLabel;
  695. }
  696. void MachineFunction::setCallSiteLandingPad(MCSymbol *Sym,
  697. ArrayRef<unsigned> Sites) {
  698. LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end());
  699. }
  700. unsigned MachineFunction::getTypeIDFor(const GlobalValue *TI) {
  701. for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
  702. if (TypeInfos[i] == TI) return i + 1;
  703. TypeInfos.push_back(TI);
  704. return TypeInfos.size();
  705. }
  706. int MachineFunction::getFilterIDFor(ArrayRef<unsigned> TyIds) {
  707. // If the new filter coincides with the tail of an existing filter, then
  708. // re-use the existing filter. Folding filters more than this requires
  709. // re-ordering filters and/or their elements - probably not worth it.
  710. for (unsigned i : FilterEnds) {
  711. unsigned j = TyIds.size();
  712. while (i && j)
  713. if (FilterIds[--i] != TyIds[--j])
  714. goto try_next;
  715. if (!j)
  716. // The new filter coincides with range [i, end) of the existing filter.
  717. return -(1 + i);
  718. try_next:;
  719. }
  720. // Add the new filter.
  721. int FilterID = -(1 + FilterIds.size());
  722. FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
  723. llvm::append_range(FilterIds, TyIds);
  724. FilterEnds.push_back(FilterIds.size());
  725. FilterIds.push_back(0); // terminator
  726. return FilterID;
  727. }
  728. MachineFunction::CallSiteInfoMap::iterator
  729. MachineFunction::getCallSiteInfo(const MachineInstr *MI) {
  730. assert(MI->isCandidateForCallSiteEntry() &&
  731. "Call site info refers only to call (MI) candidates");
  732. if (!Target.Options.EmitCallSiteInfo)
  733. return CallSitesInfo.end();
  734. return CallSitesInfo.find(MI);
  735. }
  736. /// Return the call machine instruction or find a call within bundle.
  737. static const MachineInstr *getCallInstr(const MachineInstr *MI) {
  738. if (!MI->isBundle())
  739. return MI;
  740. for (const auto &BMI : make_range(getBundleStart(MI->getIterator()),
  741. getBundleEnd(MI->getIterator())))
  742. if (BMI.isCandidateForCallSiteEntry())
  743. return &BMI;
  744. llvm_unreachable("Unexpected bundle without a call site candidate");
  745. }
  746. void MachineFunction::eraseCallSiteInfo(const MachineInstr *MI) {
  747. assert(MI->shouldUpdateCallSiteInfo() &&
  748. "Call site info refers only to call (MI) candidates or "
  749. "candidates inside bundles");
  750. const MachineInstr *CallMI = getCallInstr(MI);
  751. CallSiteInfoMap::iterator CSIt = getCallSiteInfo(CallMI);
  752. if (CSIt == CallSitesInfo.end())
  753. return;
  754. CallSitesInfo.erase(CSIt);
  755. }
  756. void MachineFunction::copyCallSiteInfo(const MachineInstr *Old,
  757. const MachineInstr *New) {
  758. assert(Old->shouldUpdateCallSiteInfo() &&
  759. "Call site info refers only to call (MI) candidates or "
  760. "candidates inside bundles");
  761. if (!New->isCandidateForCallSiteEntry())
  762. return eraseCallSiteInfo(Old);
  763. const MachineInstr *OldCallMI = getCallInstr(Old);
  764. CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI);
  765. if (CSIt == CallSitesInfo.end())
  766. return;
  767. CallSiteInfo CSInfo = CSIt->second;
  768. CallSitesInfo[New] = CSInfo;
  769. }
  770. void MachineFunction::moveCallSiteInfo(const MachineInstr *Old,
  771. const MachineInstr *New) {
  772. assert(Old->shouldUpdateCallSiteInfo() &&
  773. "Call site info refers only to call (MI) candidates or "
  774. "candidates inside bundles");
  775. if (!New->isCandidateForCallSiteEntry())
  776. return eraseCallSiteInfo(Old);
  777. const MachineInstr *OldCallMI = getCallInstr(Old);
  778. CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI);
  779. if (CSIt == CallSitesInfo.end())
  780. return;
  781. CallSiteInfo CSInfo = std::move(CSIt->second);
  782. CallSitesInfo.erase(CSIt);
  783. CallSitesInfo[New] = CSInfo;
  784. }
  785. void MachineFunction::setDebugInstrNumberingCount(unsigned Num) {
  786. DebugInstrNumberingCount = Num;
  787. }
  788. void MachineFunction::makeDebugValueSubstitution(DebugInstrOperandPair A,
  789. DebugInstrOperandPair B,
  790. unsigned Subreg) {
  791. // Catch any accidental self-loops.
  792. assert(A.first != B.first);
  793. // Don't allow any substitutions _from_ the memory operand number.
  794. assert(A.second != DebugOperandMemNumber);
  795. DebugValueSubstitutions.push_back({A, B, Subreg});
  796. }
  797. void MachineFunction::substituteDebugValuesForInst(const MachineInstr &Old,
  798. MachineInstr &New,
  799. unsigned MaxOperand) {
  800. // If the Old instruction wasn't tracked at all, there is no work to do.
  801. unsigned OldInstrNum = Old.peekDebugInstrNum();
  802. if (!OldInstrNum)
  803. return;
  804. // Iterate over all operands looking for defs to create substitutions for.
  805. // Avoid creating new instr numbers unless we create a new substitution.
  806. // While this has no functional effect, it risks confusing someone reading
  807. // MIR output.
  808. // Examine all the operands, or the first N specified by the caller.
  809. MaxOperand = std::min(MaxOperand, Old.getNumOperands());
  810. for (unsigned int I = 0; I < MaxOperand; ++I) {
  811. const auto &OldMO = Old.getOperand(I);
  812. auto &NewMO = New.getOperand(I);
  813. (void)NewMO;
  814. if (!OldMO.isReg() || !OldMO.isDef())
  815. continue;
  816. assert(NewMO.isDef());
  817. unsigned NewInstrNum = New.getDebugInstrNum();
  818. makeDebugValueSubstitution(std::make_pair(OldInstrNum, I),
  819. std::make_pair(NewInstrNum, I));
  820. }
  821. }
  822. auto MachineFunction::salvageCopySSA(
  823. MachineInstr &MI, DenseMap<Register, DebugInstrOperandPair> &DbgPHICache)
  824. -> DebugInstrOperandPair {
  825. const TargetInstrInfo &TII = *getSubtarget().getInstrInfo();
  826. // Check whether this copy-like instruction has already been salvaged into
  827. // an operand pair.
  828. Register Dest;
  829. if (auto CopyDstSrc = TII.isCopyInstr(MI)) {
  830. Dest = CopyDstSrc->Destination->getReg();
  831. } else {
  832. assert(MI.isSubregToReg());
  833. Dest = MI.getOperand(0).getReg();
  834. }
  835. auto CacheIt = DbgPHICache.find(Dest);
  836. if (CacheIt != DbgPHICache.end())
  837. return CacheIt->second;
  838. // Calculate the instruction number to use, or install a DBG_PHI.
  839. auto OperandPair = salvageCopySSAImpl(MI);
  840. DbgPHICache.insert({Dest, OperandPair});
  841. return OperandPair;
  842. }
  843. auto MachineFunction::salvageCopySSAImpl(MachineInstr &MI)
  844. -> DebugInstrOperandPair {
  845. MachineRegisterInfo &MRI = getRegInfo();
  846. const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
  847. const TargetInstrInfo &TII = *getSubtarget().getInstrInfo();
  848. // Chase the value read by a copy-like instruction back to the instruction
  849. // that ultimately _defines_ that value. This may pass:
  850. // * Through multiple intermediate copies, including subregister moves /
  851. // copies,
  852. // * Copies from physical registers that must then be traced back to the
  853. // defining instruction,
  854. // * Or, physical registers may be live-in to (only) the entry block, which
  855. // requires a DBG_PHI to be created.
  856. // We can pursue this problem in that order: trace back through copies,
  857. // optionally through a physical register, to a defining instruction. We
  858. // should never move from physreg to vreg. As we're still in SSA form, no need
  859. // to worry about partial definitions of registers.
  860. // Helper lambda to interpret a copy-like instruction. Takes instruction,
  861. // returns the register read and any subregister identifying which part is
  862. // read.
  863. auto GetRegAndSubreg =
  864. [&](const MachineInstr &Cpy) -> std::pair<Register, unsigned> {
  865. Register NewReg, OldReg;
  866. unsigned SubReg;
  867. if (Cpy.isCopy()) {
  868. OldReg = Cpy.getOperand(0).getReg();
  869. NewReg = Cpy.getOperand(1).getReg();
  870. SubReg = Cpy.getOperand(1).getSubReg();
  871. } else if (Cpy.isSubregToReg()) {
  872. OldReg = Cpy.getOperand(0).getReg();
  873. NewReg = Cpy.getOperand(2).getReg();
  874. SubReg = Cpy.getOperand(3).getImm();
  875. } else {
  876. auto CopyDetails = *TII.isCopyInstr(Cpy);
  877. const MachineOperand &Src = *CopyDetails.Source;
  878. const MachineOperand &Dest = *CopyDetails.Destination;
  879. OldReg = Dest.getReg();
  880. NewReg = Src.getReg();
  881. SubReg = Src.getSubReg();
  882. }
  883. return {NewReg, SubReg};
  884. };
  885. // First seek either the defining instruction, or a copy from a physreg.
  886. // During search, the current state is the current copy instruction, and which
  887. // register we've read. Accumulate qualifying subregisters into SubregsSeen;
  888. // deal with those later.
  889. auto State = GetRegAndSubreg(MI);
  890. auto CurInst = MI.getIterator();
  891. SmallVector<unsigned, 4> SubregsSeen;
  892. while (true) {
  893. // If we've found a copy from a physreg, first portion of search is over.
  894. if (!State.first.isVirtual())
  895. break;
  896. // Record any subregister qualifier.
  897. if (State.second)
  898. SubregsSeen.push_back(State.second);
  899. assert(MRI.hasOneDef(State.first));
  900. MachineInstr &Inst = *MRI.def_begin(State.first)->getParent();
  901. CurInst = Inst.getIterator();
  902. // Any non-copy instruction is the defining instruction we're seeking.
  903. if (!Inst.isCopyLike() && !TII.isCopyInstr(Inst))
  904. break;
  905. State = GetRegAndSubreg(Inst);
  906. };
  907. // Helper lambda to apply additional subregister substitutions to a known
  908. // instruction/operand pair. Adds new (fake) substitutions so that we can
  909. // record the subregister. FIXME: this isn't very space efficient if multiple
  910. // values are tracked back through the same copies; cache something later.
  911. auto ApplySubregisters =
  912. [&](DebugInstrOperandPair P) -> DebugInstrOperandPair {
  913. for (unsigned Subreg : reverse(SubregsSeen)) {
  914. // Fetch a new instruction number, not attached to an actual instruction.
  915. unsigned NewInstrNumber = getNewDebugInstrNum();
  916. // Add a substitution from the "new" number to the known one, with a
  917. // qualifying subreg.
  918. makeDebugValueSubstitution({NewInstrNumber, 0}, P, Subreg);
  919. // Return the new number; to find the underlying value, consumers need to
  920. // deal with the qualifying subreg.
  921. P = {NewInstrNumber, 0};
  922. }
  923. return P;
  924. };
  925. // If we managed to find the defining instruction after COPYs, return an
  926. // instruction / operand pair after adding subregister qualifiers.
  927. if (State.first.isVirtual()) {
  928. // Virtual register def -- we can just look up where this happens.
  929. MachineInstr *Inst = MRI.def_begin(State.first)->getParent();
  930. for (auto &MO : Inst->operands()) {
  931. if (!MO.isReg() || !MO.isDef() || MO.getReg() != State.first)
  932. continue;
  933. return ApplySubregisters(
  934. {Inst->getDebugInstrNum(), Inst->getOperandNo(&MO)});
  935. }
  936. llvm_unreachable("Vreg def with no corresponding operand?");
  937. }
  938. // Our search ended in a copy from a physreg: walk back up the function
  939. // looking for whatever defines the physreg.
  940. assert(CurInst->isCopyLike() || TII.isCopyInstr(*CurInst));
  941. State = GetRegAndSubreg(*CurInst);
  942. Register RegToSeek = State.first;
  943. auto RMII = CurInst->getReverseIterator();
  944. auto PrevInstrs = make_range(RMII, CurInst->getParent()->instr_rend());
  945. for (auto &ToExamine : PrevInstrs) {
  946. for (auto &MO : ToExamine.operands()) {
  947. // Test for operand that defines something aliasing RegToSeek.
  948. if (!MO.isReg() || !MO.isDef() ||
  949. !TRI.regsOverlap(RegToSeek, MO.getReg()))
  950. continue;
  951. return ApplySubregisters(
  952. {ToExamine.getDebugInstrNum(), ToExamine.getOperandNo(&MO)});
  953. }
  954. }
  955. MachineBasicBlock &InsertBB = *CurInst->getParent();
  956. // We reached the start of the block before finding a defining instruction.
  957. // There are numerous scenarios where this can happen:
  958. // * Constant physical registers,
  959. // * Several intrinsics that allow LLVM-IR to read arbitary registers,
  960. // * Arguments in the entry block,
  961. // * Exception handling landing pads.
  962. // Validating all of them is too difficult, so just insert a DBG_PHI reading
  963. // the variable value at this position, rather than checking it makes sense.
  964. // Create DBG_PHI for specified physreg.
  965. auto Builder = BuildMI(InsertBB, InsertBB.getFirstNonPHI(), DebugLoc(),
  966. TII.get(TargetOpcode::DBG_PHI));
  967. Builder.addReg(State.first);
  968. unsigned NewNum = getNewDebugInstrNum();
  969. Builder.addImm(NewNum);
  970. return ApplySubregisters({NewNum, 0u});
  971. }
  972. void MachineFunction::finalizeDebugInstrRefs() {
  973. auto *TII = getSubtarget().getInstrInfo();
  974. auto MakeUndefDbgValue = [&](MachineInstr &MI) {
  975. const MCInstrDesc &RefII = TII->get(TargetOpcode::DBG_VALUE_LIST);
  976. MI.setDesc(RefII);
  977. MI.setDebugValueUndef();
  978. };
  979. DenseMap<Register, DebugInstrOperandPair> ArgDbgPHIs;
  980. for (auto &MBB : *this) {
  981. for (auto &MI : MBB) {
  982. if (!MI.isDebugRef())
  983. continue;
  984. bool IsValidRef = true;
  985. for (MachineOperand &MO : MI.debug_operands()) {
  986. if (!MO.isReg())
  987. continue;
  988. Register Reg = MO.getReg();
  989. // Some vregs can be deleted as redundant in the meantime. Mark those
  990. // as DBG_VALUE $noreg. Additionally, some normal instructions are
  991. // quickly deleted, leaving dangling references to vregs with no def.
  992. if (Reg == 0 || !RegInfo->hasOneDef(Reg)) {
  993. IsValidRef = false;
  994. break;
  995. }
  996. assert(Reg.isVirtual());
  997. MachineInstr &DefMI = *RegInfo->def_instr_begin(Reg);
  998. // If we've found a copy-like instruction, follow it back to the
  999. // instruction that defines the source value, see salvageCopySSA docs
  1000. // for why this is important.
  1001. if (DefMI.isCopyLike() || TII->isCopyInstr(DefMI)) {
  1002. auto Result = salvageCopySSA(DefMI, ArgDbgPHIs);
  1003. MO.ChangeToDbgInstrRef(Result.first, Result.second);
  1004. } else {
  1005. // Otherwise, identify the operand number that the VReg refers to.
  1006. unsigned OperandIdx = 0;
  1007. for (const auto &DefMO : DefMI.operands()) {
  1008. if (DefMO.isReg() && DefMO.isDef() && DefMO.getReg() == Reg)
  1009. break;
  1010. ++OperandIdx;
  1011. }
  1012. assert(OperandIdx < DefMI.getNumOperands());
  1013. // Morph this instr ref to point at the given instruction and operand.
  1014. unsigned ID = DefMI.getDebugInstrNum();
  1015. MO.ChangeToDbgInstrRef(ID, OperandIdx);
  1016. }
  1017. }
  1018. if (!IsValidRef)
  1019. MakeUndefDbgValue(MI);
  1020. }
  1021. }
  1022. }
  1023. bool MachineFunction::shouldUseDebugInstrRef() const {
  1024. // Disable instr-ref at -O0: it's very slow (in compile time). We can still
  1025. // have optimized code inlined into this unoptimized code, however with
  1026. // fewer and less aggressive optimizations happening, coverage and accuracy
  1027. // should not suffer.
  1028. if (getTarget().getOptLevel() == CodeGenOpt::None)
  1029. return false;
  1030. // Don't use instr-ref if this function is marked optnone.
  1031. if (F.hasFnAttribute(Attribute::OptimizeNone))
  1032. return false;
  1033. if (llvm::debuginfoShouldUseDebugInstrRef(getTarget().getTargetTriple()))
  1034. return true;
  1035. return false;
  1036. }
  1037. bool MachineFunction::useDebugInstrRef() const {
  1038. return UseDebugInstrRef;
  1039. }
  1040. void MachineFunction::setUseDebugInstrRef(bool Use) {
  1041. UseDebugInstrRef = Use;
  1042. }
  1043. // Use one million as a high / reserved number.
  1044. const unsigned MachineFunction::DebugOperandMemNumber = 1000000;
  1045. /// \}
  1046. //===----------------------------------------------------------------------===//
  1047. // MachineJumpTableInfo implementation
  1048. //===----------------------------------------------------------------------===//
  1049. /// Return the size of each entry in the jump table.
  1050. unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
  1051. // The size of a jump table entry is 4 bytes unless the entry is just the
  1052. // address of a block, in which case it is the pointer size.
  1053. switch (getEntryKind()) {
  1054. case MachineJumpTableInfo::EK_BlockAddress:
  1055. return TD.getPointerSize();
  1056. case MachineJumpTableInfo::EK_GPRel64BlockAddress:
  1057. return 8;
  1058. case MachineJumpTableInfo::EK_GPRel32BlockAddress:
  1059. case MachineJumpTableInfo::EK_LabelDifference32:
  1060. case MachineJumpTableInfo::EK_Custom32:
  1061. return 4;
  1062. case MachineJumpTableInfo::EK_Inline:
  1063. return 0;
  1064. }
  1065. llvm_unreachable("Unknown jump table encoding!");
  1066. }
  1067. /// Return the alignment of each entry in the jump table.
  1068. unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
  1069. // The alignment of a jump table entry is the alignment of int32 unless the
  1070. // entry is just the address of a block, in which case it is the pointer
  1071. // alignment.
  1072. switch (getEntryKind()) {
  1073. case MachineJumpTableInfo::EK_BlockAddress:
  1074. return TD.getPointerABIAlignment(0).value();
  1075. case MachineJumpTableInfo::EK_GPRel64BlockAddress:
  1076. return TD.getABIIntegerTypeAlignment(64).value();
  1077. case MachineJumpTableInfo::EK_GPRel32BlockAddress:
  1078. case MachineJumpTableInfo::EK_LabelDifference32:
  1079. case MachineJumpTableInfo::EK_Custom32:
  1080. return TD.getABIIntegerTypeAlignment(32).value();
  1081. case MachineJumpTableInfo::EK_Inline:
  1082. return 1;
  1083. }
  1084. llvm_unreachable("Unknown jump table encoding!");
  1085. }
  1086. /// Create a new jump table entry in the jump table info.
  1087. unsigned MachineJumpTableInfo::createJumpTableIndex(
  1088. const std::vector<MachineBasicBlock*> &DestBBs) {
  1089. assert(!DestBBs.empty() && "Cannot create an empty jump table!");
  1090. JumpTables.push_back(MachineJumpTableEntry(DestBBs));
  1091. return JumpTables.size()-1;
  1092. }
  1093. /// If Old is the target of any jump tables, update the jump tables to branch
  1094. /// to New instead.
  1095. bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
  1096. MachineBasicBlock *New) {
  1097. assert(Old != New && "Not making a change?");
  1098. bool MadeChange = false;
  1099. for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
  1100. ReplaceMBBInJumpTable(i, Old, New);
  1101. return MadeChange;
  1102. }
  1103. /// If MBB is present in any jump tables, remove it.
  1104. bool MachineJumpTableInfo::RemoveMBBFromJumpTables(MachineBasicBlock *MBB) {
  1105. bool MadeChange = false;
  1106. for (MachineJumpTableEntry &JTE : JumpTables) {
  1107. auto removeBeginItr = std::remove(JTE.MBBs.begin(), JTE.MBBs.end(), MBB);
  1108. MadeChange |= (removeBeginItr != JTE.MBBs.end());
  1109. JTE.MBBs.erase(removeBeginItr, JTE.MBBs.end());
  1110. }
  1111. return MadeChange;
  1112. }
  1113. /// If Old is a target of the jump tables, update the jump table to branch to
  1114. /// New instead.
  1115. bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
  1116. MachineBasicBlock *Old,
  1117. MachineBasicBlock *New) {
  1118. assert(Old != New && "Not making a change?");
  1119. bool MadeChange = false;
  1120. MachineJumpTableEntry &JTE = JumpTables[Idx];
  1121. for (MachineBasicBlock *&MBB : JTE.MBBs)
  1122. if (MBB == Old) {
  1123. MBB = New;
  1124. MadeChange = true;
  1125. }
  1126. return MadeChange;
  1127. }
  1128. void MachineJumpTableInfo::print(raw_ostream &OS) const {
  1129. if (JumpTables.empty()) return;
  1130. OS << "Jump Tables:\n";
  1131. for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
  1132. OS << printJumpTableEntryReference(i) << ':';
  1133. for (const MachineBasicBlock *MBB : JumpTables[i].MBBs)
  1134. OS << ' ' << printMBBReference(*MBB);
  1135. if (i != e)
  1136. OS << '\n';
  1137. }
  1138. OS << '\n';
  1139. }
  1140. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1141. LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); }
  1142. #endif
  1143. Printable llvm::printJumpTableEntryReference(unsigned Idx) {
  1144. return Printable([Idx](raw_ostream &OS) { OS << "%jump-table." << Idx; });
  1145. }
  1146. //===----------------------------------------------------------------------===//
  1147. // MachineConstantPool implementation
  1148. //===----------------------------------------------------------------------===//
  1149. void MachineConstantPoolValue::anchor() {}
  1150. unsigned MachineConstantPoolValue::getSizeInBytes(const DataLayout &DL) const {
  1151. return DL.getTypeAllocSize(Ty);
  1152. }
  1153. unsigned MachineConstantPoolEntry::getSizeInBytes(const DataLayout &DL) const {
  1154. if (isMachineConstantPoolEntry())
  1155. return Val.MachineCPVal->getSizeInBytes(DL);
  1156. return DL.getTypeAllocSize(Val.ConstVal->getType());
  1157. }
  1158. bool MachineConstantPoolEntry::needsRelocation() const {
  1159. if (isMachineConstantPoolEntry())
  1160. return true;
  1161. return Val.ConstVal->needsDynamicRelocation();
  1162. }
  1163. SectionKind
  1164. MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
  1165. if (needsRelocation())
  1166. return SectionKind::getReadOnlyWithRel();
  1167. switch (getSizeInBytes(*DL)) {
  1168. case 4:
  1169. return SectionKind::getMergeableConst4();
  1170. case 8:
  1171. return SectionKind::getMergeableConst8();
  1172. case 16:
  1173. return SectionKind::getMergeableConst16();
  1174. case 32:
  1175. return SectionKind::getMergeableConst32();
  1176. default:
  1177. return SectionKind::getReadOnly();
  1178. }
  1179. }
  1180. MachineConstantPool::~MachineConstantPool() {
  1181. // A constant may be a member of both Constants and MachineCPVsSharingEntries,
  1182. // so keep track of which we've deleted to avoid double deletions.
  1183. DenseSet<MachineConstantPoolValue*> Deleted;
  1184. for (const MachineConstantPoolEntry &C : Constants)
  1185. if (C.isMachineConstantPoolEntry()) {
  1186. Deleted.insert(C.Val.MachineCPVal);
  1187. delete C.Val.MachineCPVal;
  1188. }
  1189. for (MachineConstantPoolValue *CPV : MachineCPVsSharingEntries) {
  1190. if (Deleted.count(CPV) == 0)
  1191. delete CPV;
  1192. }
  1193. }
  1194. /// Test whether the given two constants can be allocated the same constant pool
  1195. /// entry.
  1196. static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
  1197. const DataLayout &DL) {
  1198. // Handle the trivial case quickly.
  1199. if (A == B) return true;
  1200. // If they have the same type but weren't the same constant, quickly
  1201. // reject them.
  1202. if (A->getType() == B->getType()) return false;
  1203. // We can't handle structs or arrays.
  1204. if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
  1205. isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
  1206. return false;
  1207. // For now, only support constants with the same size.
  1208. uint64_t StoreSize = DL.getTypeStoreSize(A->getType());
  1209. if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128)
  1210. return false;
  1211. Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
  1212. // Try constant folding a bitcast of both instructions to an integer. If we
  1213. // get two identical ConstantInt's, then we are good to share them. We use
  1214. // the constant folding APIs to do this so that we get the benefit of
  1215. // DataLayout.
  1216. if (isa<PointerType>(A->getType()))
  1217. A = ConstantFoldCastOperand(Instruction::PtrToInt,
  1218. const_cast<Constant *>(A), IntTy, DL);
  1219. else if (A->getType() != IntTy)
  1220. A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A),
  1221. IntTy, DL);
  1222. if (isa<PointerType>(B->getType()))
  1223. B = ConstantFoldCastOperand(Instruction::PtrToInt,
  1224. const_cast<Constant *>(B), IntTy, DL);
  1225. else if (B->getType() != IntTy)
  1226. B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B),
  1227. IntTy, DL);
  1228. return A == B;
  1229. }
  1230. /// Create a new entry in the constant pool or return an existing one.
  1231. /// User must specify the log2 of the minimum required alignment for the object.
  1232. unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
  1233. Align Alignment) {
  1234. if (Alignment > PoolAlignment) PoolAlignment = Alignment;
  1235. // Check to see if we already have this constant.
  1236. //
  1237. // FIXME, this could be made much more efficient for large constant pools.
  1238. for (unsigned i = 0, e = Constants.size(); i != e; ++i)
  1239. if (!Constants[i].isMachineConstantPoolEntry() &&
  1240. CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) {
  1241. if (Constants[i].getAlign() < Alignment)
  1242. Constants[i].Alignment = Alignment;
  1243. return i;
  1244. }
  1245. Constants.push_back(MachineConstantPoolEntry(C, Alignment));
  1246. return Constants.size()-1;
  1247. }
  1248. unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
  1249. Align Alignment) {
  1250. if (Alignment > PoolAlignment) PoolAlignment = Alignment;
  1251. // Check to see if we already have this constant.
  1252. //
  1253. // FIXME, this could be made much more efficient for large constant pools.
  1254. int Idx = V->getExistingMachineCPValue(this, Alignment);
  1255. if (Idx != -1) {
  1256. MachineCPVsSharingEntries.insert(V);
  1257. return (unsigned)Idx;
  1258. }
  1259. Constants.push_back(MachineConstantPoolEntry(V, Alignment));
  1260. return Constants.size()-1;
  1261. }
  1262. void MachineConstantPool::print(raw_ostream &OS) const {
  1263. if (Constants.empty()) return;
  1264. OS << "Constant Pool:\n";
  1265. for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
  1266. OS << " cp#" << i << ": ";
  1267. if (Constants[i].isMachineConstantPoolEntry())
  1268. Constants[i].Val.MachineCPVal->print(OS);
  1269. else
  1270. Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
  1271. OS << ", align=" << Constants[i].getAlign().value();
  1272. OS << "\n";
  1273. }
  1274. }
  1275. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1276. LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); }
  1277. #endif