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