Re-apply bottom-up fast-isel, with fixes. Be very careful to avoid emitting
[oota-llvm.git] / lib / CodeGen / SelectionDAG / FunctionLoweringInfo.cpp
1 //===-- FunctionLoweringInfo.cpp ------------------------------------------===//
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 functions from LLVM IR into
11 // Machine IR.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "function-lowering-info"
16 #include "llvm/CodeGen/FunctionLoweringInfo.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/IntrinsicInst.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Module.h"
23 #include "llvm/CodeGen/Analysis.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/Target/TargetRegisterInfo.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Target/TargetFrameInfo.h"
32 #include "llvm/Target/TargetInstrInfo.h"
33 #include "llvm/Target/TargetLowering.h"
34 #include "llvm/Target/TargetOptions.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include <algorithm>
39 using namespace llvm;
40
41 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
42 /// PHI nodes or outside of the basic block that defines it, or used by a
43 /// switch or atomic instruction, which may expand to multiple basic blocks.
44 static bool isUsedOutsideOfDefiningBlock(const Instruction *I) {
45   if (I->use_empty()) return false;
46   if (isa<PHINode>(I)) return true;
47   const BasicBlock *BB = I->getParent();
48   for (Value::const_use_iterator UI = I->use_begin(), E = I->use_end();
49         UI != E; ++UI)
50     if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
51       return true;
52   return false;
53 }
54
55 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
56 /// entry block, return true.  This includes arguments used by switches, since
57 /// the switch may expand into multiple basic blocks.
58 static bool isOnlyUsedInEntryBlock(const Argument *A, bool EnableFastISel) {
59   // With FastISel active, we may be splitting blocks, so force creation
60   // of virtual registers for all non-dead arguments.
61   if (EnableFastISel)
62     return A->use_empty();
63
64   const BasicBlock *Entry = A->getParent()->begin();
65   for (Value::const_use_iterator UI = A->use_begin(), E = A->use_end();
66        UI != E; ++UI)
67     if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
68       return false;  // Use not in entry block.
69   return true;
70 }
71
72 FunctionLoweringInfo::FunctionLoweringInfo(const TargetLowering &tli)
73   : TLI(tli) {
74 }
75
76 void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf) {
77   Fn = &fn;
78   MF = &mf;
79   RegInfo = &MF->getRegInfo();
80
81   // Check whether the function can return without sret-demotion.
82   SmallVector<ISD::OutputArg, 4> Outs;
83   GetReturnInfo(Fn->getReturnType(),
84                 Fn->getAttributes().getRetAttributes(), Outs, TLI);
85   CanLowerReturn = TLI.CanLowerReturn(Fn->getCallingConv(), Fn->isVarArg(),
86                                       Outs, Fn->getContext());
87
88   // Create a vreg for each argument register that is not dead and is used
89   // outside of the entry block for the function.
90   for (Function::const_arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
91        AI != E; ++AI)
92     if (!isOnlyUsedInEntryBlock(AI, EnableFastISel))
93       InitializeRegForValue(AI);
94
95   // Initialize the mapping of values to registers.  This is only set up for
96   // instruction values that are used outside of the block that defines
97   // them.
98   Function::const_iterator BB = Fn->begin(), EB = Fn->end();
99   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
100     if (const AllocaInst *AI = dyn_cast<AllocaInst>(I))
101       if (const ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
102         const Type *Ty = AI->getAllocatedType();
103         uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
104         unsigned Align =
105           std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
106                    AI->getAlignment());
107
108         TySize *= CUI->getZExtValue();   // Get total allocated size.
109         if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
110         StaticAllocaMap[AI] =
111           MF->getFrameInfo()->CreateStackObject(TySize, Align, false);
112       }
113
114   for (; BB != EB; ++BB)
115     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
116       if (isUsedOutsideOfDefiningBlock(I))
117         if (!isa<AllocaInst>(I) ||
118             !StaticAllocaMap.count(cast<AllocaInst>(I)))
119           InitializeRegForValue(I);
120
121   // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
122   // also creates the initial PHI MachineInstrs, though none of the input
123   // operands are populated.
124   for (BB = Fn->begin(); BB != EB; ++BB) {
125     MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
126     MBBMap[BB] = MBB;
127     MF->push_back(MBB);
128
129     // Transfer the address-taken flag. This is necessary because there could
130     // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
131     // the first one should be marked.
132     if (BB->hasAddressTaken())
133       MBB->setHasAddressTaken();
134
135     // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
136     // appropriate.
137     for (BasicBlock::const_iterator I = BB->begin();
138          const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
139       if (PN->use_empty()) continue;
140
141       DebugLoc DL = PN->getDebugLoc();
142       unsigned PHIReg = ValueMap[PN];
143       assert(PHIReg && "PHI node does not have an assigned virtual register!");
144
145       SmallVector<EVT, 4> ValueVTs;
146       ComputeValueVTs(TLI, PN->getType(), ValueVTs);
147       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
148         EVT VT = ValueVTs[vti];
149         unsigned NumRegisters = TLI.getNumRegisters(Fn->getContext(), VT);
150         const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
151         for (unsigned i = 0; i != NumRegisters; ++i)
152           BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i);
153         PHIReg += NumRegisters;
154       }
155     }
156   }
157
158   // Mark landing pad blocks.
159   for (BB = Fn->begin(); BB != EB; ++BB)
160     if (const InvokeInst *Invoke = dyn_cast<InvokeInst>(BB->getTerminator()))
161       MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
162 }
163
164 /// clear - Clear out all the function-specific state. This returns this
165 /// FunctionLoweringInfo to an empty state, ready to be used for a
166 /// different function.
167 void FunctionLoweringInfo::clear() {
168   assert(CatchInfoFound.size() == CatchInfoLost.size() &&
169          "Not all catch info was assigned to a landing pad!");
170
171   MBBMap.clear();
172   ValueMap.clear();
173   StaticAllocaMap.clear();
174 #ifndef NDEBUG
175   CatchInfoLost.clear();
176   CatchInfoFound.clear();
177 #endif
178   LiveOutRegInfo.clear();
179   ArgDbgValues.clear();
180   RegFixups.clear();
181 }
182
183 /// CreateReg - Allocate a single virtual register for the given type.
184 unsigned FunctionLoweringInfo::CreateReg(EVT VT) {
185   return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
186 }
187
188 /// CreateRegs - Allocate the appropriate number of virtual registers of
189 /// the correctly promoted or expanded types.  Assign these registers
190 /// consecutive vreg numbers and return the first assigned number.
191 ///
192 /// In the case that the given value has struct or array type, this function
193 /// will assign registers for each member or element.
194 ///
195 unsigned FunctionLoweringInfo::CreateRegs(const Type *Ty) {
196   SmallVector<EVT, 4> ValueVTs;
197   ComputeValueVTs(TLI, Ty, ValueVTs);
198
199   unsigned FirstReg = 0;
200   for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
201     EVT ValueVT = ValueVTs[Value];
202     EVT RegisterVT = TLI.getRegisterType(Ty->getContext(), ValueVT);
203
204     unsigned NumRegs = TLI.getNumRegisters(Ty->getContext(), ValueVT);
205     for (unsigned i = 0; i != NumRegs; ++i) {
206       unsigned R = CreateReg(RegisterVT);
207       if (!FirstReg) FirstReg = R;
208     }
209   }
210   return FirstReg;
211 }
212
213 /// AddCatchInfo - Extract the personality and type infos from an eh.selector
214 /// call, and add them to the specified machine basic block.
215 void llvm::AddCatchInfo(const CallInst &I, MachineModuleInfo *MMI,
216                         MachineBasicBlock *MBB) {
217   // Inform the MachineModuleInfo of the personality for this landing pad.
218   const ConstantExpr *CE = cast<ConstantExpr>(I.getArgOperand(1));
219   assert(CE->getOpcode() == Instruction::BitCast &&
220          isa<Function>(CE->getOperand(0)) &&
221          "Personality should be a function");
222   MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
223
224   // Gather all the type infos for this landing pad and pass them along to
225   // MachineModuleInfo.
226   std::vector<const GlobalVariable *> TyInfo;
227   unsigned N = I.getNumArgOperands();
228
229   for (unsigned i = N - 1; i > 1; --i) {
230     if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(i))) {
231       unsigned FilterLength = CI->getZExtValue();
232       unsigned FirstCatch = i + FilterLength + !FilterLength;
233       assert(FirstCatch <= N && "Invalid filter length");
234
235       if (FirstCatch < N) {
236         TyInfo.reserve(N - FirstCatch);
237         for (unsigned j = FirstCatch; j < N; ++j)
238           TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
239         MMI->addCatchTypeInfo(MBB, TyInfo);
240         TyInfo.clear();
241       }
242
243       if (!FilterLength) {
244         // Cleanup.
245         MMI->addCleanup(MBB);
246       } else {
247         // Filter.
248         TyInfo.reserve(FilterLength - 1);
249         for (unsigned j = i + 1; j < FirstCatch; ++j)
250           TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
251         MMI->addFilterTypeInfo(MBB, TyInfo);
252         TyInfo.clear();
253       }
254
255       N = i;
256     }
257   }
258
259   if (N > 2) {
260     TyInfo.reserve(N - 2);
261     for (unsigned j = 2; j < N; ++j)
262       TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
263     MMI->addCatchTypeInfo(MBB, TyInfo);
264   }
265 }
266
267 void llvm::CopyCatchInfo(const BasicBlock *SrcBB, const BasicBlock *DestBB,
268                          MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
269   for (BasicBlock::const_iterator I = SrcBB->begin(), E = --SrcBB->end();
270        I != E; ++I)
271     if (const EHSelectorInst *EHSel = dyn_cast<EHSelectorInst>(I)) {
272       // Apply the catch info to DestBB.
273       AddCatchInfo(*EHSel, MMI, FLI.MBBMap[DestBB]);
274 #ifndef NDEBUG
275       if (!FLI.MBBMap[SrcBB]->isLandingPad())
276         FLI.CatchInfoFound.insert(EHSel);
277 #endif
278     }
279 }