Extract helper function to merge MemoryOperand lists [NFC]
[oota-llvm.git] / include / llvm / CodeGen / MachineInstrBuilder.h
1 //===-- CodeGen/MachineInstBuilder.h - Simplify creation of MIs -*- C++ -*-===//
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 // This file exposes a function named BuildMI, which is useful for dramatically
11 // simplifying how MachineInstr's are created.  It allows use of code like this:
12 //
13 //   M = BuildMI(X86::ADDrr8, 2).addReg(argVal1).addReg(argVal2);
14 //
15 //===----------------------------------------------------------------------===//
16
17 #ifndef LLVM_CODEGEN_MACHINEINSTRBUILDER_H
18 #define LLVM_CODEGEN_MACHINEINSTRBUILDER_H
19
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstrBundle.h"
22 #include "llvm/Support/ErrorHandling.h"
23
24 namespace llvm {
25
26 class MCInstrDesc;
27 class MDNode;
28
29 namespace RegState {
30   enum {
31     Define         = 0x2,
32     Implicit       = 0x4,
33     Kill           = 0x8,
34     Dead           = 0x10,
35     Undef          = 0x20,
36     EarlyClobber   = 0x40,
37     Debug          = 0x80,
38     InternalRead   = 0x100,
39     DefineNoRead   = Define | Undef,
40     ImplicitDefine = Implicit | Define,
41     ImplicitKill   = Implicit | Kill
42   };
43 }
44
45 class MachineInstrBuilder {
46   MachineFunction *MF;
47   MachineInstr *MI;
48 public:
49   MachineInstrBuilder() : MF(nullptr), MI(nullptr) {}
50
51   /// Create a MachineInstrBuilder for manipulating an existing instruction.
52   /// F must be the machine function that was used to allocate I.
53   MachineInstrBuilder(MachineFunction &F, MachineInstr *I) : MF(&F), MI(I) {}
54
55   /// Allow automatic conversion to the machine instruction we are working on.
56   operator MachineInstr*() const { return MI; }
57   MachineInstr *operator->() const { return MI; }
58   operator MachineBasicBlock::iterator() const { return MI; }
59
60   /// If conversion operators fail, use this method to get the MachineInstr
61   /// explicitly.
62   MachineInstr *getInstr() const { return MI; }
63
64   /// Add a new virtual register operand.
65   const MachineInstrBuilder &addReg(unsigned RegNo, unsigned flags = 0,
66                                     unsigned SubReg = 0) const {
67     assert((flags & 0x1) == 0 &&
68            "Passing in 'true' to addReg is forbidden! Use enums instead.");
69     MI->addOperand(*MF, MachineOperand::CreateReg(RegNo,
70                                                flags & RegState::Define,
71                                                flags & RegState::Implicit,
72                                                flags & RegState::Kill,
73                                                flags & RegState::Dead,
74                                                flags & RegState::Undef,
75                                                flags & RegState::EarlyClobber,
76                                                SubReg,
77                                                flags & RegState::Debug,
78                                                flags & RegState::InternalRead));
79     return *this;
80   }
81
82   /// Add a new immediate operand.
83   const MachineInstrBuilder &addImm(int64_t Val) const {
84     MI->addOperand(*MF, MachineOperand::CreateImm(Val));
85     return *this;
86   }
87
88   const MachineInstrBuilder &addCImm(const ConstantInt *Val) const {
89     MI->addOperand(*MF, MachineOperand::CreateCImm(Val));
90     return *this;
91   }
92
93   const MachineInstrBuilder &addFPImm(const ConstantFP *Val) const {
94     MI->addOperand(*MF, MachineOperand::CreateFPImm(Val));
95     return *this;
96   }
97
98   const MachineInstrBuilder &addMBB(MachineBasicBlock *MBB,
99                                     unsigned char TargetFlags = 0) const {
100     MI->addOperand(*MF, MachineOperand::CreateMBB(MBB, TargetFlags));
101     return *this;
102   }
103
104   const MachineInstrBuilder &addFrameIndex(int Idx) const {
105     MI->addOperand(*MF, MachineOperand::CreateFI(Idx));
106     return *this;
107   }
108
109   const MachineInstrBuilder &addConstantPoolIndex(unsigned Idx,
110                                                   int Offset = 0,
111                                           unsigned char TargetFlags = 0) const {
112     MI->addOperand(*MF, MachineOperand::CreateCPI(Idx, Offset, TargetFlags));
113     return *this;
114   }
115
116   const MachineInstrBuilder &addTargetIndex(unsigned Idx, int64_t Offset = 0,
117                                           unsigned char TargetFlags = 0) const {
118     MI->addOperand(*MF, MachineOperand::CreateTargetIndex(Idx, Offset,
119                                                           TargetFlags));
120     return *this;
121   }
122
123   const MachineInstrBuilder &addJumpTableIndex(unsigned Idx,
124                                           unsigned char TargetFlags = 0) const {
125     MI->addOperand(*MF, MachineOperand::CreateJTI(Idx, TargetFlags));
126     return *this;
127   }
128
129   const MachineInstrBuilder &addGlobalAddress(const GlobalValue *GV,
130                                               int64_t Offset = 0,
131                                           unsigned char TargetFlags = 0) const {
132     MI->addOperand(*MF, MachineOperand::CreateGA(GV, Offset, TargetFlags));
133     return *this;
134   }
135
136   const MachineInstrBuilder &addExternalSymbol(const char *FnName,
137                                           unsigned char TargetFlags = 0) const {
138     MI->addOperand(*MF, MachineOperand::CreateES(FnName, TargetFlags));
139     return *this;
140   }
141
142   const MachineInstrBuilder &addBlockAddress(const BlockAddress *BA,
143                                              int64_t Offset = 0,
144                                           unsigned char TargetFlags = 0) const {
145     MI->addOperand(*MF, MachineOperand::CreateBA(BA, Offset, TargetFlags));
146     return *this;
147   }
148
149   const MachineInstrBuilder &addRegMask(const uint32_t *Mask) const {
150     MI->addOperand(*MF, MachineOperand::CreateRegMask(Mask));
151     return *this;
152   }
153
154   const MachineInstrBuilder &addMemOperand(MachineMemOperand *MMO) const {
155     MI->addMemOperand(*MF, MMO);
156     return *this;
157   }
158
159   const MachineInstrBuilder &setMemRefs(MachineInstr::mmo_iterator b,
160                                         MachineInstr::mmo_iterator e) const {
161     MI->setMemRefs(b, e);
162     return *this;
163   }
164
165   const MachineInstrBuilder &setMemRefs(std::pair<MachineInstr::mmo_iterator,
166                                         unsigned> MemOperandsRef) const {
167     MI->setMemRefs(MemOperandsRef);
168     return *this;
169   }
170
171   const MachineInstrBuilder &addOperand(const MachineOperand &MO) const {
172     MI->addOperand(*MF, MO);
173     return *this;
174   }
175
176   const MachineInstrBuilder &addMetadata(const MDNode *MD) const {
177     MI->addOperand(*MF, MachineOperand::CreateMetadata(MD));
178     assert((MI->isDebugValue() ? static_cast<bool>(MI->getDebugVariable())
179                                : true) &&
180            "first MDNode argument of a DBG_VALUE not a variable");
181     return *this;
182   }
183
184   const MachineInstrBuilder &addCFIIndex(unsigned CFIIndex) const {
185     MI->addOperand(*MF, MachineOperand::CreateCFIIndex(CFIIndex));
186     return *this;
187   }
188
189   const MachineInstrBuilder &addSym(MCSymbol *Sym,
190                                     unsigned char TargetFlags = 0) const {
191     MI->addOperand(*MF, MachineOperand::CreateMCSymbol(Sym, TargetFlags));
192     return *this;
193   }
194
195   const MachineInstrBuilder &setMIFlags(unsigned Flags) const {
196     MI->setFlags(Flags);
197     return *this;
198   }
199
200   const MachineInstrBuilder &setMIFlag(MachineInstr::MIFlag Flag) const {
201     MI->setFlag(Flag);
202     return *this;
203   }
204
205   // Add a displacement from an existing MachineOperand with an added offset.
206   const MachineInstrBuilder &addDisp(const MachineOperand &Disp, int64_t off,
207                                      unsigned char TargetFlags = 0) const {
208     // If caller specifies new TargetFlags then use it, otherwise the
209     // default behavior is to copy the target flags from the existing
210     // MachineOperand. This means if the caller wants to clear the
211     // target flags it needs to do so explicitly.
212     if (0 == TargetFlags)
213       TargetFlags = Disp.getTargetFlags();
214
215     switch (Disp.getType()) {
216       default:
217         llvm_unreachable("Unhandled operand type in addDisp()");
218       case MachineOperand::MO_Immediate:
219         return addImm(Disp.getImm() + off);
220       case MachineOperand::MO_ConstantPoolIndex:
221         return addConstantPoolIndex(Disp.getIndex(), Disp.getOffset() + off,
222                                     TargetFlags);
223       case MachineOperand::MO_GlobalAddress:
224         return addGlobalAddress(Disp.getGlobal(), Disp.getOffset() + off,
225                                 TargetFlags);
226     }
227   }
228
229   /// Copy all the implicit operands from OtherMI onto this one.
230   const MachineInstrBuilder &
231   copyImplicitOps(const MachineInstr *OtherMI) const {
232     MI->copyImplicitOps(*MF, OtherMI);
233     return *this;
234   }
235 };
236
237 /// Builder interface. Specify how to create the initial instruction itself.
238 inline MachineInstrBuilder BuildMI(MachineFunction &MF,
239                                    DebugLoc DL,
240                                    const MCInstrDesc &MCID) {
241   return MachineInstrBuilder(MF, MF.CreateMachineInstr(MCID, DL));
242 }
243
244 /// This version of the builder sets up the first operand as a
245 /// destination virtual register.
246 inline MachineInstrBuilder BuildMI(MachineFunction &MF,
247                                    DebugLoc DL,
248                                    const MCInstrDesc &MCID,
249                                    unsigned DestReg) {
250   return MachineInstrBuilder(MF, MF.CreateMachineInstr(MCID, DL))
251            .addReg(DestReg, RegState::Define);
252 }
253
254 /// This version of the builder inserts the newly-built instruction before
255 /// the given position in the given MachineBasicBlock, and sets up the first
256 /// operand as a destination virtual register.
257 inline MachineInstrBuilder BuildMI(MachineBasicBlock &BB,
258                                    MachineBasicBlock::iterator I,
259                                    DebugLoc DL,
260                                    const MCInstrDesc &MCID,
261                                    unsigned DestReg) {
262   MachineFunction &MF = *BB.getParent();
263   MachineInstr *MI = MF.CreateMachineInstr(MCID, DL);
264   BB.insert(I, MI);
265   return MachineInstrBuilder(MF, MI).addReg(DestReg, RegState::Define);
266 }
267
268 inline MachineInstrBuilder BuildMI(MachineBasicBlock &BB,
269                                    MachineBasicBlock::instr_iterator I,
270                                    DebugLoc DL,
271                                    const MCInstrDesc &MCID,
272                                    unsigned DestReg) {
273   MachineFunction &MF = *BB.getParent();
274   MachineInstr *MI = MF.CreateMachineInstr(MCID, DL);
275   BB.insert(I, MI);
276   return MachineInstrBuilder(MF, MI).addReg(DestReg, RegState::Define);
277 }
278
279 inline MachineInstrBuilder BuildMI(MachineBasicBlock &BB,
280                                    MachineInstr *I,
281                                    DebugLoc DL,
282                                    const MCInstrDesc &MCID,
283                                    unsigned DestReg) {
284   if (I->isInsideBundle()) {
285     MachineBasicBlock::instr_iterator MII(I);
286     return BuildMI(BB, MII, DL, MCID, DestReg);
287   }
288
289   MachineBasicBlock::iterator MII = I;
290   return BuildMI(BB, MII, DL, MCID, DestReg);
291 }
292
293 /// This version of the builder inserts the newly-built instruction before the
294 /// given position in the given MachineBasicBlock, and does NOT take a
295 /// destination register.
296 inline MachineInstrBuilder BuildMI(MachineBasicBlock &BB,
297                                    MachineBasicBlock::iterator I,
298                                    DebugLoc DL,
299                                    const MCInstrDesc &MCID) {
300   MachineFunction &MF = *BB.getParent();
301   MachineInstr *MI = MF.CreateMachineInstr(MCID, DL);
302   BB.insert(I, MI);
303   return MachineInstrBuilder(MF, MI);
304 }
305
306 inline MachineInstrBuilder BuildMI(MachineBasicBlock &BB,
307                                    MachineBasicBlock::instr_iterator I,
308                                    DebugLoc DL,
309                                    const MCInstrDesc &MCID) {
310   MachineFunction &MF = *BB.getParent();
311   MachineInstr *MI = MF.CreateMachineInstr(MCID, DL);
312   BB.insert(I, MI);
313   return MachineInstrBuilder(MF, MI);
314 }
315
316 inline MachineInstrBuilder BuildMI(MachineBasicBlock &BB,
317                                    MachineInstr *I,
318                                    DebugLoc DL,
319                                    const MCInstrDesc &MCID) {
320   if (I->isInsideBundle()) {
321     MachineBasicBlock::instr_iterator MII(I);
322     return BuildMI(BB, MII, DL, MCID);
323   }
324
325   MachineBasicBlock::iterator MII = I;
326   return BuildMI(BB, MII, DL, MCID);
327 }
328
329 /// This version of the builder inserts the newly-built instruction at the end
330 /// of the given MachineBasicBlock, and does NOT take a destination register.
331 inline MachineInstrBuilder BuildMI(MachineBasicBlock *BB,
332                                    DebugLoc DL,
333                                    const MCInstrDesc &MCID) {
334   return BuildMI(*BB, BB->end(), DL, MCID);
335 }
336
337 /// This version of the builder inserts the newly-built instruction at the
338 /// end of the given MachineBasicBlock, and sets up the first operand as a
339 /// destination virtual register.
340 inline MachineInstrBuilder BuildMI(MachineBasicBlock *BB,
341                                    DebugLoc DL,
342                                    const MCInstrDesc &MCID,
343                                    unsigned DestReg) {
344   return BuildMI(*BB, BB->end(), DL, MCID, DestReg);
345 }
346
347 /// This version of the builder builds a DBG_VALUE intrinsic
348 /// for either a value in a register or a register-indirect+offset
349 /// address.  The convention is that a DBG_VALUE is indirect iff the
350 /// second operand is an immediate.
351 inline MachineInstrBuilder BuildMI(MachineFunction &MF, DebugLoc DL,
352                                    const MCInstrDesc &MCID, bool IsIndirect,
353                                    unsigned Reg, unsigned Offset,
354                                    const MDNode *Variable, const MDNode *Expr) {
355   assert(isa<DILocalVariable>(Variable) && "not a variable");
356   assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
357   assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
358          "Expected inlined-at fields to agree");
359   if (IsIndirect)
360     return BuildMI(MF, DL, MCID)
361         .addReg(Reg, RegState::Debug)
362         .addImm(Offset)
363         .addMetadata(Variable)
364         .addMetadata(Expr);
365   else {
366     assert(Offset == 0 && "A direct address cannot have an offset.");
367     return BuildMI(MF, DL, MCID)
368         .addReg(Reg, RegState::Debug)
369         .addReg(0U, RegState::Debug)
370         .addMetadata(Variable)
371         .addMetadata(Expr);
372   }
373 }
374
375 /// This version of the builder builds a DBG_VALUE intrinsic
376 /// for either a value in a register or a register-indirect+offset
377 /// address and inserts it at position I.
378 inline MachineInstrBuilder BuildMI(MachineBasicBlock &BB,
379                                    MachineBasicBlock::iterator I, DebugLoc DL,
380                                    const MCInstrDesc &MCID, bool IsIndirect,
381                                    unsigned Reg, unsigned Offset,
382                                    const MDNode *Variable, const MDNode *Expr) {
383   assert(isa<DILocalVariable>(Variable) && "not a variable");
384   assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
385   MachineFunction &MF = *BB.getParent();
386   MachineInstr *MI =
387       BuildMI(MF, DL, MCID, IsIndirect, Reg, Offset, Variable, Expr);
388   BB.insert(I, MI);
389   return MachineInstrBuilder(MF, MI);
390 }
391
392
393 inline unsigned getDefRegState(bool B) {
394   return B ? RegState::Define : 0;
395 }
396 inline unsigned getImplRegState(bool B) {
397   return B ? RegState::Implicit : 0;
398 }
399 inline unsigned getKillRegState(bool B) {
400   return B ? RegState::Kill : 0;
401 }
402 inline unsigned getDeadRegState(bool B) {
403   return B ? RegState::Dead : 0;
404 }
405 inline unsigned getUndefRegState(bool B) {
406   return B ? RegState::Undef : 0;
407 }
408 inline unsigned getInternalReadRegState(bool B) {
409   return B ? RegState::InternalRead : 0;
410 }
411 inline unsigned getDebugRegState(bool B) {
412   return B ? RegState::Debug : 0;
413 }
414
415
416 /// Helper class for constructing bundles of MachineInstrs.
417 ///
418 /// MIBundleBuilder can create a bundle from scratch by inserting new
419 /// MachineInstrs one at a time, or it can create a bundle from a sequence of
420 /// existing MachineInstrs in a basic block.
421 class MIBundleBuilder {
422   MachineBasicBlock &MBB;
423   MachineBasicBlock::instr_iterator Begin;
424   MachineBasicBlock::instr_iterator End;
425
426 public:
427   /// Create an MIBundleBuilder that inserts instructions into a new bundle in
428   /// BB above the bundle or instruction at Pos.
429   MIBundleBuilder(MachineBasicBlock &BB,
430                   MachineBasicBlock::iterator Pos)
431     : MBB(BB), Begin(Pos.getInstrIterator()), End(Begin) {}
432
433   /// Create a bundle from the sequence of instructions between B and E.
434   MIBundleBuilder(MachineBasicBlock &BB,
435                   MachineBasicBlock::iterator B,
436                   MachineBasicBlock::iterator E)
437     : MBB(BB), Begin(B.getInstrIterator()), End(E.getInstrIterator()) {
438     assert(B != E && "No instructions to bundle");
439     ++B;
440     while (B != E) {
441       MachineInstr *MI = B;
442       ++B;
443       MI->bundleWithPred();
444     }
445   }
446
447   /// Create an MIBundleBuilder representing an existing instruction or bundle
448   /// that has MI as its head.
449   explicit MIBundleBuilder(MachineInstr *MI)
450     : MBB(*MI->getParent()), Begin(MI), End(getBundleEnd(MI)) {}
451
452   /// Return a reference to the basic block containing this bundle.
453   MachineBasicBlock &getMBB() const { return MBB; }
454
455   /// Return true if no instructions have been inserted in this bundle yet.
456   /// Empty bundles aren't representable in a MachineBasicBlock.
457   bool empty() const { return Begin == End; }
458
459   /// Return an iterator to the first bundled instruction.
460   MachineBasicBlock::instr_iterator begin() const { return Begin; }
461
462   /// Return an iterator beyond the last bundled instruction.
463   MachineBasicBlock::instr_iterator end() const { return End; }
464
465   /// Insert MI into this bundle before I which must point to an instruction in
466   /// the bundle, or end().
467   MIBundleBuilder &insert(MachineBasicBlock::instr_iterator I,
468                           MachineInstr *MI) {
469     MBB.insert(I, MI);
470     if (I == Begin) {
471       if (!empty())
472         MI->bundleWithSucc();
473       Begin = MI->getIterator();
474       return *this;
475     }
476     if (I == End) {
477       MI->bundleWithPred();
478       return *this;
479     }
480     // MI was inserted in the middle of the bundle, so its neighbors' flags are
481     // already fine. Update MI's bundle flags manually.
482     MI->setFlag(MachineInstr::BundledPred);
483     MI->setFlag(MachineInstr::BundledSucc);
484     return *this;
485   }
486
487   /// Insert MI into MBB by prepending it to the instructions in the bundle.
488   /// MI will become the first instruction in the bundle.
489   MIBundleBuilder &prepend(MachineInstr *MI) {
490     return insert(begin(), MI);
491   }
492
493   /// Insert MI into MBB by appending it to the instructions in the bundle.
494   /// MI will become the last instruction in the bundle.
495   MIBundleBuilder &append(MachineInstr *MI) {
496     return insert(end(), MI);
497   }
498 };
499
500 } // End llvm namespace
501
502 #endif