xref: /freebsd/contrib/llvm-project/llvm/include/llvm/CodeGen/MachineInstrBuilder.h (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1 //===- CodeGen/MachineInstrBuilder.h - Simplify creation of MIs --*- C++ -*-===//
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 // This file exposes a function named BuildMI, which is useful for dramatically
10 // simplifying how MachineInstr's are created.  It allows use of code like this:
11 //
12 //   MIMetadata MIMD(MI);  // Propagates DebugLoc and other metadata
13 //   M = BuildMI(MBB, MI, MIMD, TII.get(X86::ADD8rr), Dst)
14 //           .addReg(argVal1)
15 //           .addReg(argVal2);
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #ifndef LLVM_CODEGEN_MACHINEINSTRBUILDER_H
20 #define LLVM_CODEGEN_MACHINEINSTRBUILDER_H
21 
22 #include "llvm/ADT/ArrayRef.h"
23 #include "llvm/CodeGen/GlobalISel/Utils.h"
24 #include "llvm/CodeGen/MachineBasicBlock.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/CodeGen/MachineInstrBundle.h"
28 #include "llvm/CodeGen/MachineOperand.h"
29 #include "llvm/CodeGen/TargetRegisterInfo.h"
30 #include "llvm/IR/InstrTypes.h"
31 #include "llvm/IR/Intrinsics.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include <cassert>
34 #include <cstdint>
35 
36 namespace llvm {
37 
38 class MCInstrDesc;
39 class MDNode;
40 
41 namespace RegState {
42 
43 // Keep this in sync with the table in MIRLangRef.rst.
44 enum {
45   /// Register definition.
46   Define = 0x2,
47   /// Not emitted register (e.g. carry, or temporary result).
48   Implicit = 0x4,
49   /// The last use of a register.
50   Kill = 0x8,
51   /// Unused definition.
52   Dead = 0x10,
53   /// Value of the register doesn't matter.
54   Undef = 0x20,
55   /// Register definition happens before uses.
56   EarlyClobber = 0x40,
57   /// Register 'use' is for debugging purpose.
58   Debug = 0x80,
59   /// Register reads a value that is defined inside the same instruction or
60   /// bundle.
61   InternalRead = 0x100,
62   /// Register that may be renamed.
63   Renamable = 0x200,
64   DefineNoRead = Define | Undef,
65   ImplicitDefine = Implicit | Define,
66   ImplicitKill = Implicit | Kill
67 };
68 
69 } // end namespace RegState
70 
71 class MachineInstrBuilder {
72   MachineFunction *MF = nullptr;
73   MachineInstr *MI = nullptr;
74 
75 public:
76   MachineInstrBuilder() = default;
77 
78   /// Create a MachineInstrBuilder for manipulating an existing instruction.
79   /// F must be the machine function that was used to allocate I.
MachineInstrBuilder(MachineFunction & F,MachineInstr * I)80   MachineInstrBuilder(MachineFunction &F, MachineInstr *I) : MF(&F), MI(I) {}
MachineInstrBuilder(MachineFunction & F,MachineBasicBlock::iterator I)81   MachineInstrBuilder(MachineFunction &F, MachineBasicBlock::iterator I)
82       : MF(&F), MI(&*I) {}
83 
84   /// Allow automatic conversion to the machine instruction we are working on.
85   operator MachineInstr*() const { return MI; }
86   MachineInstr *operator->() const { return MI; }
iterator()87   operator MachineBasicBlock::iterator() const { return MI; }
88 
89   /// If conversion operators fail, use this method to get the MachineInstr
90   /// explicitly.
getInstr()91   MachineInstr *getInstr() const { return MI; }
92 
93   /// Get the register for the operand index.
94   /// The operand at the index should be a register (asserted by
95   /// MachineOperand).
getReg(unsigned Idx)96   Register getReg(unsigned Idx) const { return MI->getOperand(Idx).getReg(); }
97 
98   /// Add a new virtual register operand.
99   const MachineInstrBuilder &addReg(Register RegNo, unsigned flags = 0,
100                                     unsigned SubReg = 0) const {
101     assert((flags & 0x1) == 0 &&
102            "Passing in 'true' to addReg is forbidden! Use enums instead.");
103     MI->addOperand(*MF, MachineOperand::CreateReg(RegNo,
104                                                flags & RegState::Define,
105                                                flags & RegState::Implicit,
106                                                flags & RegState::Kill,
107                                                flags & RegState::Dead,
108                                                flags & RegState::Undef,
109                                                flags & RegState::EarlyClobber,
110                                                SubReg,
111                                                flags & RegState::Debug,
112                                                flags & RegState::InternalRead,
113                                                flags & RegState::Renamable));
114     return *this;
115   }
116 
117   /// Add a virtual register definition operand.
118   const MachineInstrBuilder &addDef(Register RegNo, unsigned Flags = 0,
119                                     unsigned SubReg = 0) const {
120     return addReg(RegNo, Flags | RegState::Define, SubReg);
121   }
122 
123   /// Add a virtual register use operand. It is an error for Flags to contain
124   /// `RegState::Define` when calling this function.
125   const MachineInstrBuilder &addUse(Register RegNo, unsigned Flags = 0,
126                                     unsigned SubReg = 0) const {
127     assert(!(Flags & RegState::Define) &&
128            "Misleading addUse defines register, use addReg instead.");
129     return addReg(RegNo, Flags, SubReg);
130   }
131 
132   /// Add a new immediate operand.
addImm(int64_t Val)133   const MachineInstrBuilder &addImm(int64_t Val) const {
134     MI->addOperand(*MF, MachineOperand::CreateImm(Val));
135     return *this;
136   }
137 
addCImm(const ConstantInt * Val)138   const MachineInstrBuilder &addCImm(const ConstantInt *Val) const {
139     MI->addOperand(*MF, MachineOperand::CreateCImm(Val));
140     return *this;
141   }
142 
addFPImm(const ConstantFP * Val)143   const MachineInstrBuilder &addFPImm(const ConstantFP *Val) const {
144     MI->addOperand(*MF, MachineOperand::CreateFPImm(Val));
145     return *this;
146   }
147 
148   const MachineInstrBuilder &addMBB(MachineBasicBlock *MBB,
149                                     unsigned TargetFlags = 0) const {
150     MI->addOperand(*MF, MachineOperand::CreateMBB(MBB, TargetFlags));
151     return *this;
152   }
153 
addFrameIndex(int Idx)154   const MachineInstrBuilder &addFrameIndex(int Idx) const {
155     MI->addOperand(*MF, MachineOperand::CreateFI(Idx));
156     return *this;
157   }
158 
159   const MachineInstrBuilder &
160   addConstantPoolIndex(unsigned Idx, int Offset = 0,
161                        unsigned TargetFlags = 0) const {
162     MI->addOperand(*MF, MachineOperand::CreateCPI(Idx, Offset, TargetFlags));
163     return *this;
164   }
165 
166   const MachineInstrBuilder &addTargetIndex(unsigned Idx, int64_t Offset = 0,
167                                           unsigned TargetFlags = 0) const {
168     MI->addOperand(*MF, MachineOperand::CreateTargetIndex(Idx, Offset,
169                                                           TargetFlags));
170     return *this;
171   }
172 
173   const MachineInstrBuilder &addJumpTableIndex(unsigned Idx,
174                                                unsigned TargetFlags = 0) const {
175     MI->addOperand(*MF, MachineOperand::CreateJTI(Idx, TargetFlags));
176     return *this;
177   }
178 
179   const MachineInstrBuilder &addGlobalAddress(const GlobalValue *GV,
180                                               int64_t Offset = 0,
181                                               unsigned TargetFlags = 0) const {
182     MI->addOperand(*MF, MachineOperand::CreateGA(GV, Offset, TargetFlags));
183     return *this;
184   }
185 
186   const MachineInstrBuilder &addExternalSymbol(const char *FnName,
187                                                unsigned TargetFlags = 0) const {
188     MI->addOperand(*MF, MachineOperand::CreateES(FnName, TargetFlags));
189     return *this;
190   }
191 
192   const MachineInstrBuilder &addBlockAddress(const BlockAddress *BA,
193                                              int64_t Offset = 0,
194                                              unsigned TargetFlags = 0) const {
195     MI->addOperand(*MF, MachineOperand::CreateBA(BA, Offset, TargetFlags));
196     return *this;
197   }
198 
addRegMask(const uint32_t * Mask)199   const MachineInstrBuilder &addRegMask(const uint32_t *Mask) const {
200     MI->addOperand(*MF, MachineOperand::CreateRegMask(Mask));
201     return *this;
202   }
203 
addMemOperand(MachineMemOperand * MMO)204   const MachineInstrBuilder &addMemOperand(MachineMemOperand *MMO) const {
205     MI->addMemOperand(*MF, MMO);
206     return *this;
207   }
208 
209   const MachineInstrBuilder &
setMemRefs(ArrayRef<MachineMemOperand * > MMOs)210   setMemRefs(ArrayRef<MachineMemOperand *> MMOs) const {
211     MI->setMemRefs(*MF, MMOs);
212     return *this;
213   }
214 
cloneMemRefs(const MachineInstr & OtherMI)215   const MachineInstrBuilder &cloneMemRefs(const MachineInstr &OtherMI) const {
216     MI->cloneMemRefs(*MF, OtherMI);
217     return *this;
218   }
219 
220   const MachineInstrBuilder &
cloneMergedMemRefs(ArrayRef<const MachineInstr * > OtherMIs)221   cloneMergedMemRefs(ArrayRef<const MachineInstr *> OtherMIs) const {
222     MI->cloneMergedMemRefs(*MF, OtherMIs);
223     return *this;
224   }
225 
add(const MachineOperand & MO)226   const MachineInstrBuilder &add(const MachineOperand &MO) const {
227     MI->addOperand(*MF, MO);
228     return *this;
229   }
230 
add(ArrayRef<MachineOperand> MOs)231   const MachineInstrBuilder &add(ArrayRef<MachineOperand> MOs) const {
232     for (const MachineOperand &MO : MOs) {
233       MI->addOperand(*MF, MO);
234     }
235     return *this;
236   }
237 
addMetadata(const MDNode * MD)238   const MachineInstrBuilder &addMetadata(const MDNode *MD) const {
239     MI->addOperand(*MF, MachineOperand::CreateMetadata(MD));
240     assert((MI->isDebugValueLike() ? static_cast<bool>(MI->getDebugVariable())
241                                    : true) &&
242            "first MDNode argument of a DBG_VALUE not a variable");
243     assert((MI->isDebugLabel() ? static_cast<bool>(MI->getDebugLabel())
244                                : true) &&
245            "first MDNode argument of a DBG_LABEL not a label");
246     return *this;
247   }
248 
addCFIIndex(unsigned CFIIndex)249   const MachineInstrBuilder &addCFIIndex(unsigned CFIIndex) const {
250     MI->addOperand(*MF, MachineOperand::CreateCFIIndex(CFIIndex));
251     return *this;
252   }
253 
addIntrinsicID(Intrinsic::ID ID)254   const MachineInstrBuilder &addIntrinsicID(Intrinsic::ID ID) const {
255     MI->addOperand(*MF, MachineOperand::CreateIntrinsicID(ID));
256     return *this;
257   }
258 
addPredicate(CmpInst::Predicate Pred)259   const MachineInstrBuilder &addPredicate(CmpInst::Predicate Pred) const {
260     MI->addOperand(*MF, MachineOperand::CreatePredicate(Pred));
261     return *this;
262   }
263 
addShuffleMask(ArrayRef<int> Val)264   const MachineInstrBuilder &addShuffleMask(ArrayRef<int> Val) const {
265     MI->addOperand(*MF, MachineOperand::CreateShuffleMask(Val));
266     return *this;
267   }
268 
269   const MachineInstrBuilder &addSym(MCSymbol *Sym,
270                                     unsigned char TargetFlags = 0) const {
271     MI->addOperand(*MF, MachineOperand::CreateMCSymbol(Sym, TargetFlags));
272     return *this;
273   }
274 
setMIFlags(unsigned Flags)275   const MachineInstrBuilder &setMIFlags(unsigned Flags) const {
276     MI->setFlags(Flags);
277     return *this;
278   }
279 
setMIFlag(MachineInstr::MIFlag Flag)280   const MachineInstrBuilder &setMIFlag(MachineInstr::MIFlag Flag) const {
281     MI->setFlag(Flag);
282     return *this;
283   }
284 
setOperandDead(unsigned OpIdx)285   const MachineInstrBuilder &setOperandDead(unsigned OpIdx) const {
286     MI->getOperand(OpIdx).setIsDead();
287     return *this;
288   }
289 
290   // Add a displacement from an existing MachineOperand with an added offset.
291   const MachineInstrBuilder &addDisp(const MachineOperand &Disp, int64_t off,
292                                      unsigned char TargetFlags = 0) const {
293     // If caller specifies new TargetFlags then use it, otherwise the
294     // default behavior is to copy the target flags from the existing
295     // MachineOperand. This means if the caller wants to clear the
296     // target flags it needs to do so explicitly.
297     if (0 == TargetFlags)
298       TargetFlags = Disp.getTargetFlags();
299 
300     switch (Disp.getType()) {
301       default:
302         llvm_unreachable("Unhandled operand type in addDisp()");
303       case MachineOperand::MO_Immediate:
304         return addImm(Disp.getImm() + off);
305       case MachineOperand::MO_ConstantPoolIndex:
306         return addConstantPoolIndex(Disp.getIndex(), Disp.getOffset() + off,
307                                     TargetFlags);
308       case MachineOperand::MO_GlobalAddress:
309         return addGlobalAddress(Disp.getGlobal(), Disp.getOffset() + off,
310                                 TargetFlags);
311       case MachineOperand::MO_BlockAddress:
312         return addBlockAddress(Disp.getBlockAddress(), Disp.getOffset() + off,
313                                TargetFlags);
314       case MachineOperand::MO_JumpTableIndex:
315         assert(off == 0 && "cannot create offset into jump tables");
316         return addJumpTableIndex(Disp.getIndex(), TargetFlags);
317     }
318   }
319 
setPCSections(MDNode * MD)320   const MachineInstrBuilder &setPCSections(MDNode *MD) const {
321     if (MD)
322       MI->setPCSections(*MF, MD);
323     return *this;
324   }
325 
setMMRAMetadata(MDNode * MMRA)326   const MachineInstrBuilder &setMMRAMetadata(MDNode *MMRA) const {
327     if (MMRA)
328       MI->setMMRAMetadata(*MF, MMRA);
329     return *this;
330   }
331 
332   /// Copy all the implicit operands from OtherMI onto this one.
333   const MachineInstrBuilder &
copyImplicitOps(const MachineInstr & OtherMI)334   copyImplicitOps(const MachineInstr &OtherMI) const {
335     MI->copyImplicitOps(*MF, OtherMI);
336     return *this;
337   }
338 
constrainAllUses(const TargetInstrInfo & TII,const TargetRegisterInfo & TRI,const RegisterBankInfo & RBI)339   bool constrainAllUses(const TargetInstrInfo &TII,
340                         const TargetRegisterInfo &TRI,
341                         const RegisterBankInfo &RBI) const {
342     return constrainSelectedInstRegOperands(*MI, TII, TRI, RBI);
343   }
344 };
345 
346 /// Set of metadata that should be preserved when using BuildMI(). This provides
347 /// a more convenient way of preserving DebugLoc, PCSections and MMRA.
348 class MIMetadata {
349 public:
350   MIMetadata() = default;
351   MIMetadata(DebugLoc DL, MDNode *PCSections = nullptr, MDNode *MMRA = nullptr)
DL(std::move (DL))352       : DL(std::move(DL)), PCSections(PCSections), MMRA(MMRA) {}
353   MIMetadata(const DILocation *DI, MDNode *PCSections = nullptr,
354              MDNode *MMRA = nullptr)
DL(DI)355       : DL(DI), PCSections(PCSections), MMRA(MMRA) {}
MIMetadata(const Instruction & From)356   explicit MIMetadata(const Instruction &From)
357       : DL(From.getDebugLoc()),
358         PCSections(From.getMetadata(LLVMContext::MD_pcsections)) {}
MIMetadata(const MachineInstr & From)359   explicit MIMetadata(const MachineInstr &From)
360       : DL(From.getDebugLoc()), PCSections(From.getPCSections()) {}
361 
getDL()362   const DebugLoc &getDL() const { return DL; }
getPCSections()363   MDNode *getPCSections() const { return PCSections; }
getMMRAMetadata()364   MDNode *getMMRAMetadata() const { return MMRA; }
365 
366 private:
367   DebugLoc DL;
368   MDNode *PCSections = nullptr;
369   MDNode *MMRA = nullptr;
370 };
371 
372 /// Builder interface. Specify how to create the initial instruction itself.
BuildMI(MachineFunction & MF,const MIMetadata & MIMD,const MCInstrDesc & MCID)373 inline MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD,
374                                    const MCInstrDesc &MCID) {
375   return MachineInstrBuilder(MF, MF.CreateMachineInstr(MCID, MIMD.getDL()))
376       .setPCSections(MIMD.getPCSections())
377       .setMMRAMetadata(MIMD.getMMRAMetadata());
378 }
379 
380 /// This version of the builder sets up the first operand as a
381 /// destination virtual register.
BuildMI(MachineFunction & MF,const MIMetadata & MIMD,const MCInstrDesc & MCID,Register DestReg)382 inline MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD,
383                                    const MCInstrDesc &MCID, Register DestReg) {
384   return MachineInstrBuilder(MF, MF.CreateMachineInstr(MCID, MIMD.getDL()))
385       .setPCSections(MIMD.getPCSections())
386       .setMMRAMetadata(MIMD.getMMRAMetadata())
387       .addReg(DestReg, RegState::Define);
388 }
389 
390 /// This version of the builder inserts the newly-built instruction before
391 /// the given position in the given MachineBasicBlock, and sets up the first
392 /// operand as a destination virtual register.
BuildMI(MachineBasicBlock & BB,MachineBasicBlock::iterator I,const MIMetadata & MIMD,const MCInstrDesc & MCID,Register DestReg)393 inline MachineInstrBuilder BuildMI(MachineBasicBlock &BB,
394                                    MachineBasicBlock::iterator I,
395                                    const MIMetadata &MIMD,
396                                    const MCInstrDesc &MCID, Register DestReg) {
397   MachineFunction &MF = *BB.getParent();
398   MachineInstr *MI = MF.CreateMachineInstr(MCID, MIMD.getDL());
399   BB.insert(I, MI);
400   return MachineInstrBuilder(MF, MI)
401       .setPCSections(MIMD.getPCSections())
402       .setMMRAMetadata(MIMD.getMMRAMetadata())
403       .addReg(DestReg, RegState::Define);
404 }
405 
406 /// This version of the builder inserts the newly-built instruction before
407 /// the given position in the given MachineBasicBlock, and sets up the first
408 /// operand as a destination virtual register.
409 ///
410 /// If \c I is inside a bundle, then the newly inserted \a MachineInstr is
411 /// added to the same bundle.
BuildMI(MachineBasicBlock & BB,MachineBasicBlock::instr_iterator I,const MIMetadata & MIMD,const MCInstrDesc & MCID,Register DestReg)412 inline MachineInstrBuilder BuildMI(MachineBasicBlock &BB,
413                                    MachineBasicBlock::instr_iterator I,
414                                    const MIMetadata &MIMD,
415                                    const MCInstrDesc &MCID, Register DestReg) {
416   MachineFunction &MF = *BB.getParent();
417   MachineInstr *MI = MF.CreateMachineInstr(MCID, MIMD.getDL());
418   BB.insert(I, MI);
419   return MachineInstrBuilder(MF, MI)
420       .setPCSections(MIMD.getPCSections())
421       .setMMRAMetadata(MIMD.getMMRAMetadata())
422       .addReg(DestReg, RegState::Define);
423 }
424 
BuildMI(MachineBasicBlock & BB,MachineInstr & I,const MIMetadata & MIMD,const MCInstrDesc & MCID,Register DestReg)425 inline MachineInstrBuilder BuildMI(MachineBasicBlock &BB, MachineInstr &I,
426                                    const MIMetadata &MIMD,
427                                    const MCInstrDesc &MCID, Register DestReg) {
428   // Calling the overload for instr_iterator is always correct.  However, the
429   // definition is not available in headers, so inline the check.
430   if (I.isInsideBundle())
431     return BuildMI(BB, MachineBasicBlock::instr_iterator(I), MIMD, MCID,
432                    DestReg);
433   return BuildMI(BB, MachineBasicBlock::iterator(I), MIMD, MCID, DestReg);
434 }
435 
BuildMI(MachineBasicBlock & BB,MachineInstr * I,const MIMetadata & MIMD,const MCInstrDesc & MCID,Register DestReg)436 inline MachineInstrBuilder BuildMI(MachineBasicBlock &BB, MachineInstr *I,
437                                    const MIMetadata &MIMD,
438                                    const MCInstrDesc &MCID, Register DestReg) {
439   return BuildMI(BB, *I, MIMD, MCID, DestReg);
440 }
441 
442 /// This version of the builder inserts the newly-built instruction before the
443 /// given position in the given MachineBasicBlock, and does NOT take a
444 /// destination register.
BuildMI(MachineBasicBlock & BB,MachineBasicBlock::iterator I,const MIMetadata & MIMD,const MCInstrDesc & MCID)445 inline MachineInstrBuilder BuildMI(MachineBasicBlock &BB,
446                                    MachineBasicBlock::iterator I,
447                                    const MIMetadata &MIMD,
448                                    const MCInstrDesc &MCID) {
449   MachineFunction &MF = *BB.getParent();
450   MachineInstr *MI = MF.CreateMachineInstr(MCID, MIMD.getDL());
451   BB.insert(I, MI);
452   return MachineInstrBuilder(MF, MI)
453       .setPCSections(MIMD.getPCSections())
454       .setMMRAMetadata(MIMD.getMMRAMetadata());
455 }
456 
BuildMI(MachineBasicBlock & BB,MachineBasicBlock::instr_iterator I,const MIMetadata & MIMD,const MCInstrDesc & MCID)457 inline MachineInstrBuilder BuildMI(MachineBasicBlock &BB,
458                                    MachineBasicBlock::instr_iterator I,
459                                    const MIMetadata &MIMD,
460                                    const MCInstrDesc &MCID) {
461   MachineFunction &MF = *BB.getParent();
462   MachineInstr *MI = MF.CreateMachineInstr(MCID, MIMD.getDL());
463   BB.insert(I, MI);
464   return MachineInstrBuilder(MF, MI)
465       .setPCSections(MIMD.getPCSections())
466       .setMMRAMetadata(MIMD.getMMRAMetadata());
467 }
468 
BuildMI(MachineBasicBlock & BB,MachineInstr & I,const MIMetadata & MIMD,const MCInstrDesc & MCID)469 inline MachineInstrBuilder BuildMI(MachineBasicBlock &BB, MachineInstr &I,
470                                    const MIMetadata &MIMD,
471                                    const MCInstrDesc &MCID) {
472   // Calling the overload for instr_iterator is always correct.  However, the
473   // definition is not available in headers, so inline the check.
474   if (I.isInsideBundle())
475     return BuildMI(BB, MachineBasicBlock::instr_iterator(I), MIMD, MCID);
476   return BuildMI(BB, MachineBasicBlock::iterator(I), MIMD, MCID);
477 }
478 
BuildMI(MachineBasicBlock & BB,MachineInstr * I,const MIMetadata & MIMD,const MCInstrDesc & MCID)479 inline MachineInstrBuilder BuildMI(MachineBasicBlock &BB, MachineInstr *I,
480                                    const MIMetadata &MIMD,
481                                    const MCInstrDesc &MCID) {
482   return BuildMI(BB, *I, MIMD, MCID);
483 }
484 
485 /// This version of the builder inserts the newly-built instruction at the end
486 /// of the given MachineBasicBlock, and does NOT take a destination register.
BuildMI(MachineBasicBlock * BB,const MIMetadata & MIMD,const MCInstrDesc & MCID)487 inline MachineInstrBuilder BuildMI(MachineBasicBlock *BB,
488                                    const MIMetadata &MIMD,
489                                    const MCInstrDesc &MCID) {
490   return BuildMI(*BB, BB->end(), MIMD, MCID);
491 }
492 
493 /// This version of the builder inserts the newly-built instruction at the
494 /// end of the given MachineBasicBlock, and sets up the first operand as a
495 /// destination virtual register.
BuildMI(MachineBasicBlock * BB,const MIMetadata & MIMD,const MCInstrDesc & MCID,Register DestReg)496 inline MachineInstrBuilder BuildMI(MachineBasicBlock *BB,
497                                    const MIMetadata &MIMD,
498                                    const MCInstrDesc &MCID, Register DestReg) {
499   return BuildMI(*BB, BB->end(), MIMD, MCID, DestReg);
500 }
501 
502 /// This version of the builder builds a DBG_VALUE intrinsic
503 /// for either a value in a register or a register-indirect
504 /// address.  The convention is that a DBG_VALUE is indirect iff the
505 /// second operand is an immediate.
506 MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL,
507                             const MCInstrDesc &MCID, bool IsIndirect,
508                             Register Reg, const MDNode *Variable,
509                             const MDNode *Expr);
510 
511 /// This version of the builder builds a DBG_VALUE or DBG_VALUE_LIST intrinsic
512 /// for a MachineOperand.
513 MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL,
514                             const MCInstrDesc &MCID, bool IsIndirect,
515                             ArrayRef<MachineOperand> MOs,
516                             const MDNode *Variable, const MDNode *Expr);
517 
518 /// This version of the builder builds a DBG_VALUE intrinsic
519 /// for either a value in a register or a register-indirect
520 /// address and inserts it at position I.
521 MachineInstrBuilder BuildMI(MachineBasicBlock &BB,
522                             MachineBasicBlock::iterator I, const DebugLoc &DL,
523                             const MCInstrDesc &MCID, bool IsIndirect,
524                             Register Reg, const MDNode *Variable,
525                             const MDNode *Expr);
526 
527 /// This version of the builder builds a DBG_VALUE, DBG_INSTR_REF, or
528 /// DBG_VALUE_LIST intrinsic for a machine operand and inserts it at position I.
529 MachineInstrBuilder BuildMI(MachineBasicBlock &BB,
530                             MachineBasicBlock::iterator I, const DebugLoc &DL,
531                             const MCInstrDesc &MCID, bool IsIndirect,
532                             ArrayRef<MachineOperand> MOs,
533                             const MDNode *Variable, const MDNode *Expr);
534 
535 /// Clone a DBG_VALUE whose value has been spilled to FrameIndex.
536 MachineInstr *buildDbgValueForSpill(MachineBasicBlock &BB,
537                                     MachineBasicBlock::iterator I,
538                                     const MachineInstr &Orig, int FrameIndex,
539                                     Register SpillReg);
540 MachineInstr *
541 buildDbgValueForSpill(MachineBasicBlock &BB, MachineBasicBlock::iterator I,
542                       const MachineInstr &Orig, int FrameIndex,
543                       SmallVectorImpl<const MachineOperand *> &SpilledOperands);
544 
545 /// Update a DBG_VALUE whose value has been spilled to FrameIndex. Useful when
546 /// modifying an instruction in place while iterating over a basic block.
547 void updateDbgValueForSpill(MachineInstr &Orig, int FrameIndex, Register Reg);
548 
getDefRegState(bool B)549 inline unsigned getDefRegState(bool B) {
550   return B ? RegState::Define : 0;
551 }
getImplRegState(bool B)552 inline unsigned getImplRegState(bool B) {
553   return B ? RegState::Implicit : 0;
554 }
getKillRegState(bool B)555 inline unsigned getKillRegState(bool B) {
556   return B ? RegState::Kill : 0;
557 }
getDeadRegState(bool B)558 inline unsigned getDeadRegState(bool B) {
559   return B ? RegState::Dead : 0;
560 }
getUndefRegState(bool B)561 inline unsigned getUndefRegState(bool B) {
562   return B ? RegState::Undef : 0;
563 }
getInternalReadRegState(bool B)564 inline unsigned getInternalReadRegState(bool B) {
565   return B ? RegState::InternalRead : 0;
566 }
getDebugRegState(bool B)567 inline unsigned getDebugRegState(bool B) {
568   return B ? RegState::Debug : 0;
569 }
getRenamableRegState(bool B)570 inline unsigned getRenamableRegState(bool B) {
571   return B ? RegState::Renamable : 0;
572 }
573 
574 /// Get all register state flags from machine operand \p RegOp.
getRegState(const MachineOperand & RegOp)575 inline unsigned getRegState(const MachineOperand &RegOp) {
576   assert(RegOp.isReg() && "Not a register operand");
577   return getDefRegState(RegOp.isDef()) | getImplRegState(RegOp.isImplicit()) |
578          getKillRegState(RegOp.isKill()) | getDeadRegState(RegOp.isDead()) |
579          getUndefRegState(RegOp.isUndef()) |
580          getInternalReadRegState(RegOp.isInternalRead()) |
581          getDebugRegState(RegOp.isDebug()) |
582          getRenamableRegState(RegOp.getReg().isPhysical() &&
583                               RegOp.isRenamable());
584 }
585 
586 /// Helper class for constructing bundles of MachineInstrs.
587 ///
588 /// MIBundleBuilder can create a bundle from scratch by inserting new
589 /// MachineInstrs one at a time, or it can create a bundle from a sequence of
590 /// existing MachineInstrs in a basic block.
591 class MIBundleBuilder {
592   MachineBasicBlock &MBB;
593   MachineBasicBlock::instr_iterator Begin;
594   MachineBasicBlock::instr_iterator End;
595 
596 public:
597   /// Create an MIBundleBuilder that inserts instructions into a new bundle in
598   /// BB above the bundle or instruction at Pos.
MIBundleBuilder(MachineBasicBlock & BB,MachineBasicBlock::iterator Pos)599   MIBundleBuilder(MachineBasicBlock &BB, MachineBasicBlock::iterator Pos)
600       : MBB(BB), Begin(Pos.getInstrIterator()), End(Begin) {}
601 
602   /// Create a bundle from the sequence of instructions between B and E.
MIBundleBuilder(MachineBasicBlock & BB,MachineBasicBlock::iterator B,MachineBasicBlock::iterator E)603   MIBundleBuilder(MachineBasicBlock &BB, MachineBasicBlock::iterator B,
604                   MachineBasicBlock::iterator E)
605       : MBB(BB), Begin(B.getInstrIterator()), End(E.getInstrIterator()) {
606     assert(B != E && "No instructions to bundle");
607     ++B;
608     while (B != E) {
609       MachineInstr &MI = *B;
610       ++B;
611       MI.bundleWithPred();
612     }
613   }
614 
615   /// Create an MIBundleBuilder representing an existing instruction or bundle
616   /// that has MI as its head.
MIBundleBuilder(MachineInstr * MI)617   explicit MIBundleBuilder(MachineInstr *MI)
618       : MBB(*MI->getParent()), Begin(MI),
619         End(getBundleEnd(MI->getIterator())) {}
620 
621   /// Return a reference to the basic block containing this bundle.
getMBB()622   MachineBasicBlock &getMBB() const { return MBB; }
623 
624   /// Return true if no instructions have been inserted in this bundle yet.
625   /// Empty bundles aren't representable in a MachineBasicBlock.
empty()626   bool empty() const { return Begin == End; }
627 
628   /// Return an iterator to the first bundled instruction.
begin()629   MachineBasicBlock::instr_iterator begin() const { return Begin; }
630 
631   /// Return an iterator beyond the last bundled instruction.
end()632   MachineBasicBlock::instr_iterator end() const { return End; }
633 
634   /// Insert MI into this bundle before I which must point to an instruction in
635   /// the bundle, or end().
insert(MachineBasicBlock::instr_iterator I,MachineInstr * MI)636   MIBundleBuilder &insert(MachineBasicBlock::instr_iterator I,
637                           MachineInstr *MI) {
638     MBB.insert(I, MI);
639     if (I == Begin) {
640       if (!empty())
641         MI->bundleWithSucc();
642       Begin = MI->getIterator();
643       return *this;
644     }
645     if (I == End) {
646       MI->bundleWithPred();
647       return *this;
648     }
649     // MI was inserted in the middle of the bundle, so its neighbors' flags are
650     // already fine. Update MI's bundle flags manually.
651     MI->setFlag(MachineInstr::BundledPred);
652     MI->setFlag(MachineInstr::BundledSucc);
653     return *this;
654   }
655 
656   /// Insert MI into MBB by prepending it to the instructions in the bundle.
657   /// MI will become the first instruction in the bundle.
prepend(MachineInstr * MI)658   MIBundleBuilder &prepend(MachineInstr *MI) {
659     return insert(begin(), MI);
660   }
661 
662   /// Insert MI into MBB by appending it to the instructions in the bundle.
663   /// MI will become the last instruction in the bundle.
append(MachineInstr * MI)664   MIBundleBuilder &append(MachineInstr *MI) {
665     return insert(end(), MI);
666   }
667 };
668 
669 } // end namespace llvm
670 
671 #endif // LLVM_CODEGEN_MACHINEINSTRBUILDER_H
672