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/SelectionDAGNodes.h"
24 #include "llvm/CodeGen/ValueTypes.h"
25 #include "llvm/Support/CallSite.h"
26 #include "llvm/Target/TargetMachine.h"
38 class ExtractElementInst;
39 class ExtractValueInst;
47 class GetElementPtrInst;
52 class InsertElementInst;
53 class InsertValueInst;
56 class MachineBasicBlock;
57 class MachineFunction;
59 class MachineModuleInfo;
60 class MachineRegisterInfo;
65 class SDISelAsmOperandInfo;
68 class ShuffleVectorInst;
76 class UnreachableInst;
81 //===--------------------------------------------------------------------===//
82 /// FunctionLoweringInfo - This contains information that is global to a
83 /// function that is used when lowering a region of the function.
85 class FunctionLoweringInfo {
90 MachineRegisterInfo *RegInfo;
92 explicit FunctionLoweringInfo(TargetLowering &TLI);
94 /// set - Initialize this FunctionLoweringInfo with the given Function
95 /// and its associated MachineFunction.
97 void set(Function &Fn, MachineFunction &MF, SelectionDAG &DAG,
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), KnownOne(1, 0), KnownZero(1, 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 /// CurDebugLoc - current file + line number. Changes as we build the DAG.
168 DebugLoc CurDebugLoc;
170 DenseMap<const Value*, SDValue> NodeMap;
172 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
173 /// them up and then emit token factor nodes when possible. This allows us to
174 /// get simple disambiguation between loads without worrying about alias
176 SmallVector<SDValue, 8> PendingLoads;
178 /// PendingExports - CopyToReg nodes that copy values to virtual registers
179 /// for export to other blocks need to be emitted before any terminator
180 /// instruction, but they have no other ordering requirements. We bunch them
181 /// up and the emit a single tokenfactor for them just before terminator
183 SmallVector<SDValue, 8> PendingExports;
185 /// Case - A struct to record the Value for a switch case, and the
186 /// case's target basic block.
190 MachineBasicBlock* BB;
192 Case() : Low(0), High(0), BB(0) { }
193 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
194 Low(low), High(high), BB(bb) { }
195 uint64_t size() const {
196 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
197 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
198 return (rHigh - rLow + 1ULL);
204 MachineBasicBlock* BB;
207 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
208 Mask(mask), BB(bb), Bits(bits) { }
211 typedef std::vector<Case> CaseVector;
212 typedef std::vector<CaseBits> CaseBitsVector;
213 typedef CaseVector::iterator CaseItr;
214 typedef std::pair<CaseItr, CaseItr> CaseRange;
216 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
217 /// of conditional branches.
219 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
220 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
222 /// CaseBB - The MBB in which to emit the compare and branch
223 MachineBasicBlock *CaseBB;
224 /// LT, GE - If nonzero, we know the current case value must be less-than or
225 /// greater-than-or-equal-to these Constants.
228 /// Range - A pair of iterators representing the range of case values to be
229 /// processed at this point in the binary search tree.
233 typedef std::vector<CaseRec> CaseRecVector;
235 /// The comparison function for sorting the switch case values in the vector.
236 /// WARNING: Case ranges should be disjoint!
238 bool operator () (const Case& C1, const Case& C2) {
239 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
240 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
241 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
242 return CI1->getValue().slt(CI2->getValue());
247 bool operator () (const CaseBits& C1, const CaseBits& C2) {
248 return C1.Bits > C2.Bits;
252 size_t Clusterify(CaseVector& Cases, const SwitchInst &SI);
254 /// CaseBlock - This structure is used to communicate between SDLowering and
255 /// SDISel for the code generation of additional basic blocks needed by multi-
256 /// case switch statements.
258 CaseBlock(ISD::CondCode cc, Value *cmplhs, Value *cmprhs, Value *cmpmiddle,
259 MachineBasicBlock *truebb, MachineBasicBlock *falsebb,
260 MachineBasicBlock *me)
261 : CC(cc), CmpLHS(cmplhs), CmpMHS(cmpmiddle), CmpRHS(cmprhs),
262 TrueBB(truebb), FalseBB(falsebb), ThisBB(me) {}
263 // CC - the condition code to use for the case block's setcc node
265 // CmpLHS/CmpRHS/CmpMHS - The LHS/MHS/RHS of the comparison to emit.
266 // Emit by default LHS op RHS. MHS is used for range comparisons:
267 // If MHS is not null: (LHS <= MHS) and (MHS <= RHS).
268 Value *CmpLHS, *CmpMHS, *CmpRHS;
269 // TrueBB/FalseBB - the block to branch to if the setcc is true/false.
270 MachineBasicBlock *TrueBB, *FalseBB;
271 // ThisBB - the block into which to emit the code for the setcc and branches
272 MachineBasicBlock *ThisBB;
275 JumpTable(unsigned R, unsigned J, MachineBasicBlock *M,
276 MachineBasicBlock *D): Reg(R), JTI(J), MBB(M), Default(D) {}
278 /// Reg - the virtual register containing the index of the jump table entry
281 /// JTI - the JumpTableIndex for this jump table in the function.
283 /// MBB - the MBB into which to emit the code for the indirect jump.
284 MachineBasicBlock *MBB;
285 /// Default - the MBB of the default bb, which is a successor of the range
286 /// check MBB. This is when updating PHI nodes in successors.
287 MachineBasicBlock *Default;
289 struct JumpTableHeader {
290 JumpTableHeader(APInt F, APInt L, Value* SV, MachineBasicBlock* H,
292 First(F), Last(L), SValue(SV), HeaderBB(H), Emitted(E) {}
296 MachineBasicBlock *HeaderBB;
299 typedef std::pair<JumpTableHeader, JumpTable> JumpTableBlock;
302 BitTestCase(uint64_t M, MachineBasicBlock* T, MachineBasicBlock* Tr):
303 Mask(M), ThisBB(T), TargetBB(Tr) { }
305 MachineBasicBlock* ThisBB;
306 MachineBasicBlock* TargetBB;
309 typedef SmallVector<BitTestCase, 3> BitTestInfo;
311 struct BitTestBlock {
312 BitTestBlock(APInt F, APInt R, Value* SV,
314 MachineBasicBlock* P, MachineBasicBlock* D,
315 const BitTestInfo& C):
316 First(F), Range(R), SValue(SV), Reg(Rg), Emitted(E),
317 Parent(P), Default(D), Cases(C) { }
323 MachineBasicBlock *Parent;
324 MachineBasicBlock *Default;
329 // TLI - This is information that describes the available target features we
330 // need for lowering. This indicates when operations are unavailable,
331 // implemented with a libcall, etc.
334 const TargetData *TD;
337 /// SwitchCases - Vector of CaseBlock structures used to communicate
338 /// SwitchInst code generation information.
339 std::vector<CaseBlock> SwitchCases;
340 /// JTCases - Vector of JumpTable structures used to communicate
341 /// SwitchInst code generation information.
342 std::vector<JumpTableBlock> JTCases;
343 /// BitTestCases - Vector of BitTestBlock structures used to communicate
344 /// SwitchInst code generation information.
345 std::vector<BitTestBlock> BitTestCases;
347 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
349 // Emit PHI-node-operand constants only once even if used by multiple
351 DenseMap<Constant*, unsigned> ConstantsOut;
353 /// FuncInfo - Information about the function as a whole.
355 FunctionLoweringInfo &FuncInfo;
357 /// OptLevel - What optimization level we're generating code for.
359 CodeGenOpt::Level OptLevel;
361 /// GFI - Garbage collection metadata for the function.
364 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
365 FunctionLoweringInfo &funcinfo,
366 CodeGenOpt::Level ol)
367 : CurDebugLoc(DebugLoc::getUnknownLoc()),
368 TLI(tli), DAG(dag), FuncInfo(funcinfo), OptLevel(ol) {
371 void init(GCFunctionInfo *gfi, AliasAnalysis &aa);
373 /// clear - Clear out the curret SelectionDAG and the associated
374 /// state and prepare this SelectionDAGLowering object to be used
375 /// for a new block. This doesn't clear out information about
376 /// additional blocks that are needed to complete switch lowering
377 /// or PHI node updating; that information is cleared out as it is
381 /// getRoot - Return the current virtual root of the Selection DAG,
382 /// flushing any PendingLoad items. This must be done before emitting
383 /// a store or any other node that may need to be ordered after any
384 /// prior load instructions.
388 /// getControlRoot - Similar to getRoot, but instead of flushing all the
389 /// PendingLoad items, flush all the PendingExports items. It is necessary
390 /// to do this before emitting a terminator instruction.
392 SDValue getControlRoot();
394 DebugLoc getCurDebugLoc() const { return CurDebugLoc; }
395 void setCurDebugLoc(DebugLoc dl) { CurDebugLoc = dl; }
397 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
399 void visit(Instruction &I);
401 void visit(unsigned Opcode, User &I);
403 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
405 SDValue getValue(const Value *V);
407 void setValue(const Value *V, SDValue NewN) {
408 SDValue &N = NodeMap[V];
409 assert(N.getNode() == 0 && "Already set a value for this node!");
413 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
414 std::set<unsigned> &OutputRegs,
415 std::set<unsigned> &InputRegs);
417 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
418 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
420 void EmitBranchForMergedCondition(Value *Cond, MachineBasicBlock *TBB,
421 MachineBasicBlock *FBB,
422 MachineBasicBlock *CurBB);
423 bool ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases);
424 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
425 void CopyToExportRegsIfNeeded(Value *V);
426 void ExportFromCurrentBlock(Value *V);
427 void LowerCallTo(CallSite CS, SDValue Callee, bool IsTailCall,
428 MachineBasicBlock *LandingPad = NULL);
431 // Terminator instructions.
432 void visitRet(ReturnInst &I);
433 void visitBr(BranchInst &I);
434 void visitSwitch(SwitchInst &I);
435 void visitUnreachable(UnreachableInst &I) { /* noop */ }
437 // Helpers for visitSwitch
438 bool handleSmallSwitchRange(CaseRec& CR,
439 CaseRecVector& WorkList,
441 MachineBasicBlock* Default);
442 bool handleJTSwitchCase(CaseRec& CR,
443 CaseRecVector& WorkList,
445 MachineBasicBlock* Default);
446 bool handleBTSplitSwitchCase(CaseRec& CR,
447 CaseRecVector& WorkList,
449 MachineBasicBlock* Default);
450 bool handleBitTestsSwitchCase(CaseRec& CR,
451 CaseRecVector& WorkList,
453 MachineBasicBlock* Default);
455 void visitSwitchCase(CaseBlock &CB);
456 void visitBitTestHeader(BitTestBlock &B);
457 void visitBitTestCase(MachineBasicBlock* NextMBB,
460 void visitJumpTable(JumpTable &JT);
461 void visitJumpTableHeader(JumpTable &JT, JumpTableHeader &JTH);
464 // These all get lowered before this pass.
465 void visitInvoke(InvokeInst &I);
466 void visitUnwind(UnwindInst &I);
468 void visitBinary(User &I, unsigned OpCode);
469 void visitShift(User &I, unsigned Opcode);
470 void visitAdd(User &I) { visitBinary(I, ISD::ADD); }
471 void visitFAdd(User &I) { visitBinary(I, ISD::FADD); }
472 void visitSub(User &I) { visitBinary(I, ISD::SUB); }
473 void visitFSub(User &I);
474 void visitMul(User &I) { visitBinary(I, ISD::MUL); }
475 void visitFMul(User &I) { visitBinary(I, ISD::FMUL); }
476 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
477 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
478 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
479 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
480 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
481 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
482 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
483 void visitOr (User &I) { visitBinary(I, ISD::OR); }
484 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
485 void visitShl (User &I) { visitShift(I, ISD::SHL); }
486 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
487 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
488 void visitICmp(User &I);
489 void visitFCmp(User &I);
490 // Visit the conversion instructions
491 void visitTrunc(User &I);
492 void visitZExt(User &I);
493 void visitSExt(User &I);
494 void visitFPTrunc(User &I);
495 void visitFPExt(User &I);
496 void visitFPToUI(User &I);
497 void visitFPToSI(User &I);
498 void visitUIToFP(User &I);
499 void visitSIToFP(User &I);
500 void visitPtrToInt(User &I);
501 void visitIntToPtr(User &I);
502 void visitBitCast(User &I);
504 void visitExtractElement(User &I);
505 void visitInsertElement(User &I);
506 void visitShuffleVector(User &I);
508 void visitExtractValue(ExtractValueInst &I);
509 void visitInsertValue(InsertValueInst &I);
511 void visitGetElementPtr(User &I);
512 void visitSelect(User &I);
514 void visitMalloc(MallocInst &I);
515 void visitFree(FreeInst &I);
516 void visitAlloca(AllocaInst &I);
517 void visitLoad(LoadInst &I);
518 void visitStore(StoreInst &I);
519 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
520 void visitCall(CallInst &I);
521 void visitInlineAsm(CallSite CS);
522 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
523 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
525 void visitPow(CallInst &I);
526 void visitExp2(CallInst &I);
527 void visitExp(CallInst &I);
528 void visitLog(CallInst &I);
529 void visitLog2(CallInst &I);
530 void visitLog10(CallInst &I);
532 void visitVAStart(CallInst &I);
533 void visitVAArg(VAArgInst &I);
534 void visitVAEnd(CallInst &I);
535 void visitVACopy(CallInst &I);
537 void visitUserOp1(Instruction &I) {
538 assert(0 && "UserOp1 should not exist at instruction selection time!");
541 void visitUserOp2(Instruction &I) {
542 assert(0 && "UserOp2 should not exist at instruction selection time!");
546 const char *implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op);
547 const char *implVisitAluOverflow(CallInst &I, ISD::NodeType Op);
550 /// AddCatchInfo - Extract the personality and type infos from an eh.selector
551 /// call, and add them to the specified machine basic block.
552 void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
553 MachineBasicBlock *MBB);
555 } // end namespace llvm