1 //===-- SelectionDAGBuilder.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 SELECTIONDAGBUILDER_H
15 #define SELECTIONDAGBUILDER_H
17 #include "llvm/Constants.h"
18 #include "llvm/CodeGen/SelectionDAG.h"
19 #include "llvm/ADT/APInt.h"
20 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/CodeGen/SelectionDAGNodes.h"
25 #include "llvm/CodeGen/ValueTypes.h"
26 #include "llvm/Support/CallSite.h"
27 #include "llvm/Support/ErrorHandling.h"
39 class ExtractElementInst;
40 class ExtractValueInst;
47 class FunctionLoweringInfo;
48 class GetElementPtrInst;
54 class InsertElementInst;
55 class InsertValueInst;
58 class MachineBasicBlock;
60 class MachineRegisterInfo;
64 class SDISelAsmOperandInfo;
67 class ShuffleVectorInst;
75 class UnreachableInst;
80 //===----------------------------------------------------------------------===//
81 /// SelectionDAGBuilder - This is the common target-independent lowering
82 /// implementation that is parameterized by a TargetLowering object.
84 class SelectionDAGBuilder {
85 /// CurDebugLoc - current file + line number. Changes as we build the DAG.
88 DenseMap<const Value*, SDValue> NodeMap;
91 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
92 /// them up and then emit token factor nodes when possible. This allows us to
93 /// get simple disambiguation between loads without worrying about alias
95 SmallVector<SDValue, 8> PendingLoads;
98 /// PendingExports - CopyToReg nodes that copy values to virtual registers
99 /// for export to other blocks need to be emitted before any terminator
100 /// instruction, but they have no other ordering requirements. We bunch them
101 /// up and the emit a single tokenfactor for them just before terminator
103 SmallVector<SDValue, 8> PendingExports;
105 /// SDNodeOrder - A unique monotonically increasing number used to order the
106 /// SDNodes we create.
107 unsigned SDNodeOrder;
109 /// Case - A struct to record the Value for a switch case, and the
110 /// case's target basic block.
114 MachineBasicBlock* BB;
116 Case() : Low(0), High(0), BB(0) { }
117 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
118 Low(low), High(high), BB(bb) { }
120 const APInt &rHigh = cast<ConstantInt>(High)->getValue();
121 const APInt &rLow = cast<ConstantInt>(Low)->getValue();
122 return (rHigh - rLow + 1ULL);
128 MachineBasicBlock* BB;
131 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
132 Mask(mask), BB(bb), Bits(bits) { }
135 typedef std::vector<Case> CaseVector;
136 typedef std::vector<CaseBits> CaseBitsVector;
137 typedef CaseVector::iterator CaseItr;
138 typedef std::pair<CaseItr, CaseItr> CaseRange;
140 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
141 /// of conditional branches.
143 CaseRec(MachineBasicBlock *bb, const Constant *lt, const Constant *ge,
145 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
147 /// CaseBB - The MBB in which to emit the compare and branch
148 MachineBasicBlock *CaseBB;
149 /// LT, GE - If nonzero, we know the current case value must be less-than or
150 /// greater-than-or-equal-to these Constants.
153 /// Range - A pair of iterators representing the range of case values to be
154 /// processed at this point in the binary search tree.
158 typedef std::vector<CaseRec> CaseRecVector;
160 /// The comparison function for sorting the switch case values in the vector.
161 /// WARNING: Case ranges should be disjoint!
163 bool operator()(const Case &C1, const Case &C2) {
164 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
165 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
166 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
167 return CI1->getValue().slt(CI2->getValue());
172 bool operator()(const CaseBits &C1, const CaseBits &C2) {
173 return C1.Bits > C2.Bits;
177 size_t Clusterify(CaseVector &Cases, const SwitchInst &SI);
179 /// CaseBlock - This structure is used to communicate between
180 /// SelectionDAGBuilder and SDISel for the code generation of additional basic
181 /// blocks needed by multi-case switch statements.
183 CaseBlock(ISD::CondCode cc, const Value *cmplhs, const Value *cmprhs,
184 const Value *cmpmiddle,
185 MachineBasicBlock *truebb, MachineBasicBlock *falsebb,
186 MachineBasicBlock *me)
187 : CC(cc), CmpLHS(cmplhs), CmpMHS(cmpmiddle), CmpRHS(cmprhs),
188 TrueBB(truebb), FalseBB(falsebb), ThisBB(me) {}
189 // CC - the condition code to use for the case block's setcc node
191 // CmpLHS/CmpRHS/CmpMHS - The LHS/MHS/RHS of the comparison to emit.
192 // Emit by default LHS op RHS. MHS is used for range comparisons:
193 // If MHS is not null: (LHS <= MHS) and (MHS <= RHS).
194 const Value *CmpLHS, *CmpMHS, *CmpRHS;
195 // TrueBB/FalseBB - the block to branch to if the setcc is true/false.
196 MachineBasicBlock *TrueBB, *FalseBB;
197 // ThisBB - the block into which to emit the code for the setcc and branches
198 MachineBasicBlock *ThisBB;
201 JumpTable(unsigned R, unsigned J, MachineBasicBlock *M,
202 MachineBasicBlock *D): Reg(R), JTI(J), MBB(M), Default(D) {}
204 /// Reg - the virtual register containing the index of the jump table entry
207 /// JTI - the JumpTableIndex for this jump table in the function.
209 /// MBB - the MBB into which to emit the code for the indirect jump.
210 MachineBasicBlock *MBB;
211 /// Default - the MBB of the default bb, which is a successor of the range
212 /// check MBB. This is when updating PHI nodes in successors.
213 MachineBasicBlock *Default;
215 struct JumpTableHeader {
216 JumpTableHeader(APInt F, APInt L, const Value *SV, MachineBasicBlock *H,
218 First(F), Last(L), SValue(SV), HeaderBB(H), Emitted(E) {}
222 MachineBasicBlock *HeaderBB;
225 typedef std::pair<JumpTableHeader, JumpTable> JumpTableBlock;
228 BitTestCase(uint64_t M, MachineBasicBlock* T, MachineBasicBlock* Tr):
229 Mask(M), ThisBB(T), TargetBB(Tr) { }
231 MachineBasicBlock *ThisBB;
232 MachineBasicBlock *TargetBB;
235 typedef SmallVector<BitTestCase, 3> BitTestInfo;
237 struct BitTestBlock {
238 BitTestBlock(APInt F, APInt R, const Value* SV,
240 MachineBasicBlock* P, MachineBasicBlock* D,
241 const BitTestInfo& C):
242 First(F), Range(R), SValue(SV), Reg(Rg), Emitted(E),
243 Parent(P), Default(D), Cases(C) { }
249 MachineBasicBlock *Parent;
250 MachineBasicBlock *Default;
255 // TLI - This is information that describes the available target features we
256 // need for lowering. This indicates when operations are unavailable,
257 // implemented with a libcall, etc.
258 const TargetMachine &TM;
259 const TargetLowering &TLI;
261 const TargetData *TD;
264 /// SwitchCases - Vector of CaseBlock structures used to communicate
265 /// SwitchInst code generation information.
266 std::vector<CaseBlock> SwitchCases;
267 /// JTCases - Vector of JumpTable structures used to communicate
268 /// SwitchInst code generation information.
269 std::vector<JumpTableBlock> JTCases;
270 /// BitTestCases - Vector of BitTestBlock structures used to communicate
271 /// SwitchInst code generation information.
272 std::vector<BitTestBlock> BitTestCases;
274 /// EdgeMapping - If an edge from CurMBB to any MBB is changed (e.g. due to
275 /// scheduler custom lowering), track the change here.
276 DenseMap<MachineBasicBlock*, MachineBasicBlock*> EdgeMapping;
278 // Emit PHI-node-operand constants only once even if used by multiple
280 DenseMap<const Constant *, unsigned> ConstantsOut;
282 /// FuncInfo - Information about the function as a whole.
284 FunctionLoweringInfo &FuncInfo;
286 /// OptLevel - What optimization level we're generating code for.
288 CodeGenOpt::Level OptLevel;
290 /// GFI - Garbage collection metadata for the function.
293 /// HasTailCall - This is set to true if a call in the current
294 /// block has been translated as a tail call. In this case,
295 /// no subsequent DAG nodes should be created.
299 LLVMContext *Context;
301 SelectionDAGBuilder(SelectionDAG &dag, FunctionLoweringInfo &funcinfo,
302 CodeGenOpt::Level ol)
303 : SDNodeOrder(0), TM(dag.getTarget()), TLI(dag.getTargetLoweringInfo()),
304 DAG(dag), FuncInfo(funcinfo), OptLevel(ol),
305 HasTailCall(false), Context(dag.getContext()) {
308 void init(GCFunctionInfo *gfi, AliasAnalysis &aa);
310 /// clear - Clear out the current SelectionDAG and the associated
311 /// state and prepare this SelectionDAGBuilder object to be used
312 /// for a new block. This doesn't clear out information about
313 /// additional blocks that are needed to complete switch lowering
314 /// or PHI node updating; that information is cleared out as it is
318 /// getRoot - Return the current virtual root of the Selection DAG,
319 /// flushing any PendingLoad items. This must be done before emitting
320 /// a store or any other node that may need to be ordered after any
321 /// prior load instructions.
325 /// getControlRoot - Similar to getRoot, but instead of flushing all the
326 /// PendingLoad items, flush all the PendingExports items. It is necessary
327 /// to do this before emitting a terminator instruction.
329 SDValue getControlRoot();
331 DebugLoc getCurDebugLoc() const { return CurDebugLoc; }
333 unsigned getSDNodeOrder() const { return SDNodeOrder; }
335 void CopyValueToVirtualRegister(const Value *V, unsigned Reg);
337 /// AssignOrderingToNode - Assign an ordering to the node. The order is gotten
338 /// from how the code appeared in the source. The ordering is used by the
339 /// scheduler to effectively turn off scheduling.
340 void AssignOrderingToNode(const SDNode *Node);
342 void visit(const Instruction &I);
344 void visit(unsigned Opcode, const User &I);
346 SDValue getValue(const Value *V);
348 void setValue(const Value *V, SDValue NewN) {
349 SDValue &N = NodeMap[V];
350 assert(N.getNode() == 0 && "Already set a value for this node!");
354 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
355 std::set<unsigned> &OutputRegs,
356 std::set<unsigned> &InputRegs);
358 void FindMergedConditions(const Value *Cond, MachineBasicBlock *TBB,
359 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
360 MachineBasicBlock *SwitchBB, unsigned Opc);
361 void EmitBranchForMergedCondition(const Value *Cond, MachineBasicBlock *TBB,
362 MachineBasicBlock *FBB,
363 MachineBasicBlock *CurBB,
364 MachineBasicBlock *SwitchBB);
365 bool ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases);
366 bool isExportableFromCurrentBlock(const Value *V, const BasicBlock *FromBB);
367 void CopyToExportRegsIfNeeded(const Value *V);
368 void ExportFromCurrentBlock(const Value *V);
369 void LowerCallTo(ImmutableCallSite CS, SDValue Callee, bool IsTailCall,
370 MachineBasicBlock *LandingPad = NULL);
373 // Terminator instructions.
374 void visitRet(const ReturnInst &I);
375 void visitBr(const BranchInst &I);
376 void visitSwitch(const SwitchInst &I);
377 void visitIndirectBr(const IndirectBrInst &I);
378 void visitUnreachable(const UnreachableInst &I) { /* noop */ }
380 // Helpers for visitSwitch
381 bool handleSmallSwitchRange(CaseRec& CR,
382 CaseRecVector& WorkList,
384 MachineBasicBlock* Default,
385 MachineBasicBlock *SwitchBB);
386 bool handleJTSwitchCase(CaseRec& CR,
387 CaseRecVector& WorkList,
389 MachineBasicBlock* Default,
390 MachineBasicBlock *SwitchBB);
391 bool handleBTSplitSwitchCase(CaseRec& CR,
392 CaseRecVector& WorkList,
394 MachineBasicBlock* Default,
395 MachineBasicBlock *SwitchBB);
396 bool handleBitTestsSwitchCase(CaseRec& CR,
397 CaseRecVector& WorkList,
399 MachineBasicBlock* Default,
400 MachineBasicBlock *SwitchBB);
402 void visitSwitchCase(CaseBlock &CB,
403 MachineBasicBlock *SwitchBB);
404 void visitBitTestHeader(BitTestBlock &B, MachineBasicBlock *SwitchBB);
405 void visitBitTestCase(MachineBasicBlock* NextMBB,
408 MachineBasicBlock *SwitchBB);
409 void visitJumpTable(JumpTable &JT);
410 void visitJumpTableHeader(JumpTable &JT, JumpTableHeader &JTH,
411 MachineBasicBlock *SwitchBB);
414 // These all get lowered before this pass.
415 void visitInvoke(const InvokeInst &I);
416 void visitUnwind(const UnwindInst &I);
418 void visitBinary(const User &I, unsigned OpCode);
419 void visitShift(const User &I, unsigned Opcode);
420 void visitAdd(const User &I) { visitBinary(I, ISD::ADD); }
421 void visitFAdd(const User &I) { visitBinary(I, ISD::FADD); }
422 void visitSub(const User &I) { visitBinary(I, ISD::SUB); }
423 void visitFSub(const User &I);
424 void visitMul(const User &I) { visitBinary(I, ISD::MUL); }
425 void visitFMul(const User &I) { visitBinary(I, ISD::FMUL); }
426 void visitURem(const User &I) { visitBinary(I, ISD::UREM); }
427 void visitSRem(const User &I) { visitBinary(I, ISD::SREM); }
428 void visitFRem(const User &I) { visitBinary(I, ISD::FREM); }
429 void visitUDiv(const User &I) { visitBinary(I, ISD::UDIV); }
430 void visitSDiv(const User &I) { visitBinary(I, ISD::SDIV); }
431 void visitFDiv(const User &I) { visitBinary(I, ISD::FDIV); }
432 void visitAnd (const User &I) { visitBinary(I, ISD::AND); }
433 void visitOr (const User &I) { visitBinary(I, ISD::OR); }
434 void visitXor (const User &I) { visitBinary(I, ISD::XOR); }
435 void visitShl (const User &I) { visitShift(I, ISD::SHL); }
436 void visitLShr(const User &I) { visitShift(I, ISD::SRL); }
437 void visitAShr(const User &I) { visitShift(I, ISD::SRA); }
438 void visitICmp(const User &I);
439 void visitFCmp(const User &I);
440 // Visit the conversion instructions
441 void visitTrunc(const User &I);
442 void visitZExt(const User &I);
443 void visitSExt(const User &I);
444 void visitFPTrunc(const User &I);
445 void visitFPExt(const User &I);
446 void visitFPToUI(const User &I);
447 void visitFPToSI(const User &I);
448 void visitUIToFP(const User &I);
449 void visitSIToFP(const User &I);
450 void visitPtrToInt(const User &I);
451 void visitIntToPtr(const User &I);
452 void visitBitCast(const User &I);
454 void visitExtractElement(const User &I);
455 void visitInsertElement(const User &I);
456 void visitShuffleVector(const User &I);
458 void visitExtractValue(const ExtractValueInst &I);
459 void visitInsertValue(const InsertValueInst &I);
461 void visitGetElementPtr(const User &I);
462 void visitSelect(const User &I);
464 void visitAlloca(const AllocaInst &I);
465 void visitLoad(const LoadInst &I);
466 void visitStore(const StoreInst &I);
467 void visitPHI(const PHINode &I);
468 void visitCall(const CallInst &I);
469 bool visitMemCmpCall(const CallInst &I);
471 void visitInlineAsm(ImmutableCallSite CS);
472 const char *visitIntrinsicCall(const CallInst &I, unsigned Intrinsic);
473 void visitTargetIntrinsic(const CallInst &I, unsigned Intrinsic);
475 void visitPow(const CallInst &I);
476 void visitExp2(const CallInst &I);
477 void visitExp(const CallInst &I);
478 void visitLog(const CallInst &I);
479 void visitLog2(const CallInst &I);
480 void visitLog10(const CallInst &I);
482 void visitVAStart(const CallInst &I);
483 void visitVAArg(const VAArgInst &I);
484 void visitVAEnd(const CallInst &I);
485 void visitVACopy(const CallInst &I);
487 void visitUserOp1(const Instruction &I) {
488 llvm_unreachable("UserOp1 should not exist at instruction selection time!");
490 void visitUserOp2(const Instruction &I) {
491 llvm_unreachable("UserOp2 should not exist at instruction selection time!");
494 const char *implVisitBinaryAtomic(const CallInst& I, ISD::NodeType Op);
495 const char *implVisitAluOverflow(const CallInst &I, ISD::NodeType Op);
497 void HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB);
500 } // end namespace llvm