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;
78 //===----------------------------------------------------------------------===//
79 /// SelectionDAGBuilder - This is the common target-independent lowering
80 /// implementation that is parameterized by a TargetLowering object.
82 class SelectionDAGBuilder {
83 /// CurDebugLoc - current file + line number. Changes as we build the DAG.
86 DenseMap<const Value*, SDValue> NodeMap;
88 /// UnusedArgNodeMap - Maps argument value for unused arguments. This is used
89 /// to preserve debug information for incoming arguments.
90 DenseMap<const Value*, SDValue> UnusedArgNodeMap;
92 /// DanglingDebugInfo - Helper type for DanglingDebugInfoMap.
93 class DanglingDebugInfo {
94 const DbgValueInst* DI;
98 DanglingDebugInfo() : DI(0), dl(DebugLoc()), SDNodeOrder(0) { }
99 DanglingDebugInfo(const DbgValueInst *di, DebugLoc DL, unsigned SDNO) :
100 DI(di), dl(DL), SDNodeOrder(SDNO) { }
101 const DbgValueInst* getDI() { return DI; }
102 DebugLoc getdl() { return dl; }
103 unsigned getSDNodeOrder() { return SDNodeOrder; }
106 /// DanglingDebugInfoMap - Keeps track of dbg_values for which we have not
107 /// yet seen the referent. We defer handling these until we do see it.
108 DenseMap<const Value*, DanglingDebugInfo> DanglingDebugInfoMap;
111 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
112 /// them up and then emit token factor nodes when possible. This allows us to
113 /// get simple disambiguation between loads without worrying about alias
115 SmallVector<SDValue, 8> PendingLoads;
118 /// PendingExports - CopyToReg nodes that copy values to virtual registers
119 /// for export to other blocks need to be emitted before any terminator
120 /// instruction, but they have no other ordering requirements. We bunch them
121 /// up and the emit a single tokenfactor for them just before terminator
123 SmallVector<SDValue, 8> PendingExports;
125 /// SDNodeOrder - A unique monotonically increasing number used to order the
126 /// SDNodes we create.
127 unsigned SDNodeOrder;
129 /// Case - A struct to record the Value for a switch case, and the
130 /// case's target basic block.
133 const Constant *High;
134 MachineBasicBlock* BB;
135 uint32_t ExtraWeight;
137 Case() : Low(0), High(0), BB(0), ExtraWeight(0) { }
138 Case(const Constant *low, const Constant *high, MachineBasicBlock *bb,
139 uint32_t extraweight) : Low(low), High(high), BB(bb),
140 ExtraWeight(extraweight) { }
143 const APInt &rHigh = cast<ConstantInt>(High)->getValue();
144 const APInt &rLow = cast<ConstantInt>(Low)->getValue();
145 return (rHigh - rLow + 1ULL);
151 MachineBasicBlock* BB;
154 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
155 Mask(mask), BB(bb), Bits(bits) { }
158 typedef std::vector<Case> CaseVector;
159 typedef std::vector<CaseBits> CaseBitsVector;
160 typedef CaseVector::iterator CaseItr;
161 typedef std::pair<CaseItr, CaseItr> CaseRange;
163 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
164 /// of conditional branches.
166 CaseRec(MachineBasicBlock *bb, const Constant *lt, const Constant *ge,
168 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
170 /// CaseBB - The MBB in which to emit the compare and branch
171 MachineBasicBlock *CaseBB;
172 /// LT, GE - If nonzero, we know the current case value must be less-than or
173 /// greater-than-or-equal-to these Constants.
176 /// Range - A pair of iterators representing the range of case values to be
177 /// processed at this point in the binary search tree.
181 typedef std::vector<CaseRec> CaseRecVector;
183 /// The comparison function for sorting the switch case values in the vector.
184 /// WARNING: Case ranges should be disjoint!
186 bool operator()(const Case &C1, const Case &C2) {
187 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
188 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
189 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
190 return CI1->getValue().slt(CI2->getValue());
195 bool operator()(const CaseBits &C1, const CaseBits &C2) {
196 return C1.Bits > C2.Bits;
200 size_t Clusterify(CaseVector &Cases, const SwitchInst &SI);
202 /// CaseBlock - This structure is used to communicate between
203 /// SelectionDAGBuilder and SDISel for the code generation of additional basic
204 /// blocks needed by multi-case switch statements.
206 CaseBlock(ISD::CondCode cc, const Value *cmplhs, const Value *cmprhs,
207 const Value *cmpmiddle,
208 MachineBasicBlock *truebb, MachineBasicBlock *falsebb,
209 MachineBasicBlock *me,
210 uint32_t trueweight = 0, uint32_t falseweight = 0)
211 : CC(cc), CmpLHS(cmplhs), CmpMHS(cmpmiddle), CmpRHS(cmprhs),
212 TrueBB(truebb), FalseBB(falsebb), ThisBB(me),
213 TrueWeight(trueweight), FalseWeight(falseweight) { }
215 // CC - the condition code to use for the case block's setcc node
218 // CmpLHS/CmpRHS/CmpMHS - The LHS/MHS/RHS of the comparison to emit.
219 // Emit by default LHS op RHS. MHS is used for range comparisons:
220 // If MHS is not null: (LHS <= MHS) and (MHS <= RHS).
221 const Value *CmpLHS, *CmpMHS, *CmpRHS;
223 // TrueBB/FalseBB - the block to branch to if the setcc is true/false.
224 MachineBasicBlock *TrueBB, *FalseBB;
226 // ThisBB - the block into which to emit the code for the setcc and branches
227 MachineBasicBlock *ThisBB;
229 // TrueWeight/FalseWeight - branch weights.
230 uint32_t TrueWeight, FalseWeight;
234 JumpTable(unsigned R, unsigned J, MachineBasicBlock *M,
235 MachineBasicBlock *D): Reg(R), JTI(J), MBB(M), Default(D) {}
237 /// Reg - the virtual register containing the index of the jump table entry
240 /// JTI - the JumpTableIndex for this jump table in the function.
242 /// MBB - the MBB into which to emit the code for the indirect jump.
243 MachineBasicBlock *MBB;
244 /// Default - the MBB of the default bb, which is a successor of the range
245 /// check MBB. This is when updating PHI nodes in successors.
246 MachineBasicBlock *Default;
248 struct JumpTableHeader {
249 JumpTableHeader(APInt F, APInt L, const Value *SV, MachineBasicBlock *H,
251 First(F), Last(L), SValue(SV), HeaderBB(H), Emitted(E) {}
255 MachineBasicBlock *HeaderBB;
258 typedef std::pair<JumpTableHeader, JumpTable> JumpTableBlock;
261 BitTestCase(uint64_t M, MachineBasicBlock* T, MachineBasicBlock* Tr):
262 Mask(M), ThisBB(T), TargetBB(Tr) { }
264 MachineBasicBlock *ThisBB;
265 MachineBasicBlock *TargetBB;
268 typedef SmallVector<BitTestCase, 3> BitTestInfo;
270 struct BitTestBlock {
271 BitTestBlock(APInt F, APInt R, const Value* SV,
272 unsigned Rg, EVT RgVT, bool E,
273 MachineBasicBlock* P, MachineBasicBlock* D,
274 const BitTestInfo& C):
275 First(F), Range(R), SValue(SV), Reg(Rg), RegVT(RgVT), Emitted(E),
276 Parent(P), Default(D), Cases(C) { }
283 MachineBasicBlock *Parent;
284 MachineBasicBlock *Default;
289 // TLI - This is information that describes the available target features we
290 // need for lowering. This indicates when operations are unavailable,
291 // implemented with a libcall, etc.
292 const TargetMachine &TM;
293 const TargetLowering &TLI;
295 const TargetData *TD;
297 const TargetLibraryInfo *LibInfo;
299 /// SwitchCases - Vector of CaseBlock structures used to communicate
300 /// SwitchInst code generation information.
301 std::vector<CaseBlock> SwitchCases;
302 /// JTCases - Vector of JumpTable structures used to communicate
303 /// SwitchInst code generation information.
304 std::vector<JumpTableBlock> JTCases;
305 /// BitTestCases - Vector of BitTestBlock structures used to communicate
306 /// SwitchInst code generation information.
307 std::vector<BitTestBlock> BitTestCases;
309 // Emit PHI-node-operand constants only once even if used by multiple
311 DenseMap<const Constant *, unsigned> ConstantsOut;
313 /// FuncInfo - Information about the function as a whole.
315 FunctionLoweringInfo &FuncInfo;
317 /// OptLevel - What optimization level we're generating code for.
319 CodeGenOpt::Level OptLevel;
321 /// GFI - Garbage collection metadata for the function.
324 /// LPadToCallSiteMap - Map a landing pad to the call site indexes.
325 DenseMap<MachineBasicBlock*, SmallVector<unsigned, 4> > LPadToCallSiteMap;
327 /// HasTailCall - This is set to true if a call in the current
328 /// block has been translated as a tail call. In this case,
329 /// no subsequent DAG nodes should be created.
333 LLVMContext *Context;
335 SelectionDAGBuilder(SelectionDAG &dag, FunctionLoweringInfo &funcinfo,
336 CodeGenOpt::Level ol)
337 : SDNodeOrder(0), TM(dag.getTarget()), TLI(dag.getTargetLoweringInfo()),
338 DAG(dag), FuncInfo(funcinfo), OptLevel(ol),
339 HasTailCall(false), Context(dag.getContext()) {
342 void init(GCFunctionInfo *gfi, AliasAnalysis &aa,
343 const TargetLibraryInfo *li);
345 /// clear - Clear out the current SelectionDAG and the associated
346 /// state and prepare this SelectionDAGBuilder object to be used
347 /// for a new block. This doesn't clear out information about
348 /// additional blocks that are needed to complete switch lowering
349 /// or PHI node updating; that information is cleared out as it is
353 /// clearDanglingDebugInfo - Clear the dangling debug information
354 /// map. This function is seperated from the clear so that debug
355 /// information that is dangling in a basic block can be properly
356 /// resolved in a different basic block. This allows the
357 /// SelectionDAG to resolve dangling debug information attached
359 void clearDanglingDebugInfo();
361 /// getRoot - Return the current virtual root of the Selection DAG,
362 /// flushing any PendingLoad items. This must be done before emitting
363 /// a store or any other node that may need to be ordered after any
364 /// prior load instructions.
368 /// getControlRoot - Similar to getRoot, but instead of flushing all the
369 /// PendingLoad items, flush all the PendingExports items. It is necessary
370 /// to do this before emitting a terminator instruction.
372 SDValue getControlRoot();
374 DebugLoc getCurDebugLoc() const { return CurDebugLoc; }
376 unsigned getSDNodeOrder() const { return SDNodeOrder; }
378 void CopyValueToVirtualRegister(const Value *V, unsigned Reg);
380 /// AssignOrderingToNode - Assign an ordering to the node. The order is gotten
381 /// from how the code appeared in the source. The ordering is used by the
382 /// scheduler to effectively turn off scheduling.
383 void AssignOrderingToNode(const SDNode *Node);
385 void visit(const Instruction &I);
387 void visit(unsigned Opcode, const User &I);
389 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
390 // generate the debug data structures now that we've seen its definition.
391 void resolveDanglingDebugInfo(const Value *V, SDValue Val);
392 SDValue getValue(const Value *V);
393 SDValue getNonRegisterValue(const Value *V);
394 SDValue getValueImpl(const Value *V);
396 void setValue(const Value *V, SDValue NewN) {
397 SDValue &N = NodeMap[V];
398 assert(N.getNode() == 0 && "Already set a value for this node!");
402 void setUnusedArgValue(const Value *V, SDValue NewN) {
403 SDValue &N = UnusedArgNodeMap[V];
404 assert(N.getNode() == 0 && "Already set a value for this node!");
408 void FindMergedConditions(const Value *Cond, MachineBasicBlock *TBB,
409 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
410 MachineBasicBlock *SwitchBB, unsigned Opc);
411 void EmitBranchForMergedCondition(const Value *Cond, MachineBasicBlock *TBB,
412 MachineBasicBlock *FBB,
413 MachineBasicBlock *CurBB,
414 MachineBasicBlock *SwitchBB);
415 bool ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases);
416 bool isExportableFromCurrentBlock(const Value *V, const BasicBlock *FromBB);
417 void CopyToExportRegsIfNeeded(const Value *V);
418 void ExportFromCurrentBlock(const Value *V);
419 void LowerCallTo(ImmutableCallSite CS, SDValue Callee, bool IsTailCall,
420 MachineBasicBlock *LandingPad = NULL);
422 /// UpdateSplitBlock - When an MBB was split during scheduling, update the
423 /// references that ned to refer to the last resulting block.
424 void UpdateSplitBlock(MachineBasicBlock *First, MachineBasicBlock *Last);
427 // Terminator instructions.
428 void visitRet(const ReturnInst &I);
429 void visitBr(const BranchInst &I);
430 void visitSwitch(const SwitchInst &I);
431 void visitIndirectBr(const IndirectBrInst &I);
432 void visitUnreachable(const UnreachableInst &I) { /* noop */ }
434 // Helpers for visitSwitch
435 bool handleSmallSwitchRange(CaseRec& CR,
436 CaseRecVector& WorkList,
438 MachineBasicBlock* Default,
439 MachineBasicBlock *SwitchBB);
440 bool handleJTSwitchCase(CaseRec& CR,
441 CaseRecVector& WorkList,
443 MachineBasicBlock* Default,
444 MachineBasicBlock *SwitchBB);
445 bool handleBTSplitSwitchCase(CaseRec& CR,
446 CaseRecVector& WorkList,
448 MachineBasicBlock* Default,
449 MachineBasicBlock *SwitchBB);
450 bool handleBitTestsSwitchCase(CaseRec& CR,
451 CaseRecVector& WorkList,
453 MachineBasicBlock* Default,
454 MachineBasicBlock *SwitchBB);
456 uint32_t getEdgeWeight(const MachineBasicBlock *Src,
457 const MachineBasicBlock *Dst) const;
458 void addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst,
459 uint32_t Weight = 0);
461 void visitSwitchCase(CaseBlock &CB,
462 MachineBasicBlock *SwitchBB);
463 void visitBitTestHeader(BitTestBlock &B, MachineBasicBlock *SwitchBB);
464 void visitBitTestCase(BitTestBlock &BB,
465 MachineBasicBlock* NextMBB,
468 MachineBasicBlock *SwitchBB);
469 void visitJumpTable(JumpTable &JT);
470 void visitJumpTableHeader(JumpTable &JT, JumpTableHeader &JTH,
471 MachineBasicBlock *SwitchBB);
474 // These all get lowered before this pass.
475 void visitInvoke(const InvokeInst &I);
476 void visitResume(const ResumeInst &I);
478 void visitBinary(const User &I, unsigned OpCode);
479 void visitShift(const User &I, unsigned Opcode);
480 void visitAdd(const User &I) { visitBinary(I, ISD::ADD); }
481 void visitFAdd(const User &I) { visitBinary(I, ISD::FADD); }
482 void visitSub(const User &I) { visitBinary(I, ISD::SUB); }
483 void visitFSub(const User &I);
484 void visitMul(const User &I) { visitBinary(I, ISD::MUL); }
485 void visitFMul(const User &I) { visitBinary(I, ISD::FMUL); }
486 void visitURem(const User &I) { visitBinary(I, ISD::UREM); }
487 void visitSRem(const User &I) { visitBinary(I, ISD::SREM); }
488 void visitFRem(const User &I) { visitBinary(I, ISD::FREM); }
489 void visitUDiv(const User &I) { visitBinary(I, ISD::UDIV); }
490 void visitSDiv(const User &I);
491 void visitFDiv(const User &I) { visitBinary(I, ISD::FDIV); }
492 void visitAnd (const User &I) { visitBinary(I, ISD::AND); }
493 void visitOr (const User &I) { visitBinary(I, ISD::OR); }
494 void visitXor (const User &I) { visitBinary(I, ISD::XOR); }
495 void visitShl (const User &I) { visitShift(I, ISD::SHL); }
496 void visitLShr(const User &I) { visitShift(I, ISD::SRL); }
497 void visitAShr(const User &I) { visitShift(I, ISD::SRA); }
498 void visitICmp(const User &I);
499 void visitFCmp(const User &I);
500 // Visit the conversion instructions
501 void visitTrunc(const User &I);
502 void visitZExt(const User &I);
503 void visitSExt(const User &I);
504 void visitFPTrunc(const User &I);
505 void visitFPExt(const User &I);
506 void visitFPToUI(const User &I);
507 void visitFPToSI(const User &I);
508 void visitUIToFP(const User &I);
509 void visitSIToFP(const User &I);
510 void visitPtrToInt(const User &I);
511 void visitIntToPtr(const User &I);
512 void visitBitCast(const User &I);
514 void visitExtractElement(const User &I);
515 void visitInsertElement(const User &I);
516 void visitShuffleVector(const User &I);
518 void visitExtractValue(const ExtractValueInst &I);
519 void visitInsertValue(const InsertValueInst &I);
520 void visitLandingPad(const LandingPadInst &I);
522 void visitGetElementPtr(const User &I);
523 void visitSelect(const User &I);
525 void visitAlloca(const AllocaInst &I);
526 void visitLoad(const LoadInst &I);
527 void visitStore(const StoreInst &I);
528 void visitAtomicCmpXchg(const AtomicCmpXchgInst &I);
529 void visitAtomicRMW(const AtomicRMWInst &I);
530 void visitFence(const FenceInst &I);
531 void visitPHI(const PHINode &I);
532 void visitCall(const CallInst &I);
533 bool visitMemCmpCall(const CallInst &I);
534 void visitAtomicLoad(const LoadInst &I);
535 void visitAtomicStore(const StoreInst &I);
537 void visitInlineAsm(ImmutableCallSite CS);
538 const char *visitIntrinsicCall(const CallInst &I, unsigned Intrinsic);
539 void visitTargetIntrinsic(const CallInst &I, unsigned Intrinsic);
541 void visitPow(const CallInst &I);
542 void visitExp2(const CallInst &I);
543 void visitExp(const CallInst &I);
544 void visitLog(const CallInst &I);
545 void visitLog2(const CallInst &I);
546 void visitLog10(const CallInst &I);
548 void visitVAStart(const CallInst &I);
549 void visitVAArg(const VAArgInst &I);
550 void visitVAEnd(const CallInst &I);
551 void visitVACopy(const CallInst &I);
553 void visitUserOp1(const Instruction &I) {
554 llvm_unreachable("UserOp1 should not exist at instruction selection time!");
556 void visitUserOp2(const Instruction &I) {
557 llvm_unreachable("UserOp2 should not exist at instruction selection time!");
560 const char *implVisitAluOverflow(const CallInst &I, ISD::NodeType Op);
562 void HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB);
564 /// EmitFuncArgumentDbgValue - If V is an function argument then create
565 /// corresponding DBG_VALUE machine instruction for it now. At the end of
566 /// instruction selection, they will be inserted to the entry BB.
567 bool EmitFuncArgumentDbgValue(const Value *V, MDNode *Variable,
568 int64_t Offset, const SDValue &N);
571 } // end namespace llvm