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"
21 #include "llvm/CodeGen/SelectionDAGNodes.h"
22 #include "llvm/CodeGen/ValueTypes.h"
23 #include "llvm/Support/CallSite.h"
24 #include "llvm/Support/ErrorHandling.h"
36 class ExtractElementInst;
37 class ExtractValueInst;
44 class FunctionLoweringInfo;
45 class GetElementPtrInst;
51 class InsertElementInst;
52 class InsertValueInst;
55 class MachineBasicBlock;
57 class MachineRegisterInfo;
65 class ShuffleVectorInst;
70 class TargetLibraryInfo;
74 class UnreachableInst;
79 //===----------------------------------------------------------------------===//
80 /// SelectionDAGBuilder - This is the common target-independent lowering
81 /// implementation that is parameterized by a TargetLowering object.
83 class SelectionDAGBuilder {
84 /// CurDebugLoc - current file + line number. Changes as we build the DAG.
87 DenseMap<const Value*, SDValue> NodeMap;
89 /// UnusedArgNodeMap - Maps argument value for unused arguments. This is used
90 /// to preserve debug information for incoming arguments.
91 DenseMap<const Value*, SDValue> UnusedArgNodeMap;
93 /// DanglingDebugInfo - Helper type for DanglingDebugInfoMap.
94 class DanglingDebugInfo {
95 const DbgValueInst* DI;
99 DanglingDebugInfo() : DI(0), dl(DebugLoc()), SDNodeOrder(0) { }
100 DanglingDebugInfo(const DbgValueInst *di, DebugLoc DL, unsigned SDNO) :
101 DI(di), dl(DL), SDNodeOrder(SDNO) { }
102 const DbgValueInst* getDI() { return DI; }
103 DebugLoc getdl() { return dl; }
104 unsigned getSDNodeOrder() { return SDNodeOrder; }
107 /// DanglingDebugInfoMap - Keeps track of dbg_values for which we have not
108 /// yet seen the referent. We defer handling these until we do see it.
109 DenseMap<const Value*, DanglingDebugInfo> DanglingDebugInfoMap;
112 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
113 /// them up and then emit token factor nodes when possible. This allows us to
114 /// get simple disambiguation between loads without worrying about alias
116 SmallVector<SDValue, 8> PendingLoads;
119 /// PendingExports - CopyToReg nodes that copy values to virtual registers
120 /// for export to other blocks need to be emitted before any terminator
121 /// instruction, but they have no other ordering requirements. We bunch them
122 /// up and the emit a single tokenfactor for them just before terminator
124 SmallVector<SDValue, 8> PendingExports;
126 /// SDNodeOrder - A unique monotonically increasing number used to order the
127 /// SDNodes we create.
128 unsigned SDNodeOrder;
130 /// Case - A struct to record the Value for a switch case, and the
131 /// case's target basic block.
135 MachineBasicBlock* BB;
136 uint32_t ExtraWeight;
138 Case() : Low(0), High(0), BB(0), ExtraWeight(0) { }
139 Case(Constant* low, Constant* high, MachineBasicBlock* bb,
140 uint32_t extraweight) : Low(low), High(high), BB(bb),
141 ExtraWeight(extraweight) { }
144 const APInt &rHigh = cast<ConstantInt>(High)->getValue();
145 const APInt &rLow = cast<ConstantInt>(Low)->getValue();
146 return (rHigh - rLow + 1ULL);
152 MachineBasicBlock* BB;
155 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
156 Mask(mask), BB(bb), Bits(bits) { }
159 typedef std::vector<Case> CaseVector;
160 typedef std::vector<CaseBits> CaseBitsVector;
161 typedef CaseVector::iterator CaseItr;
162 typedef std::pair<CaseItr, CaseItr> CaseRange;
164 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
165 /// of conditional branches.
167 CaseRec(MachineBasicBlock *bb, const Constant *lt, const Constant *ge,
169 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
171 /// CaseBB - The MBB in which to emit the compare and branch
172 MachineBasicBlock *CaseBB;
173 /// LT, GE - If nonzero, we know the current case value must be less-than or
174 /// greater-than-or-equal-to these Constants.
177 /// Range - A pair of iterators representing the range of case values to be
178 /// processed at this point in the binary search tree.
182 typedef std::vector<CaseRec> CaseRecVector;
184 /// The comparison function for sorting the switch case values in the vector.
185 /// WARNING: Case ranges should be disjoint!
187 bool operator()(const Case &C1, const Case &C2) {
188 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
189 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
190 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
191 return CI1->getValue().slt(CI2->getValue());
196 bool operator()(const CaseBits &C1, const CaseBits &C2) {
197 return C1.Bits > C2.Bits;
201 size_t Clusterify(CaseVector &Cases, const SwitchInst &SI);
203 /// CaseBlock - This structure is used to communicate between
204 /// SelectionDAGBuilder and SDISel for the code generation of additional basic
205 /// blocks needed by multi-case switch statements.
207 CaseBlock(ISD::CondCode cc, const Value *cmplhs, const Value *cmprhs,
208 const Value *cmpmiddle,
209 MachineBasicBlock *truebb, MachineBasicBlock *falsebb,
210 MachineBasicBlock *me,
211 uint32_t trueweight = 0, uint32_t falseweight = 0)
212 : CC(cc), CmpLHS(cmplhs), CmpMHS(cmpmiddle), CmpRHS(cmprhs),
213 TrueBB(truebb), FalseBB(falsebb), ThisBB(me),
214 TrueWeight(trueweight), FalseWeight(falseweight) { }
216 // CC - the condition code to use for the case block's setcc node
219 // CmpLHS/CmpRHS/CmpMHS - The LHS/MHS/RHS of the comparison to emit.
220 // Emit by default LHS op RHS. MHS is used for range comparisons:
221 // If MHS is not null: (LHS <= MHS) and (MHS <= RHS).
222 const Value *CmpLHS, *CmpMHS, *CmpRHS;
224 // TrueBB/FalseBB - the block to branch to if the setcc is true/false.
225 MachineBasicBlock *TrueBB, *FalseBB;
227 // ThisBB - the block into which to emit the code for the setcc and branches
228 MachineBasicBlock *ThisBB;
230 // TrueWeight/FalseWeight - branch weights.
231 uint32_t TrueWeight, FalseWeight;
235 JumpTable(unsigned R, unsigned J, MachineBasicBlock *M,
236 MachineBasicBlock *D): Reg(R), JTI(J), MBB(M), Default(D) {}
238 /// Reg - the virtual register containing the index of the jump table entry
241 /// JTI - the JumpTableIndex for this jump table in the function.
243 /// MBB - the MBB into which to emit the code for the indirect jump.
244 MachineBasicBlock *MBB;
245 /// Default - the MBB of the default bb, which is a successor of the range
246 /// check MBB. This is when updating PHI nodes in successors.
247 MachineBasicBlock *Default;
249 struct JumpTableHeader {
250 JumpTableHeader(APInt F, APInt L, const Value *SV, MachineBasicBlock *H,
252 First(F), Last(L), SValue(SV), HeaderBB(H), Emitted(E) {}
256 MachineBasicBlock *HeaderBB;
259 typedef std::pair<JumpTableHeader, JumpTable> JumpTableBlock;
262 BitTestCase(uint64_t M, MachineBasicBlock* T, MachineBasicBlock* Tr):
263 Mask(M), ThisBB(T), TargetBB(Tr) { }
265 MachineBasicBlock *ThisBB;
266 MachineBasicBlock *TargetBB;
269 typedef SmallVector<BitTestCase, 3> BitTestInfo;
271 struct BitTestBlock {
272 BitTestBlock(APInt F, APInt R, const Value* SV,
273 unsigned Rg, EVT RgVT, bool E,
274 MachineBasicBlock* P, MachineBasicBlock* D,
275 const BitTestInfo& C):
276 First(F), Range(R), SValue(SV), Reg(Rg), RegVT(RgVT), Emitted(E),
277 Parent(P), Default(D), Cases(C) { }
284 MachineBasicBlock *Parent;
285 MachineBasicBlock *Default;
290 // TLI - This is information that describes the available target features we
291 // need for lowering. This indicates when operations are unavailable,
292 // implemented with a libcall, etc.
293 const TargetMachine &TM;
294 const TargetLowering &TLI;
296 const TargetData *TD;
298 const TargetLibraryInfo *LibInfo;
300 /// SwitchCases - Vector of CaseBlock structures used to communicate
301 /// SwitchInst code generation information.
302 std::vector<CaseBlock> SwitchCases;
303 /// JTCases - Vector of JumpTable structures used to communicate
304 /// SwitchInst code generation information.
305 std::vector<JumpTableBlock> JTCases;
306 /// BitTestCases - Vector of BitTestBlock structures used to communicate
307 /// SwitchInst code generation information.
308 std::vector<BitTestBlock> BitTestCases;
310 // Emit PHI-node-operand constants only once even if used by multiple
312 DenseMap<const Constant *, unsigned> ConstantsOut;
314 /// FuncInfo - Information about the function as a whole.
316 FunctionLoweringInfo &FuncInfo;
318 /// OptLevel - What optimization level we're generating code for.
320 CodeGenOpt::Level OptLevel;
322 /// GFI - Garbage collection metadata for the function.
325 /// LPadToCallSiteMap - Map a landing pad to the call site indexes.
326 DenseMap<MachineBasicBlock*, SmallVector<unsigned, 4> > LPadToCallSiteMap;
328 /// HasTailCall - This is set to true if a call in the current
329 /// block has been translated as a tail call. In this case,
330 /// no subsequent DAG nodes should be created.
334 LLVMContext *Context;
336 SelectionDAGBuilder(SelectionDAG &dag, FunctionLoweringInfo &funcinfo,
337 CodeGenOpt::Level ol)
338 : SDNodeOrder(0), TM(dag.getTarget()), TLI(dag.getTargetLoweringInfo()),
339 DAG(dag), FuncInfo(funcinfo), OptLevel(ol),
340 HasTailCall(false), Context(dag.getContext()) {
343 void init(GCFunctionInfo *gfi, AliasAnalysis &aa,
344 const TargetLibraryInfo *li);
346 /// clear - Clear out the current SelectionDAG and the associated
347 /// state and prepare this SelectionDAGBuilder object to be used
348 /// for a new block. This doesn't clear out information about
349 /// additional blocks that are needed to complete switch lowering
350 /// or PHI node updating; that information is cleared out as it is
354 /// clearDanglingDebugInfo - Clear the dangling debug information
355 /// map. This function is seperated from the clear so that debug
356 /// information that is dangling in a basic block can be properly
357 /// resolved in a different basic block. This allows the
358 /// SelectionDAG to resolve dangling debug information attached
360 void clearDanglingDebugInfo();
362 /// getRoot - Return the current virtual root of the Selection DAG,
363 /// flushing any PendingLoad items. This must be done before emitting
364 /// a store or any other node that may need to be ordered after any
365 /// prior load instructions.
369 /// getControlRoot - Similar to getRoot, but instead of flushing all the
370 /// PendingLoad items, flush all the PendingExports items. It is necessary
371 /// to do this before emitting a terminator instruction.
373 SDValue getControlRoot();
375 DebugLoc getCurDebugLoc() const { return CurDebugLoc; }
377 unsigned getSDNodeOrder() const { return SDNodeOrder; }
379 void CopyValueToVirtualRegister(const Value *V, unsigned Reg);
381 /// AssignOrderingToNode - Assign an ordering to the node. The order is gotten
382 /// from how the code appeared in the source. The ordering is used by the
383 /// scheduler to effectively turn off scheduling.
384 void AssignOrderingToNode(const SDNode *Node);
386 void visit(const Instruction &I);
388 void visit(unsigned Opcode, const User &I);
390 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
391 // generate the debug data structures now that we've seen its definition.
392 void resolveDanglingDebugInfo(const Value *V, SDValue Val);
393 SDValue getValue(const Value *V);
394 SDValue getNonRegisterValue(const Value *V);
395 SDValue getValueImpl(const Value *V);
397 void setValue(const Value *V, SDValue NewN) {
398 SDValue &N = NodeMap[V];
399 assert(N.getNode() == 0 && "Already set a value for this node!");
403 void setUnusedArgValue(const Value *V, SDValue NewN) {
404 SDValue &N = UnusedArgNodeMap[V];
405 assert(N.getNode() == 0 && "Already set a value for this node!");
409 void FindMergedConditions(const Value *Cond, MachineBasicBlock *TBB,
410 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
411 MachineBasicBlock *SwitchBB, unsigned Opc);
412 void EmitBranchForMergedCondition(const Value *Cond, MachineBasicBlock *TBB,
413 MachineBasicBlock *FBB,
414 MachineBasicBlock *CurBB,
415 MachineBasicBlock *SwitchBB);
416 bool ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases);
417 bool isExportableFromCurrentBlock(const Value *V, const BasicBlock *FromBB);
418 void CopyToExportRegsIfNeeded(const Value *V);
419 void ExportFromCurrentBlock(const Value *V);
420 void LowerCallTo(ImmutableCallSite CS, SDValue Callee, bool IsTailCall,
421 MachineBasicBlock *LandingPad = NULL);
423 /// UpdateSplitBlock - When an MBB was split during scheduling, update the
424 /// references that ned to refer to the last resulting block.
425 void UpdateSplitBlock(MachineBasicBlock *First, MachineBasicBlock *Last);
428 // Terminator instructions.
429 void visitRet(const ReturnInst &I);
430 void visitBr(const BranchInst &I);
431 void visitSwitch(const SwitchInst &I);
432 void visitIndirectBr(const IndirectBrInst &I);
433 void visitUnreachable(const UnreachableInst &I) { /* noop */ }
435 // Helpers for visitSwitch
436 bool handleSmallSwitchRange(CaseRec& CR,
437 CaseRecVector& WorkList,
439 MachineBasicBlock* Default,
440 MachineBasicBlock *SwitchBB);
441 bool handleJTSwitchCase(CaseRec& CR,
442 CaseRecVector& WorkList,
444 MachineBasicBlock* Default,
445 MachineBasicBlock *SwitchBB);
446 bool handleBTSplitSwitchCase(CaseRec& CR,
447 CaseRecVector& WorkList,
449 MachineBasicBlock* Default,
450 MachineBasicBlock *SwitchBB);
451 bool handleBitTestsSwitchCase(CaseRec& CR,
452 CaseRecVector& WorkList,
454 MachineBasicBlock* Default,
455 MachineBasicBlock *SwitchBB);
457 uint32_t getEdgeWeight(const MachineBasicBlock *Src,
458 const MachineBasicBlock *Dst) const;
459 void addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst,
460 uint32_t Weight = 0);
462 void visitSwitchCase(CaseBlock &CB,
463 MachineBasicBlock *SwitchBB);
464 void visitBitTestHeader(BitTestBlock &B, MachineBasicBlock *SwitchBB);
465 void visitBitTestCase(BitTestBlock &BB,
466 MachineBasicBlock* NextMBB,
469 MachineBasicBlock *SwitchBB);
470 void visitJumpTable(JumpTable &JT);
471 void visitJumpTableHeader(JumpTable &JT, JumpTableHeader &JTH,
472 MachineBasicBlock *SwitchBB);
475 // These all get lowered before this pass.
476 void visitInvoke(const InvokeInst &I);
477 void visitResume(const ResumeInst &I);
478 void visitUnwind(const UnwindInst &I);
480 void visitBinary(const User &I, unsigned OpCode);
481 void visitShift(const User &I, unsigned Opcode);
482 void visitAdd(const User &I) { visitBinary(I, ISD::ADD); }
483 void visitFAdd(const User &I) { visitBinary(I, ISD::FADD); }
484 void visitSub(const User &I) { visitBinary(I, ISD::SUB); }
485 void visitFSub(const User &I);
486 void visitMul(const User &I) { visitBinary(I, ISD::MUL); }
487 void visitFMul(const User &I) { visitBinary(I, ISD::FMUL); }
488 void visitURem(const User &I) { visitBinary(I, ISD::UREM); }
489 void visitSRem(const User &I) { visitBinary(I, ISD::SREM); }
490 void visitFRem(const User &I) { visitBinary(I, ISD::FREM); }
491 void visitUDiv(const User &I) { visitBinary(I, ISD::UDIV); }
492 void visitSDiv(const User &I);
493 void visitFDiv(const User &I) { visitBinary(I, ISD::FDIV); }
494 void visitAnd (const User &I) { visitBinary(I, ISD::AND); }
495 void visitOr (const User &I) { visitBinary(I, ISD::OR); }
496 void visitXor (const User &I) { visitBinary(I, ISD::XOR); }
497 void visitShl (const User &I) { visitShift(I, ISD::SHL); }
498 void visitLShr(const User &I) { visitShift(I, ISD::SRL); }
499 void visitAShr(const User &I) { visitShift(I, ISD::SRA); }
500 void visitICmp(const User &I);
501 void visitFCmp(const User &I);
502 // Visit the conversion instructions
503 void visitTrunc(const User &I);
504 void visitZExt(const User &I);
505 void visitSExt(const User &I);
506 void visitFPTrunc(const User &I);
507 void visitFPExt(const User &I);
508 void visitFPToUI(const User &I);
509 void visitFPToSI(const User &I);
510 void visitUIToFP(const User &I);
511 void visitSIToFP(const User &I);
512 void visitPtrToInt(const User &I);
513 void visitIntToPtr(const User &I);
514 void visitBitCast(const User &I);
516 void visitExtractElement(const User &I);
517 void visitInsertElement(const User &I);
518 void visitShuffleVector(const User &I);
520 void visitExtractValue(const ExtractValueInst &I);
521 void visitInsertValue(const InsertValueInst &I);
522 void visitLandingPad(const LandingPadInst &I);
524 void visitGetElementPtr(const User &I);
525 void visitSelect(const User &I);
527 void visitAlloca(const AllocaInst &I);
528 void visitLoad(const LoadInst &I);
529 void visitStore(const StoreInst &I);
530 void visitAtomicCmpXchg(const AtomicCmpXchgInst &I);
531 void visitAtomicRMW(const AtomicRMWInst &I);
532 void visitFence(const FenceInst &I);
533 void visitPHI(const PHINode &I);
534 void visitCall(const CallInst &I);
535 bool visitMemCmpCall(const CallInst &I);
536 void visitAtomicLoad(const LoadInst &I);
537 void visitAtomicStore(const StoreInst &I);
539 void visitInlineAsm(ImmutableCallSite CS);
540 const char *visitIntrinsicCall(const CallInst &I, unsigned Intrinsic);
541 void visitTargetIntrinsic(const CallInst &I, unsigned Intrinsic);
543 void visitPow(const CallInst &I);
544 void visitExp2(const CallInst &I);
545 void visitExp(const CallInst &I);
546 void visitLog(const CallInst &I);
547 void visitLog2(const CallInst &I);
548 void visitLog10(const CallInst &I);
550 void visitVAStart(const CallInst &I);
551 void visitVAArg(const VAArgInst &I);
552 void visitVAEnd(const CallInst &I);
553 void visitVACopy(const CallInst &I);
555 void visitUserOp1(const Instruction &I) {
556 llvm_unreachable("UserOp1 should not exist at instruction selection time!");
558 void visitUserOp2(const Instruction &I) {
559 llvm_unreachable("UserOp2 should not exist at instruction selection time!");
562 const char *implVisitAluOverflow(const CallInst &I, ISD::NodeType Op);
564 void HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB);
566 /// EmitFuncArgumentDbgValue - If V is an function argument then create
567 /// corresponding DBG_VALUE machine instruction for it now. At the end of
568 /// instruction selection, they will be inserted to the entry BB.
569 bool EmitFuncArgumentDbgValue(const Value *V, MDNode *Variable,
570 int64_t Offset, const SDValue &N);
573 } // end namespace llvm