1 //===-- FunctionLoweringInfo.cpp ------------------------------------------===//
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 functions from LLVM IR into
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "function-lowering-info"
16 #include "FunctionLoweringInfo.h"
17 #include "llvm/CallingConv.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Function.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/IntrinsicInst.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/Module.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/Analysis/DebugInfo.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/TargetIntrinsicInfo.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include "llvm/Support/Compiler.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/MathExtras.h"
42 #include "llvm/Support/raw_ostream.h"
46 /// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
47 /// of insertvalue or extractvalue indices that identify a member, return
48 /// the linearized index of the start of the member.
50 unsigned llvm::ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
51 const unsigned *Indices,
52 const unsigned *IndicesEnd,
54 // Base case: We're done.
55 if (Indices && Indices == IndicesEnd)
58 // Given a struct type, recursively traverse the elements.
59 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
60 for (StructType::element_iterator EB = STy->element_begin(),
62 EE = STy->element_end();
64 if (Indices && *Indices == unsigned(EI - EB))
65 return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
66 CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
70 // Given an array type, recursively traverse the elements.
71 else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
72 const Type *EltTy = ATy->getElementType();
73 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
74 if (Indices && *Indices == i)
75 return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
76 CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
80 // We haven't found the type we're looking for, so keep searching.
84 /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
85 /// EVTs that represent all the individual underlying
86 /// non-aggregate types that comprise it.
88 /// If Offsets is non-null, it points to a vector to be filled in
89 /// with the in-memory offsets of each of the individual values.
91 void llvm::ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
92 SmallVectorImpl<EVT> &ValueVTs,
93 SmallVectorImpl<uint64_t> *Offsets,
94 uint64_t StartingOffset) {
95 // Given a struct type, recursively traverse the elements.
96 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
97 const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
98 for (StructType::element_iterator EB = STy->element_begin(),
100 EE = STy->element_end();
102 ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
103 StartingOffset + SL->getElementOffset(EI - EB));
106 // Given an array type, recursively traverse the elements.
107 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
108 const Type *EltTy = ATy->getElementType();
109 uint64_t EltSize = TLI.getTargetData()->getTypeAllocSize(EltTy);
110 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
111 ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
112 StartingOffset + i * EltSize);
115 // Interpret void as zero return values.
118 // Base case: we can get an EVT for this LLVM IR type.
119 ValueVTs.push_back(TLI.getValueType(Ty));
121 Offsets->push_back(StartingOffset);
124 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
125 /// PHI nodes or outside of the basic block that defines it, or used by a
126 /// switch or atomic instruction, which may expand to multiple basic blocks.
127 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
128 if (isa<PHINode>(I)) return true;
129 BasicBlock *BB = I->getParent();
130 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
131 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
136 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
137 /// entry block, return true. This includes arguments used by switches, since
138 /// the switch may expand into multiple basic blocks.
139 static bool isOnlyUsedInEntryBlock(Argument *A, bool EnableFastISel) {
140 // With FastISel active, we may be splitting blocks, so force creation
141 // of virtual registers for all non-dead arguments.
142 // Don't force virtual registers for byval arguments though, because
143 // fast-isel can't handle those in all cases.
144 if (EnableFastISel && !A->hasByValAttr())
145 return A->use_empty();
147 BasicBlock *Entry = A->getParent()->begin();
148 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
149 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
150 return false; // Use not in entry block.
154 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli)
158 void FunctionLoweringInfo::set(Function &fn, MachineFunction &mf,
159 bool EnableFastISel) {
162 RegInfo = &MF->getRegInfo();
164 // Create a vreg for each argument register that is not dead and is used
165 // outside of the entry block for the function.
166 for (Function::arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
168 if (!isOnlyUsedInEntryBlock(AI, EnableFastISel))
169 InitializeRegForValue(AI);
171 // Initialize the mapping of values to registers. This is only set up for
172 // instruction values that are used outside of the block that defines
174 Function::iterator BB = Fn->begin(), EB = Fn->end();
175 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
176 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
177 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
178 const Type *Ty = AI->getAllocatedType();
179 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
181 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
184 TySize *= CUI->getZExtValue(); // Get total allocated size.
185 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
186 StaticAllocaMap[AI] =
187 MF->getFrameInfo()->CreateStackObject(TySize, Align, false);
190 for (; BB != EB; ++BB)
191 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
192 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
193 if (!isa<AllocaInst>(I) ||
194 !StaticAllocaMap.count(cast<AllocaInst>(I)))
195 InitializeRegForValue(I);
197 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
198 // also creates the initial PHI MachineInstrs, though none of the input
199 // operands are populated.
200 for (BB = Fn->begin(), EB = Fn->end(); BB != EB; ++BB) {
201 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
205 // Transfer the address-taken flag. This is necessary because there could
206 // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
207 // the first one should be marked.
208 if (BB->hasAddressTaken())
209 MBB->setHasAddressTaken();
211 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
215 for (BasicBlock::iterator
216 I = BB->begin(), E = BB->end(); I != E; ++I) {
218 PN = dyn_cast<PHINode>(I);
219 if (!PN || PN->use_empty()) continue;
221 unsigned PHIReg = ValueMap[PN];
222 assert(PHIReg && "PHI node does not have an assigned virtual register!");
224 SmallVector<EVT, 4> ValueVTs;
225 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
226 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
227 EVT VT = ValueVTs[vti];
228 unsigned NumRegisters = TLI.getNumRegisters(Fn->getContext(), VT);
229 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
230 for (unsigned i = 0; i != NumRegisters; ++i)
231 BuildMI(MBB, DL, TII->get(TargetInstrInfo::PHI), PHIReg + i);
232 PHIReg += NumRegisters;
238 /// clear - Clear out all the function-specific state. This returns this
239 /// FunctionLoweringInfo to an empty state, ready to be used for a
240 /// different function.
241 void FunctionLoweringInfo::clear() {
244 StaticAllocaMap.clear();
246 CatchInfoLost.clear();
247 CatchInfoFound.clear();
249 LiveOutRegInfo.clear();
252 unsigned FunctionLoweringInfo::MakeReg(EVT VT) {
253 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
256 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
257 /// the correctly promoted or expanded types. Assign these registers
258 /// consecutive vreg numbers and return the first assigned number.
260 /// In the case that the given value has struct or array type, this function
261 /// will assign registers for each member or element.
263 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
264 SmallVector<EVT, 4> ValueVTs;
265 ComputeValueVTs(TLI, V->getType(), ValueVTs);
267 unsigned FirstReg = 0;
268 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
269 EVT ValueVT = ValueVTs[Value];
270 EVT RegisterVT = TLI.getRegisterType(V->getContext(), ValueVT);
272 unsigned NumRegs = TLI.getNumRegisters(V->getContext(), ValueVT);
273 for (unsigned i = 0; i != NumRegs; ++i) {
274 unsigned R = MakeReg(RegisterVT);
275 if (!FirstReg) FirstReg = R;
281 /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
282 GlobalVariable *llvm::ExtractTypeInfo(Value *V) {
283 V = V->stripPointerCasts();
284 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
285 assert ((GV || isa<ConstantPointerNull>(V)) &&
286 "TypeInfo must be a global variable or NULL");
290 /// AddCatchInfo - Extract the personality and type infos from an eh.selector
291 /// call, and add them to the specified machine basic block.
292 void llvm::AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
293 MachineBasicBlock *MBB) {
294 // Inform the MachineModuleInfo of the personality for this landing pad.
295 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
296 assert(CE->getOpcode() == Instruction::BitCast &&
297 isa<Function>(CE->getOperand(0)) &&
298 "Personality should be a function");
299 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
301 // Gather all the type infos for this landing pad and pass them along to
302 // MachineModuleInfo.
303 std::vector<GlobalVariable *> TyInfo;
304 unsigned N = I.getNumOperands();
306 for (unsigned i = N - 1; i > 2; --i) {
307 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
308 unsigned FilterLength = CI->getZExtValue();
309 unsigned FirstCatch = i + FilterLength + !FilterLength;
310 assert (FirstCatch <= N && "Invalid filter length");
312 if (FirstCatch < N) {
313 TyInfo.reserve(N - FirstCatch);
314 for (unsigned j = FirstCatch; j < N; ++j)
315 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
316 MMI->addCatchTypeInfo(MBB, TyInfo);
322 MMI->addCleanup(MBB);
325 TyInfo.reserve(FilterLength - 1);
326 for (unsigned j = i + 1; j < FirstCatch; ++j)
327 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
328 MMI->addFilterTypeInfo(MBB, TyInfo);
337 TyInfo.reserve(N - 3);
338 for (unsigned j = 3; j < N; ++j)
339 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
340 MMI->addCatchTypeInfo(MBB, TyInfo);
344 void llvm::CopyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
345 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
346 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
347 if (EHSelectorInst *EHSel = dyn_cast<EHSelectorInst>(I)) {
348 // Apply the catch info to DestBB.
349 AddCatchInfo(*EHSel, MMI, FLI.MBBMap[DestBB]);
351 if (!FLI.MBBMap[SrcBB]->isLandingPad())
352 FLI.CatchInfoFound.insert(EHSel);