LLVM  4.0.0
MachineFunction.cpp
Go to the documentation of this file.
1 //===-- MachineFunction.cpp -----------------------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Collect native machine code information for a function. This allows
11 // target-specific information about the generated code to be stored with each
12 // function.
13 //
14 //===----------------------------------------------------------------------===//
15 
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallString.h"
29 #include "llvm/CodeGen/Passes.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/DebugInfo.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/Module.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/MC/MCContext.h"
39 #include "llvm/Support/Debug.h"
46 using namespace llvm;
47 
48 #define DEBUG_TYPE "codegen"
49 
50 static cl::opt<unsigned>
51  AlignAllFunctions("align-all-functions",
52  cl::desc("Force the alignment of all functions."),
53  cl::init(0), cl::Hidden);
54 
55 void MachineFunctionInitializer::anchor() {}
56 
59  switch(Prop) {
60  case P::FailedISel: return "FailedISel";
61  case P::IsSSA: return "IsSSA";
62  case P::Legalized: return "Legalized";
63  case P::NoPHIs: return "NoPHIs";
64  case P::NoVRegs: return "NoVRegs";
65  case P::RegBankSelected: return "RegBankSelected";
66  case P::Selected: return "Selected";
67  case P::TracksLiveness: return "TracksLiveness";
68  }
69  llvm_unreachable("Invalid machine function property");
70 }
71 
73  const char *Separator = "";
74  for (BitVector::size_type I = 0; I < Properties.size(); ++I) {
75  if (!Properties[I])
76  continue;
77  OS << Separator << getPropertyName(static_cast<Property>(I));
78  Separator = ", ";
79  }
80 }
81 
82 //===----------------------------------------------------------------------===//
83 // MachineFunction implementation
84 //===----------------------------------------------------------------------===//
85 
86 // Out-of-line virtual method.
88 
91 }
92 
93 static inline unsigned getFnStackAlignment(const TargetSubtargetInfo *STI,
94  const Function *Fn) {
95  if (Fn->hasFnAttribute(Attribute::StackAlignment))
96  return Fn->getFnStackAlignment();
97  return STI->getFrameLowering()->getStackAlignment();
98 }
99 
100 MachineFunction::MachineFunction(const Function *F, const TargetMachine &TM,
101  unsigned FunctionNum, MachineModuleInfo &mmi)
102  : Fn(F), Target(TM), STI(TM.getSubtargetImpl(*F)), Ctx(mmi.getContext()),
103  MMI(mmi) {
104  FunctionNumber = FunctionNum;
105  init();
106 }
107 
108 void MachineFunction::init() {
109  // Assume the function starts in SSA form with correct liveness.
112  if (STI->getRegisterInfo())
113  RegInfo = new (Allocator) MachineRegisterInfo(this);
114  else
115  RegInfo = nullptr;
116 
117  MFInfo = nullptr;
118  // We can realign the stack if the target supports it and the user hasn't
119  // explicitly asked us not to.
120  bool CanRealignSP = STI->getFrameLowering()->isStackRealignable() &&
121  !Fn->hasFnAttribute("no-realign-stack");
122  FrameInfo = new (Allocator) MachineFrameInfo(
123  getFnStackAlignment(STI, Fn), /*StackRealignable=*/CanRealignSP,
124  /*ForceRealign=*/CanRealignSP &&
125  Fn->hasFnAttribute(Attribute::StackAlignment));
126 
127  if (Fn->hasFnAttribute(Attribute::StackAlignment))
128  FrameInfo->ensureMaxAlignment(Fn->getFnStackAlignment());
129 
130  ConstantPool = new (Allocator) MachineConstantPool(getDataLayout());
131  Alignment = STI->getTargetLowering()->getMinFunctionAlignment();
132 
133  // FIXME: Shouldn't use pref alignment if explicit alignment is set on Fn.
134  // FIXME: Use Function::optForSize().
135  if (!Fn->hasFnAttribute(Attribute::OptimizeForSize))
136  Alignment = std::max(Alignment,
138 
139  if (AlignAllFunctions)
140  Alignment = AlignAllFunctions;
141 
142  JumpTableInfo = nullptr;
143 
145  Fn->hasPersonalityFn() ? Fn->getPersonalityFn() : nullptr))) {
146  WinEHInfo = new (Allocator) WinEHFuncInfo();
147  }
148 
149  assert(Target.isCompatibleDataLayout(getDataLayout()) &&
150  "Can't create a MachineFunction using a Module with a "
151  "Target-incompatible DataLayout attached\n");
152 
153  PSVManager = llvm::make_unique<PseudoSourceValueManager>();
154 }
155 
157  clear();
158 }
159 
160 void MachineFunction::clear() {
161  Properties.reset();
162  // Don't call destructors on MachineInstr and MachineOperand. All of their
163  // memory comes from the BumpPtrAllocator which is about to be purged.
164  //
165  // Do call MachineBasicBlock destructors, it contains std::vectors.
166  for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
167  I->Insts.clearAndLeakNodesUnsafely();
168 
169  InstructionRecycler.clear(Allocator);
170  OperandRecycler.clear(Allocator);
171  BasicBlockRecycler.clear(Allocator);
172  if (RegInfo) {
173  RegInfo->~MachineRegisterInfo();
174  Allocator.Deallocate(RegInfo);
175  }
176  if (MFInfo) {
177  MFInfo->~MachineFunctionInfo();
178  Allocator.Deallocate(MFInfo);
179  }
180 
181  FrameInfo->~MachineFrameInfo();
182  Allocator.Deallocate(FrameInfo);
183 
184  ConstantPool->~MachineConstantPool();
185  Allocator.Deallocate(ConstantPool);
186 
187  if (JumpTableInfo) {
188  JumpTableInfo->~MachineJumpTableInfo();
189  Allocator.Deallocate(JumpTableInfo);
190  }
191 
192  if (WinEHInfo) {
193  WinEHInfo->~WinEHFuncInfo();
194  Allocator.Deallocate(WinEHInfo);
195  }
196 }
197 
199  return Fn->getParent()->getDataLayout();
200 }
201 
202 /// Get the JumpTableInfo for this function.
203 /// If it does not already exist, allocate one.
205 getOrCreateJumpTableInfo(unsigned EntryKind) {
206  if (JumpTableInfo) return JumpTableInfo;
207 
208  JumpTableInfo = new (Allocator)
210  return JumpTableInfo;
211 }
212 
213 /// Should we be emitting segmented stack stuff for the function
215  return getFunction()->hasFnAttribute("split-stack");
216 }
217 
218 /// This discards all of the MachineBasicBlock numbers and recomputes them.
219 /// This guarantees that the MBB numbers are sequential, dense, and match the
220 /// ordering of the blocks within the function. If a specific MachineBasicBlock
221 /// is specified, only that block and those after it are renumbered.
223  if (empty()) { MBBNumbering.clear(); return; }
224  MachineFunction::iterator MBBI, E = end();
225  if (MBB == nullptr)
226  MBBI = begin();
227  else
228  MBBI = MBB->getIterator();
229 
230  // Figure out the block number this should have.
231  unsigned BlockNo = 0;
232  if (MBBI != begin())
233  BlockNo = std::prev(MBBI)->getNumber() + 1;
234 
235  for (; MBBI != E; ++MBBI, ++BlockNo) {
236  if (MBBI->getNumber() != (int)BlockNo) {
237  // Remove use of the old number.
238  if (MBBI->getNumber() != -1) {
239  assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
240  "MBB number mismatch!");
241  MBBNumbering[MBBI->getNumber()] = nullptr;
242  }
243 
244  // If BlockNo is already taken, set that block's number to -1.
245  if (MBBNumbering[BlockNo])
246  MBBNumbering[BlockNo]->setNumber(-1);
247 
248  MBBNumbering[BlockNo] = &*MBBI;
249  MBBI->setNumber(BlockNo);
250  }
251  }
252 
253  // Okay, all the blocks are renumbered. If we have compactified the block
254  // numbering, shrink MBBNumbering now.
255  assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
256  MBBNumbering.resize(BlockNo);
257 }
258 
259 /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'.
261  const DebugLoc &DL,
262  bool NoImp) {
263  return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
264  MachineInstr(*this, MCID, DL, NoImp);
265 }
266 
267 /// Create a new MachineInstr which is a copy of the 'Orig' instruction,
268 /// identical in all ways except the instruction has no parent, prev, or next.
269 MachineInstr *
271  return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
272  MachineInstr(*this, *Orig);
273 }
274 
275 /// Delete the given MachineInstr.
276 ///
277 /// This function also serves as the MachineInstr destructor - the real
278 /// ~MachineInstr() destructor must be empty.
279 void
281  // Strip it for parts. The operand array and the MI object itself are
282  // independently recyclable.
283  if (MI->Operands)
284  deallocateOperandArray(MI->CapOperands, MI->Operands);
285  // Don't call ~MachineInstr() which must be trivial anyway because
286  // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
287  // destructors.
288  InstructionRecycler.Deallocate(Allocator, MI);
289 }
290 
291 /// Allocate a new MachineBasicBlock. Use this instead of
292 /// `new MachineBasicBlock'.
295  return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
296  MachineBasicBlock(*this, bb);
297 }
298 
299 /// Delete the given MachineBasicBlock.
300 void
302  assert(MBB->getParent() == this && "MBB parent mismatch!");
303  MBB->~MachineBasicBlock();
304  BasicBlockRecycler.Deallocate(Allocator, MBB);
305 }
306 
308  MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s,
309  unsigned base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges,
310  SynchronizationScope SynchScope, AtomicOrdering Ordering,
311  AtomicOrdering FailureOrdering) {
312  return new (Allocator)
313  MachineMemOperand(PtrInfo, f, s, base_alignment, AAInfo, Ranges,
314  SynchScope, Ordering, FailureOrdering);
315 }
316 
319  int64_t Offset, uint64_t Size) {
320  if (MMO->getValue())
321  return new (Allocator)
323  MMO->getOffset()+Offset),
324  MMO->getFlags(), Size, MMO->getBaseAlignment(),
325  AAMDNodes(), nullptr, MMO->getSynchScope(),
326  MMO->getOrdering(), MMO->getFailureOrdering());
327  return new (Allocator)
329  MMO->getOffset()+Offset),
330  MMO->getFlags(), Size, MMO->getBaseAlignment(),
331  AAMDNodes(), nullptr, MMO->getSynchScope(),
332  MMO->getOrdering(), MMO->getFailureOrdering());
333 }
334 
337  return Allocator.Allocate<MachineMemOperand *>(Num);
338 }
339 
340 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
343  // Count the number of load mem refs.
344  unsigned Num = 0;
345  for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
346  if ((*I)->isLoad())
347  ++Num;
348 
349  // Allocate a new array and populate it with the load information.
351  unsigned Index = 0;
352  for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
353  if ((*I)->isLoad()) {
354  if (!(*I)->isStore())
355  // Reuse the MMO.
356  Result[Index] = *I;
357  else {
358  // Clone the MMO and unset the store flag.
359  MachineMemOperand *JustLoad =
360  getMachineMemOperand((*I)->getPointerInfo(),
361  (*I)->getFlags() & ~MachineMemOperand::MOStore,
362  (*I)->getSize(), (*I)->getBaseAlignment(),
363  (*I)->getAAInfo(), nullptr,
364  (*I)->getSynchScope(), (*I)->getOrdering(),
365  (*I)->getFailureOrdering());
366  Result[Index] = JustLoad;
367  }
368  ++Index;
369  }
370  }
371  return std::make_pair(Result, Result + Num);
372 }
373 
374 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
377  // Count the number of load mem refs.
378  unsigned Num = 0;
379  for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
380  if ((*I)->isStore())
381  ++Num;
382 
383  // Allocate a new array and populate it with the store information.
385  unsigned Index = 0;
386  for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
387  if ((*I)->isStore()) {
388  if (!(*I)->isLoad())
389  // Reuse the MMO.
390  Result[Index] = *I;
391  else {
392  // Clone the MMO and unset the load flag.
393  MachineMemOperand *JustStore =
394  getMachineMemOperand((*I)->getPointerInfo(),
395  (*I)->getFlags() & ~MachineMemOperand::MOLoad,
396  (*I)->getSize(), (*I)->getBaseAlignment(),
397  (*I)->getAAInfo(), nullptr,
398  (*I)->getSynchScope(), (*I)->getOrdering(),
399  (*I)->getFailureOrdering());
400  Result[Index] = JustStore;
401  }
402  ++Index;
403  }
404  }
405  return std::make_pair(Result, Result + Num);
406 }
407 
409  char *Dest = Allocator.Allocate<char>(Name.size() + 1);
410  std::copy(Name.begin(), Name.end(), Dest);
411  Dest[Name.size()] = 0;
412  return Dest;
413 }
414 
415 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
417  print(dbgs());
418 }
419 #endif
420 
422  assert(getFunction() && "No function!");
423  return getFunction()->getName();
424 }
425 
426 void MachineFunction::print(raw_ostream &OS, const SlotIndexes *Indexes) const {
427  OS << "# Machine code for function " << getName() << ": ";
428  getProperties().print(OS);
429  OS << '\n';
430 
431  // Print Frame Information
432  FrameInfo->print(*this, OS);
433 
434  // Print JumpTable Information
435  if (JumpTableInfo)
436  JumpTableInfo->print(OS);
437 
438  // Print Constant Pool
439  ConstantPool->print(OS);
440 
442 
443  if (RegInfo && !RegInfo->livein_empty()) {
444  OS << "Function Live Ins: ";
446  I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
447  OS << PrintReg(I->first, TRI);
448  if (I->second)
449  OS << " in " << PrintReg(I->second, TRI);
450  if (std::next(I) != E)
451  OS << ", ";
452  }
453  OS << '\n';
454  }
455 
458  for (const auto &BB : *this) {
459  OS << '\n';
460  BB.print(OS, MST, Indexes);
461  }
462 
463  OS << "\n# End machine code for function " << getName() << ".\n\n";
464 }
465 
466 namespace llvm {
467  template<>
469 
471 
472  static std::string getGraphName(const MachineFunction *F) {
473  return ("CFG for '" + F->getName() + "' function").str();
474  }
475 
476  std::string getNodeLabel(const MachineBasicBlock *Node,
477  const MachineFunction *Graph) {
478  std::string OutStr;
479  {
480  raw_string_ostream OSS(OutStr);
481 
482  if (isSimple()) {
483  OSS << "BB#" << Node->getNumber();
484  if (const BasicBlock *BB = Node->getBasicBlock())
485  OSS << ": " << BB->getName();
486  } else
487  Node->print(OSS);
488  }
489 
490  if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
491 
492  // Process string output to make it nicer...
493  for (unsigned i = 0; i != OutStr.length(); ++i)
494  if (OutStr[i] == '\n') { // Left justify
495  OutStr[i] = '\\';
496  OutStr.insert(OutStr.begin()+i+1, 'l');
497  }
498  return OutStr;
499  }
500  };
501 }
502 
504 {
505 #ifndef NDEBUG
506  ViewGraph(this, "mf" + getName());
507 #else
508  errs() << "MachineFunction::viewCFG is only available in debug builds on "
509  << "systems with Graphviz or gv!\n";
510 #endif // NDEBUG
511 }
512 
514 {
515 #ifndef NDEBUG
516  ViewGraph(this, "mf" + getName(), true);
517 #else
518  errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
519  << "systems with Graphviz or gv!\n";
520 #endif // NDEBUG
521 }
522 
523 /// Add the specified physical register as a live-in value and
524 /// create a corresponding virtual register for it.
525 unsigned MachineFunction::addLiveIn(unsigned PReg,
526  const TargetRegisterClass *RC) {
528  unsigned VReg = MRI.getLiveInVirtReg(PReg);
529  if (VReg) {
530  const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
531  (void)VRegRC;
532  // A physical register can be added several times.
533  // Between two calls, the register class of the related virtual register
534  // may have been constrained to match some operation constraints.
535  // In that case, check that the current register class includes the
536  // physical register and is a sub class of the specified RC.
537  assert((VRegRC == RC || (VRegRC->contains(PReg) &&
538  RC->hasSubClassEq(VRegRC))) &&
539  "Register class mismatch!");
540  return VReg;
541  }
542  VReg = MRI.createVirtualRegister(RC);
543  MRI.addLiveIn(PReg, VReg);
544  return VReg;
545 }
546 
547 /// Return the MCSymbol for the specified non-empty jump table.
548 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
549 /// normal 'L' label is returned.
551  bool isLinkerPrivate) const {
552  const DataLayout &DL = getDataLayout();
553  assert(JumpTableInfo && "No jump tables");
554  assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
555 
556  StringRef Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix()
557  : DL.getPrivateGlobalPrefix();
559  raw_svector_ostream(Name)
560  << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
561  return Ctx.getOrCreateSymbol(Name);
562 }
563 
564 /// Return a function-local symbol to represent the PIC base.
566  const DataLayout &DL = getDataLayout();
568  Twine(getFunctionNumber()) + "$pb");
569 }
570 
571 /// \name Exception Handling
572 /// \{
573 
576  unsigned N = LandingPads.size();
577  for (unsigned i = 0; i < N; ++i) {
578  LandingPadInfo &LP = LandingPads[i];
579  if (LP.LandingPadBlock == LandingPad)
580  return LP;
581  }
582 
583  LandingPads.push_back(LandingPadInfo(LandingPad));
584  return LandingPads[N];
585 }
586 
588  MCSymbol *BeginLabel, MCSymbol *EndLabel) {
589  LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
590  LP.BeginLabels.push_back(BeginLabel);
591  LP.EndLabels.push_back(EndLabel);
592 }
593 
595  MCSymbol *LandingPadLabel = Ctx.createTempSymbol();
596  LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
597  LP.LandingPadLabel = LandingPadLabel;
598  return LandingPadLabel;
599 }
600 
603  LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
604  for (unsigned N = TyInfo.size(); N; --N)
605  LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1]));
606 }
607 
610  LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
611  std::vector<unsigned> IdsInFilter(TyInfo.size());
612  for (unsigned I = 0, E = TyInfo.size(); I != E; ++I)
613  IdsInFilter[I] = getTypeIDFor(TyInfo[I]);
614  LP.TypeIds.push_back(getFilterIDFor(IdsInFilter));
615 }
616 
618  for (unsigned i = 0; i != LandingPads.size(); ) {
619  LandingPadInfo &LandingPad = LandingPads[i];
620  if (LandingPad.LandingPadLabel &&
621  !LandingPad.LandingPadLabel->isDefined() &&
622  (!LPMap || (*LPMap)[LandingPad.LandingPadLabel] == 0))
623  LandingPad.LandingPadLabel = nullptr;
624 
625  // Special case: we *should* emit LPs with null LP MBB. This indicates
626  // "nounwind" case.
627  if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) {
628  LandingPads.erase(LandingPads.begin() + i);
629  continue;
630  }
631 
632  for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) {
633  MCSymbol *BeginLabel = LandingPad.BeginLabels[j];
634  MCSymbol *EndLabel = LandingPad.EndLabels[j];
635  if ((BeginLabel->isDefined() ||
636  (LPMap && (*LPMap)[BeginLabel] != 0)) &&
637  (EndLabel->isDefined() ||
638  (LPMap && (*LPMap)[EndLabel] != 0))) continue;
639 
640  LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j);
641  LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j);
642  --j;
643  --e;
644  }
645 
646  // Remove landing pads with no try-ranges.
647  if (LandingPads[i].BeginLabels.empty()) {
648  LandingPads.erase(LandingPads.begin() + i);
649  continue;
650  }
651 
652  // If there is no landing pad, ensure that the list of typeids is empty.
653  // If the only typeid is a cleanup, this is the same as having no typeids.
654  if (!LandingPad.LandingPadBlock ||
655  (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0]))
656  LandingPad.TypeIds.clear();
657  ++i;
658  }
659 }
660 
662  LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
663  LP.TypeIds.push_back(0);
664 }
665 
667  const Function *Filter,
668  const BlockAddress *RecoverBA) {
669  LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
670  SEHHandler Handler;
671  Handler.FilterOrFinally = Filter;
672  Handler.RecoverBA = RecoverBA;
673  LP.SEHHandlers.push_back(Handler);
674 }
675 
677  const Function *Cleanup) {
678  LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
679  SEHHandler Handler;
680  Handler.FilterOrFinally = Cleanup;
681  Handler.RecoverBA = nullptr;
682  LP.SEHHandlers.push_back(Handler);
683 }
684 
686  ArrayRef<unsigned> Sites) {
687  LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end());
688 }
689 
691  for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
692  if (TypeInfos[i] == TI) return i + 1;
693 
694  TypeInfos.push_back(TI);
695  return TypeInfos.size();
696 }
697 
698 int MachineFunction::getFilterIDFor(std::vector<unsigned> &TyIds) {
699  // If the new filter coincides with the tail of an existing filter, then
700  // re-use the existing filter. Folding filters more than this requires
701  // re-ordering filters and/or their elements - probably not worth it.
702  for (std::vector<unsigned>::iterator I = FilterEnds.begin(),
703  E = FilterEnds.end(); I != E; ++I) {
704  unsigned i = *I, j = TyIds.size();
705 
706  while (i && j)
707  if (FilterIds[--i] != TyIds[--j])
708  goto try_next;
709 
710  if (!j)
711  // The new filter coincides with range [i, end) of the existing filter.
712  return -(1 + i);
713 
714 try_next:;
715  }
716 
717  // Add the new filter.
718  int FilterID = -(1 + FilterIds.size());
719  FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
720  FilterIds.insert(FilterIds.end(), TyIds.begin(), TyIds.end());
721  FilterEnds.push_back(FilterIds.size());
722  FilterIds.push_back(0); // terminator
723  return FilterID;
724 }
725 
727  MachineFunction &MF = *MBB.getParent();
728  if (const auto *PF = dyn_cast<Function>(
730  MF.getMMI().addPersonality(PF);
731 
732  if (I.isCleanup())
733  MF.addCleanup(&MBB);
734 
735  // FIXME: New EH - Add the clauses in reverse order. This isn't 100% correct,
736  // but we need to do it this way because of how the DWARF EH emitter
737  // processes the clauses.
738  for (unsigned i = I.getNumClauses(); i != 0; --i) {
739  Value *Val = I.getClause(i - 1);
740  if (I.isCatch(i - 1)) {
741  MF.addCatchTypeInfo(&MBB,
742  dyn_cast<GlobalValue>(Val->stripPointerCasts()));
743  } else {
744  // Add filters in a list.
745  Constant *CVal = cast<Constant>(Val);
747  for (User::op_iterator II = CVal->op_begin(), IE = CVal->op_end();
748  II != IE; ++II)
749  FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts()));
750 
751  MF.addFilterTypeInfo(&MBB, FilterList);
752  }
753  }
754 }
755 
756 /// \}
757 
758 //===----------------------------------------------------------------------===//
759 // MachineFrameInfo implementation
760 //===----------------------------------------------------------------------===//
761 
762 /// Make sure the function is at least Align bytes aligned.
764  if (!StackRealignable)
765  assert(Align <= StackAlignment &&
766  "For targets without stack realignment, Align is out of limit!");
767  if (MaxAlignment < Align) MaxAlignment = Align;
768 }
769 
770 /// Clamp the alignment if requested and emit a warning.
771 static inline unsigned clampStackAlignment(bool ShouldClamp, unsigned Align,
772  unsigned StackAlign) {
773  if (!ShouldClamp || Align <= StackAlign)
774  return Align;
775  DEBUG(dbgs() << "Warning: requested alignment " << Align
776  << " exceeds the stack alignment " << StackAlign
777  << " when stack realignment is off" << '\n');
778  return StackAlign;
779 }
780 
781 /// Create a new statically sized stack object, returning a nonnegative
782 /// identifier to represent it.
783 int MachineFrameInfo::CreateStackObject(uint64_t Size, unsigned Alignment,
784  bool isSS, const AllocaInst *Alloca) {
785  assert(Size != 0 && "Cannot allocate zero size stack objects!");
786  Alignment = clampStackAlignment(!StackRealignable, Alignment, StackAlignment);
787  Objects.push_back(StackObject(Size, Alignment, 0, false, isSS, Alloca,
788  !isSS));
789  int Index = (int)Objects.size() - NumFixedObjects - 1;
790  assert(Index >= 0 && "Bad frame index!");
791  ensureMaxAlignment(Alignment);
792  return Index;
793 }
794 
795 /// Create a new statically sized stack object that represents a spill slot,
796 /// returning a nonnegative identifier to represent it.
798  unsigned Alignment) {
799  Alignment = clampStackAlignment(!StackRealignable, Alignment, StackAlignment);
800  CreateStackObject(Size, Alignment, true);
801  int Index = (int)Objects.size() - NumFixedObjects - 1;
802  ensureMaxAlignment(Alignment);
803  return Index;
804 }
805 
806 /// Notify the MachineFrameInfo object that a variable sized object has been
807 /// created. This must be created whenever a variable sized object is created,
808 /// whether or not the index returned is actually used.
810  const AllocaInst *Alloca) {
811  HasVarSizedObjects = true;
812  Alignment = clampStackAlignment(!StackRealignable, Alignment, StackAlignment);
813  Objects.push_back(StackObject(0, Alignment, 0, false, false, Alloca, true));
814  ensureMaxAlignment(Alignment);
815  return (int)Objects.size()-NumFixedObjects-1;
816 }
817 
818 /// Create a new object at a fixed location on the stack.
819 /// All fixed objects should be created before other objects are created for
820 /// efficiency. By default, fixed objects are immutable. This returns an
821 /// index with a negative value.
822 int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
823  bool Immutable, bool isAliased) {
824  assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
825  // The alignment of the frame index can be determined from its offset from
826  // the incoming frame position. If the frame object is at offset 32 and
827  // the stack is guaranteed to be 16-byte aligned, then we know that the
828  // object is 16-byte aligned. Note that unlike the non-fixed case, if the
829  // stack needs realignment, we can't assume that the stack will in fact be
830  // aligned.
831  unsigned Align = MinAlign(SPOffset, ForcedRealign ? 1 : StackAlignment);
832  Align = clampStackAlignment(!StackRealignable, Align, StackAlignment);
833  Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset, Immutable,
834  /*isSS*/ false,
835  /*Alloca*/ nullptr, isAliased));
836  return -++NumFixedObjects;
837 }
838 
839 /// Create a spill slot at a fixed location on the stack.
840 /// Returns an index with a negative value.
842  int64_t SPOffset,
843  bool Immutable) {
844  unsigned Align = MinAlign(SPOffset, ForcedRealign ? 1 : StackAlignment);
845  Align = clampStackAlignment(!StackRealignable, Align, StackAlignment);
846  Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset, Immutable,
847  /*isSS*/ true,
848  /*Alloca*/ nullptr,
849  /*isAliased*/ false));
850  return -++NumFixedObjects;
851 }
852 
854  const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
855  BitVector BV(TRI->getNumRegs());
856 
857  // Before CSI is calculated, no registers are considered pristine. They can be
858  // freely used and PEI will make sure they are saved.
859  if (!isCalleeSavedInfoValid())
860  return BV;
861 
862  for (const MCPhysReg *CSR = TRI->getCalleeSavedRegs(&MF); CSR && *CSR; ++CSR)
863  BV.set(*CSR);
864 
865  // Saved CSRs are not pristine.
866  for (auto &I : getCalleeSavedInfo())
867  for (MCSubRegIterator S(I.getReg(), TRI, true); S.isValid(); ++S)
868  BV.reset(*S);
869 
870  return BV;
871 }
872 
875  const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
876  unsigned MaxAlign = getMaxAlignment();
877  int Offset = 0;
878 
879  // This code is very, very similar to PEI::calculateFrameObjectOffsets().
880  // It really should be refactored to share code. Until then, changes
881  // should keep in mind that there's tight coupling between the two.
882 
883  for (int i = getObjectIndexBegin(); i != 0; ++i) {
884  int FixedOff = -getObjectOffset(i);
885  if (FixedOff > Offset) Offset = FixedOff;
886  }
887  for (unsigned i = 0, e = getObjectIndexEnd(); i != e; ++i) {
888  if (isDeadObjectIndex(i))
889  continue;
890  Offset += getObjectSize(i);
891  unsigned Align = getObjectAlignment(i);
892  // Adjust to alignment boundary
893  Offset = (Offset+Align-1)/Align*Align;
894 
895  MaxAlign = std::max(Align, MaxAlign);
896  }
897 
898  if (adjustsStack() && TFI->hasReservedCallFrame(MF))
899  Offset += getMaxCallFrameSize();
900 
901  // Round up the size to a multiple of the alignment. If the function has
902  // any calls or alloca's, align to the target's StackAlignment value to
903  // ensure that the callee's frame or the alloca data is suitably aligned;
904  // otherwise, for leaf functions, align to the TransientStackAlignment
905  // value.
906  unsigned StackAlign;
907  if (adjustsStack() || hasVarSizedObjects() ||
908  (RegInfo->needsStackRealignment(MF) && getObjectIndexEnd() != 0))
909  StackAlign = TFI->getStackAlignment();
910  else
911  StackAlign = TFI->getTransientStackAlignment();
912 
913  // If the frame pointer is eliminated, all frame offsets will be relative to
914  // SP not FP. Align to MaxAlign so this works.
915  StackAlign = std::max(StackAlign, MaxAlign);
916  unsigned AlignMask = StackAlign - 1;
917  Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
918 
919  return (unsigned)Offset;
920 }
921 
923  if (Objects.empty()) return;
924 
926  int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0);
927 
928  OS << "Frame Objects:\n";
929 
930  for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
931  const StackObject &SO = Objects[i];
932  OS << " fi#" << (int)(i-NumFixedObjects) << ": ";
933  if (SO.Size == ~0ULL) {
934  OS << "dead\n";
935  continue;
936  }
937  if (SO.Size == 0)
938  OS << "variable sized";
939  else
940  OS << "size=" << SO.Size;
941  OS << ", align=" << SO.Alignment;
942 
943  if (i < NumFixedObjects)
944  OS << ", fixed";
945  if (i < NumFixedObjects || SO.SPOffset != -1) {
946  int64_t Off = SO.SPOffset - ValOffset;
947  OS << ", at location [SP";
948  if (Off > 0)
949  OS << "+" << Off;
950  else if (Off < 0)
951  OS << Off;
952  OS << "]";
953  }
954  OS << "\n";
955  }
956 }
957 
958 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
960  print(MF, dbgs());
961 }
962 #endif
963 
964 //===----------------------------------------------------------------------===//
965 // MachineJumpTableInfo implementation
966 //===----------------------------------------------------------------------===//
967 
968 /// Return the size of each entry in the jump table.
970  // The size of a jump table entry is 4 bytes unless the entry is just the
971  // address of a block, in which case it is the pointer size.
972  switch (getEntryKind()) {
974  return TD.getPointerSize();
976  return 8;
980  return 4;
982  return 0;
983  }
984  llvm_unreachable("Unknown jump table encoding!");
985 }
986 
987 /// Return the alignment of each entry in the jump table.
989  // The alignment of a jump table entry is the alignment of int32 unless the
990  // entry is just the address of a block, in which case it is the pointer
991  // alignment.
992  switch (getEntryKind()) {
994  return TD.getPointerABIAlignment();
996  return TD.getABIIntegerTypeAlignment(64);
1000  return TD.getABIIntegerTypeAlignment(32);
1002  return 1;
1003  }
1004  llvm_unreachable("Unknown jump table encoding!");
1005 }
1006 
1007 /// Create a new jump table entry in the jump table info.
1009  const std::vector<MachineBasicBlock*> &DestBBs) {
1010  assert(!DestBBs.empty() && "Cannot create an empty jump table!");
1011  JumpTables.push_back(MachineJumpTableEntry(DestBBs));
1012  return JumpTables.size()-1;
1013 }
1014 
1015 /// If Old is the target of any jump tables, update the jump tables to branch
1016 /// to New instead.
1018  MachineBasicBlock *New) {
1019  assert(Old != New && "Not making a change?");
1020  bool MadeChange = false;
1021  for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
1022  ReplaceMBBInJumpTable(i, Old, New);
1023  return MadeChange;
1024 }
1025 
1026 /// If Old is a target of the jump tables, update the jump table to branch to
1027 /// New instead.
1029  MachineBasicBlock *Old,
1030  MachineBasicBlock *New) {
1031  assert(Old != New && "Not making a change?");
1032  bool MadeChange = false;
1033  MachineJumpTableEntry &JTE = JumpTables[Idx];
1034  for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
1035  if (JTE.MBBs[j] == Old) {
1036  JTE.MBBs[j] = New;
1037  MadeChange = true;
1038  }
1039  return MadeChange;
1040 }
1041 
1043  if (JumpTables.empty()) return;
1044 
1045  OS << "Jump Tables:\n";
1046 
1047  for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
1048  OS << " jt#" << i << ": ";
1049  for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
1050  OS << " BB#" << JumpTables[i].MBBs[j]->getNumber();
1051  }
1052 
1053  OS << '\n';
1054 }
1055 
1056 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1058 #endif
1059 
1060 
1061 //===----------------------------------------------------------------------===//
1062 // MachineConstantPool implementation
1063 //===----------------------------------------------------------------------===//
1064 
1065 void MachineConstantPoolValue::anchor() { }
1066 
1069  return Val.MachineCPVal->getType();
1070  return Val.ConstVal->getType();
1071 }
1072 
1075  return true;
1076  return Val.ConstVal->needsRelocation();
1077 }
1078 
1081  if (needsRelocation())
1083  switch (DL->getTypeAllocSize(getType())) {
1084  case 4:
1086  case 8:
1088  case 16:
1090  case 32:
1092  default:
1093  return SectionKind::getReadOnly();
1094  }
1095 }
1096 
1098  // A constant may be a member of both Constants and MachineCPVsSharingEntries,
1099  // so keep track of which we've deleted to avoid double deletions.
1101  for (unsigned i = 0, e = Constants.size(); i != e; ++i)
1102  if (Constants[i].isMachineConstantPoolEntry()) {
1103  Deleted.insert(Constants[i].Val.MachineCPVal);
1104  delete Constants[i].Val.MachineCPVal;
1105  }
1107  MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
1108  I != E; ++I) {
1109  if (Deleted.count(*I) == 0)
1110  delete *I;
1111  }
1112 }
1113 
1114 /// Test whether the given two constants can be allocated the same constant pool
1115 /// entry.
1116 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
1117  const DataLayout &DL) {
1118  // Handle the trivial case quickly.
1119  if (A == B) return true;
1120 
1121  // If they have the same type but weren't the same constant, quickly
1122  // reject them.
1123  if (A->getType() == B->getType()) return false;
1124 
1125  // We can't handle structs or arrays.
1126  if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
1127  isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
1128  return false;
1129 
1130  // For now, only support constants with the same size.
1131  uint64_t StoreSize = DL.getTypeStoreSize(A->getType());
1132  if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128)
1133  return false;
1134 
1135  Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
1136 
1137  // Try constant folding a bitcast of both instructions to an integer. If we
1138  // get two identical ConstantInt's, then we are good to share them. We use
1139  // the constant folding APIs to do this so that we get the benefit of
1140  // DataLayout.
1141  if (isa<PointerType>(A->getType()))
1142  A = ConstantFoldCastOperand(Instruction::PtrToInt,
1143  const_cast<Constant *>(A), IntTy, DL);
1144  else if (A->getType() != IntTy)
1145  A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A),
1146  IntTy, DL);
1147  if (isa<PointerType>(B->getType()))
1148  B = ConstantFoldCastOperand(Instruction::PtrToInt,
1149  const_cast<Constant *>(B), IntTy, DL);
1150  else if (B->getType() != IntTy)
1151  B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B),
1152  IntTy, DL);
1153 
1154  return A == B;
1155 }
1156 
1157 /// Create a new entry in the constant pool or return an existing one.
1158 /// User must specify the log2 of the minimum required alignment for the object.
1160  unsigned Alignment) {
1161  assert(Alignment && "Alignment must be specified!");
1162  if (Alignment > PoolAlignment) PoolAlignment = Alignment;
1163 
1164  // Check to see if we already have this constant.
1165  //
1166  // FIXME, this could be made much more efficient for large constant pools.
1167  for (unsigned i = 0, e = Constants.size(); i != e; ++i)
1168  if (!Constants[i].isMachineConstantPoolEntry() &&
1169  CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) {
1170  if ((unsigned)Constants[i].getAlignment() < Alignment)
1171  Constants[i].Alignment = Alignment;
1172  return i;
1173  }
1174 
1175  Constants.push_back(MachineConstantPoolEntry(C, Alignment));
1176  return Constants.size()-1;
1177 }
1178 
1180  unsigned Alignment) {
1181  assert(Alignment && "Alignment must be specified!");
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 
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].getAlignment();
1208  OS << "\n";
1209  }
1210 }
1211 
1212 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1214 #endif
Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
unsigned getStackAlignment() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
void push_back(const T &Elt)
Definition: SmallVector.h:211
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:102
BitVector & set()
Definition: BitVector.h:219
The MachineConstantPool class keeps track of constants referenced by a function which must be spilled...
SectionKind getSectionKind(const DataLayout *DL) const
StringRef getPrivateGlobalPrefix() const
Definition: DataLayout.h:284
size_type size() const
size - Returns the number of bits in this bitvector.
Definition: BitVector.h:119
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
Flags getFlags() const
Return the raw flags of the source value,.
static SectionKind getMergeableConst32()
Definition: SectionKind.h:195
BitVector getPristineRegs(const MachineFunction &MF) const
Return a set of physical registers that are pristine.
iterator erase(iterator where)
Definition: ilist.h:280
size_t i
unsigned getPrefFunctionAlignment() const
Return the preferred function alignment.
MachineFunctionProperties & reset(Property P)
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
Definition: Compiler.h:450
bool isValid() const
isValid - returns true if this iterator is not yet at the end.
void RenumberBlocks(MachineBasicBlock *MBBFrom=nullptr)
RenumberBlocks - This discards all of the MachineBasicBlock numbers and recomputes them...
livein_iterator livein_end() const
MCSymbol * addLandingPad(MachineBasicBlock *LandingPad)
Add a new panding pad. Returns the label ID for the landing pad entry.
StringRef getLinkerPrivateGlobalPrefix() const
Definition: DataLayout.h:264
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:39
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
Constant * getClause(unsigned Idx) const
Get the value of the clause at index Idx.
unsigned createVirtualRegister(const TargetRegisterClass *RegClass)
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
void addLiveIn(unsigned Reg, unsigned vreg=0)
addLiveIn - Add the specified register as a live-in.
const Function * FilterOrFinally
Filter or finally function. Null indicates a catch-all.
Implements a dense probed hash-table based set.
Definition: DenseSet.h:202
void addLandingPadInfo(const LandingPadInst &I, MachineBasicBlock &MBB)
Extract the exception handling information from the landingpad instruction and add them to the specif...
bool hasSubClassEq(const TargetRegisterClass *RC) const
Returns true if RC is a sub-class of or equal to this class.
unsigned addLiveIn(unsigned PReg, const TargetRegisterClass *RC)
addLiveIn - Add the specified physical register as a live-in value and create a corresponding virtual...
Describe properties that are true of each instruction in the target description file.
Definition: MCInstrDesc.h:163
iterator end() const
Definition: ArrayRef.h:130
void print(raw_ostream &OS, const SlotIndexes *=nullptr) const
EK_Inline - Jump table entries are emitted inline at their point of use.
std::string getNodeLabel(const MachineBasicBlock *Node, const MachineFunction *Graph)
bool adjustsStack() const
Return true if this function adjusts the stack – e.g., when calling another function.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
static SectionKind getMergeableConst8()
Definition: SectionKind.h:193
static SectionKind getMergeableConst16()
Definition: SectionKind.h:194
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:490
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:100
A debug info location.
Definition: DebugLoc.h:34
Metadata node.
Definition: Metadata.h:830
const Function * getFunction() const
getFunction - Return the LLVM function that this machine code represents
Manage lifetime of a slot tracker for printing IR.
unsigned getTypeIDFor(const GlobalValue *TI)
Return the type id for the specified typeinfo. This is function wide.
unsigned getFunctionNumber() const
getFunctionNumber - Return a unique ID for the current function.
MachineInstr * CreateMachineInstr(const MCInstrDesc &MCID, const DebugLoc &DL, bool NoImp=false)
CreateMachineInstr - Allocate a new MachineInstr.
void DeleteMachineBasicBlock(MachineBasicBlock *MBB)
DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
static SectionKind getMergeableConst4()
Definition: SectionKind.h:192
op_iterator op_begin()
Definition: User.h:205
bool ReplaceMBBInJumpTable(unsigned Idx, MachineBasicBlock *Old, MachineBasicBlock *New)
ReplaceMBBInJumpTable - If Old is a target of the jump tables, update the jump table to branch to New...
bool isStackRealignable() const
isStackRealignable - This method returns whether the stack can be realigned.
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:191
MachineJumpTableInfo * getOrCreateJumpTableInfo(unsigned JTEntryKind)
getOrCreateJumpTableInfo - Get the JumpTableInfo for this function, if it does already exist...
unsigned getMaxAlignment() const
Return the alignment in bytes that this function must be aligned to, which is greater than the defaul...
const std::vector< CalleeSavedInfo > & getCalleeSavedInfo() const
Returns a reference to call saved info vector for the current function.
void viewCFG() const
viewCFG - This function is meant for use from the debugger.
JTEntryKind
JTEntryKind - This enum indicates how each entry of the jump table is represented and emitted...
The address of a basic block.
Definition: Constants.h:822
AtomicOrdering getOrdering() const
Return the atomic ordering requirements for this memory operation.
void addSEHCleanupHandler(MachineBasicBlock *LandingPad, const Function *Cleanup)
A description of a memory reference used in the backend.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
SmallVector< MCSymbol *, 1 > EndLabels
unsigned getPointerABIAlignment(unsigned AS=0) const
Layout pointer alignment FIXME: The defaults need to be removed once all of the backends/clients are ...
Definition: DataLayout.cpp:590
static unsigned clampStackAlignment(bool ShouldClamp, unsigned Align, unsigned StackAlign)
Clamp the alignment if requested and emit a warning.
A Use represents the edge between a Value definition and its users.
Definition: Use.h:56
SmallVector< SEHHandler, 1 > SEHHandlers
void addCatchTypeInfo(MachineBasicBlock *LandingPad, ArrayRef< const GlobalValue * > TyInfo)
Provide the catch typeinfo for a landing pad.
const TargetRegisterClass * getRegClass(unsigned Reg) const
Return the register class of the specified virtual register.
const MachineFunctionProperties & getProperties() const
Get the function properties.
Constant * getPersonalityFn() const
Get the personality function associated with this function.
Definition: Function.cpp:1218
void addFilterTypeInfo(MachineBasicBlock *LandingPad, ArrayRef< const GlobalValue * > TyInfo)
Provide the filter typeinfo for a landing pad.
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted...
std::pair< MachineInstr::mmo_iterator, MachineInstr::mmo_iterator > extractLoadMemRefs(MachineInstr::mmo_iterator Begin, MachineInstr::mmo_iterator End)
extractLoadMemRefs - Allocate an array and populate it with just the load information from the given ...
SynchronizationScope
Definition: Instructions.h:50
int getFilterIDFor(std::vector< unsigned > &TyIds)
Return the id of the filter encoded by TyIds. This is function wide.
void Deallocate(const void *Ptr, size_t Size)
Definition: Allocator.h:266
int CreateFixedSpillStackObject(uint64_t Size, int64_t SPOffset, bool Immutable=false)
Create a spill slot at a fixed location on the stack.
AtomicOrdering
Atomic ordering for LLVM's memory model.
static bool isSimple(Instruction *I)
Context object for machine code objects.
Definition: MCContext.h:51
This structure is used to retain landing pad info for the current function.
unsigned getNumRegs() const
Return the number of registers this target has (useful for sizing arrays holding per register informa...
void print(const MachineFunction &MF, raw_ostream &OS) const
Used by the MachineFunction printer to print information about stack objects.
#define F(x, y, z)
Definition: MD5.cpp:51
int getObjectIndexBegin() const
Return the minimum frame object index.
SlotIndexes pass.
Definition: SlotIndexes.h:323
unsigned createJumpTableIndex(const std::vector< MachineBasicBlock * > &DestBBs)
createJumpTableIndex - Create a new jump table.
EK_LabelDifference32 - Each entry is the address of the block minus the address of the jump table...
MachineBasicBlock * MBB
virtual int getExistingMachineCPValue(MachineConstantPool *CP, unsigned Alignment)=0
static std::string getGraphName(const MachineFunction *F)
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
EK_BlockAddress - Each entry is a plain address of block, e.g.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
unsigned getNumClauses() const
Get the number of clauses for this landing pad.
static GCRegistry::Add< OcamlGC > B("ocaml","ocaml 3.10-compatible GC")
This class is a data container for one entry in a MachineConstantPool.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
Definition: StringRef.h:135
Printable PrintReg(unsigned Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubRegIdx=0)
Prints virtual and physical registers with or without a TRI instance.
virtual const MCPhysReg * getCalleeSavedRegs(const MachineFunction *MF) const =0
Return a null-terminated list of all of the callee-saved registers on this target.
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:141
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *bb=nullptr)
CreateMachineBasicBlock - Allocate a new MachineBasicBlock.
unsigned getTransientStackAlignment() const
getTransientStackAlignment - This method returns the number of bytes to which the stack pointer must ...
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
unsigned estimateStackSize(const MachineFunction &MF) const
Estimate and return the size of the stack frame.
static GCRegistry::Add< CoreCLRGC > E("coreclr","CoreCLR-compatible GC")
bool isMachineConstantPoolEntry() const
isMachineConstantPoolEntry - Return true if the MachineConstantPoolEntry is indeed a target specific ...
iterator begin() const
Definition: StringRef.h:103
static unsigned getFnStackAlignment(const TargetSubtargetInfo *STI, const Function *Fn)
unsigned getEntrySize(const DataLayout &TD) const
getEntrySize - Return the size of each entry in the jump table.
constexpr uint64_t MinAlign(uint64_t A, uint64_t B)
MinAlign - A and B are either alignments or offsets.
Definition: MathExtras.h:589
unsigned getEntryAlignment(const DataLayout &TD) const
getEntryAlignment - Return the alignment of each entry in the jump table.
#define P(N)
EK_GPRel64BlockAddress - Each entry is an address of block, encoded with a relocation as gp-relative...
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:395
unsigned getABIIntegerTypeAlignment(unsigned BitWidth) const
Returns the minimum ABI-required alignment for an integer type of the specified bitwidth.
Definition: DataLayout.cpp:695
The landingpad instruction holds all of the information necessary to generate correct exception handl...
MCSymbol * createTempSymbol(bool CanBeUnnamed=true)
Create and return a new assembler temporary symbol with a unique but unspecified name.
Definition: MCContext.cpp:218
EK_Custom32 - Each entry is a 32-bit value that is custom lowered by the TargetLowering::LowerCustomJ...
unsigned const MachineRegisterInfo * MRI
Constant * stripPointerCasts()
Definition: Constant.h:155
LLVM Basic Block Representation.
Definition: BasicBlock.h:51
void addInvoke(MachineBasicBlock *LandingPad, MCSymbol *BeginLabel, MCSymbol *EndLabel)
Provide the begin and end labels of an invoke style call and associate it with a try landing pad bloc...
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
void addSEHCatchHandler(MachineBasicBlock *LandingPad, const Function *Filter, const BlockAddress *RecoverLabel)
static cl::opt< unsigned > AlignAllFunctions("align-all-functions", cl::desc("Force the alignment of all functions."), cl::init(0), cl::Hidden)
SynchronizationScope getSynchScope() const
Return the synchronization scope for this memory operation.
void addPersonality(const Function *Personality)
Provide the personality function for the exception information.
This is an important base class in LLVM.
Definition: Constant.h:42
SmallVector< MCSymbol *, 1 > BeginLabels
LLVM_ATTRIBUTE_RETURNS_NONNULL LLVM_ATTRIBUTE_RETURNS_NOALIAS void * Allocate(size_t Size, size_t Alignment)
Allocate space at the specified alignment.
Definition: Allocator.h:212
static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B, const DataLayout &DL)
Test whether the given two constants can be allocated the same constant pool entry.
unsigned getLiveInVirtReg(unsigned PReg) const
getLiveInVirtReg - If PReg is a live-in physical register, return the corresponding live-in physical ...
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition: Function.h:581
void viewCFGOnly() const
viewCFGOnly - This function is meant for use from the debugger.
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
op_iterator op_end()
Definition: User.h:207
BitVector & reset()
Definition: BitVector.h:260
bool shouldSplitStack() const
Should we be emitting segmented stack stuff for the function.
uint32_t Offset
std::vector< int > TypeIds
void print(raw_ostream &OS) const
Print the MachineFunctionProperties in human-readable form.
static const unsigned End
iterator begin() const
Definition: ArrayRef.h:129
SectionKind - This is a simple POD value that classifies the properties of a section.
Definition: SectionKind.h:23
self_iterator getIterator()
Definition: ilist_node.h:81
const PseudoSourceValue * getPseudoValue() const
void ViewGraph(const GraphType &G, const Twine &Name, bool ShortNames=false, const Twine &Title="", GraphProgram::Name Program=GraphProgram::DOT)
ViewGraph - Emit a dot graph, run 'dot', run gv on the postscript file, then cleanup.
Definition: GraphWriter.h:339
int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool Immutable, bool isAliased=false)
Create a new object at a fixed location on the stack.
bool isCalleeSavedInfoValid() const
Has the callee saved info been calculated yet?
std::vector< MachineBasicBlock * > MBBs
MBBs - The vector of basic blocks from which to create the jump table.
unsigned size() const
void incorporateFunction(const Function &F)
Incorporate the given function.
Definition: AsmWriter.cpp:720
void DeleteMachineInstr(MachineInstr *MI)
DeleteMachineInstr - Delete the given MachineInstr.
int CreateSpillStackObject(uint64_t Size, unsigned Alignment)
Create a new statically sized stack object that represents a spill slot, returning a nonnegative iden...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
MCSubRegIterator enumerates all sub-registers of Reg.
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:654
Abstract base class for all machine specific constantpool value subclasses.
This class contains a discriminated union of information about pointers in memory operands...
const char * createExternalSymbolName(StringRef Name)
Allocate a string and populate it with the given external symbol name.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void dump() const
dump - Print the current MachineFunction to cerr, useful for debugger use.
void addCleanup(MachineBasicBlock *LandingPad)
Add a cleanup action for a landing pad.
virtual bool hasReservedCallFrame(const MachineFunction &MF) const
hasReservedCallFrame - Under normal circumstances, when a frame pointer is not required, we reserve argument space for call sites in the function immediately on entry to the current function.
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
bool isDeadObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a dead object.
void print(raw_ostream &OS) const
print - Used by the MachineFunction printer to print information about constant pool objects...
DOTGraphTraits - Template class that can be specialized to customize how graphs are converted to 'dot...
virtual const TargetFrameLowering * getFrameLowering() const
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition: Type.cpp:234
Iterator for intrusive lists based on ilist_node.
void print(raw_ostream &OS) const
print - Used by the MachineFunction printer to print information about jump tables.
MCSymbol * getPICBaseSymbol() const
getPICBaseSymbol - Return a function-local symbol to represent the PIC base.
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:408
bool isFuncletEHPersonality(EHPersonality Pers)
Returns true if this is a personality function that invokes handler funclets (which must return to it...
MachineInstr * CloneMachineInstr(const MachineInstr *Orig)
CloneMachineInstr - Create a new MachineInstr which is a copy of the 'Orig' instruction, identical in all ways except the instruction has no parent, prev, or next.
static const char * Separator
bool ReplaceMBBInJumpTables(MachineBasicBlock *Old, MachineBasicBlock *New)
ReplaceMBBInJumpTables - If Old is the target of any jump tables, update the jump tables to branch to...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:843
unsigned getObjectAlignment(int ObjectIdx) const
Return the alignment of the specified stack object.
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:230
int getOffsetOfLocalArea() const
getOffsetOfLocalArea - This method returns the offset of the local area from the stack pointer on ent...
virtual const TargetLowering * getTargetLowering() const
unsigned getMaxCallFrameSize() const
Return the maximum size of a call frame that must be allocated for an outgoing function call...
Information about stack frame layout on the target.
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition: Metadata.h:625
static SectionKind getReadOnlyWithRel()
Definition: SectionKind.h:203
Value * stripPointerCasts()
Strip off pointer casts, all-zero GEPs, and aliases.
Definition: Value.cpp:490
livein_iterator livein_begin() const
bool isDefined(bool SetUsed=true) const
isDefined - Check if this symbol is defined (i.e., it has an address).
Definition: MCSymbol.h:245
void clear(AllocatorType &Allocator)
Release all the tracked allocations to the allocator.
static void deleteNode(NodeTy *V)
Definition: ilist.h:42
static GCRegistry::Add< ShadowStackGC > C("shadow-stack","Very portable GC for uncooperative code generators")
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
MCSymbol * getJTISymbol(unsigned JTI, MCContext &Ctx, bool isLinkerPrivate=false) const
getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
void setCallSiteLandingPad(MCSymbol *Sym, ArrayRef< unsigned > Sites)
Map the landing pad's EH symbol to the call site indexes.
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s, unsigned base_alignment, const AAMDNodes &AAInfo=AAMDNodes(), const MDNode *Ranges=nullptr, SynchronizationScope SynchScope=CrossThread, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
Target - Wrapper for Target specific information.
const Value * getValue() const
Return the base address of the memory access.
MachineJumpTableEntry - One jump table in the jump table info.
MachineBasicBlock * LandingPadBlock
Flags
Flags values. These may be or'd together.
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
MachineFunctionProperties & set(Property P)
TargetSubtargetInfo - Generic base class for all target subtargets.
static const char * getPropertyName(MachineFunctionProperties::Property Prop)
Representation of each machine instruction.
Definition: MachineInstr.h:52
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.cpp:384
void ensureMaxAlignment(unsigned Align)
Make sure the function is at least Align bytes aligned.
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition: Function.h:226
size_type count(const ValueT &V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition: DenseSet.h:81
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
Definition: MCContext.cpp:114
unsigned getMinFunctionAlignment() const
Return the minimum function alignment.
bool isCatch(unsigned Idx) const
Return 'true' if the clause and index Idx is a catch clause.
#define I(x, y, z)
Definition: MD5.cpp:54
#define N
void print(raw_ostream &OS, const SlotIndexes *=nullptr) const
print - Print out the MachineFunction in a format suitable for debugging to the specified stream...
uint64_t getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
Definition: DataLayout.h:391
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
int CreateStackObject(uint64_t Size, unsigned Alignment, bool isSS, const AllocaInst *Alloca=nullptr)
Create a new statically sized stack object, returning a nonnegative identifier to represent it...
JTEntryKind getEntryKind() const
std::vector< std::pair< unsigned, unsigned > >::const_iterator livein_iterator
std::pair< MachineInstr::mmo_iterator, MachineInstr::mmo_iterator > extractStoreMemRefs(MachineInstr::mmo_iterator Begin, MachineInstr::mmo_iterator End)
extractStoreMemRefs - Allocate an array and populate it with just the store information from the give...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool needsRelocation() const
This method classifies the entry according to whether or not it may generate a relocation entry...
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:463
aarch64 promote const
void dump(const MachineFunction &MF) const
dump - Print the function to stderr.
LandingPadInfo & getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad)
Find or create an LandingPadInfo for the specified MachineBasicBlock.
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:537
LLVM Value Representation.
Definition: Value.h:71
int64_t getOffset() const
For normal values, this is a byte offset added to the base address.
void deallocateOperandArray(OperandCapacity Cap, MachineOperand *Array)
Dellocate an array of MachineOperands and recycle the memory.
const BlockAddress * RecoverBA
Address of block to recover at. Null for a finally handler.
static const Function * getParent(const Value *V)
iterator end() const
Definition: StringRef.h:105
BasicBlockListType::iterator iterator
uint64_t getSize() const
Return the size in bytes of the memory reference.
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:44
void dump() const
dump - Call print(cerr) to be called from the debugger.
#define DEBUG(X)
Definition: Debug.h:100
DefaultDOTGraphTraits - This class provides the default implementations of all of the DOTGraphTraits ...
Primary interface to the complete machine description for the target machine.
bool isCleanup() const
Return 'true' if this landingpad instruction is a cleanup.
IRTranslator LLVM IR MI
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:47
MachineModuleInfo & getMMI() const
EK_GPRel32BlockAddress - Each entry is an address of block, encoded with a relocation as gp-relative...
bool needsStackRealignment(const MachineFunction &MF) const
True if storage within the function requires the stack pointer to be aligned more than the normal cal...
int getObjectIndexEnd() const
Return one past the maximum frame object index.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
union llvm::MachineConstantPoolEntry::@35 Val
The constant itself.
AtomicOrdering getFailureOrdering() const
For cmpxchg atomic operations, return the atomic ordering requirements when store does not occur...
unsigned getPointerSize(unsigned AS=0) const
Layout pointer size FIXME: The defaults need to be removed once all of the backends/clients are updat...
Definition: DataLayout.cpp:608
int CreateVariableSizedObject(unsigned Alignment, const AllocaInst *Alloca)
Notify the MachineFrameInfo object that a variable sized object has been created. ...
static GCRegistry::Add< ErlangGC > A("erlang","erlang-compatible garbage collector")
static SectionKind getReadOnly()
Definition: SectionKind.h:182
MachineInstr::mmo_iterator allocateMemRefsArray(unsigned long Num)
allocateMemRefsArray - Allocate an array to hold MachineMemOperand pointers.
const BasicBlock * getParent() const
Definition: Instruction.h:62
unsigned getFnStackAlignment() const
Return the stack alignment for the function.
Definition: Function.h:242
int64_t getObjectSize(int ObjectIdx) const
Return the size of the specified object.
unsigned getConstantPoolIndex(const Constant *C, unsigned Alignment)
getConstantPoolIndex - Create a new entry in the constant pool or return an existing one...
This class contains meta information specific to a module.
This file describes how to lower LLVM code to machine code.
void dump() const
dump - Call to stderr.
an instruction to allocate memory on the stack
Definition: Instructions.h:60
uint64_t getBaseAlignment() const
Return the minimum known alignment in bytes of the base address, without the offset.
void tidyLandingPads(DenseMap< MCSymbol *, uintptr_t > *LPMap=nullptr)
Remap landing pad labels and remove any deleted landing pads.
bool contains(unsigned Reg) const
Return true if the specified register is included in this register class.