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/CodeGen/FunctionLoweringInfo.h"
17 #include "llvm/ADT/PostOrderIterator.h"
18 #include "llvm/CodeGen/Analysis.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineModuleInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/DebugInfo.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/IntrinsicInst.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Target/TargetInstrInfo.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.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(), Fn->getAttributes(), Outs, TLI);
70 CanLowerReturn = TLI.CanLowerReturn(Fn->getCallingConv(), *MF,
72 Outs, Fn->getContext());
74 // Initialize the mapping of values to registers. This is only set up for
75 // instruction values that are used outside of the block that defines
77 Function::const_iterator BB = Fn->begin(), EB = Fn->end();
78 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
79 if (const AllocaInst *AI = dyn_cast<AllocaInst>(I))
80 if (const ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
81 Type *Ty = AI->getAllocatedType();
82 uint64_t TySize = TLI.getDataLayout()->getTypeAllocSize(Ty);
84 std::max((unsigned)TLI.getDataLayout()->getPrefTypeAlignment(Ty),
87 TySize *= CUI->getZExtValue(); // Get total allocated size.
88 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
90 // The object may need to be placed onto the stack near the stack
91 // protector if one exists. Determine here if this object is a suitable
92 // candidate. I.e., it would trigger the creation of a stack protector.
94 (AI->isArrayAllocation() ||
95 (TySize >= 8 && isa<ArrayType>(Ty) &&
96 cast<ArrayType>(Ty)->getElementType()->isIntegerTy(8)));
98 MF->getFrameInfo()->CreateStackObject(TySize, Align, false,
102 for (; BB != EB; ++BB)
103 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
105 // Mark values used outside their block as exported, by allocating
106 // a virtual register for them.
107 if (isUsedOutsideOfDefiningBlock(I))
108 if (!isa<AllocaInst>(I) ||
109 !StaticAllocaMap.count(cast<AllocaInst>(I)))
110 InitializeRegForValue(I);
112 // Collect llvm.dbg.declare information. This is done now instead of
113 // during the initial isel pass through the IR so that it is done
114 // in a predictable order.
115 if (const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(I)) {
116 MachineModuleInfo &MMI = MF->getMMI();
117 if (MMI.hasDebugInfo() &&
118 DIVariable(DI->getVariable()).Verify() &&
119 !DI->getDebugLoc().isUnknown()) {
120 // Don't handle byval struct arguments or VLAs, for example.
121 // Non-byval arguments are handled here (they refer to the stack
122 // temporary alloca at this point).
123 const Value *Address = DI->getAddress();
125 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
126 Address = BCI->getOperand(0);
127 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
128 DenseMap<const AllocaInst *, int>::iterator SI =
129 StaticAllocaMap.find(AI);
130 if (SI != StaticAllocaMap.end()) { // Check for VLAs.
132 MMI.setVariableDbgInfo(DI->getVariable(),
133 FI, DI->getDebugLoc());
141 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
142 // also creates the initial PHI MachineInstrs, though none of the input
143 // operands are populated.
144 for (BB = Fn->begin(); BB != EB; ++BB) {
145 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
149 // Transfer the address-taken flag. This is necessary because there could
150 // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
151 // the first one should be marked.
152 if (BB->hasAddressTaken())
153 MBB->setHasAddressTaken();
155 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
157 for (BasicBlock::const_iterator I = BB->begin();
158 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
159 if (PN->use_empty()) continue;
162 if (PN->getType()->isEmptyTy())
165 DebugLoc DL = PN->getDebugLoc();
166 unsigned PHIReg = ValueMap[PN];
167 assert(PHIReg && "PHI node does not have an assigned virtual register!");
169 SmallVector<EVT, 4> ValueVTs;
170 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
171 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
172 EVT VT = ValueVTs[vti];
173 unsigned NumRegisters = TLI.getNumRegisters(Fn->getContext(), VT);
174 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
175 for (unsigned i = 0; i != NumRegisters; ++i)
176 BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i);
177 PHIReg += NumRegisters;
182 // Mark landing pad blocks.
183 for (BB = Fn->begin(); BB != EB; ++BB)
184 if (const InvokeInst *Invoke = dyn_cast<InvokeInst>(BB->getTerminator()))
185 MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
188 /// clear - Clear out all the function-specific state. This returns this
189 /// FunctionLoweringInfo to an empty state, ready to be used for a
190 /// different function.
191 void FunctionLoweringInfo::clear() {
192 assert(CatchInfoFound.size() == CatchInfoLost.size() &&
193 "Not all catch info was assigned to a landing pad!");
197 StaticAllocaMap.clear();
199 CatchInfoLost.clear();
200 CatchInfoFound.clear();
202 LiveOutRegInfo.clear();
204 ArgDbgValues.clear();
205 ByValArgFrameIndexMap.clear();
209 /// CreateReg - Allocate a single virtual register for the given type.
210 unsigned FunctionLoweringInfo::CreateReg(MVT VT) {
211 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
214 /// CreateRegs - Allocate the appropriate number of virtual registers of
215 /// the correctly promoted or expanded types. Assign these registers
216 /// consecutive vreg numbers and return the first assigned number.
218 /// In the case that the given value has struct or array type, this function
219 /// will assign registers for each member or element.
221 unsigned FunctionLoweringInfo::CreateRegs(Type *Ty) {
222 SmallVector<EVT, 4> ValueVTs;
223 ComputeValueVTs(TLI, Ty, ValueVTs);
225 unsigned FirstReg = 0;
226 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
227 EVT ValueVT = ValueVTs[Value];
228 MVT RegisterVT = TLI.getRegisterType(Ty->getContext(), ValueVT);
230 unsigned NumRegs = TLI.getNumRegisters(Ty->getContext(), ValueVT);
231 for (unsigned i = 0; i != NumRegs; ++i) {
232 unsigned R = CreateReg(RegisterVT);
233 if (!FirstReg) FirstReg = R;
239 /// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the
240 /// register is a PHI destination and the PHI's LiveOutInfo is not valid. If
241 /// the register's LiveOutInfo is for a smaller bit width, it is extended to
242 /// the larger bit width by zero extension. The bit width must be no smaller
243 /// than the LiveOutInfo's existing bit width.
244 const FunctionLoweringInfo::LiveOutInfo *
245 FunctionLoweringInfo::GetLiveOutRegInfo(unsigned Reg, unsigned BitWidth) {
246 if (!LiveOutRegInfo.inBounds(Reg))
249 LiveOutInfo *LOI = &LiveOutRegInfo[Reg];
253 if (BitWidth > LOI->KnownZero.getBitWidth()) {
254 LOI->NumSignBits = 1;
255 LOI->KnownZero = LOI->KnownZero.zextOrTrunc(BitWidth);
256 LOI->KnownOne = LOI->KnownOne.zextOrTrunc(BitWidth);
262 /// ComputePHILiveOutRegInfo - Compute LiveOutInfo for a PHI's destination
263 /// register based on the LiveOutInfo of its operands.
264 void FunctionLoweringInfo::ComputePHILiveOutRegInfo(const PHINode *PN) {
265 Type *Ty = PN->getType();
266 if (!Ty->isIntegerTy() || Ty->isVectorTy())
269 SmallVector<EVT, 1> ValueVTs;
270 ComputeValueVTs(TLI, Ty, ValueVTs);
271 assert(ValueVTs.size() == 1 &&
272 "PHIs with non-vector integer types should have a single VT.");
273 EVT IntVT = ValueVTs[0];
275 if (TLI.getNumRegisters(PN->getContext(), IntVT) != 1)
277 IntVT = TLI.getTypeToTransformTo(PN->getContext(), IntVT);
278 unsigned BitWidth = IntVT.getSizeInBits();
280 unsigned DestReg = ValueMap[PN];
281 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
283 LiveOutRegInfo.grow(DestReg);
284 LiveOutInfo &DestLOI = LiveOutRegInfo[DestReg];
286 Value *V = PN->getIncomingValue(0);
287 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
288 DestLOI.NumSignBits = 1;
289 APInt Zero(BitWidth, 0);
290 DestLOI.KnownZero = Zero;
291 DestLOI.KnownOne = Zero;
295 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
296 APInt Val = CI->getValue().zextOrTrunc(BitWidth);
297 DestLOI.NumSignBits = Val.getNumSignBits();
298 DestLOI.KnownZero = ~Val;
299 DestLOI.KnownOne = Val;
301 assert(ValueMap.count(V) && "V should have been placed in ValueMap when its"
302 "CopyToReg node was created.");
303 unsigned SrcReg = ValueMap[V];
304 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
305 DestLOI.IsValid = false;
308 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
310 DestLOI.IsValid = false;
316 assert(DestLOI.KnownZero.getBitWidth() == BitWidth &&
317 DestLOI.KnownOne.getBitWidth() == BitWidth &&
318 "Masks should have the same bit width as the type.");
320 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
321 Value *V = PN->getIncomingValue(i);
322 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
323 DestLOI.NumSignBits = 1;
324 APInt Zero(BitWidth, 0);
325 DestLOI.KnownZero = Zero;
326 DestLOI.KnownOne = Zero;
330 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
331 APInt Val = CI->getValue().zextOrTrunc(BitWidth);
332 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, Val.getNumSignBits());
333 DestLOI.KnownZero &= ~Val;
334 DestLOI.KnownOne &= Val;
338 assert(ValueMap.count(V) && "V should have been placed in ValueMap when "
339 "its CopyToReg node was created.");
340 unsigned SrcReg = ValueMap[V];
341 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
342 DestLOI.IsValid = false;
345 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
347 DestLOI.IsValid = false;
350 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, SrcLOI->NumSignBits);
351 DestLOI.KnownZero &= SrcLOI->KnownZero;
352 DestLOI.KnownOne &= SrcLOI->KnownOne;
356 /// setArgumentFrameIndex - Record frame index for the byval
357 /// argument. This overrides previous frame index entry for this argument,
359 void FunctionLoweringInfo::setArgumentFrameIndex(const Argument *A,
361 ByValArgFrameIndexMap[A] = FI;
364 /// getArgumentFrameIndex - Get frame index for the byval argument.
365 /// If the argument does not have any assigned frame index then 0 is
367 int FunctionLoweringInfo::getArgumentFrameIndex(const Argument *A) {
368 DenseMap<const Argument *, int>::iterator I =
369 ByValArgFrameIndexMap.find(A);
370 if (I != ByValArgFrameIndexMap.end())
372 DEBUG(dbgs() << "Argument does not have assigned frame index!\n");
376 /// ComputeUsesVAFloatArgument - Determine if any floating-point values are
377 /// being passed to this variadic function, and set the MachineModuleInfo's
378 /// usesVAFloatArgument flag if so. This flag is used to emit an undefined
379 /// reference to _fltused on Windows, which will link in MSVCRT's
380 /// floating-point support.
381 void llvm::ComputeUsesVAFloatArgument(const CallInst &I,
382 MachineModuleInfo *MMI)
384 FunctionType *FT = cast<FunctionType>(
385 I.getCalledValue()->getType()->getContainedType(0));
386 if (FT->isVarArg() && !MMI->usesVAFloatArgument()) {
387 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
388 Type* T = I.getArgOperand(i)->getType();
389 for (po_iterator<Type*> i = po_begin(T), e = po_end(T);
391 if (i->isFloatingPointTy()) {
392 MMI->setUsesVAFloatArgument(true);
400 /// AddCatchInfo - Extract the personality and type infos from an eh.selector
401 /// call, and add them to the specified machine basic block.
402 void llvm::AddCatchInfo(const CallInst &I, MachineModuleInfo *MMI,
403 MachineBasicBlock *MBB) {
404 // Inform the MachineModuleInfo of the personality for this landing pad.
405 const ConstantExpr *CE = cast<ConstantExpr>(I.getArgOperand(1));
406 assert(CE->getOpcode() == Instruction::BitCast &&
407 isa<Function>(CE->getOperand(0)) &&
408 "Personality should be a function");
409 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
411 // Gather all the type infos for this landing pad and pass them along to
412 // MachineModuleInfo.
413 std::vector<const GlobalVariable *> TyInfo;
414 unsigned N = I.getNumArgOperands();
416 for (unsigned i = N - 1; i > 1; --i) {
417 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(i))) {
418 unsigned FilterLength = CI->getZExtValue();
419 unsigned FirstCatch = i + FilterLength + !FilterLength;
420 assert(FirstCatch <= N && "Invalid filter length");
422 if (FirstCatch < N) {
423 TyInfo.reserve(N - FirstCatch);
424 for (unsigned j = FirstCatch; j < N; ++j)
425 TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
426 MMI->addCatchTypeInfo(MBB, TyInfo);
432 MMI->addCleanup(MBB);
435 TyInfo.reserve(FilterLength - 1);
436 for (unsigned j = i + 1; j < FirstCatch; ++j)
437 TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
438 MMI->addFilterTypeInfo(MBB, TyInfo);
447 TyInfo.reserve(N - 2);
448 for (unsigned j = 2; j < N; ++j)
449 TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
450 MMI->addCatchTypeInfo(MBB, TyInfo);
454 /// AddLandingPadInfo - Extract the exception handling information from the
455 /// landingpad instruction and add them to the specified machine module info.
456 void llvm::AddLandingPadInfo(const LandingPadInst &I, MachineModuleInfo &MMI,
457 MachineBasicBlock *MBB) {
458 MMI.addPersonality(MBB,
459 cast<Function>(I.getPersonalityFn()->stripPointerCasts()));
464 // FIXME: New EH - Add the clauses in reverse order. This isn't 100% correct,
465 // but we need to do it this way because of how the DWARF EH emitter
466 // processes the clauses.
467 for (unsigned i = I.getNumClauses(); i != 0; --i) {
468 Value *Val = I.getClause(i - 1);
469 if (I.isCatch(i - 1)) {
470 MMI.addCatchTypeInfo(MBB,
471 dyn_cast<GlobalVariable>(Val->stripPointerCasts()));
473 // Add filters in a list.
474 Constant *CVal = cast<Constant>(Val);
475 SmallVector<const GlobalVariable*, 4> FilterList;
476 for (User::op_iterator
477 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II)
478 FilterList.push_back(cast<GlobalVariable>((*II)->stripPointerCasts()));
480 MMI.addFilterTypeInfo(MBB, FilterList);