[FastISel] Rename public visible FastISel functions. NFC.
[oota-llvm.git] / include / llvm / CodeGen / FastISel.h
1 //===-- FastISel.h - Definition of the FastISel class ---*- 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 /// \file
11 /// This file defines the FastISel class.
12 ///
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_CODEGEN_FASTISEL_H
16 #define LLVM_CODEGEN_FASTISEL_H
17
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/CodeGen/CallingConvLower.h"
20 #include "llvm/CodeGen/MachineBasicBlock.h"
21 #include "llvm/Target/TargetLowering.h"
22 #include "llvm/IR/CallingConv.h"
23 #include "llvm/IR/IntrinsicInst.h"
24
25 namespace llvm {
26
27 /// \brief This is a fast-path instruction selection class that generates poor
28 /// code and doesn't support illegal types or non-trivial lowering, but runs
29 /// quickly.
30 class FastISel {
31 public:
32   struct ArgListEntry {
33     Value *Val;
34     Type *Ty;
35     bool IsSExt : 1;
36     bool IsZExt : 1;
37     bool IsInReg : 1;
38     bool IsSRet : 1;
39     bool IsNest : 1;
40     bool IsByVal : 1;
41     bool IsInAlloca : 1;
42     bool IsReturned : 1;
43     uint16_t Alignment;
44
45     ArgListEntry()
46         : Val(nullptr), Ty(nullptr), IsSExt(false), IsZExt(false),
47           IsInReg(false), IsSRet(false), IsNest(false), IsByVal(false),
48           IsInAlloca(false), IsReturned(false), Alignment(0) {}
49
50     /// \brief Set CallLoweringInfo attribute flags based on a call instruction
51     /// and called function attributes.
52     void setAttributes(ImmutableCallSite *CS, unsigned AttrIdx);
53   };
54   typedef std::vector<ArgListEntry> ArgListTy;
55
56   struct CallLoweringInfo {
57     Type *RetTy;
58     bool RetSExt : 1;
59     bool RetZExt : 1;
60     bool IsVarArg : 1;
61     bool IsInReg : 1;
62     bool DoesNotReturn : 1;
63     bool IsReturnValueUsed : 1;
64
65     // \brief IsTailCall Should be modified by implementations of FastLowerCall
66     // that perform tail call conversions.
67     bool IsTailCall;
68
69     unsigned NumFixedArgs;
70     CallingConv::ID CallConv;
71     const Value *Callee;
72     const char *SymName;
73     ArgListTy Args;
74     ImmutableCallSite *CS;
75     MachineInstr *Call;
76     unsigned ResultReg;
77     unsigned NumResultRegs;
78
79     SmallVector<Value *, 16> OutVals;
80     SmallVector<ISD::ArgFlagsTy, 16> OutFlags;
81     SmallVector<unsigned, 16> OutRegs;
82     SmallVector<ISD::InputArg, 4> Ins;
83     SmallVector<unsigned, 4> InRegs;
84
85     CallLoweringInfo()
86         : RetTy(nullptr), RetSExt(false), RetZExt(false), IsVarArg(false),
87           IsInReg(false), DoesNotReturn(false), IsReturnValueUsed(true),
88           IsTailCall(false), NumFixedArgs(-1), CallConv(CallingConv::C),
89           Callee(nullptr), SymName(nullptr), CS(nullptr), Call(nullptr),
90           ResultReg(0), NumResultRegs(0) {}
91
92     CallLoweringInfo &setCallee(Type *ResultTy, FunctionType *FuncTy,
93                                 const Value *Target, ArgListTy &&ArgsList,
94                                 ImmutableCallSite &Call) {
95       RetTy = ResultTy;
96       Callee = Target;
97
98       IsInReg = Call.paramHasAttr(0, Attribute::InReg);
99       DoesNotReturn = Call.doesNotReturn();
100       IsVarArg = FuncTy->isVarArg();
101       IsReturnValueUsed = !Call.getInstruction()->use_empty();
102       RetSExt = Call.paramHasAttr(0, Attribute::SExt);
103       RetZExt = Call.paramHasAttr(0, Attribute::ZExt);
104
105       CallConv = Call.getCallingConv();
106       NumFixedArgs = FuncTy->getNumParams();
107       Args = std::move(ArgsList);
108
109       CS = &Call;
110
111       return *this;
112     }
113
114     CallLoweringInfo &setCallee(Type *ResultTy, FunctionType *FuncTy,
115                                 const char *Target, ArgListTy &&ArgsList,
116                                 ImmutableCallSite &Call,
117                                 unsigned FixedArgs = ~0U) {
118       RetTy = ResultTy;
119       Callee = Call.getCalledValue();
120       SymName = Target;
121
122       IsInReg = Call.paramHasAttr(0, Attribute::InReg);
123       DoesNotReturn = Call.doesNotReturn();
124       IsVarArg = FuncTy->isVarArg();
125       IsReturnValueUsed = !Call.getInstruction()->use_empty();
126       RetSExt = Call.paramHasAttr(0, Attribute::SExt);
127       RetZExt = Call.paramHasAttr(0, Attribute::ZExt);
128
129       CallConv = Call.getCallingConv();
130       NumFixedArgs = (FixedArgs == ~0U) ? FuncTy->getNumParams() : FixedArgs;
131       Args = std::move(ArgsList);
132
133       CS = &Call;
134
135       return *this;
136     }
137
138     CallLoweringInfo &setCallee(CallingConv::ID CC, Type *ResultTy,
139                                 const Value *Target, ArgListTy &&ArgsList,
140                                 unsigned FixedArgs = ~0U) {
141       RetTy = ResultTy;
142       Callee = Target;
143       CallConv = CC;
144       NumFixedArgs = (FixedArgs == ~0U) ? Args.size() : FixedArgs;
145       Args = std::move(ArgsList);
146       return *this;
147     }
148
149     CallLoweringInfo &setTailCall(bool Value = true) {
150       IsTailCall = Value;
151       return *this;
152     }
153
154     ArgListTy &getArgs() { return Args; }
155
156     void clearOuts() {
157       OutVals.clear();
158       OutFlags.clear();
159       OutRegs.clear();
160     }
161
162     void clearIns() {
163       Ins.clear();
164       InRegs.clear();
165     }
166   };
167
168 protected:
169   DenseMap<const Value *, unsigned> LocalValueMap;
170   FunctionLoweringInfo &FuncInfo;
171   MachineFunction *MF;
172   MachineRegisterInfo &MRI;
173   MachineFrameInfo &MFI;
174   MachineConstantPool &MCP;
175   DebugLoc DbgLoc;
176   const TargetMachine &TM;
177   const DataLayout &DL;
178   const TargetInstrInfo &TII;
179   const TargetLowering &TLI;
180   const TargetRegisterInfo &TRI;
181   const TargetLibraryInfo *LibInfo;
182   bool SkipTargetIndependentISel;
183
184   /// \brief The position of the last instruction for materializing constants
185   /// for use in the current block. It resets to EmitStartPt when it makes sense
186   /// (for example, it's usually profitable to avoid function calls between the
187   /// definition and the use)
188   MachineInstr *LastLocalValue;
189
190   /// \brief The top most instruction in the current block that is allowed for
191   /// emitting local variables. LastLocalValue resets to EmitStartPt when it
192   /// makes sense (for example, on function calls)
193   MachineInstr *EmitStartPt;
194
195 public:
196   /// \brief Return the position of the last instruction emitted for
197   /// materializing constants for use in the current block.
198   MachineInstr *getLastLocalValue() { return LastLocalValue; }
199
200   /// \brief Update the position of the last instruction emitted for
201   /// materializing constants for use in the current block.
202   void setLastLocalValue(MachineInstr *I) {
203     EmitStartPt = I;
204     LastLocalValue = I;
205   }
206
207   /// \brief Set the current block to which generated machine instructions will
208   /// be appended, and clear the local CSE map.
209   void startNewBlock();
210
211   /// \brief Return current debug location information.
212   DebugLoc getCurDebugLoc() const { return DbgLoc; }
213
214   /// \brief Do "fast" instruction selection for function arguments and append
215   /// the machine instructions to the current block. Returns true when
216   /// successful.
217   bool lowerArguments();
218
219   /// \brief Do "fast" instruction selection for the given LLVM IR instruction
220   /// and append the generated machine instructions to the current block.
221   /// Returns true if selection was successful.
222   bool selectInstruction(const Instruction *I);
223
224   /// \brief Do "fast" instruction selection for the given LLVM IR operator
225   /// (Instruction or ConstantExpr), and append generated machine instructions
226   /// to the current block. Return true if selection was successful.
227   bool selectOperator(const User *I, unsigned Opcode);
228
229   /// \brief Create a virtual register and arrange for it to be assigned the
230   /// value for the given LLVM value.
231   unsigned getRegForValue(const Value *V);
232
233   /// \brief Look up the value to see if its value is already cached in a
234   /// register. It may be defined by instructions across blocks or defined
235   /// locally.
236   unsigned lookUpRegForValue(const Value *V);
237
238   /// \brief This is a wrapper around getRegForValue that also takes care of
239   /// truncating or sign-extending the given getelementptr index value.
240   std::pair<unsigned, bool> getRegForGEPIndex(const Value *V);
241
242   /// \brief We're checking to see if we can fold \p LI into \p FoldInst. Note
243   /// that we could have a sequence where multiple LLVM IR instructions are
244   /// folded into the same machineinstr.  For example we could have:
245   ///
246   ///   A: x = load i32 *P
247   ///   B: y = icmp A, 42
248   ///   C: br y, ...
249   ///
250   /// In this scenario, \p LI is "A", and \p FoldInst is "C".  We know about "B"
251   /// (and any other folded instructions) because it is between A and C.
252   ///
253   /// If we succeed folding, return true.
254   bool tryToFoldLoad(const LoadInst *LI, const Instruction *FoldInst);
255
256   /// \brief The specified machine instr operand is a vreg, and that vreg is
257   /// being provided by the specified load instruction.  If possible, try to
258   /// fold the load as an operand to the instruction, returning true if
259   /// possible.
260   ///
261   /// This method should be implemented by targets.
262   virtual bool tryToFoldLoadIntoMI(MachineInstr * /*MI*/, unsigned /*OpNo*/,
263                                    const LoadInst * /*LI*/) {
264     return false;
265   }
266
267   /// \brief Reset InsertPt to prepare for inserting instructions into the
268   /// current block.
269   void recomputeInsertPt();
270
271   /// \brief Remove all dead instructions between the I and E.
272   void removeDeadCode(MachineBasicBlock::iterator I,
273                       MachineBasicBlock::iterator E);
274
275   struct SavePoint {
276     MachineBasicBlock::iterator InsertPt;
277     DebugLoc DL;
278   };
279
280   /// \brief Prepare InsertPt to begin inserting instructions into the local
281   /// value area and return the old insert position.
282   SavePoint enterLocalValueArea();
283
284   /// \brief Reset InsertPt to the given old insert position.
285   void leaveLocalValueArea(SavePoint Old);
286
287   virtual ~FastISel();
288
289 protected:
290   explicit FastISel(FunctionLoweringInfo &FuncInfo,
291                     const TargetLibraryInfo *LibInfo,
292                     bool SkipTargetIndependentISel = false);
293
294   /// \brief This method is called by target-independent code when the normal
295   /// FastISel process fails to select an instruction. This gives targets a
296   /// chance to emit code for anything that doesn't fit into FastISel's
297   /// framework. It returns true if it was successful.
298   virtual bool fastSelectInstruction(const Instruction *I) = 0;
299
300   /// \brief This method is called by target-independent code to do target-
301   /// specific argument lowering. It returns true if it was successful.
302   virtual bool fastLowerArguments();
303
304   /// \brief This method is called by target-independent code to do target-
305   /// specific call lowering. It returns true if it was successful.
306   virtual bool fastLowerCall(CallLoweringInfo &CLI);
307
308   /// \brief This method is called by target-independent code to do target-
309   /// specific intrinsic lowering. It returns true if it was successful.
310   virtual bool fastLowerIntrinsicCall(const IntrinsicInst *II);
311
312   /// \brief This method is called by target-independent code to request that an
313   /// instruction with the given type and opcode be emitted.
314   virtual unsigned FastEmit_(MVT VT, MVT RetVT, unsigned Opcode);
315
316   /// \brief This method is called by target-independent code to request that an
317   /// instruction with the given type, opcode, and register operand be emitted.
318   virtual unsigned FastEmit_r(MVT VT, MVT RetVT, unsigned Opcode, unsigned Op0,
319                               bool Op0IsKill);
320
321   /// \brief This method is called by target-independent code to request that an
322   /// instruction with the given type, opcode, and register operands be emitted.
323   virtual unsigned FastEmit_rr(MVT VT, MVT RetVT, unsigned Opcode, unsigned Op0,
324                                bool Op0IsKill, unsigned Op1, bool Op1IsKill);
325
326   /// \brief This method is called by target-independent code to request that an
327   /// instruction with the given type, opcode, and register and immediate
328   // operands be emitted.
329   virtual unsigned FastEmit_ri(MVT VT, MVT RetVT, unsigned Opcode, unsigned Op0,
330                                bool Op0IsKill, uint64_t Imm);
331
332   /// \brief This method is called by target-independent code to request that an
333   /// instruction with the given type, opcode, and register and floating-point
334   /// immediate operands be emitted.
335   virtual unsigned FastEmit_rf(MVT VT, MVT RetVT, unsigned Opcode, unsigned Op0,
336                                bool Op0IsKill, const ConstantFP *FPImm);
337
338   /// \brief This method is called by target-independent code to request that an
339   /// instruction with the given type, opcode, and register and immediate
340   /// operands be emitted.
341   virtual unsigned FastEmit_rri(MVT VT, MVT RetVT, unsigned Opcode,
342                                 unsigned Op0, bool Op0IsKill, unsigned Op1,
343                                 bool Op1IsKill, uint64_t Imm);
344
345   /// \brief This method is a wrapper of FastEmit_ri.
346   ///
347   /// It first tries to emit an instruction with an immediate operand using
348   /// FastEmit_ri.  If that fails, it materializes the immediate into a register
349   /// and try FastEmit_rr instead.
350   unsigned FastEmit_ri_(MVT VT, unsigned Opcode, unsigned Op0, bool Op0IsKill,
351                         uint64_t Imm, MVT ImmType);
352
353   /// \brief This method is called by target-independent code to request that an
354   /// instruction with the given type, opcode, and immediate operand be emitted.
355   virtual unsigned FastEmit_i(MVT VT, MVT RetVT, unsigned Opcode, uint64_t Imm);
356
357   /// \brief This method is called by target-independent code to request that an
358   /// instruction with the given type, opcode, and floating-point immediate
359   /// operand be emitted.
360   virtual unsigned FastEmit_f(MVT VT, MVT RetVT, unsigned Opcode,
361                               const ConstantFP *FPImm);
362
363   /// \brief Emit a MachineInstr with no operands and a result register in the
364   /// given register class.
365   unsigned FastEmitInst_(unsigned MachineInstOpcode,
366                          const TargetRegisterClass *RC);
367
368   /// \brief Emit a MachineInstr with one register operand and a result register
369   /// in the given register class.
370   unsigned FastEmitInst_r(unsigned MachineInstOpcode,
371                           const TargetRegisterClass *RC, unsigned Op0,
372                           bool Op0IsKill);
373
374   /// \brief Emit a MachineInstr with two register operands and a result
375   /// register in the given register class.
376   unsigned FastEmitInst_rr(unsigned MachineInstOpcode,
377                            const TargetRegisterClass *RC, unsigned Op0,
378                            bool Op0IsKill, unsigned Op1, bool Op1IsKill);
379
380   /// \brief Emit a MachineInstr with three register operands and a result
381   /// register in the given register class.
382   unsigned FastEmitInst_rrr(unsigned MachineInstOpcode,
383                             const TargetRegisterClass *RC, unsigned Op0,
384                             bool Op0IsKill, unsigned Op1, bool Op1IsKill,
385                             unsigned Op2, bool Op2IsKill);
386
387   /// \brief Emit a MachineInstr with a register operand, an immediate, and a
388   /// result register in the given register class.
389   unsigned FastEmitInst_ri(unsigned MachineInstOpcode,
390                            const TargetRegisterClass *RC, unsigned Op0,
391                            bool Op0IsKill, uint64_t Imm);
392
393   /// \brief Emit a MachineInstr with one register operand and two immediate
394   /// operands.
395   unsigned FastEmitInst_rii(unsigned MachineInstOpcode,
396                             const TargetRegisterClass *RC, unsigned Op0,
397                             bool Op0IsKill, uint64_t Imm1, uint64_t Imm2);
398
399   /// \brief Emit a MachineInstr with two register operands and a result
400   /// register in the given register class.
401   unsigned FastEmitInst_rf(unsigned MachineInstOpcode,
402                            const TargetRegisterClass *RC, unsigned Op0,
403                            bool Op0IsKill, const ConstantFP *FPImm);
404
405   /// \brief Emit a MachineInstr with two register operands, an immediate, and a
406   /// result register in the given register class.
407   unsigned FastEmitInst_rri(unsigned MachineInstOpcode,
408                             const TargetRegisterClass *RC, unsigned Op0,
409                             bool Op0IsKill, unsigned Op1, bool Op1IsKill,
410                             uint64_t Imm);
411
412   /// \brief Emit a MachineInstr with two register operands, two immediates
413   /// operands, and a result register in the given register class.
414   unsigned FastEmitInst_rrii(unsigned MachineInstOpcode,
415                              const TargetRegisterClass *RC, unsigned Op0,
416                              bool Op0IsKill, unsigned Op1, bool Op1IsKill,
417                              uint64_t Imm1, uint64_t Imm2);
418
419   /// \brief Emit a MachineInstr with a single immediate operand, and a result
420   /// register in the given register class.
421   unsigned FastEmitInst_i(unsigned MachineInstrOpcode,
422                           const TargetRegisterClass *RC, uint64_t Imm);
423
424   /// \brief Emit a MachineInstr with a two immediate operands.
425   unsigned FastEmitInst_ii(unsigned MachineInstrOpcode,
426                            const TargetRegisterClass *RC, uint64_t Imm1,
427                            uint64_t Imm2);
428
429   /// \brief Emit a MachineInstr for an extract_subreg from a specified index of
430   /// a superregister to a specified type.
431   unsigned FastEmitInst_extractsubreg(MVT RetVT, unsigned Op0, bool Op0IsKill,
432                                       uint32_t Idx);
433
434   /// \brief Emit MachineInstrs to compute the value of Op with all but the
435   /// least significant bit set to zero.
436   unsigned fastEmitZExtFromI1(MVT VT, unsigned Op0, bool Op0IsKill);
437
438   /// \brief Emit an unconditional branch to the given block, unless it is the
439   /// immediate (fall-through) successor, and update the CFG.
440   void fastEmitBranch(MachineBasicBlock *MBB, DebugLoc DL);
441
442   /// \brief Update the value map to include the new mapping for this
443   /// instruction, or insert an extra copy to get the result in a previous
444   /// determined register.
445   ///
446   /// NOTE: This is only necessary because we might select a block that uses a
447   /// value before we select the block that defines the value. It might be
448   /// possible to fix this by selecting blocks in reverse postorder.
449   void updateValueMap(const Value *I, unsigned Reg, unsigned NumRegs = 1);
450
451   unsigned createResultReg(const TargetRegisterClass *RC);
452
453   /// \brief Try to constrain Op so that it is usable by argument OpNum of the
454   /// provided MCInstrDesc. If this fails, create a new virtual register in the
455   /// correct class and COPY the value there.
456   unsigned constrainOperandRegClass(const MCInstrDesc &II, unsigned Op,
457                                     unsigned OpNum);
458
459   /// \brief Emit a constant in a register using target-specific logic, such as
460   /// constant pool loads.
461   virtual unsigned fastMaterializeConstant(const Constant *C) { return 0; }
462
463   /// \brief Emit an alloca address in a register using target-specific logic.
464   virtual unsigned fastMaterializeAlloca(const AllocaInst *C) { return 0; }
465
466   /// \brief Emit the floating-point constant +0.0 in a register using target-
467   /// specific logic.
468   virtual unsigned fastMaterializeFloatZero(const ConstantFP *CF) {
469     return 0;
470   }
471
472   /// \brief Check if \c Add is an add that can be safely folded into \c GEP.
473   ///
474   /// \c Add can be folded into \c GEP if:
475   /// - \c Add is an add,
476   /// - \c Add's size matches \c GEP's,
477   /// - \c Add is in the same basic block as \c GEP, and
478   /// - \c Add has a constant operand.
479   bool canFoldAddIntoGEP(const User *GEP, const Value *Add);
480
481   /// \brief Test whether the given value has exactly one use.
482   bool hasTrivialKill(const Value *V);
483
484   /// \brief Create a machine mem operand from the given instruction.
485   MachineMemOperand *createMachineMemOperandFor(const Instruction *I) const;
486
487   bool lowerCallTo(const CallInst *CI, const char *SymName, unsigned NumArgs);
488   bool lowerCallTo(CallLoweringInfo &CLI);
489
490   bool isCommutativeIntrinsic(IntrinsicInst const *II) {
491     switch (II->getIntrinsicID()) {
492     case Intrinsic::sadd_with_overflow:
493     case Intrinsic::uadd_with_overflow:
494     case Intrinsic::smul_with_overflow:
495     case Intrinsic::umul_with_overflow:
496       return true;
497     default:
498       return false;
499     }
500   }
501
502
503   bool lowerCall(const CallInst *I);
504   /// \brief Select and emit code for a binary operator instruction, which has
505   /// an opcode which directly corresponds to the given ISD opcode.
506   bool selectBinaryOp(const User *I, unsigned ISDOpcode);
507   bool selectFNeg(const User *I);
508   bool selectGetElementPtr(const User *I);
509   bool selectStackmap(const CallInst *I);
510   bool selectPatchpoint(const CallInst *I);
511   bool selectCall(const User *Call);
512   bool selectIntrinsicCall(const IntrinsicInst *II);
513   bool selectBitCast(const User *I);
514   bool selectCast(const User *I, unsigned Opcode);
515   bool selectExtractValue(const User *I);
516   bool selectInsertValue(const User *I);
517
518 private:
519   /// \brief Handle PHI nodes in successor blocks.
520   ///
521   /// Emit code to ensure constants are copied into registers when needed.
522   /// Remember the virtual registers that need to be added to the Machine PHI
523   /// nodes as input.  We cannot just directly add them, because expansion might
524   /// result in multiple MBB's for one BB.  As such, the start of the BB might
525   /// correspond to a different MBB than the end.
526   bool handlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB);
527
528   /// \brief Helper for materializeRegForValue to materialize a constant in a
529   /// target-independent way.
530   unsigned materializeConstant(const Value *V, MVT VT);
531
532   /// \brief Helper for getRegForVale. This function is called when the value
533   /// isn't already available in a register and must be materialized with new
534   /// instructions.
535   unsigned materializeRegForValue(const Value *V, MVT VT);
536
537   /// \brief Clears LocalValueMap and moves the area for the new local variables
538   /// to the beginning of the block. It helps to avoid spilling cached variables
539   /// across heavy instructions like calls.
540   void flushLocalValueMap();
541
542   /// \brief Add a stackmap or patchpoint intrinsic call's live variable
543   /// operands to a stackmap or patchpoint machine instruction.
544   bool addStackMapLiveVars(SmallVectorImpl<MachineOperand> &Ops,
545                            const CallInst *CI, unsigned StartIdx);
546   bool lowerCallOperands(const CallInst *CI, unsigned ArgIdx, unsigned NumArgs,
547                          const Value *Callee, bool ForceRetVoidTy,
548                          CallLoweringInfo &CLI);
549 };
550
551 } // end namespace llvm
552
553 #endif