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 "llvm/ADT/PostOrderIterator.h"
17 #include "llvm/CodeGen/FunctionLoweringInfo.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/Analysis/DebugInfo.h"
25 #include "llvm/CodeGen/Analysis.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineModuleInfo.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
32 #include "llvm/Target/TargetData.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"
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.
45 static 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();
52 if (cast<Instruction>(U)->getParent() != BB || isa<PHINode>(U))
58 FunctionLoweringInfo::FunctionLoweringInfo(const TargetLowering &tli)
62 void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf) {
65 RegInfo = &MF->getRegInfo();
67 // Check whether the function can return without sret-demotion.
68 SmallVector<ISD::OutputArg, 4> Outs;
69 GetReturnInfo(Fn->getReturnType(),
70 Fn->getAttributes().getRetAttributes(), Outs, TLI);
71 CanLowerReturn = TLI.CanLowerReturn(Fn->getCallingConv(), *MF,
73 Outs, Fn->getContext());
75 // Initialize the mapping of values to registers. This is only set up for
76 // instruction values that are used outside of the block that defines
78 Function::const_iterator BB = Fn->begin(), EB = Fn->end();
79 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
80 if (const AllocaInst *AI = dyn_cast<AllocaInst>(I))
81 if (const ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
82 Type *Ty = AI->getAllocatedType();
83 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
85 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
88 TySize *= CUI->getZExtValue(); // Get total allocated size.
89 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
91 // The object may need to be placed onto the stack near the stack
92 // protector if one exists. Determine here if this object is a suitable
93 // candidate. I.e., it would trigger the creation of a stack protector.
95 (AI->isArrayAllocation() ||
96 (TySize >= 8 && isa<ArrayType>(Ty) &&
97 cast<ArrayType>(Ty)->getElementType()->isIntegerTy(8)));
99 MF->getFrameInfo()->CreateStackObject(TySize, Align, false, MayNeedSP);
102 for (; BB != EB; ++BB)
103 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
104 // Mark values used outside their block as exported, by allocating
105 // a virtual register for them.
106 if (isUsedOutsideOfDefiningBlock(I))
107 if (!isa<AllocaInst>(I) ||
108 !StaticAllocaMap.count(cast<AllocaInst>(I)))
109 InitializeRegForValue(I);
111 // Collect llvm.dbg.declare information. This is done now instead of
112 // during the initial isel pass through the IR so that it is done
113 // in a predictable order.
114 if (const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(I)) {
115 MachineModuleInfo &MMI = MF->getMMI();
116 if (MMI.hasDebugInfo() &&
117 DIVariable(DI->getVariable()).Verify() &&
118 !DI->getDebugLoc().isUnknown()) {
119 // Don't handle byval struct arguments or VLAs, for example.
120 // Non-byval arguments are handled here (they refer to the stack
121 // temporary alloca at this point).
122 const Value *Address = DI->getAddress();
124 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
125 Address = BCI->getOperand(0);
126 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
127 DenseMap<const AllocaInst *, int>::iterator SI =
128 StaticAllocaMap.find(AI);
129 if (SI != StaticAllocaMap.end()) { // Check for VLAs.
131 MMI.setVariableDbgInfo(DI->getVariable(),
132 FI, DI->getDebugLoc());
140 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
141 // also creates the initial PHI MachineInstrs, though none of the input
142 // operands are populated.
143 for (BB = Fn->begin(); BB != EB; ++BB) {
144 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
148 // Transfer the address-taken flag. This is necessary because there could
149 // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
150 // the first one should be marked.
151 if (BB->hasAddressTaken())
152 MBB->setHasAddressTaken();
154 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
156 for (BasicBlock::const_iterator I = BB->begin();
157 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
158 if (PN->use_empty()) continue;
161 if (PN->getType()->isEmptyTy())
164 DebugLoc DL = PN->getDebugLoc();
165 unsigned PHIReg = ValueMap[PN];
166 assert(PHIReg && "PHI node does not have an assigned virtual register!");
168 SmallVector<EVT, 4> ValueVTs;
169 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
170 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
171 EVT VT = ValueVTs[vti];
172 unsigned NumRegisters = TLI.getNumRegisters(Fn->getContext(), VT);
173 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
174 for (unsigned i = 0; i != NumRegisters; ++i)
175 BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i);
176 PHIReg += NumRegisters;
181 // Mark landing pad blocks.
182 for (BB = Fn->begin(); BB != EB; ++BB)
183 if (const InvokeInst *Invoke = dyn_cast<InvokeInst>(BB->getTerminator()))
184 MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
187 /// clear - Clear out all the function-specific state. This returns this
188 /// FunctionLoweringInfo to an empty state, ready to be used for a
189 /// different function.
190 void FunctionLoweringInfo::clear() {
191 assert(CatchInfoFound.size() == CatchInfoLost.size() &&
192 "Not all catch info was assigned to a landing pad!");
196 StaticAllocaMap.clear();
198 CatchInfoLost.clear();
199 CatchInfoFound.clear();
201 LiveOutRegInfo.clear();
203 ArgDbgValues.clear();
204 ByValArgFrameIndexMap.clear();
208 /// CreateReg - Allocate a single virtual register for the given type.
209 unsigned FunctionLoweringInfo::CreateReg(EVT VT) {
210 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
213 /// CreateRegs - Allocate the appropriate number of virtual registers of
214 /// the correctly promoted or expanded types. Assign these registers
215 /// consecutive vreg numbers and return the first assigned number.
217 /// In the case that the given value has struct or array type, this function
218 /// will assign registers for each member or element.
220 unsigned FunctionLoweringInfo::CreateRegs(Type *Ty) {
221 SmallVector<EVT, 4> ValueVTs;
222 ComputeValueVTs(TLI, Ty, ValueVTs);
224 unsigned FirstReg = 0;
225 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
226 EVT ValueVT = ValueVTs[Value];
227 EVT RegisterVT = TLI.getRegisterType(Ty->getContext(), ValueVT);
229 unsigned NumRegs = TLI.getNumRegisters(Ty->getContext(), ValueVT);
230 for (unsigned i = 0; i != NumRegs; ++i) {
231 unsigned R = CreateReg(RegisterVT);
232 if (!FirstReg) FirstReg = R;
238 /// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the
239 /// register is a PHI destination and the PHI's LiveOutInfo is not valid. If
240 /// the register's LiveOutInfo is for a smaller bit width, it is extended to
241 /// the larger bit width by zero extension. The bit width must be no smaller
242 /// than the LiveOutInfo's existing bit width.
243 const FunctionLoweringInfo::LiveOutInfo *
244 FunctionLoweringInfo::GetLiveOutRegInfo(unsigned Reg, unsigned BitWidth) {
245 if (!LiveOutRegInfo.inBounds(Reg))
248 LiveOutInfo *LOI = &LiveOutRegInfo[Reg];
252 if (BitWidth > LOI->KnownZero.getBitWidth()) {
253 LOI->NumSignBits = 1;
254 LOI->KnownZero = LOI->KnownZero.zextOrTrunc(BitWidth);
255 LOI->KnownOne = LOI->KnownOne.zextOrTrunc(BitWidth);
261 /// ComputePHILiveOutRegInfo - Compute LiveOutInfo for a PHI's destination
262 /// register based on the LiveOutInfo of its operands.
263 void FunctionLoweringInfo::ComputePHILiveOutRegInfo(const PHINode *PN) {
264 Type *Ty = PN->getType();
265 if (!Ty->isIntegerTy() || Ty->isVectorTy())
268 SmallVector<EVT, 1> ValueVTs;
269 ComputeValueVTs(TLI, Ty, ValueVTs);
270 assert(ValueVTs.size() == 1 &&
271 "PHIs with non-vector integer types should have a single VT.");
272 EVT IntVT = ValueVTs[0];
274 if (TLI.getNumRegisters(PN->getContext(), IntVT) != 1)
276 IntVT = TLI.getTypeToTransformTo(PN->getContext(), IntVT);
277 unsigned BitWidth = IntVT.getSizeInBits();
279 unsigned DestReg = ValueMap[PN];
280 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
282 LiveOutRegInfo.grow(DestReg);
283 LiveOutInfo &DestLOI = LiveOutRegInfo[DestReg];
285 Value *V = PN->getIncomingValue(0);
286 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
287 DestLOI.NumSignBits = 1;
288 APInt Zero(BitWidth, 0);
289 DestLOI.KnownZero = Zero;
290 DestLOI.KnownOne = Zero;
294 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
295 APInt Val = CI->getValue().zextOrTrunc(BitWidth);
296 DestLOI.NumSignBits = Val.getNumSignBits();
297 DestLOI.KnownZero = ~Val;
298 DestLOI.KnownOne = Val;
300 assert(ValueMap.count(V) && "V should have been placed in ValueMap when its"
301 "CopyToReg node was created.");
302 unsigned SrcReg = ValueMap[V];
303 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
304 DestLOI.IsValid = false;
307 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
309 DestLOI.IsValid = false;
315 assert(DestLOI.KnownZero.getBitWidth() == BitWidth &&
316 DestLOI.KnownOne.getBitWidth() == BitWidth &&
317 "Masks should have the same bit width as the type.");
319 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
320 Value *V = PN->getIncomingValue(i);
321 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
322 DestLOI.NumSignBits = 1;
323 APInt Zero(BitWidth, 0);
324 DestLOI.KnownZero = Zero;
325 DestLOI.KnownOne = Zero;
329 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
330 APInt Val = CI->getValue().zextOrTrunc(BitWidth);
331 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, Val.getNumSignBits());
332 DestLOI.KnownZero &= ~Val;
333 DestLOI.KnownOne &= Val;
337 assert(ValueMap.count(V) && "V should have been placed in ValueMap when "
338 "its CopyToReg node was created.");
339 unsigned SrcReg = ValueMap[V];
340 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
341 DestLOI.IsValid = false;
344 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
346 DestLOI.IsValid = false;
349 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, SrcLOI->NumSignBits);
350 DestLOI.KnownZero &= SrcLOI->KnownZero;
351 DestLOI.KnownOne &= SrcLOI->KnownOne;
355 /// setArgumentFrameIndex - Record frame index for the byval
356 /// argument. This overrides previous frame index entry for this argument,
358 void FunctionLoweringInfo::setArgumentFrameIndex(const Argument *A,
360 ByValArgFrameIndexMap[A] = FI;
363 /// getArgumentFrameIndex - Get frame index for the byval argument.
364 /// If the argument does not have any assigned frame index then 0 is
366 int FunctionLoweringInfo::getArgumentFrameIndex(const Argument *A) {
367 DenseMap<const Argument *, int>::iterator I =
368 ByValArgFrameIndexMap.find(A);
369 if (I != ByValArgFrameIndexMap.end())
371 DEBUG(dbgs() << "Argument does not have assigned frame index!");
375 /// ComputeUsesVAFloatArgument - Determine if any floating-point values are
376 /// being passed to this variadic function, and set the MachineModuleInfo's
377 /// usesVAFloatArgument flag if so. This flag is used to emit an undefined
378 /// reference to _fltused on Windows, which will link in MSVCRT's
379 /// floating-point support.
380 void llvm::ComputeUsesVAFloatArgument(const CallInst &I,
381 MachineModuleInfo *MMI)
383 FunctionType *FT = cast<FunctionType>(
384 I.getCalledValue()->getType()->getContainedType(0));
385 if (FT->isVarArg() && !MMI->usesVAFloatArgument()) {
386 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
387 Type* T = I.getArgOperand(i)->getType();
388 for (po_iterator<Type*> i = po_begin(T), e = po_end(T);
390 if (i->isFloatingPointTy()) {
391 MMI->setUsesVAFloatArgument(true);
399 /// AddCatchInfo - Extract the personality and type infos from an eh.selector
400 /// call, and add them to the specified machine basic block.
401 void llvm::AddCatchInfo(const CallInst &I, MachineModuleInfo *MMI,
402 MachineBasicBlock *MBB) {
403 // Inform the MachineModuleInfo of the personality for this landing pad.
404 const ConstantExpr *CE = cast<ConstantExpr>(I.getArgOperand(1));
405 assert(CE->getOpcode() == Instruction::BitCast &&
406 isa<Function>(CE->getOperand(0)) &&
407 "Personality should be a function");
408 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
410 // Gather all the type infos for this landing pad and pass them along to
411 // MachineModuleInfo.
412 std::vector<const GlobalVariable *> TyInfo;
413 unsigned N = I.getNumArgOperands();
415 for (unsigned i = N - 1; i > 1; --i) {
416 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(i))) {
417 unsigned FilterLength = CI->getZExtValue();
418 unsigned FirstCatch = i + FilterLength + !FilterLength;
419 assert(FirstCatch <= N && "Invalid filter length");
421 if (FirstCatch < N) {
422 TyInfo.reserve(N - FirstCatch);
423 for (unsigned j = FirstCatch; j < N; ++j)
424 TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
425 MMI->addCatchTypeInfo(MBB, TyInfo);
431 MMI->addCleanup(MBB);
434 TyInfo.reserve(FilterLength - 1);
435 for (unsigned j = i + 1; j < FirstCatch; ++j)
436 TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
437 MMI->addFilterTypeInfo(MBB, TyInfo);
446 TyInfo.reserve(N - 2);
447 for (unsigned j = 2; j < N; ++j)
448 TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
449 MMI->addCatchTypeInfo(MBB, TyInfo);
453 /// AddLandingPadInfo - Extract the exception handling information from the
454 /// landingpad instruction and add them to the specified machine module info.
455 void llvm::AddLandingPadInfo(const LandingPadInst &I, MachineModuleInfo &MMI,
456 MachineBasicBlock *MBB) {
457 MMI.addPersonality(MBB,
458 cast<Function>(I.getPersonalityFn()->stripPointerCasts()));
463 // FIXME: New EH - Add the clauses in reverse order. This isn't 100% correct,
464 // but we need to do it this way because of how the DWARF EH emitter
465 // processes the clauses.
466 for (unsigned i = I.getNumClauses(); i != 0; --i) {
467 Value *Val = I.getClause(i - 1);
468 if (I.isCatch(i - 1)) {
469 MMI.addCatchTypeInfo(MBB,
470 dyn_cast<GlobalVariable>(Val->stripPointerCasts()));
472 // Add filters in a list.
473 Constant *CVal = cast<Constant>(Val);
474 SmallVector<const GlobalVariable*, 4> FilterList;
475 for (User::op_iterator
476 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II)
477 FilterList.push_back(cast<GlobalVariable>((*II)->stripPointerCasts()));
479 MMI.addFilterTypeInfo(MBB, FilterList);