[docs] Add LICENSE.txt to the root of the mono-repo
[llvm-project.git] / llvm / lib / CodeGen / MachineFunction.cpp
blobd2c224898fe2351e88e73e0db85b5011866f359c
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.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/CodeGen/MachineFunction.h"
16 #include "llvm/ADT/BitVector.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/DenseSet.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/Analysis/ConstantFolding.h"
25 #include "llvm/Analysis/EHPersonalities.h"
26 #include "llvm/CodeGen/MachineBasicBlock.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineInstr.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineMemOperand.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/PseudoSourceValue.h"
35 #include "llvm/CodeGen/TargetFrameLowering.h"
36 #include "llvm/CodeGen/TargetInstrInfo.h"
37 #include "llvm/CodeGen/TargetLowering.h"
38 #include "llvm/CodeGen/TargetRegisterInfo.h"
39 #include "llvm/CodeGen/TargetSubtargetInfo.h"
40 #include "llvm/CodeGen/WasmEHFuncInfo.h"
41 #include "llvm/CodeGen/WinEHFuncInfo.h"
42 #include "llvm/Config/llvm-config.h"
43 #include "llvm/IR/Attributes.h"
44 #include "llvm/IR/BasicBlock.h"
45 #include "llvm/IR/Constant.h"
46 #include "llvm/IR/DataLayout.h"
47 #include "llvm/IR/DerivedTypes.h"
48 #include "llvm/IR/Function.h"
49 #include "llvm/IR/GlobalValue.h"
50 #include "llvm/IR/Instruction.h"
51 #include "llvm/IR/Instructions.h"
52 #include "llvm/IR/Metadata.h"
53 #include "llvm/IR/Module.h"
54 #include "llvm/IR/ModuleSlotTracker.h"
55 #include "llvm/IR/Value.h"
56 #include "llvm/MC/MCContext.h"
57 #include "llvm/MC/MCSymbol.h"
58 #include "llvm/MC/SectionKind.h"
59 #include "llvm/Support/Casting.h"
60 #include "llvm/Support/CommandLine.h"
61 #include "llvm/Support/Compiler.h"
62 #include "llvm/Support/DOTGraphTraits.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 <type_traits>
74 #include <utility>
75 #include <vector>
77 #include "LiveDebugValues/LiveDebugValues.h"
79 using namespace llvm;
81 #define DEBUG_TYPE "codegen"
83 static cl::opt<unsigned> AlignAllFunctions(
84 "align-all-functions",
85 cl::desc("Force the alignment of all functions in log2 format (e.g. 4 "
86 "means align on 16B boundaries)."),
87 cl::init(0), cl::Hidden);
89 static const char *getPropertyName(MachineFunctionProperties::Property Prop) {
90 using P = MachineFunctionProperties::Property;
92 // clang-format off
93 switch(Prop) {
94 case P::FailedISel: return "FailedISel";
95 case P::IsSSA: return "IsSSA";
96 case P::Legalized: return "Legalized";
97 case P::NoPHIs: return "NoPHIs";
98 case P::NoVRegs: return "NoVRegs";
99 case P::RegBankSelected: return "RegBankSelected";
100 case P::Selected: return "Selected";
101 case P::TracksLiveness: return "TracksLiveness";
102 case P::TiedOpsRewritten: return "TiedOpsRewritten";
103 case P::FailsVerification: return "FailsVerification";
104 case P::TracksDebugUserValues: return "TracksDebugUserValues";
106 // clang-format on
107 llvm_unreachable("Invalid machine function property");
110 void setUnsafeStackSize(const Function &F, MachineFrameInfo &FrameInfo) {
111 if (!F.hasFnAttribute(Attribute::SafeStack))
112 return;
114 auto *Existing =
115 dyn_cast_or_null<MDTuple>(F.getMetadata(LLVMContext::MD_annotation));
117 if (!Existing || Existing->getNumOperands() != 2)
118 return;
120 auto *MetadataName = "unsafe-stack-size";
121 if (auto &N = Existing->getOperand(0)) {
122 if (cast<MDString>(N.get())->getString() == MetadataName) {
123 if (auto &Op = Existing->getOperand(1)) {
124 auto Val = mdconst::extract<ConstantInt>(Op)->getZExtValue();
125 FrameInfo.setUnsafeStackSize(Val);
131 // Pin the vtable to this file.
132 void MachineFunction::Delegate::anchor() {}
134 void MachineFunctionProperties::print(raw_ostream &OS) const {
135 const char *Separator = "";
136 for (BitVector::size_type I = 0; I < Properties.size(); ++I) {
137 if (!Properties[I])
138 continue;
139 OS << Separator << getPropertyName(static_cast<Property>(I));
140 Separator = ", ";
144 //===----------------------------------------------------------------------===//
145 // MachineFunction implementation
146 //===----------------------------------------------------------------------===//
148 // Out-of-line virtual method.
149 MachineFunctionInfo::~MachineFunctionInfo() = default;
151 void ilist_alloc_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
152 MBB->getParent()->deleteMachineBasicBlock(MBB);
155 static inline Align getFnStackAlignment(const TargetSubtargetInfo *STI,
156 const Function &F) {
157 if (auto MA = F.getFnStackAlign())
158 return *MA;
159 return STI->getFrameLowering()->getStackAlign();
162 MachineFunction::MachineFunction(Function &F, const LLVMTargetMachine &Target,
163 const TargetSubtargetInfo &STI,
164 unsigned FunctionNum, MachineModuleInfo &mmi)
165 : F(F), Target(Target), STI(&STI), Ctx(mmi.getContext()), MMI(mmi) {
166 FunctionNumber = FunctionNum;
167 init();
170 void MachineFunction::handleInsertion(MachineInstr &MI) {
171 if (TheDelegate)
172 TheDelegate->MF_HandleInsertion(MI);
175 void MachineFunction::handleRemoval(MachineInstr &MI) {
176 if (TheDelegate)
177 TheDelegate->MF_HandleRemoval(MI);
180 void MachineFunction::init() {
181 // Assume the function starts in SSA form with correct liveness.
182 Properties.set(MachineFunctionProperties::Property::IsSSA);
183 Properties.set(MachineFunctionProperties::Property::TracksLiveness);
184 if (STI->getRegisterInfo())
185 RegInfo = new (Allocator) MachineRegisterInfo(this);
186 else
187 RegInfo = nullptr;
189 MFInfo = nullptr;
190 // We can realign the stack if the target supports it and the user hasn't
191 // explicitly asked us not to.
192 bool CanRealignSP = STI->getFrameLowering()->isStackRealignable() &&
193 !F.hasFnAttribute("no-realign-stack");
194 FrameInfo = new (Allocator) MachineFrameInfo(
195 getFnStackAlignment(STI, F), /*StackRealignable=*/CanRealignSP,
196 /*ForcedRealign=*/CanRealignSP &&
197 F.hasFnAttribute(Attribute::StackAlignment));
199 setUnsafeStackSize(F, *FrameInfo);
201 if (F.hasFnAttribute(Attribute::StackAlignment))
202 FrameInfo->ensureMaxAlignment(*F.getFnStackAlign());
204 ConstantPool = new (Allocator) MachineConstantPool(getDataLayout());
205 Alignment = STI->getTargetLowering()->getMinFunctionAlignment();
207 // FIXME: Shouldn't use pref alignment if explicit alignment is set on F.
208 // FIXME: Use Function::hasOptSize().
209 if (!F.hasFnAttribute(Attribute::OptimizeForSize))
210 Alignment = std::max(Alignment,
211 STI->getTargetLowering()->getPrefFunctionAlignment());
213 if (AlignAllFunctions)
214 Alignment = Align(1ULL << AlignAllFunctions);
216 JumpTableInfo = nullptr;
218 if (isFuncletEHPersonality(classifyEHPersonality(
219 F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
220 WinEHInfo = new (Allocator) WinEHFuncInfo();
223 if (isScopedEHPersonality(classifyEHPersonality(
224 F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
225 WasmEHInfo = new (Allocator) WasmEHFuncInfo();
228 assert(Target.isCompatibleDataLayout(getDataLayout()) &&
229 "Can't create a MachineFunction using a Module with a "
230 "Target-incompatible DataLayout attached\n");
232 PSVManager = std::make_unique<PseudoSourceValueManager>(getTarget());
235 MachineFunction::~MachineFunction() {
236 clear();
239 void MachineFunction::clear() {
240 Properties.reset();
241 // Don't call destructors on MachineInstr and MachineOperand. All of their
242 // memory comes from the BumpPtrAllocator which is about to be purged.
244 // Do call MachineBasicBlock destructors, it contains std::vectors.
245 for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
246 I->Insts.clearAndLeakNodesUnsafely();
247 MBBNumbering.clear();
249 InstructionRecycler.clear(Allocator);
250 OperandRecycler.clear(Allocator);
251 BasicBlockRecycler.clear(Allocator);
252 CodeViewAnnotations.clear();
253 VariableDbgInfos.clear();
254 if (RegInfo) {
255 RegInfo->~MachineRegisterInfo();
256 Allocator.Deallocate(RegInfo);
258 if (MFInfo) {
259 MFInfo->~MachineFunctionInfo();
260 Allocator.Deallocate(MFInfo);
263 FrameInfo->~MachineFrameInfo();
264 Allocator.Deallocate(FrameInfo);
266 ConstantPool->~MachineConstantPool();
267 Allocator.Deallocate(ConstantPool);
269 if (JumpTableInfo) {
270 JumpTableInfo->~MachineJumpTableInfo();
271 Allocator.Deallocate(JumpTableInfo);
274 if (WinEHInfo) {
275 WinEHInfo->~WinEHFuncInfo();
276 Allocator.Deallocate(WinEHInfo);
279 if (WasmEHInfo) {
280 WasmEHInfo->~WasmEHFuncInfo();
281 Allocator.Deallocate(WasmEHInfo);
285 const DataLayout &MachineFunction::getDataLayout() const {
286 return F.getParent()->getDataLayout();
289 /// Get the JumpTableInfo for this function.
290 /// If it does not already exist, allocate one.
291 MachineJumpTableInfo *MachineFunction::
292 getOrCreateJumpTableInfo(unsigned EntryKind) {
293 if (JumpTableInfo) return JumpTableInfo;
295 JumpTableInfo = new (Allocator)
296 MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
297 return JumpTableInfo;
300 DenormalMode MachineFunction::getDenormalMode(const fltSemantics &FPType) const {
301 return F.getDenormalMode(FPType);
304 /// Should we be emitting segmented stack stuff for the function
305 bool MachineFunction::shouldSplitStack() const {
306 return getFunction().hasFnAttribute("split-stack");
309 [[nodiscard]] unsigned
310 MachineFunction::addFrameInst(const MCCFIInstruction &Inst) {
311 FrameInstructions.push_back(Inst);
312 return FrameInstructions.size() - 1;
315 /// This discards all of the MachineBasicBlock numbers and recomputes them.
316 /// This guarantees that the MBB numbers are sequential, dense, and match the
317 /// ordering of the blocks within the function. If a specific MachineBasicBlock
318 /// is specified, only that block and those after it are renumbered.
319 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
320 if (empty()) { MBBNumbering.clear(); return; }
321 MachineFunction::iterator MBBI, E = end();
322 if (MBB == nullptr)
323 MBBI = begin();
324 else
325 MBBI = MBB->getIterator();
327 // Figure out the block number this should have.
328 unsigned BlockNo = 0;
329 if (MBBI != begin())
330 BlockNo = std::prev(MBBI)->getNumber() + 1;
332 for (; MBBI != E; ++MBBI, ++BlockNo) {
333 if (MBBI->getNumber() != (int)BlockNo) {
334 // Remove use of the old number.
335 if (MBBI->getNumber() != -1) {
336 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
337 "MBB number mismatch!");
338 MBBNumbering[MBBI->getNumber()] = nullptr;
341 // If BlockNo is already taken, set that block's number to -1.
342 if (MBBNumbering[BlockNo])
343 MBBNumbering[BlockNo]->setNumber(-1);
345 MBBNumbering[BlockNo] = &*MBBI;
346 MBBI->setNumber(BlockNo);
350 // Okay, all the blocks are renumbered. If we have compactified the block
351 // numbering, shrink MBBNumbering now.
352 assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
353 MBBNumbering.resize(BlockNo);
356 /// This method iterates over the basic blocks and assigns their IsBeginSection
357 /// and IsEndSection fields. This must be called after MBB layout is finalized
358 /// and the SectionID's are assigned to MBBs.
359 void MachineFunction::assignBeginEndSections() {
360 front().setIsBeginSection();
361 auto CurrentSectionID = front().getSectionID();
362 for (auto MBBI = std::next(begin()), E = end(); MBBI != E; ++MBBI) {
363 if (MBBI->getSectionID() == CurrentSectionID)
364 continue;
365 MBBI->setIsBeginSection();
366 std::prev(MBBI)->setIsEndSection();
367 CurrentSectionID = MBBI->getSectionID();
369 back().setIsEndSection();
372 /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'.
373 MachineInstr *MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
374 DebugLoc DL,
375 bool NoImplicit) {
376 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
377 MachineInstr(*this, MCID, std::move(DL), NoImplicit);
380 /// Create a new MachineInstr which is a copy of the 'Orig' instruction,
381 /// identical in all ways except the instruction has no parent, prev, or next.
382 MachineInstr *
383 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
384 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
385 MachineInstr(*this, *Orig);
388 MachineInstr &MachineFunction::cloneMachineInstrBundle(
389 MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
390 const MachineInstr &Orig) {
391 MachineInstr *FirstClone = nullptr;
392 MachineBasicBlock::const_instr_iterator I = Orig.getIterator();
393 while (true) {
394 MachineInstr *Cloned = CloneMachineInstr(&*I);
395 MBB.insert(InsertBefore, Cloned);
396 if (FirstClone == nullptr) {
397 FirstClone = Cloned;
398 } else {
399 Cloned->bundleWithPred();
402 if (!I->isBundledWithSucc())
403 break;
404 ++I;
406 // Copy over call site info to the cloned instruction if needed. If Orig is in
407 // a bundle, copyCallSiteInfo takes care of finding the call instruction in
408 // the bundle.
409 if (Orig.shouldUpdateCallSiteInfo())
410 copyCallSiteInfo(&Orig, FirstClone);
411 return *FirstClone;
414 /// Delete the given MachineInstr.
416 /// This function also serves as the MachineInstr destructor - the real
417 /// ~MachineInstr() destructor must be empty.
418 void MachineFunction::deleteMachineInstr(MachineInstr *MI) {
419 // Verify that a call site info is at valid state. This assertion should
420 // be triggered during the implementation of support for the
421 // call site info of a new architecture. If the assertion is triggered,
422 // back trace will tell where to insert a call to updateCallSiteInfo().
423 assert((!MI->isCandidateForCallSiteEntry() ||
424 CallSitesInfo.find(MI) == CallSitesInfo.end()) &&
425 "Call site info was not updated!");
426 // Strip it for parts. The operand array and the MI object itself are
427 // independently recyclable.
428 if (MI->Operands)
429 deallocateOperandArray(MI->CapOperands, MI->Operands);
430 // Don't call ~MachineInstr() which must be trivial anyway because
431 // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
432 // destructors.
433 InstructionRecycler.Deallocate(Allocator, MI);
436 /// Allocate a new MachineBasicBlock. Use this instead of
437 /// `new MachineBasicBlock'.
438 MachineBasicBlock *
439 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
440 return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
441 MachineBasicBlock(*this, bb);
444 /// Delete the given MachineBasicBlock.
445 void MachineFunction::deleteMachineBasicBlock(MachineBasicBlock *MBB) {
446 assert(MBB->getParent() == this && "MBB parent mismatch!");
447 // Clean up any references to MBB in jump tables before deleting it.
448 if (JumpTableInfo)
449 JumpTableInfo->RemoveMBBFromJumpTables(MBB);
450 MBB->~MachineBasicBlock();
451 BasicBlockRecycler.Deallocate(Allocator, MBB);
454 MachineMemOperand *MachineFunction::getMachineMemOperand(
455 MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s,
456 Align base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges,
457 SyncScope::ID SSID, AtomicOrdering Ordering,
458 AtomicOrdering FailureOrdering) {
459 return new (Allocator)
460 MachineMemOperand(PtrInfo, f, s, base_alignment, AAInfo, Ranges,
461 SSID, Ordering, FailureOrdering);
464 MachineMemOperand *MachineFunction::getMachineMemOperand(
465 MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, LLT MemTy,
466 Align base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges,
467 SyncScope::ID SSID, AtomicOrdering Ordering,
468 AtomicOrdering FailureOrdering) {
469 return new (Allocator)
470 MachineMemOperand(PtrInfo, f, MemTy, base_alignment, AAInfo, Ranges, SSID,
471 Ordering, FailureOrdering);
474 MachineMemOperand *MachineFunction::getMachineMemOperand(
475 const MachineMemOperand *MMO, const MachinePointerInfo &PtrInfo, uint64_t Size) {
476 return new (Allocator)
477 MachineMemOperand(PtrInfo, MMO->getFlags(), Size, MMO->getBaseAlign(),
478 AAMDNodes(), nullptr, MMO->getSyncScopeID(),
479 MMO->getSuccessOrdering(), MMO->getFailureOrdering());
482 MachineMemOperand *MachineFunction::getMachineMemOperand(
483 const MachineMemOperand *MMO, const MachinePointerInfo &PtrInfo, LLT Ty) {
484 return new (Allocator)
485 MachineMemOperand(PtrInfo, MMO->getFlags(), Ty, MMO->getBaseAlign(),
486 AAMDNodes(), nullptr, MMO->getSyncScopeID(),
487 MMO->getSuccessOrdering(), MMO->getFailureOrdering());
490 MachineMemOperand *
491 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
492 int64_t Offset, LLT Ty) {
493 const MachinePointerInfo &PtrInfo = MMO->getPointerInfo();
495 // If there is no pointer value, the offset isn't tracked so we need to adjust
496 // the base alignment.
497 Align Alignment = PtrInfo.V.isNull()
498 ? commonAlignment(MMO->getBaseAlign(), Offset)
499 : MMO->getBaseAlign();
501 // Do not preserve ranges, since we don't necessarily know what the high bits
502 // are anymore.
503 return new (Allocator) MachineMemOperand(
504 PtrInfo.getWithOffset(Offset), MMO->getFlags(), Ty, Alignment,
505 MMO->getAAInfo(), nullptr, MMO->getSyncScopeID(),
506 MMO->getSuccessOrdering(), MMO->getFailureOrdering());
509 MachineMemOperand *
510 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
511 const AAMDNodes &AAInfo) {
512 MachinePointerInfo MPI = MMO->getValue() ?
513 MachinePointerInfo(MMO->getValue(), MMO->getOffset()) :
514 MachinePointerInfo(MMO->getPseudoValue(), MMO->getOffset());
516 return new (Allocator) MachineMemOperand(
517 MPI, MMO->getFlags(), MMO->getSize(), MMO->getBaseAlign(), AAInfo,
518 MMO->getRanges(), MMO->getSyncScopeID(), MMO->getSuccessOrdering(),
519 MMO->getFailureOrdering());
522 MachineMemOperand *
523 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
524 MachineMemOperand::Flags Flags) {
525 return new (Allocator) MachineMemOperand(
526 MMO->getPointerInfo(), Flags, MMO->getSize(), MMO->getBaseAlign(),
527 MMO->getAAInfo(), MMO->getRanges(), MMO->getSyncScopeID(),
528 MMO->getSuccessOrdering(), MMO->getFailureOrdering());
531 MachineInstr::ExtraInfo *MachineFunction::createMIExtraInfo(
532 ArrayRef<MachineMemOperand *> MMOs, MCSymbol *PreInstrSymbol,
533 MCSymbol *PostInstrSymbol, MDNode *HeapAllocMarker) {
534 return MachineInstr::ExtraInfo::create(Allocator, MMOs, PreInstrSymbol,
535 PostInstrSymbol, HeapAllocMarker);
538 const char *MachineFunction::createExternalSymbolName(StringRef Name) {
539 char *Dest = Allocator.Allocate<char>(Name.size() + 1);
540 llvm::copy(Name, Dest);
541 Dest[Name.size()] = 0;
542 return Dest;
545 uint32_t *MachineFunction::allocateRegMask() {
546 unsigned NumRegs = getSubtarget().getRegisterInfo()->getNumRegs();
547 unsigned Size = MachineOperand::getRegMaskSize(NumRegs);
548 uint32_t *Mask = Allocator.Allocate<uint32_t>(Size);
549 memset(Mask, 0, Size * sizeof(Mask[0]));
550 return Mask;
553 ArrayRef<int> MachineFunction::allocateShuffleMask(ArrayRef<int> Mask) {
554 int* AllocMask = Allocator.Allocate<int>(Mask.size());
555 copy(Mask, AllocMask);
556 return {AllocMask, Mask.size()};
559 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
560 LLVM_DUMP_METHOD void MachineFunction::dump() const {
561 print(dbgs());
563 #endif
565 StringRef MachineFunction::getName() const {
566 return getFunction().getName();
569 void MachineFunction::print(raw_ostream &OS, const SlotIndexes *Indexes) const {
570 OS << "# Machine code for function " << getName() << ": ";
571 getProperties().print(OS);
572 OS << '\n';
574 // Print Frame Information
575 FrameInfo->print(*this, OS);
577 // Print JumpTable Information
578 if (JumpTableInfo)
579 JumpTableInfo->print(OS);
581 // Print Constant Pool
582 ConstantPool->print(OS);
584 const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo();
586 if (RegInfo && !RegInfo->livein_empty()) {
587 OS << "Function Live Ins: ";
588 for (MachineRegisterInfo::livein_iterator
589 I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
590 OS << printReg(I->first, TRI);
591 if (I->second)
592 OS << " in " << printReg(I->second, TRI);
593 if (std::next(I) != E)
594 OS << ", ";
596 OS << '\n';
599 ModuleSlotTracker MST(getFunction().getParent());
600 MST.incorporateFunction(getFunction());
601 for (const auto &BB : *this) {
602 OS << '\n';
603 // If we print the whole function, print it at its most verbose level.
604 BB.print(OS, MST, Indexes, /*IsStandalone=*/true);
607 OS << "\n# End machine code for function " << getName() << ".\n\n";
610 /// True if this function needs frame moves for debug or exceptions.
611 bool MachineFunction::needsFrameMoves() const {
612 return getMMI().hasDebugInfo() ||
613 getTarget().Options.ForceDwarfFrameSection ||
614 F.needsUnwindTableEntry();
617 namespace llvm {
619 template<>
620 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
621 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
623 static std::string getGraphName(const MachineFunction *F) {
624 return ("CFG for '" + F->getName() + "' function").str();
627 std::string getNodeLabel(const MachineBasicBlock *Node,
628 const MachineFunction *Graph) {
629 std::string OutStr;
631 raw_string_ostream OSS(OutStr);
633 if (isSimple()) {
634 OSS << printMBBReference(*Node);
635 if (const BasicBlock *BB = Node->getBasicBlock())
636 OSS << ": " << BB->getName();
637 } else
638 Node->print(OSS);
641 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
643 // Process string output to make it nicer...
644 for (unsigned i = 0; i != OutStr.length(); ++i)
645 if (OutStr[i] == '\n') { // Left justify
646 OutStr[i] = '\\';
647 OutStr.insert(OutStr.begin()+i+1, 'l');
649 return OutStr;
653 } // end namespace llvm
655 void MachineFunction::viewCFG() const
657 #ifndef NDEBUG
658 ViewGraph(this, "mf" + getName());
659 #else
660 errs() << "MachineFunction::viewCFG is only available in debug builds on "
661 << "systems with Graphviz or gv!\n";
662 #endif // NDEBUG
665 void MachineFunction::viewCFGOnly() const
667 #ifndef NDEBUG
668 ViewGraph(this, "mf" + getName(), true);
669 #else
670 errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
671 << "systems with Graphviz or gv!\n";
672 #endif // NDEBUG
675 /// Add the specified physical register as a live-in value and
676 /// create a corresponding virtual register for it.
677 Register MachineFunction::addLiveIn(MCRegister PReg,
678 const TargetRegisterClass *RC) {
679 MachineRegisterInfo &MRI = getRegInfo();
680 Register VReg = MRI.getLiveInVirtReg(PReg);
681 if (VReg) {
682 const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
683 (void)VRegRC;
684 // A physical register can be added several times.
685 // Between two calls, the register class of the related virtual register
686 // may have been constrained to match some operation constraints.
687 // In that case, check that the current register class includes the
688 // physical register and is a sub class of the specified RC.
689 assert((VRegRC == RC || (VRegRC->contains(PReg) &&
690 RC->hasSubClassEq(VRegRC))) &&
691 "Register class mismatch!");
692 return VReg;
694 VReg = MRI.createVirtualRegister(RC);
695 MRI.addLiveIn(PReg, VReg);
696 return VReg;
699 /// Return the MCSymbol for the specified non-empty jump table.
700 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
701 /// normal 'L' label is returned.
702 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
703 bool isLinkerPrivate) const {
704 const DataLayout &DL = getDataLayout();
705 assert(JumpTableInfo && "No jump tables");
706 assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
708 StringRef Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix()
709 : DL.getPrivateGlobalPrefix();
710 SmallString<60> Name;
711 raw_svector_ostream(Name)
712 << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
713 return Ctx.getOrCreateSymbol(Name);
716 /// Return a function-local symbol to represent the PIC base.
717 MCSymbol *MachineFunction::getPICBaseSymbol() const {
718 const DataLayout &DL = getDataLayout();
719 return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
720 Twine(getFunctionNumber()) + "$pb");
723 /// \name Exception Handling
724 /// \{
726 LandingPadInfo &
727 MachineFunction::getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad) {
728 unsigned N = LandingPads.size();
729 for (unsigned i = 0; i < N; ++i) {
730 LandingPadInfo &LP = LandingPads[i];
731 if (LP.LandingPadBlock == LandingPad)
732 return LP;
735 LandingPads.push_back(LandingPadInfo(LandingPad));
736 return LandingPads[N];
739 void MachineFunction::addInvoke(MachineBasicBlock *LandingPad,
740 MCSymbol *BeginLabel, MCSymbol *EndLabel) {
741 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
742 LP.BeginLabels.push_back(BeginLabel);
743 LP.EndLabels.push_back(EndLabel);
746 MCSymbol *MachineFunction::addLandingPad(MachineBasicBlock *LandingPad) {
747 MCSymbol *LandingPadLabel = Ctx.createTempSymbol();
748 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
749 LP.LandingPadLabel = LandingPadLabel;
751 const Instruction *FirstI = LandingPad->getBasicBlock()->getFirstNonPHI();
752 if (const auto *LPI = dyn_cast<LandingPadInst>(FirstI)) {
753 if (const auto *PF =
754 dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts()))
755 getMMI().addPersonality(PF);
757 if (LPI->isCleanup())
758 addCleanup(LandingPad);
760 // FIXME: New EH - Add the clauses in reverse order. This isn't 100%
761 // correct, but we need to do it this way because of how the DWARF EH
762 // emitter processes the clauses.
763 for (unsigned I = LPI->getNumClauses(); I != 0; --I) {
764 Value *Val = LPI->getClause(I - 1);
765 if (LPI->isCatch(I - 1)) {
766 addCatchTypeInfo(LandingPad,
767 dyn_cast<GlobalValue>(Val->stripPointerCasts()));
768 } else {
769 // Add filters in a list.
770 auto *CVal = cast<Constant>(Val);
771 SmallVector<const GlobalValue *, 4> FilterList;
772 for (const Use &U : CVal->operands())
773 FilterList.push_back(cast<GlobalValue>(U->stripPointerCasts()));
775 addFilterTypeInfo(LandingPad, FilterList);
779 } else if (const auto *CPI = dyn_cast<CatchPadInst>(FirstI)) {
780 for (unsigned I = CPI->getNumArgOperands(); I != 0; --I) {
781 Value *TypeInfo = CPI->getArgOperand(I - 1)->stripPointerCasts();
782 addCatchTypeInfo(LandingPad, dyn_cast<GlobalValue>(TypeInfo));
785 } else {
786 assert(isa<CleanupPadInst>(FirstI) && "Invalid landingpad!");
789 return LandingPadLabel;
792 void MachineFunction::addCatchTypeInfo(MachineBasicBlock *LandingPad,
793 ArrayRef<const GlobalValue *> TyInfo) {
794 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
795 for (const GlobalValue *GV : llvm::reverse(TyInfo))
796 LP.TypeIds.push_back(getTypeIDFor(GV));
799 void MachineFunction::addFilterTypeInfo(MachineBasicBlock *LandingPad,
800 ArrayRef<const GlobalValue *> TyInfo) {
801 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
802 std::vector<unsigned> IdsInFilter(TyInfo.size());
803 for (unsigned I = 0, E = TyInfo.size(); I != E; ++I)
804 IdsInFilter[I] = getTypeIDFor(TyInfo[I]);
805 LP.TypeIds.push_back(getFilterIDFor(IdsInFilter));
808 void MachineFunction::tidyLandingPads(DenseMap<MCSymbol *, uintptr_t> *LPMap,
809 bool TidyIfNoBeginLabels) {
810 for (unsigned i = 0; i != LandingPads.size(); ) {
811 LandingPadInfo &LandingPad = LandingPads[i];
812 if (LandingPad.LandingPadLabel &&
813 !LandingPad.LandingPadLabel->isDefined() &&
814 (!LPMap || (*LPMap)[LandingPad.LandingPadLabel] == 0))
815 LandingPad.LandingPadLabel = nullptr;
817 // Special case: we *should* emit LPs with null LP MBB. This indicates
818 // "nounwind" case.
819 if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) {
820 LandingPads.erase(LandingPads.begin() + i);
821 continue;
824 if (TidyIfNoBeginLabels) {
825 for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) {
826 MCSymbol *BeginLabel = LandingPad.BeginLabels[j];
827 MCSymbol *EndLabel = LandingPad.EndLabels[j];
828 if ((BeginLabel->isDefined() || (LPMap && (*LPMap)[BeginLabel] != 0)) &&
829 (EndLabel->isDefined() || (LPMap && (*LPMap)[EndLabel] != 0)))
830 continue;
832 LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j);
833 LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j);
834 --j;
835 --e;
838 // Remove landing pads with no try-ranges.
839 if (LandingPads[i].BeginLabels.empty()) {
840 LandingPads.erase(LandingPads.begin() + i);
841 continue;
845 // If there is no landing pad, ensure that the list of typeids is empty.
846 // If the only typeid is a cleanup, this is the same as having no typeids.
847 if (!LandingPad.LandingPadBlock ||
848 (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0]))
849 LandingPad.TypeIds.clear();
850 ++i;
854 void MachineFunction::addCleanup(MachineBasicBlock *LandingPad) {
855 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
856 LP.TypeIds.push_back(0);
859 void MachineFunction::setCallSiteLandingPad(MCSymbol *Sym,
860 ArrayRef<unsigned> Sites) {
861 LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end());
864 unsigned MachineFunction::getTypeIDFor(const GlobalValue *TI) {
865 for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
866 if (TypeInfos[i] == TI) return i + 1;
868 TypeInfos.push_back(TI);
869 return TypeInfos.size();
872 int MachineFunction::getFilterIDFor(std::vector<unsigned> &TyIds) {
873 // If the new filter coincides with the tail of an existing filter, then
874 // re-use the existing filter. Folding filters more than this requires
875 // re-ordering filters and/or their elements - probably not worth it.
876 for (unsigned i : FilterEnds) {
877 unsigned j = TyIds.size();
879 while (i && j)
880 if (FilterIds[--i] != TyIds[--j])
881 goto try_next;
883 if (!j)
884 // The new filter coincides with range [i, end) of the existing filter.
885 return -(1 + i);
887 try_next:;
890 // Add the new filter.
891 int FilterID = -(1 + FilterIds.size());
892 FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
893 llvm::append_range(FilterIds, TyIds);
894 FilterEnds.push_back(FilterIds.size());
895 FilterIds.push_back(0); // terminator
896 return FilterID;
899 MachineFunction::CallSiteInfoMap::iterator
900 MachineFunction::getCallSiteInfo(const MachineInstr *MI) {
901 assert(MI->isCandidateForCallSiteEntry() &&
902 "Call site info refers only to call (MI) candidates");
904 if (!Target.Options.EmitCallSiteInfo)
905 return CallSitesInfo.end();
906 return CallSitesInfo.find(MI);
909 /// Return the call machine instruction or find a call within bundle.
910 static const MachineInstr *getCallInstr(const MachineInstr *MI) {
911 if (!MI->isBundle())
912 return MI;
914 for (const auto &BMI : make_range(getBundleStart(MI->getIterator()),
915 getBundleEnd(MI->getIterator())))
916 if (BMI.isCandidateForCallSiteEntry())
917 return &BMI;
919 llvm_unreachable("Unexpected bundle without a call site candidate");
922 void MachineFunction::eraseCallSiteInfo(const MachineInstr *MI) {
923 assert(MI->shouldUpdateCallSiteInfo() &&
924 "Call site info refers only to call (MI) candidates or "
925 "candidates inside bundles");
927 const MachineInstr *CallMI = getCallInstr(MI);
928 CallSiteInfoMap::iterator CSIt = getCallSiteInfo(CallMI);
929 if (CSIt == CallSitesInfo.end())
930 return;
931 CallSitesInfo.erase(CSIt);
934 void MachineFunction::copyCallSiteInfo(const MachineInstr *Old,
935 const MachineInstr *New) {
936 assert(Old->shouldUpdateCallSiteInfo() &&
937 "Call site info refers only to call (MI) candidates or "
938 "candidates inside bundles");
940 if (!New->isCandidateForCallSiteEntry())
941 return eraseCallSiteInfo(Old);
943 const MachineInstr *OldCallMI = getCallInstr(Old);
944 CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI);
945 if (CSIt == CallSitesInfo.end())
946 return;
948 CallSiteInfo CSInfo = CSIt->second;
949 CallSitesInfo[New] = CSInfo;
952 void MachineFunction::moveCallSiteInfo(const MachineInstr *Old,
953 const MachineInstr *New) {
954 assert(Old->shouldUpdateCallSiteInfo() &&
955 "Call site info refers only to call (MI) candidates or "
956 "candidates inside bundles");
958 if (!New->isCandidateForCallSiteEntry())
959 return eraseCallSiteInfo(Old);
961 const MachineInstr *OldCallMI = getCallInstr(Old);
962 CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI);
963 if (CSIt == CallSitesInfo.end())
964 return;
966 CallSiteInfo CSInfo = std::move(CSIt->second);
967 CallSitesInfo.erase(CSIt);
968 CallSitesInfo[New] = CSInfo;
971 void MachineFunction::setDebugInstrNumberingCount(unsigned Num) {
972 DebugInstrNumberingCount = Num;
975 void MachineFunction::makeDebugValueSubstitution(DebugInstrOperandPair A,
976 DebugInstrOperandPair B,
977 unsigned Subreg) {
978 // Catch any accidental self-loops.
979 assert(A.first != B.first);
980 // Don't allow any substitutions _from_ the memory operand number.
981 assert(A.second != DebugOperandMemNumber);
983 DebugValueSubstitutions.push_back({A, B, Subreg});
986 void MachineFunction::substituteDebugValuesForInst(const MachineInstr &Old,
987 MachineInstr &New,
988 unsigned MaxOperand) {
989 // If the Old instruction wasn't tracked at all, there is no work to do.
990 unsigned OldInstrNum = Old.peekDebugInstrNum();
991 if (!OldInstrNum)
992 return;
994 // Iterate over all operands looking for defs to create substitutions for.
995 // Avoid creating new instr numbers unless we create a new substitution.
996 // While this has no functional effect, it risks confusing someone reading
997 // MIR output.
998 // Examine all the operands, or the first N specified by the caller.
999 MaxOperand = std::min(MaxOperand, Old.getNumOperands());
1000 for (unsigned int I = 0; I < MaxOperand; ++I) {
1001 const auto &OldMO = Old.getOperand(I);
1002 auto &NewMO = New.getOperand(I);
1003 (void)NewMO;
1005 if (!OldMO.isReg() || !OldMO.isDef())
1006 continue;
1007 assert(NewMO.isDef());
1009 unsigned NewInstrNum = New.getDebugInstrNum();
1010 makeDebugValueSubstitution(std::make_pair(OldInstrNum, I),
1011 std::make_pair(NewInstrNum, I));
1015 auto MachineFunction::salvageCopySSA(
1016 MachineInstr &MI, DenseMap<Register, DebugInstrOperandPair> &DbgPHICache)
1017 -> DebugInstrOperandPair {
1018 const TargetInstrInfo &TII = *getSubtarget().getInstrInfo();
1020 // Check whether this copy-like instruction has already been salvaged into
1021 // an operand pair.
1022 Register Dest;
1023 if (auto CopyDstSrc = TII.isCopyInstr(MI)) {
1024 Dest = CopyDstSrc->Destination->getReg();
1025 } else {
1026 assert(MI.isSubregToReg());
1027 Dest = MI.getOperand(0).getReg();
1030 auto CacheIt = DbgPHICache.find(Dest);
1031 if (CacheIt != DbgPHICache.end())
1032 return CacheIt->second;
1034 // Calculate the instruction number to use, or install a DBG_PHI.
1035 auto OperandPair = salvageCopySSAImpl(MI);
1036 DbgPHICache.insert({Dest, OperandPair});
1037 return OperandPair;
1040 auto MachineFunction::salvageCopySSAImpl(MachineInstr &MI)
1041 -> DebugInstrOperandPair {
1042 MachineRegisterInfo &MRI = getRegInfo();
1043 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
1044 const TargetInstrInfo &TII = *getSubtarget().getInstrInfo();
1046 // Chase the value read by a copy-like instruction back to the instruction
1047 // that ultimately _defines_ that value. This may pass:
1048 // * Through multiple intermediate copies, including subregister moves /
1049 // copies,
1050 // * Copies from physical registers that must then be traced back to the
1051 // defining instruction,
1052 // * Or, physical registers may be live-in to (only) the entry block, which
1053 // requires a DBG_PHI to be created.
1054 // We can pursue this problem in that order: trace back through copies,
1055 // optionally through a physical register, to a defining instruction. We
1056 // should never move from physreg to vreg. As we're still in SSA form, no need
1057 // to worry about partial definitions of registers.
1059 // Helper lambda to interpret a copy-like instruction. Takes instruction,
1060 // returns the register read and any subregister identifying which part is
1061 // read.
1062 auto GetRegAndSubreg =
1063 [&](const MachineInstr &Cpy) -> std::pair<Register, unsigned> {
1064 Register NewReg, OldReg;
1065 unsigned SubReg;
1066 if (Cpy.isCopy()) {
1067 OldReg = Cpy.getOperand(0).getReg();
1068 NewReg = Cpy.getOperand(1).getReg();
1069 SubReg = Cpy.getOperand(1).getSubReg();
1070 } else if (Cpy.isSubregToReg()) {
1071 OldReg = Cpy.getOperand(0).getReg();
1072 NewReg = Cpy.getOperand(2).getReg();
1073 SubReg = Cpy.getOperand(3).getImm();
1074 } else {
1075 auto CopyDetails = *TII.isCopyInstr(Cpy);
1076 const MachineOperand &Src = *CopyDetails.Source;
1077 const MachineOperand &Dest = *CopyDetails.Destination;
1078 OldReg = Dest.getReg();
1079 NewReg = Src.getReg();
1080 SubReg = Src.getSubReg();
1083 return {NewReg, SubReg};
1086 // First seek either the defining instruction, or a copy from a physreg.
1087 // During search, the current state is the current copy instruction, and which
1088 // register we've read. Accumulate qualifying subregisters into SubregsSeen;
1089 // deal with those later.
1090 auto State = GetRegAndSubreg(MI);
1091 auto CurInst = MI.getIterator();
1092 SmallVector<unsigned, 4> SubregsSeen;
1093 while (true) {
1094 // If we've found a copy from a physreg, first portion of search is over.
1095 if (!State.first.isVirtual())
1096 break;
1098 // Record any subregister qualifier.
1099 if (State.second)
1100 SubregsSeen.push_back(State.second);
1102 assert(MRI.hasOneDef(State.first));
1103 MachineInstr &Inst = *MRI.def_begin(State.first)->getParent();
1104 CurInst = Inst.getIterator();
1106 // Any non-copy instruction is the defining instruction we're seeking.
1107 if (!Inst.isCopyLike() && !TII.isCopyInstr(Inst))
1108 break;
1109 State = GetRegAndSubreg(Inst);
1112 // Helper lambda to apply additional subregister substitutions to a known
1113 // instruction/operand pair. Adds new (fake) substitutions so that we can
1114 // record the subregister. FIXME: this isn't very space efficient if multiple
1115 // values are tracked back through the same copies; cache something later.
1116 auto ApplySubregisters =
1117 [&](DebugInstrOperandPair P) -> DebugInstrOperandPair {
1118 for (unsigned Subreg : reverse(SubregsSeen)) {
1119 // Fetch a new instruction number, not attached to an actual instruction.
1120 unsigned NewInstrNumber = getNewDebugInstrNum();
1121 // Add a substitution from the "new" number to the known one, with a
1122 // qualifying subreg.
1123 makeDebugValueSubstitution({NewInstrNumber, 0}, P, Subreg);
1124 // Return the new number; to find the underlying value, consumers need to
1125 // deal with the qualifying subreg.
1126 P = {NewInstrNumber, 0};
1128 return P;
1131 // If we managed to find the defining instruction after COPYs, return an
1132 // instruction / operand pair after adding subregister qualifiers.
1133 if (State.first.isVirtual()) {
1134 // Virtual register def -- we can just look up where this happens.
1135 MachineInstr *Inst = MRI.def_begin(State.first)->getParent();
1136 for (auto &MO : Inst->operands()) {
1137 if (!MO.isReg() || !MO.isDef() || MO.getReg() != State.first)
1138 continue;
1139 return ApplySubregisters(
1140 {Inst->getDebugInstrNum(), Inst->getOperandNo(&MO)});
1143 llvm_unreachable("Vreg def with no corresponding operand?");
1146 // Our search ended in a copy from a physreg: walk back up the function
1147 // looking for whatever defines the physreg.
1148 assert(CurInst->isCopyLike() || TII.isCopyInstr(*CurInst));
1149 State = GetRegAndSubreg(*CurInst);
1150 Register RegToSeek = State.first;
1152 auto RMII = CurInst->getReverseIterator();
1153 auto PrevInstrs = make_range(RMII, CurInst->getParent()->instr_rend());
1154 for (auto &ToExamine : PrevInstrs) {
1155 for (auto &MO : ToExamine.operands()) {
1156 // Test for operand that defines something aliasing RegToSeek.
1157 if (!MO.isReg() || !MO.isDef() ||
1158 !TRI.regsOverlap(RegToSeek, MO.getReg()))
1159 continue;
1161 return ApplySubregisters(
1162 {ToExamine.getDebugInstrNum(), ToExamine.getOperandNo(&MO)});
1166 MachineBasicBlock &InsertBB = *CurInst->getParent();
1168 // We reached the start of the block before finding a defining instruction.
1169 // There are numerous scenarios where this can happen:
1170 // * Constant physical registers,
1171 // * Several intrinsics that allow LLVM-IR to read arbitary registers,
1172 // * Arguments in the entry block,
1173 // * Exception handling landing pads.
1174 // Validating all of them is too difficult, so just insert a DBG_PHI reading
1175 // the variable value at this position, rather than checking it makes sense.
1177 // Create DBG_PHI for specified physreg.
1178 auto Builder = BuildMI(InsertBB, InsertBB.getFirstNonPHI(), DebugLoc(),
1179 TII.get(TargetOpcode::DBG_PHI));
1180 Builder.addReg(State.first);
1181 unsigned NewNum = getNewDebugInstrNum();
1182 Builder.addImm(NewNum);
1183 return ApplySubregisters({NewNum, 0u});
1186 void MachineFunction::finalizeDebugInstrRefs() {
1187 auto *TII = getSubtarget().getInstrInfo();
1189 auto MakeUndefDbgValue = [&](MachineInstr &MI) {
1190 const MCInstrDesc &RefII = TII->get(TargetOpcode::DBG_VALUE);
1191 MI.setDesc(RefII);
1192 MI.getOperand(0).setReg(0);
1193 MI.getOperand(1).ChangeToRegister(0, false);
1196 DenseMap<Register, DebugInstrOperandPair> ArgDbgPHIs;
1197 for (auto &MBB : *this) {
1198 for (auto &MI : MBB) {
1199 if (!MI.isDebugRef() || !MI.getOperand(0).isReg())
1200 continue;
1202 Register Reg = MI.getOperand(0).getReg();
1204 // Some vregs can be deleted as redundant in the meantime. Mark those
1205 // as DBG_VALUE $noreg. Additionally, some normal instructions are
1206 // quickly deleted, leaving dangling references to vregs with no def.
1207 if (Reg == 0 || !RegInfo->hasOneDef(Reg)) {
1208 MakeUndefDbgValue(MI);
1209 continue;
1212 assert(Reg.isVirtual());
1213 MachineInstr &DefMI = *RegInfo->def_instr_begin(Reg);
1215 // If we've found a copy-like instruction, follow it back to the
1216 // instruction that defines the source value, see salvageCopySSA docs
1217 // for why this is important.
1218 if (DefMI.isCopyLike() || TII->isCopyInstr(DefMI)) {
1219 auto Result = salvageCopySSA(DefMI, ArgDbgPHIs);
1220 MI.getOperand(0).ChangeToImmediate(Result.first);
1221 MI.getOperand(1).setImm(Result.second);
1222 } else {
1223 // Otherwise, identify the operand number that the VReg refers to.
1224 unsigned OperandIdx = 0;
1225 for (const auto &MO : DefMI.operands()) {
1226 if (MO.isReg() && MO.isDef() && MO.getReg() == Reg)
1227 break;
1228 ++OperandIdx;
1230 assert(OperandIdx < DefMI.getNumOperands());
1232 // Morph this instr ref to point at the given instruction and operand.
1233 unsigned ID = DefMI.getDebugInstrNum();
1234 MI.getOperand(0).ChangeToImmediate(ID);
1235 MI.getOperand(1).setImm(OperandIdx);
1241 bool MachineFunction::useDebugInstrRef() const {
1242 // Disable instr-ref at -O0: it's very slow (in compile time). We can still
1243 // have optimized code inlined into this unoptimized code, however with
1244 // fewer and less aggressive optimizations happening, coverage and accuracy
1245 // should not suffer.
1246 if (getTarget().getOptLevel() == CodeGenOpt::None)
1247 return false;
1249 // Don't use instr-ref if this function is marked optnone.
1250 if (F.hasFnAttribute(Attribute::OptimizeNone))
1251 return false;
1253 if (llvm::debuginfoShouldUseDebugInstrRef(getTarget().getTargetTriple()))
1254 return true;
1256 return false;
1259 // Use one million as a high / reserved number.
1260 const unsigned MachineFunction::DebugOperandMemNumber = 1000000;
1262 /// \}
1264 //===----------------------------------------------------------------------===//
1265 // MachineJumpTableInfo implementation
1266 //===----------------------------------------------------------------------===//
1268 /// Return the size of each entry in the jump table.
1269 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
1270 // The size of a jump table entry is 4 bytes unless the entry is just the
1271 // address of a block, in which case it is the pointer size.
1272 switch (getEntryKind()) {
1273 case MachineJumpTableInfo::EK_BlockAddress:
1274 return TD.getPointerSize();
1275 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
1276 return 8;
1277 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
1278 case MachineJumpTableInfo::EK_LabelDifference32:
1279 case MachineJumpTableInfo::EK_Custom32:
1280 return 4;
1281 case MachineJumpTableInfo::EK_Inline:
1282 return 0;
1284 llvm_unreachable("Unknown jump table encoding!");
1287 /// Return the alignment of each entry in the jump table.
1288 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
1289 // The alignment of a jump table entry is the alignment of int32 unless the
1290 // entry is just the address of a block, in which case it is the pointer
1291 // alignment.
1292 switch (getEntryKind()) {
1293 case MachineJumpTableInfo::EK_BlockAddress:
1294 return TD.getPointerABIAlignment(0).value();
1295 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
1296 return TD.getABIIntegerTypeAlignment(64).value();
1297 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
1298 case MachineJumpTableInfo::EK_LabelDifference32:
1299 case MachineJumpTableInfo::EK_Custom32:
1300 return TD.getABIIntegerTypeAlignment(32).value();
1301 case MachineJumpTableInfo::EK_Inline:
1302 return 1;
1304 llvm_unreachable("Unknown jump table encoding!");
1307 /// Create a new jump table entry in the jump table info.
1308 unsigned MachineJumpTableInfo::createJumpTableIndex(
1309 const std::vector<MachineBasicBlock*> &DestBBs) {
1310 assert(!DestBBs.empty() && "Cannot create an empty jump table!");
1311 JumpTables.push_back(MachineJumpTableEntry(DestBBs));
1312 return JumpTables.size()-1;
1315 /// If Old is the target of any jump tables, update the jump tables to branch
1316 /// to New instead.
1317 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
1318 MachineBasicBlock *New) {
1319 assert(Old != New && "Not making a change?");
1320 bool MadeChange = false;
1321 for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
1322 ReplaceMBBInJumpTable(i, Old, New);
1323 return MadeChange;
1326 /// If MBB is present in any jump tables, remove it.
1327 bool MachineJumpTableInfo::RemoveMBBFromJumpTables(MachineBasicBlock *MBB) {
1328 bool MadeChange = false;
1329 for (MachineJumpTableEntry &JTE : JumpTables) {
1330 auto removeBeginItr = std::remove(JTE.MBBs.begin(), JTE.MBBs.end(), MBB);
1331 MadeChange |= (removeBeginItr != JTE.MBBs.end());
1332 JTE.MBBs.erase(removeBeginItr, JTE.MBBs.end());
1334 return MadeChange;
1337 /// If Old is a target of the jump tables, update the jump table to branch to
1338 /// New instead.
1339 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
1340 MachineBasicBlock *Old,
1341 MachineBasicBlock *New) {
1342 assert(Old != New && "Not making a change?");
1343 bool MadeChange = false;
1344 MachineJumpTableEntry &JTE = JumpTables[Idx];
1345 for (MachineBasicBlock *&MBB : JTE.MBBs)
1346 if (MBB == Old) {
1347 MBB = New;
1348 MadeChange = true;
1350 return MadeChange;
1353 void MachineJumpTableInfo::print(raw_ostream &OS) const {
1354 if (JumpTables.empty()) return;
1356 OS << "Jump Tables:\n";
1358 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
1359 OS << printJumpTableEntryReference(i) << ':';
1360 for (const MachineBasicBlock *MBB : JumpTables[i].MBBs)
1361 OS << ' ' << printMBBReference(*MBB);
1362 if (i != e)
1363 OS << '\n';
1366 OS << '\n';
1369 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1370 LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); }
1371 #endif
1373 Printable llvm::printJumpTableEntryReference(unsigned Idx) {
1374 return Printable([Idx](raw_ostream &OS) { OS << "%jump-table." << Idx; });
1377 //===----------------------------------------------------------------------===//
1378 // MachineConstantPool implementation
1379 //===----------------------------------------------------------------------===//
1381 void MachineConstantPoolValue::anchor() {}
1383 unsigned MachineConstantPoolValue::getSizeInBytes(const DataLayout &DL) const {
1384 return DL.getTypeAllocSize(Ty);
1387 unsigned MachineConstantPoolEntry::getSizeInBytes(const DataLayout &DL) const {
1388 if (isMachineConstantPoolEntry())
1389 return Val.MachineCPVal->getSizeInBytes(DL);
1390 return DL.getTypeAllocSize(Val.ConstVal->getType());
1393 bool MachineConstantPoolEntry::needsRelocation() const {
1394 if (isMachineConstantPoolEntry())
1395 return true;
1396 return Val.ConstVal->needsDynamicRelocation();
1399 SectionKind
1400 MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
1401 if (needsRelocation())
1402 return SectionKind::getReadOnlyWithRel();
1403 switch (getSizeInBytes(*DL)) {
1404 case 4:
1405 return SectionKind::getMergeableConst4();
1406 case 8:
1407 return SectionKind::getMergeableConst8();
1408 case 16:
1409 return SectionKind::getMergeableConst16();
1410 case 32:
1411 return SectionKind::getMergeableConst32();
1412 default:
1413 return SectionKind::getReadOnly();
1417 MachineConstantPool::~MachineConstantPool() {
1418 // A constant may be a member of both Constants and MachineCPVsSharingEntries,
1419 // so keep track of which we've deleted to avoid double deletions.
1420 DenseSet<MachineConstantPoolValue*> Deleted;
1421 for (const MachineConstantPoolEntry &C : Constants)
1422 if (C.isMachineConstantPoolEntry()) {
1423 Deleted.insert(C.Val.MachineCPVal);
1424 delete C.Val.MachineCPVal;
1426 for (MachineConstantPoolValue *CPV : MachineCPVsSharingEntries) {
1427 if (Deleted.count(CPV) == 0)
1428 delete CPV;
1432 /// Test whether the given two constants can be allocated the same constant pool
1433 /// entry.
1434 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
1435 const DataLayout &DL) {
1436 // Handle the trivial case quickly.
1437 if (A == B) return true;
1439 // If they have the same type but weren't the same constant, quickly
1440 // reject them.
1441 if (A->getType() == B->getType()) return false;
1443 // We can't handle structs or arrays.
1444 if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
1445 isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
1446 return false;
1448 // For now, only support constants with the same size.
1449 uint64_t StoreSize = DL.getTypeStoreSize(A->getType());
1450 if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128)
1451 return false;
1453 Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
1455 // Try constant folding a bitcast of both instructions to an integer. If we
1456 // get two identical ConstantInt's, then we are good to share them. We use
1457 // the constant folding APIs to do this so that we get the benefit of
1458 // DataLayout.
1459 if (isa<PointerType>(A->getType()))
1460 A = ConstantFoldCastOperand(Instruction::PtrToInt,
1461 const_cast<Constant *>(A), IntTy, DL);
1462 else if (A->getType() != IntTy)
1463 A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A),
1464 IntTy, DL);
1465 if (isa<PointerType>(B->getType()))
1466 B = ConstantFoldCastOperand(Instruction::PtrToInt,
1467 const_cast<Constant *>(B), IntTy, DL);
1468 else if (B->getType() != IntTy)
1469 B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B),
1470 IntTy, DL);
1472 return A == B;
1475 /// Create a new entry in the constant pool or return an existing one.
1476 /// User must specify the log2 of the minimum required alignment for the object.
1477 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
1478 Align Alignment) {
1479 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
1481 // Check to see if we already have this constant.
1483 // FIXME, this could be made much more efficient for large constant pools.
1484 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
1485 if (!Constants[i].isMachineConstantPoolEntry() &&
1486 CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) {
1487 if (Constants[i].getAlign() < Alignment)
1488 Constants[i].Alignment = Alignment;
1489 return i;
1492 Constants.push_back(MachineConstantPoolEntry(C, Alignment));
1493 return Constants.size()-1;
1496 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
1497 Align Alignment) {
1498 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
1500 // Check to see if we already have this constant.
1502 // FIXME, this could be made much more efficient for large constant pools.
1503 int Idx = V->getExistingMachineCPValue(this, Alignment);
1504 if (Idx != -1) {
1505 MachineCPVsSharingEntries.insert(V);
1506 return (unsigned)Idx;
1509 Constants.push_back(MachineConstantPoolEntry(V, Alignment));
1510 return Constants.size()-1;
1513 void MachineConstantPool::print(raw_ostream &OS) const {
1514 if (Constants.empty()) return;
1516 OS << "Constant Pool:\n";
1517 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1518 OS << " cp#" << i << ": ";
1519 if (Constants[i].isMachineConstantPoolEntry())
1520 Constants[i].Val.MachineCPVal->print(OS);
1521 else
1522 Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
1523 OS << ", align=" << Constants[i].getAlign().value();
1524 OS << "\n";
1528 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1529 LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); }
1530 #endif