1 //===-- SelectionDAGBuild.h - Selection-DAG building ----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements routines for translating from LLVM IR into SelectionDAG IR.
12 //===----------------------------------------------------------------------===//
14 #ifndef SELECTIONDAGBUILD_H
15 #define SELECTIONDAGBUILD_H
17 #include "llvm/Constants.h"
18 #include "llvm/ADT/APInt.h"
19 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/CodeGen/ValueTypes.h"
24 #include "llvm/CodeGen/SelectionDAGNodes.h"
25 #include "llvm/Support/CallSite.h"
37 class ExtractElementInst;
38 class ExtractValueInst;
46 class GetElementPtrInst;
51 class InsertElementInst;
52 class InsertValueInst;
55 class MachineBasicBlock;
56 class MachineFunction;
58 class MachineModuleInfo;
59 class MachineRegisterInfo;
64 class SDISelAsmOperandInfo;
67 class ShuffleVectorInst;
75 class UnreachableInst;
82 //===--------------------------------------------------------------------===//
83 /// FunctionLoweringInfo - This contains information that is global to a
84 /// function that is used when lowering a region of the function.
86 class FunctionLoweringInfo {
91 MachineRegisterInfo *RegInfo;
93 explicit FunctionLoweringInfo(TargetLowering &TLI);
95 /// set - Initialize this FunctionLoweringInfo with the given Function
96 /// and its associated MachineFunction.
98 void set(Function &Fn, MachineFunction &MF, bool EnableFastISel);
100 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
101 DenseMap<const BasicBlock*, MachineBasicBlock *> MBBMap;
103 /// ValueMap - Since we emit code for the function a basic block at a time,
104 /// we must remember which virtual registers hold the values for
105 /// cross-basic-block values.
106 DenseMap<const Value*, unsigned> ValueMap;
108 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
109 /// the entry block. This allows the allocas to be efficiently referenced
110 /// anywhere in the function.
111 DenseMap<const AllocaInst*, int> StaticAllocaMap;
114 SmallSet<Instruction*, 8> CatchInfoLost;
115 SmallSet<Instruction*, 8> CatchInfoFound;
118 unsigned MakeReg(MVT VT);
120 /// isExportedInst - Return true if the specified value is an instruction
121 /// exported from its block.
122 bool isExportedInst(const Value *V) {
123 return ValueMap.count(V);
126 unsigned CreateRegForValue(const Value *V);
128 unsigned InitializeRegForValue(const Value *V) {
129 unsigned &R = ValueMap[V];
130 assert(R == 0 && "Already initialized this value register!");
131 return R = CreateRegForValue(V);
135 unsigned NumSignBits;
136 APInt KnownOne, KnownZero;
137 LiveOutInfo() : NumSignBits(0) {}
140 /// LiveOutRegInfo - Information about live out vregs, indexed by their
141 /// register number offset by 'FirstVirtualRegister'.
142 std::vector<LiveOutInfo> LiveOutRegInfo;
144 /// clear - Clear out all the function-specific state. This returns this
145 /// FunctionLoweringInfo to an empty state, ready to be used for a
146 /// different function.
150 StaticAllocaMap.clear();
152 CatchInfoLost.clear();
153 CatchInfoFound.clear();
155 LiveOutRegInfo.clear();
159 //===----------------------------------------------------------------------===//
160 /// SelectionDAGLowering - This is the common target-independent lowering
161 /// implementation that is parameterized by a TargetLowering object.
162 /// Also, targets can overload any lowering method.
164 class SelectionDAGLowering {
165 MachineBasicBlock *CurMBB;
167 DenseMap<const Value*, SDValue> NodeMap;
169 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
170 /// them up and then emit token factor nodes when possible. This allows us to
171 /// get simple disambiguation between loads without worrying about alias
173 SmallVector<SDValue, 8> PendingLoads;
175 /// PendingExports - CopyToReg nodes that copy values to virtual registers
176 /// for export to other blocks need to be emitted before any terminator
177 /// instruction, but they have no other ordering requirements. We bunch them
178 /// up and the emit a single tokenfactor for them just before terminator
180 SmallVector<SDValue, 8> PendingExports;
182 /// Case - A struct to record the Value for a switch case, and the
183 /// case's target basic block.
187 MachineBasicBlock* BB;
189 Case() : Low(0), High(0), BB(0) { }
190 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
191 Low(low), High(high), BB(bb) { }
192 uint64_t size() const {
193 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
194 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
195 return (rHigh - rLow + 1ULL);
201 MachineBasicBlock* BB;
204 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
205 Mask(mask), BB(bb), Bits(bits) { }
208 typedef std::vector<Case> CaseVector;
209 typedef std::vector<CaseBits> CaseBitsVector;
210 typedef CaseVector::iterator CaseItr;
211 typedef std::pair<CaseItr, CaseItr> CaseRange;
213 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
214 /// of conditional branches.
216 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
217 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
219 /// CaseBB - The MBB in which to emit the compare and branch
220 MachineBasicBlock *CaseBB;
221 /// LT, GE - If nonzero, we know the current case value must be less-than or
222 /// greater-than-or-equal-to these Constants.
225 /// Range - A pair of iterators representing the range of case values to be
226 /// processed at this point in the binary search tree.
230 typedef std::vector<CaseRec> CaseRecVector;
232 /// The comparison function for sorting the switch case values in the vector.
233 /// WARNING: Case ranges should be disjoint!
235 bool operator () (const Case& C1, const Case& C2) {
236 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
237 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
238 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
239 return CI1->getValue().slt(CI2->getValue());
244 bool operator () (const CaseBits& C1, const CaseBits& C2) {
245 return C1.Bits > C2.Bits;
249 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
251 /// CaseBlock - This structure is used to communicate between SDLowering and
252 /// SDISel for the code generation of additional basic blocks needed by multi-
253 /// case switch statements.
255 CaseBlock(ISD::CondCode cc, Value *cmplhs, Value *cmprhs, Value *cmpmiddle,
256 MachineBasicBlock *truebb, MachineBasicBlock *falsebb,
257 MachineBasicBlock *me)
258 : CC(cc), CmpLHS(cmplhs), CmpMHS(cmpmiddle), CmpRHS(cmprhs),
259 TrueBB(truebb), FalseBB(falsebb), ThisBB(me) {}
260 // CC - the condition code to use for the case block's setcc node
262 // CmpLHS/CmpRHS/CmpMHS - The LHS/MHS/RHS of the comparison to emit.
263 // Emit by default LHS op RHS. MHS is used for range comparisons:
264 // If MHS is not null: (LHS <= MHS) and (MHS <= RHS).
265 Value *CmpLHS, *CmpMHS, *CmpRHS;
266 // TrueBB/FalseBB - the block to branch to if the setcc is true/false.
267 MachineBasicBlock *TrueBB, *FalseBB;
268 // ThisBB - the block into which to emit the code for the setcc and branches
269 MachineBasicBlock *ThisBB;
272 JumpTable(unsigned R, unsigned J, MachineBasicBlock *M,
273 MachineBasicBlock *D): Reg(R), JTI(J), MBB(M), Default(D) {}
275 /// Reg - the virtual register containing the index of the jump table entry
278 /// JTI - the JumpTableIndex for this jump table in the function.
280 /// MBB - the MBB into which to emit the code for the indirect jump.
281 MachineBasicBlock *MBB;
282 /// Default - the MBB of the default bb, which is a successor of the range
283 /// check MBB. This is when updating PHI nodes in successors.
284 MachineBasicBlock *Default;
286 struct JumpTableHeader {
287 JumpTableHeader(uint64_t F, uint64_t L, Value* SV, MachineBasicBlock* H,
289 First(F), Last(L), SValue(SV), HeaderBB(H), Emitted(E) {}
293 MachineBasicBlock *HeaderBB;
296 typedef std::pair<JumpTableHeader, JumpTable> JumpTableBlock;
299 BitTestCase(uint64_t M, MachineBasicBlock* T, MachineBasicBlock* Tr):
300 Mask(M), ThisBB(T), TargetBB(Tr) { }
302 MachineBasicBlock* ThisBB;
303 MachineBasicBlock* TargetBB;
306 typedef SmallVector<BitTestCase, 3> BitTestInfo;
308 struct BitTestBlock {
309 BitTestBlock(uint64_t F, uint64_t R, Value* SV,
311 MachineBasicBlock* P, MachineBasicBlock* D,
312 const BitTestInfo& C):
313 First(F), Range(R), SValue(SV), Reg(Rg), Emitted(E),
314 Parent(P), Default(D), Cases(C) { }
320 MachineBasicBlock *Parent;
321 MachineBasicBlock *Default;
326 // TLI - This is information that describes the available target features we
327 // need for lowering. This indicates when operations are unavailable,
328 // implemented with a libcall, etc.
331 const TargetData *TD;
334 /// SwitchCases - Vector of CaseBlock structures used to communicate
335 /// SwitchInst code generation information.
336 std::vector<CaseBlock> SwitchCases;
337 /// JTCases - Vector of JumpTable structures used to communicate
338 /// SwitchInst code generation information.
339 std::vector<JumpTableBlock> JTCases;
340 /// BitTestCases - Vector of BitTestBlock structures used to communicate
341 /// SwitchInst code generation information.
342 std::vector<BitTestBlock> BitTestCases;
344 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
346 // Emit PHI-node-operand constants only once even if used by multiple
348 DenseMap<Constant*, unsigned> ConstantsOut;
350 /// FuncInfo - Information about the function as a whole.
352 FunctionLoweringInfo &FuncInfo;
354 /// GFI - Garbage collection metadata for the function.
357 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
358 FunctionLoweringInfo &funcinfo)
359 : TLI(tli), DAG(dag), FuncInfo(funcinfo) {
362 void init(GCFunctionInfo *gfi, AliasAnalysis &aa);
364 /// clear - Clear out the curret SelectionDAG and the associated
365 /// state and prepare this SelectionDAGLowering object to be used
366 /// for a new block. This doesn't clear out information about
367 /// additional blocks that are needed to complete switch lowering
368 /// or PHI node updating; that information is cleared out as it is
372 /// getRoot - Return the current virtual root of the Selection DAG,
373 /// flushing any PendingLoad items. This must be done before emitting
374 /// a store or any other node that may need to be ordered after any
375 /// prior load instructions.
379 /// getControlRoot - Similar to getRoot, but instead of flushing all the
380 /// PendingLoad items, flush all the PendingExports items. It is necessary
381 /// to do this before emitting a terminator instruction.
383 SDValue getControlRoot();
385 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
387 void visit(Instruction &I);
389 void visit(unsigned Opcode, User &I);
391 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
393 SDValue getValue(const Value *V);
395 void setValue(const Value *V, SDValue NewN) {
396 SDValue &N = NodeMap[V];
397 assert(N.getNode() == 0 && "Already set a value for this node!");
401 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
402 std::set<unsigned> &OutputRegs,
403 std::set<unsigned> &InputRegs);
405 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
406 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
408 bool ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases);
409 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
410 void ExportFromCurrentBlock(Value *V);
411 void LowerCallTo(CallSite CS, SDValue Callee, bool IsTailCall,
412 MachineBasicBlock *LandingPad = NULL);
415 // Terminator instructions.
416 void visitRet(ReturnInst &I);
417 void visitBr(BranchInst &I);
418 void visitSwitch(SwitchInst &I);
419 void visitUnreachable(UnreachableInst &I) { /* noop */ }
421 // Helpers for visitSwitch
422 bool handleSmallSwitchRange(CaseRec& CR,
423 CaseRecVector& WorkList,
425 MachineBasicBlock* Default);
426 bool handleJTSwitchCase(CaseRec& CR,
427 CaseRecVector& WorkList,
429 MachineBasicBlock* Default);
430 bool handleBTSplitSwitchCase(CaseRec& CR,
431 CaseRecVector& WorkList,
433 MachineBasicBlock* Default);
434 bool handleBitTestsSwitchCase(CaseRec& CR,
435 CaseRecVector& WorkList,
437 MachineBasicBlock* Default);
439 void visitSwitchCase(CaseBlock &CB);
440 void visitBitTestHeader(BitTestBlock &B);
441 void visitBitTestCase(MachineBasicBlock* NextMBB,
444 void visitJumpTable(JumpTable &JT);
445 void visitJumpTableHeader(JumpTable &JT, JumpTableHeader &JTH);
448 // These all get lowered before this pass.
449 void visitInvoke(InvokeInst &I);
450 void visitUnwind(UnwindInst &I);
452 void visitBinary(User &I, unsigned OpCode);
453 void visitShift(User &I, unsigned Opcode);
454 void visitAdd(User &I);
455 void visitSub(User &I);
456 void visitMul(User &I);
457 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
458 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
459 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
460 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
461 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
462 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
463 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
464 void visitOr (User &I) { visitBinary(I, ISD::OR); }
465 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
466 void visitShl (User &I) { visitShift(I, ISD::SHL); }
467 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
468 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
469 void visitICmp(User &I);
470 void visitFCmp(User &I);
471 void visitVICmp(User &I);
472 void visitVFCmp(User &I);
473 // Visit the conversion instructions
474 void visitTrunc(User &I);
475 void visitZExt(User &I);
476 void visitSExt(User &I);
477 void visitFPTrunc(User &I);
478 void visitFPExt(User &I);
479 void visitFPToUI(User &I);
480 void visitFPToSI(User &I);
481 void visitUIToFP(User &I);
482 void visitSIToFP(User &I);
483 void visitPtrToInt(User &I);
484 void visitIntToPtr(User &I);
485 void visitBitCast(User &I);
487 void visitExtractElement(User &I);
488 void visitInsertElement(User &I);
489 void visitShuffleVector(User &I);
491 void visitExtractValue(ExtractValueInst &I);
492 void visitInsertValue(InsertValueInst &I);
494 void visitGetElementPtr(User &I);
495 void visitSelect(User &I);
497 void visitMalloc(MallocInst &I);
498 void visitFree(FreeInst &I);
499 void visitAlloca(AllocaInst &I);
500 void visitLoad(LoadInst &I);
501 void visitStore(StoreInst &I);
502 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
503 void visitCall(CallInst &I);
504 void visitInlineAsm(CallSite CS);
505 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
506 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
508 void visitPow(CallInst &I);
509 void visitExp2(CallInst &I);
510 void visitExp(CallInst &I);
511 void visitLog(CallInst &I);
512 void visitLog2(CallInst &I);
513 void visitLog10(CallInst &I);
515 void visitVAStart(CallInst &I);
516 void visitVAArg(VAArgInst &I);
517 void visitVAEnd(CallInst &I);
518 void visitVACopy(CallInst &I);
520 void visitUserOp1(Instruction &I) {
521 assert(0 && "UserOp1 should not exist at instruction selection time!");
524 void visitUserOp2(Instruction &I) {
525 assert(0 && "UserOp2 should not exist at instruction selection time!");
529 const char *implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op);
532 /// AddCatchInfo - Extract the personality and type infos from an eh.selector
533 /// call, and add them to the specified machine basic block.
534 void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
535 MachineBasicBlock *MBB);
537 } // end namespace llvm