FunctionLoweringInfo.cpp revision 4c3fd9f92f89810d659973d2666ab729758de64a
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>
39using 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.
44static 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.
58static 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
72FunctionLoweringInfo::FunctionLoweringInfo(const TargetLowering &tli)
73  : TLI(tli) {
74}
75
76void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf) {
77  Fn = &fn;
78  MF = &mf;
79  RegInfo = &MF->getRegInfo();
80
81  // Create a vreg for each argument register that is not dead and is used
82  // outside of the entry block for the function.
83  for (Function::const_arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
84       AI != E; ++AI)
85    if (!isOnlyUsedInEntryBlock(AI, EnableFastISel))
86      InitializeRegForValue(AI);
87
88  // Initialize the mapping of values to registers.  This is only set up for
89  // instruction values that are used outside of the block that defines
90  // them.
91  Function::const_iterator BB = Fn->begin(), EB = Fn->end();
92  for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
93    if (const AllocaInst *AI = dyn_cast<AllocaInst>(I))
94      if (const ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
95        const Type *Ty = AI->getAllocatedType();
96        uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
97        unsigned Align =
98          std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
99                   AI->getAlignment());
100
101        TySize *= CUI->getZExtValue();   // Get total allocated size.
102        if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
103        StaticAllocaMap[AI] =
104          MF->getFrameInfo()->CreateStackObject(TySize, Align, false);
105      }
106
107  for (; BB != EB; ++BB)
108    for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
109      if (isUsedOutsideOfDefiningBlock(I))
110        if (!isa<AllocaInst>(I) ||
111            !StaticAllocaMap.count(cast<AllocaInst>(I)))
112          InitializeRegForValue(I);
113
114  // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
115  // also creates the initial PHI MachineInstrs, though none of the input
116  // operands are populated.
117  for (BB = Fn->begin(); BB != EB; ++BB) {
118    MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
119    MBBMap[BB] = MBB;
120    MF->push_back(MBB);
121
122    // Transfer the address-taken flag. This is necessary because there could
123    // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
124    // the first one should be marked.
125    if (BB->hasAddressTaken())
126      MBB->setHasAddressTaken();
127
128    // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
129    // appropriate.
130    for (BasicBlock::const_iterator I = BB->begin();
131         const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
132      if (PN->use_empty()) continue;
133
134      DebugLoc DL = PN->getDebugLoc();
135      unsigned PHIReg = ValueMap[PN];
136      assert(PHIReg && "PHI node does not have an assigned virtual register!");
137
138      SmallVector<EVT, 4> ValueVTs;
139      ComputeValueVTs(TLI, PN->getType(), ValueVTs);
140      for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
141        EVT VT = ValueVTs[vti];
142        unsigned NumRegisters = TLI.getNumRegisters(Fn->getContext(), VT);
143        const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
144        for (unsigned i = 0; i != NumRegisters; ++i)
145          BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i);
146        PHIReg += NumRegisters;
147      }
148    }
149  }
150
151  // Mark landing pad blocks.
152  for (BB = Fn->begin(); BB != EB; ++BB)
153    if (const InvokeInst *Invoke = dyn_cast<InvokeInst>(BB->getTerminator()))
154      MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
155}
156
157/// clear - Clear out all the function-specific state. This returns this
158/// FunctionLoweringInfo to an empty state, ready to be used for a
159/// different function.
160void FunctionLoweringInfo::clear() {
161  assert(CatchInfoFound.size() == CatchInfoLost.size() &&
162         "Not all catch info was assigned to a landing pad!");
163
164  MBBMap.clear();
165  ValueMap.clear();
166  StaticAllocaMap.clear();
167#ifndef NDEBUG
168  CatchInfoLost.clear();
169  CatchInfoFound.clear();
170#endif
171  LiveOutRegInfo.clear();
172  ArgDbgValues.clear();
173}
174
175/// CreateReg - Allocate a single virtual register for the given type.
176unsigned FunctionLoweringInfo::CreateReg(EVT VT) {
177  return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
178}
179
180/// CreateRegs - Allocate the appropriate number of virtual registers of
181/// the correctly promoted or expanded types.  Assign these registers
182/// consecutive vreg numbers and return the first assigned number.
183///
184/// In the case that the given value has struct or array type, this function
185/// will assign registers for each member or element.
186///
187unsigned FunctionLoweringInfo::CreateRegs(const Type *Ty) {
188  SmallVector<EVT, 4> ValueVTs;
189  ComputeValueVTs(TLI, Ty, ValueVTs);
190
191  unsigned FirstReg = 0;
192  for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
193    EVT ValueVT = ValueVTs[Value];
194    EVT RegisterVT = TLI.getRegisterType(Ty->getContext(), ValueVT);
195
196    unsigned NumRegs = TLI.getNumRegisters(Ty->getContext(), ValueVT);
197    for (unsigned i = 0; i != NumRegs; ++i) {
198      unsigned R = CreateReg(RegisterVT);
199      if (!FirstReg) FirstReg = R;
200    }
201  }
202  return FirstReg;
203}
204
205/// AddCatchInfo - Extract the personality and type infos from an eh.selector
206/// call, and add them to the specified machine basic block.
207void llvm::AddCatchInfo(const CallInst &I, MachineModuleInfo *MMI,
208                        MachineBasicBlock *MBB) {
209  // Inform the MachineModuleInfo of the personality for this landing pad.
210  const ConstantExpr *CE = cast<ConstantExpr>(I.getArgOperand(1));
211  assert(CE->getOpcode() == Instruction::BitCast &&
212         isa<Function>(CE->getOperand(0)) &&
213         "Personality should be a function");
214  MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
215
216  // Gather all the type infos for this landing pad and pass them along to
217  // MachineModuleInfo.
218  std::vector<const GlobalVariable *> TyInfo;
219  unsigned N = I.getNumArgOperands();
220
221  for (unsigned i = N - 1; i > 1; --i) {
222    if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(i))) {
223      unsigned FilterLength = CI->getZExtValue();
224      unsigned FirstCatch = i + FilterLength + !FilterLength;
225      assert(FirstCatch <= N && "Invalid filter length");
226
227      if (FirstCatch < N) {
228        TyInfo.reserve(N - FirstCatch);
229        for (unsigned j = FirstCatch; j < N; ++j)
230          TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
231        MMI->addCatchTypeInfo(MBB, TyInfo);
232        TyInfo.clear();
233      }
234
235      if (!FilterLength) {
236        // Cleanup.
237        MMI->addCleanup(MBB);
238      } else {
239        // Filter.
240        TyInfo.reserve(FilterLength - 1);
241        for (unsigned j = i + 1; j < FirstCatch; ++j)
242          TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
243        MMI->addFilterTypeInfo(MBB, TyInfo);
244        TyInfo.clear();
245      }
246
247      N = i;
248    }
249  }
250
251  if (N > 2) {
252    TyInfo.reserve(N - 2);
253    for (unsigned j = 2; j < N; ++j)
254      TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
255    MMI->addCatchTypeInfo(MBB, TyInfo);
256  }
257}
258
259void llvm::CopyCatchInfo(const BasicBlock *SrcBB, const BasicBlock *DestBB,
260                         MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
261  for (BasicBlock::const_iterator I = SrcBB->begin(), E = --SrcBB->end();
262       I != E; ++I)
263    if (const EHSelectorInst *EHSel = dyn_cast<EHSelectorInst>(I)) {
264      // Apply the catch info to DestBB.
265      AddCatchInfo(*EHSel, MMI, FLI.MBBMap[DestBB]);
266#ifndef NDEBUG
267      if (!FLI.MBBMap[SrcBB]->isLandingPad())
268        FLI.CatchInfoFound.insert(EHSel);
269#endif
270    }
271}
272