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