blob: 397f7b1a249d28f9dbac83e1b90139b6da57de9c [file] [log] [blame]
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001//===-- SelectionDAGBuild.h - Selection-DAG building ----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This implements routines for translating from LLVM IR into SelectionDAG IR.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef SELECTIONDAGBUILD_H
15#define SELECTIONDAGBUILD_H
16
17#include "llvm/Constants.h"
18#include "llvm/ADT/APInt.h"
19#include "llvm/ADT/DenseMap.h"
20#ifndef NDEBUG
21#include "llvm/ADT/SmallSet.h"
22#endif
23#include "llvm/CodeGen/ValueTypes.h"
24#include "llvm/CodeGen/SelectionDAGNodes.h"
25#include "llvm/Support/CallSite.h"
26#include <vector>
27#include <set>
28
29namespace llvm {
30
31class AliasAnalysis;
32class AllocaInst;
33class BasicBlock;
34class BitCastInst;
35class BranchInst;
36class CallInst;
37class ExtractElementInst;
38class ExtractValueInst;
39class FCmpInst;
40class FPExtInst;
41class FPToSIInst;
42class FPToUIInst;
43class FPTruncInst;
44class FreeInst;
45class Function;
46class GetElementPtrInst;
47class GCFunctionInfo;
48class ICmpInst;
49class IntToPtrInst;
50class InvokeInst;
51class InsertElementInst;
52class InsertValueInst;
53class Instruction;
54class LoadInst;
55class MachineBasicBlock;
56class MachineFunction;
57class MachineInstr;
58class MachineModuleInfo;
59class MachineRegisterInfo;
60class MallocInst;
61class PHINode;
62class PtrToIntInst;
63class ReturnInst;
64class SDISelAsmOperandInfo;
65class SExtInst;
66class SelectInst;
67class ShuffleVectorInst;
68class SIToFPInst;
69class StoreInst;
70class SwitchInst;
71class TargetData;
72class TargetLowering;
73class TruncInst;
74class UIToFPInst;
75class UnreachableInst;
76class UnwindInst;
77class VICmpInst;
78class VFCmpInst;
79class VAArgInst;
80class ZExtInst;
81
82//===--------------------------------------------------------------------===//
83/// FunctionLoweringInfo - This contains information that is global to a
84/// function that is used when lowering a region of the function.
85///
86class FunctionLoweringInfo {
87public:
88 TargetLowering &TLI;
89 Function *Fn;
90 MachineFunction *MF;
91 MachineRegisterInfo *RegInfo;
92
93 explicit FunctionLoweringInfo(TargetLowering &TLI);
94
95 /// set - Initialize this FunctionLoweringInfo with the given Function
96 /// and its associated MachineFunction.
97 ///
98 void set(Function &Fn, MachineFunction &MF, bool EnableFastISel);
99
100 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
101 DenseMap<const BasicBlock*, MachineBasicBlock *> MBBMap;
102
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;
107
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;
112
113#ifndef NDEBUG
114 SmallSet<Instruction*, 8> CatchInfoLost;
115 SmallSet<Instruction*, 8> CatchInfoFound;
116#endif
117
118 unsigned MakeReg(MVT VT);
119
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);
124 }
125
126 unsigned CreateRegForValue(const Value *V);
127
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);
132 }
133
134 struct LiveOutInfo {
135 unsigned NumSignBits;
136 APInt KnownOne, KnownZero;
137 LiveOutInfo() : NumSignBits(0) {}
138 };
139
140 /// LiveOutRegInfo - Information about live out vregs, indexed by their
141 /// register number offset by 'FirstVirtualRegister'.
142 std::vector<LiveOutInfo> LiveOutRegInfo;
143
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.
147 void clear() {
148 MBBMap.clear();
149 ValueMap.clear();
150 StaticAllocaMap.clear();
151#ifndef NDEBUG
152 CatchInfoLost.clear();
153 CatchInfoFound.clear();
154#endif
155 LiveOutRegInfo.clear();
156 }
157};
158
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.
163///
164class SelectionDAGLowering {
165 MachineBasicBlock *CurMBB;
166
Dale Johannesen66978ee2009-01-31 02:22:37 +0000167 /// CurDebugLoc - current file + line number. Changes as we build the DAG.
168 DebugLoc CurDebugLoc;
169
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000170 DenseMap<const Value*, SDValue> NodeMap;
171
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
175 /// analysis.
176 SmallVector<SDValue, 8> PendingLoads;
177
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
182 /// instructions.
183 SmallVector<SDValue, 8> PendingExports;
184
185 /// Case - A struct to record the Value for a switch case, and the
186 /// case's target basic block.
187 struct Case {
188 Constant* Low;
189 Constant* High;
190 MachineBasicBlock* BB;
191
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);
199 }
200 };
201
202 struct CaseBits {
203 uint64_t Mask;
204 MachineBasicBlock* BB;
205 unsigned Bits;
206
207 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
208 Mask(mask), BB(bb), Bits(bits) { }
209 };
210
211 typedef std::vector<Case> CaseVector;
212 typedef std::vector<CaseBits> CaseBitsVector;
213 typedef CaseVector::iterator CaseItr;
214 typedef std::pair<CaseItr, CaseItr> CaseRange;
215
216 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
217 /// of conditional branches.
218 struct CaseRec {
219 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
220 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
221
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.
226 Constant *LT;
227 Constant *GE;
228 /// Range - A pair of iterators representing the range of case values to be
229 /// processed at this point in the binary search tree.
230 CaseRange Range;
231 };
232
233 typedef std::vector<CaseRec> CaseRecVector;
234
235 /// The comparison function for sorting the switch case values in the vector.
236 /// WARNING: Case ranges should be disjoint!
237 struct CaseCmp {
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());
243 }
244 };
245
246 struct CaseBitsCmp {
247 bool operator () (const CaseBits& C1, const CaseBits& C2) {
248 return C1.Bits > C2.Bits;
249 }
250 };
251
Anton Korobeynikov23218582008-12-23 22:25:27 +0000252 size_t Clusterify(CaseVector& Cases, const SwitchInst &SI);
253
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000254 /// 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.
257 struct CaseBlock {
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
264 ISD::CondCode CC;
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;
273 };
274 struct JumpTable {
275 JumpTable(unsigned R, unsigned J, MachineBasicBlock *M,
276 MachineBasicBlock *D): Reg(R), JTI(J), MBB(M), Default(D) {}
277
278 /// Reg - the virtual register containing the index of the jump table entry
279 //. to jump to.
280 unsigned Reg;
281 /// JTI - the JumpTableIndex for this jump table in the function.
282 unsigned JTI;
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;
288 };
289 struct JumpTableHeader {
Anton Korobeynikov23218582008-12-23 22:25:27 +0000290 JumpTableHeader(APInt F, APInt L, Value* SV, MachineBasicBlock* H,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000291 bool E = false):
292 First(F), Last(L), SValue(SV), HeaderBB(H), Emitted(E) {}
Anton Korobeynikov23218582008-12-23 22:25:27 +0000293 APInt First;
294 APInt Last;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000295 Value *SValue;
296 MachineBasicBlock *HeaderBB;
297 bool Emitted;
298 };
299 typedef std::pair<JumpTableHeader, JumpTable> JumpTableBlock;
300
301 struct BitTestCase {
302 BitTestCase(uint64_t M, MachineBasicBlock* T, MachineBasicBlock* Tr):
303 Mask(M), ThisBB(T), TargetBB(Tr) { }
304 uint64_t Mask;
305 MachineBasicBlock* ThisBB;
306 MachineBasicBlock* TargetBB;
307 };
308
309 typedef SmallVector<BitTestCase, 3> BitTestInfo;
310
311 struct BitTestBlock {
Anton Korobeynikov23218582008-12-23 22:25:27 +0000312 BitTestBlock(APInt F, APInt R, Value* SV,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000313 unsigned Rg, bool E,
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) { }
Anton Korobeynikov23218582008-12-23 22:25:27 +0000318 APInt First;
319 APInt Range;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000320 Value *SValue;
321 unsigned Reg;
322 bool Emitted;
323 MachineBasicBlock *Parent;
324 MachineBasicBlock *Default;
325 BitTestInfo Cases;
326 };
327
328public:
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.
332 TargetLowering &TLI;
333 SelectionDAG &DAG;
334 const TargetData *TD;
335 AliasAnalysis *AA;
336
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;
346
347 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
348
349 // Emit PHI-node-operand constants only once even if used by multiple
350 // PHI nodes.
351 DenseMap<Constant*, unsigned> ConstantsOut;
352
353 /// FuncInfo - Information about the function as a whole.
354 ///
355 FunctionLoweringInfo &FuncInfo;
356
357 /// GFI - Garbage collection metadata for the function.
358 GCFunctionInfo *GFI;
359
360 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
361 FunctionLoweringInfo &funcinfo)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000362 : CurDebugLoc(DebugLoc::getUnknownLoc()),
363 TLI(tli), DAG(dag), FuncInfo(funcinfo) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000364 }
365
366 void init(GCFunctionInfo *gfi, AliasAnalysis &aa);
367
368 /// clear - Clear out the curret SelectionDAG and the associated
369 /// state and prepare this SelectionDAGLowering object to be used
370 /// for a new block. This doesn't clear out information about
371 /// additional blocks that are needed to complete switch lowering
372 /// or PHI node updating; that information is cleared out as it is
373 /// consumed.
374 void clear();
375
376 /// getRoot - Return the current virtual root of the Selection DAG,
377 /// flushing any PendingLoad items. This must be done before emitting
378 /// a store or any other node that may need to be ordered after any
379 /// prior load instructions.
380 ///
381 SDValue getRoot();
382
383 /// getControlRoot - Similar to getRoot, but instead of flushing all the
384 /// PendingLoad items, flush all the PendingExports items. It is necessary
385 /// to do this before emitting a terminator instruction.
386 ///
387 SDValue getControlRoot();
388
Dale Johannesen66978ee2009-01-31 02:22:37 +0000389 DebugLoc getCurDebugLoc() const { return CurDebugLoc; }
390
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000391 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
392
393 void visit(Instruction &I);
394
395 void visit(unsigned Opcode, User &I);
396
397 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
398
399 SDValue getValue(const Value *V);
400
401 void setValue(const Value *V, SDValue NewN) {
402 SDValue &N = NodeMap[V];
403 assert(N.getNode() == 0 && "Already set a value for this node!");
404 N = NewN;
405 }
406
Dale Johannesen8e3455b2008-09-24 23:13:09 +0000407 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000408 std::set<unsigned> &OutputRegs,
409 std::set<unsigned> &InputRegs);
410
411 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
412 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
413 unsigned Opc);
Dan Gohmanc2277342008-10-17 21:16:08 +0000414 void EmitBranchForMergedCondition(Value *Cond, MachineBasicBlock *TBB,
415 MachineBasicBlock *FBB,
416 MachineBasicBlock *CurBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000417 bool ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases);
418 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
419 void ExportFromCurrentBlock(Value *V);
420 void LowerCallTo(CallSite CS, SDValue Callee, bool IsTailCall,
421 MachineBasicBlock *LandingPad = NULL);
422
423private:
424 // Terminator instructions.
425 void visitRet(ReturnInst &I);
426 void visitBr(BranchInst &I);
427 void visitSwitch(SwitchInst &I);
428 void visitUnreachable(UnreachableInst &I) { /* noop */ }
429
430 // Helpers for visitSwitch
431 bool handleSmallSwitchRange(CaseRec& CR,
432 CaseRecVector& WorkList,
433 Value* SV,
434 MachineBasicBlock* Default);
435 bool handleJTSwitchCase(CaseRec& CR,
436 CaseRecVector& WorkList,
437 Value* SV,
438 MachineBasicBlock* Default);
439 bool handleBTSplitSwitchCase(CaseRec& CR,
440 CaseRecVector& WorkList,
441 Value* SV,
442 MachineBasicBlock* Default);
443 bool handleBitTestsSwitchCase(CaseRec& CR,
444 CaseRecVector& WorkList,
445 Value* SV,
446 MachineBasicBlock* Default);
447public:
448 void visitSwitchCase(CaseBlock &CB);
449 void visitBitTestHeader(BitTestBlock &B);
450 void visitBitTestCase(MachineBasicBlock* NextMBB,
451 unsigned Reg,
452 BitTestCase &B);
453 void visitJumpTable(JumpTable &JT);
454 void visitJumpTableHeader(JumpTable &JT, JumpTableHeader &JTH);
455
456private:
457 // These all get lowered before this pass.
458 void visitInvoke(InvokeInst &I);
459 void visitUnwind(UnwindInst &I);
460
461 void visitBinary(User &I, unsigned OpCode);
462 void visitShift(User &I, unsigned Opcode);
463 void visitAdd(User &I);
464 void visitSub(User &I);
465 void visitMul(User &I);
466 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
467 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
468 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
469 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
470 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
471 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
472 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
473 void visitOr (User &I) { visitBinary(I, ISD::OR); }
474 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
475 void visitShl (User &I) { visitShift(I, ISD::SHL); }
476 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
477 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
478 void visitICmp(User &I);
479 void visitFCmp(User &I);
480 void visitVICmp(User &I);
481 void visitVFCmp(User &I);
482 // Visit the conversion instructions
483 void visitTrunc(User &I);
484 void visitZExt(User &I);
485 void visitSExt(User &I);
486 void visitFPTrunc(User &I);
487 void visitFPExt(User &I);
488 void visitFPToUI(User &I);
489 void visitFPToSI(User &I);
490 void visitUIToFP(User &I);
491 void visitSIToFP(User &I);
492 void visitPtrToInt(User &I);
493 void visitIntToPtr(User &I);
494 void visitBitCast(User &I);
495
496 void visitExtractElement(User &I);
497 void visitInsertElement(User &I);
498 void visitShuffleVector(User &I);
499
500 void visitExtractValue(ExtractValueInst &I);
501 void visitInsertValue(InsertValueInst &I);
502
503 void visitGetElementPtr(User &I);
504 void visitSelect(User &I);
505
506 void visitMalloc(MallocInst &I);
507 void visitFree(FreeInst &I);
508 void visitAlloca(AllocaInst &I);
509 void visitLoad(LoadInst &I);
510 void visitStore(StoreInst &I);
511 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
512 void visitCall(CallInst &I);
513 void visitInlineAsm(CallSite CS);
514 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
515 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
516
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +0000517 void visitPow(CallInst &I);
Dale Johannesen601d3c02008-09-05 01:48:15 +0000518 void visitExp2(CallInst &I);
Dale Johannesen59e577f2008-09-05 18:38:42 +0000519 void visitExp(CallInst &I);
520 void visitLog(CallInst &I);
521 void visitLog2(CallInst &I);
522 void visitLog10(CallInst &I);
Dale Johannesen601d3c02008-09-05 01:48:15 +0000523
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000524 void visitVAStart(CallInst &I);
525 void visitVAArg(VAArgInst &I);
526 void visitVAEnd(CallInst &I);
527 void visitVACopy(CallInst &I);
528
529 void visitUserOp1(Instruction &I) {
530 assert(0 && "UserOp1 should not exist at instruction selection time!");
531 abort();
532 }
533 void visitUserOp2(Instruction &I) {
534 assert(0 && "UserOp2 should not exist at instruction selection time!");
535 abort();
536 }
537
538 const char *implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op);
Bill Wendling74c37652008-12-09 22:08:41 +0000539 const char *implVisitAluOverflow(CallInst &I, ISD::NodeType Op);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000540
541 void setCurDebugLoc(DebugLoc dl) { CurDebugLoc = dl; }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000542};
543
544/// AddCatchInfo - Extract the personality and type infos from an eh.selector
545/// call, and add them to the specified machine basic block.
546void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
547 MachineBasicBlock *MBB);
548
549} // end namespace llvm
550
551#endif