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 #include "llvm/CodeGen/FunctionLoweringInfo.h"
16 #include "llvm/ADT/PostOrderIterator.h"
17 #include "llvm/CodeGen/Analysis.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DebugInfo.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/IntrinsicInst.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Target/TargetFrameLowering.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"
39 #include "llvm/Target/TargetSubtargetInfo.h"
43 #define DEBUG_TYPE "function-lowering-info"
45 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
46 /// PHI nodes or outside of the basic block that defines it, or used by a
47 /// switch or atomic instruction, which may expand to multiple basic blocks.
48 static bool isUsedOutsideOfDefiningBlock(const Instruction *I) {
49 if (I->use_empty()) return false;
50 if (isa<PHINode>(I)) return true;
51 const BasicBlock *BB = I->getParent();
52 for (const User *U : I->users())
53 if (cast<Instruction>(U)->getParent() != BB || isa<PHINode>(U))
59 void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf,
61 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
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 (; BB != EB; ++BB)
79 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
81 if (const AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
82 // Static allocas can be folded into the initial stack frame adjustment.
83 if (AI->isStaticAlloca()) {
84 const ConstantInt *CUI = cast<ConstantInt>(AI->getArraySize());
85 Type *Ty = AI->getAllocatedType();
86 uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty);
88 std::max((unsigned)TLI->getDataLayout()->getPrefTypeAlignment(Ty),
91 TySize *= CUI->getZExtValue(); // Get total allocated size.
92 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
95 MF->getFrameInfo()->CreateStackObject(TySize, Align, false, AI);
98 unsigned Align = std::max(
99 (unsigned)TLI->getDataLayout()->getPrefTypeAlignment(
100 AI->getAllocatedType()),
102 unsigned StackAlign =
103 TM.getSubtargetImpl()->getFrameLowering()->getStackAlignment();
104 if (Align <= StackAlign)
106 // Inform the Frame Information that we have variable-sized objects.
107 MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1, AI);
111 // Look for inline asm that clobbers the SP register.
112 if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
113 ImmutableCallSite CS(I);
114 if (isa<InlineAsm>(CS.getCalledValue())) {
115 unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
116 std::vector<TargetLowering::AsmOperandInfo> Ops =
117 TLI->ParseConstraints(CS);
118 for (size_t I = 0, E = Ops.size(); I != E; ++I) {
119 TargetLowering::AsmOperandInfo &Op = Ops[I];
120 if (Op.Type == InlineAsm::isClobber) {
121 // Clobbers don't have SDValue operands, hence SDValue().
122 TLI->ComputeConstraintToUse(Op, SDValue(), DAG);
123 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
124 TLI->getRegForInlineAsmConstraint(Op.ConstraintCode,
126 if (PhysReg.first == SP)
127 MF->getFrameInfo()->setHasInlineAsmWithSPAdjust(true);
133 // Look for calls to the @llvm.va_start intrinsic. We can omit some
134 // prologue boilerplate for variadic functions that don't examine their
136 if (const auto *II = dyn_cast<IntrinsicInst>(I)) {
137 if (II->getIntrinsicID() == Intrinsic::vastart)
138 MF->getFrameInfo()->setHasVAStart(true);
141 // If we have a musttail call in a variadic funciton, we need to ensure we
142 // forward implicit register parameters.
143 if (const auto *CI = dyn_cast<CallInst>(I)) {
144 if (CI->isMustTailCall() && Fn->isVarArg())
145 MF->getFrameInfo()->setHasMustTailInVarArgFunc(true);
148 // Mark values used outside their block as exported, by allocating
149 // a virtual register for them.
150 if (isUsedOutsideOfDefiningBlock(I))
151 if (!isa<AllocaInst>(I) ||
152 !StaticAllocaMap.count(cast<AllocaInst>(I)))
153 InitializeRegForValue(I);
155 // Collect llvm.dbg.declare information. This is done now instead of
156 // during the initial isel pass through the IR so that it is done
157 // in a predictable order.
158 if (const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(I)) {
159 MachineModuleInfo &MMI = MF->getMMI();
160 DIVariable DIVar(DI->getVariable());
161 assert((!DIVar || DIVar.isVariable()) &&
162 "Variable in DbgDeclareInst should be either null or a DIVariable.");
163 if (MMI.hasDebugInfo() &&
165 !DI->getDebugLoc().isUnknown()) {
166 // Don't handle byval struct arguments or VLAs, for example.
167 // Non-byval arguments are handled here (they refer to the stack
168 // temporary alloca at this point).
169 const Value *Address = DI->getAddress();
171 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
172 Address = BCI->getOperand(0);
173 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
174 DenseMap<const AllocaInst *, int>::iterator SI =
175 StaticAllocaMap.find(AI);
176 if (SI != StaticAllocaMap.end()) { // Check for VLAs.
178 MMI.setVariableDbgInfo(DI->getVariable(),
179 FI, DI->getDebugLoc());
187 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
188 // also creates the initial PHI MachineInstrs, though none of the input
189 // operands are populated.
190 for (BB = Fn->begin(); BB != EB; ++BB) {
191 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
195 // Transfer the address-taken flag. This is necessary because there could
196 // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
197 // the first one should be marked.
198 if (BB->hasAddressTaken())
199 MBB->setHasAddressTaken();
201 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
203 for (BasicBlock::const_iterator I = BB->begin();
204 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
205 if (PN->use_empty()) continue;
208 if (PN->getType()->isEmptyTy())
211 DebugLoc DL = PN->getDebugLoc();
212 unsigned PHIReg = ValueMap[PN];
213 assert(PHIReg && "PHI node does not have an assigned virtual register!");
215 SmallVector<EVT, 4> ValueVTs;
216 ComputeValueVTs(*TLI, PN->getType(), ValueVTs);
217 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
218 EVT VT = ValueVTs[vti];
219 unsigned NumRegisters = TLI->getNumRegisters(Fn->getContext(), VT);
220 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
221 for (unsigned i = 0; i != NumRegisters; ++i)
222 BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i);
223 PHIReg += NumRegisters;
228 // Mark landing pad blocks.
229 for (BB = Fn->begin(); BB != EB; ++BB)
230 if (const InvokeInst *Invoke = dyn_cast<InvokeInst>(BB->getTerminator()))
231 MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
234 /// clear - Clear out all the function-specific state. This returns this
235 /// FunctionLoweringInfo to an empty state, ready to be used for a
236 /// different function.
237 void FunctionLoweringInfo::clear() {
238 assert(CatchInfoFound.size() == CatchInfoLost.size() &&
239 "Not all catch info was assigned to a landing pad!");
243 StaticAllocaMap.clear();
245 CatchInfoLost.clear();
246 CatchInfoFound.clear();
248 LiveOutRegInfo.clear();
250 ArgDbgValues.clear();
251 ByValArgFrameIndexMap.clear();
255 /// CreateReg - Allocate a single virtual register for the given type.
256 unsigned FunctionLoweringInfo::CreateReg(MVT VT) {
257 return RegInfo->createVirtualRegister(
258 TM.getSubtargetImpl()->getTargetLowering()->getRegClassFor(VT));
261 /// CreateRegs - Allocate the appropriate number of virtual registers of
262 /// the correctly promoted or expanded types. Assign these registers
263 /// consecutive vreg numbers and return the first assigned number.
265 /// In the case that the given value has struct or array type, this function
266 /// will assign registers for each member or element.
268 unsigned FunctionLoweringInfo::CreateRegs(Type *Ty) {
269 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
271 SmallVector<EVT, 4> ValueVTs;
272 ComputeValueVTs(*TLI, Ty, ValueVTs);
274 unsigned FirstReg = 0;
275 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
276 EVT ValueVT = ValueVTs[Value];
277 MVT RegisterVT = TLI->getRegisterType(Ty->getContext(), ValueVT);
279 unsigned NumRegs = TLI->getNumRegisters(Ty->getContext(), ValueVT);
280 for (unsigned i = 0; i != NumRegs; ++i) {
281 unsigned R = CreateReg(RegisterVT);
282 if (!FirstReg) FirstReg = R;
288 /// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the
289 /// register is a PHI destination and the PHI's LiveOutInfo is not valid. If
290 /// the register's LiveOutInfo is for a smaller bit width, it is extended to
291 /// the larger bit width by zero extension. The bit width must be no smaller
292 /// than the LiveOutInfo's existing bit width.
293 const FunctionLoweringInfo::LiveOutInfo *
294 FunctionLoweringInfo::GetLiveOutRegInfo(unsigned Reg, unsigned BitWidth) {
295 if (!LiveOutRegInfo.inBounds(Reg))
298 LiveOutInfo *LOI = &LiveOutRegInfo[Reg];
302 if (BitWidth > LOI->KnownZero.getBitWidth()) {
303 LOI->NumSignBits = 1;
304 LOI->KnownZero = LOI->KnownZero.zextOrTrunc(BitWidth);
305 LOI->KnownOne = LOI->KnownOne.zextOrTrunc(BitWidth);
311 /// ComputePHILiveOutRegInfo - Compute LiveOutInfo for a PHI's destination
312 /// register based on the LiveOutInfo of its operands.
313 void FunctionLoweringInfo::ComputePHILiveOutRegInfo(const PHINode *PN) {
314 Type *Ty = PN->getType();
315 if (!Ty->isIntegerTy() || Ty->isVectorTy())
318 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
320 SmallVector<EVT, 1> ValueVTs;
321 ComputeValueVTs(*TLI, Ty, ValueVTs);
322 assert(ValueVTs.size() == 1 &&
323 "PHIs with non-vector integer types should have a single VT.");
324 EVT IntVT = ValueVTs[0];
326 if (TLI->getNumRegisters(PN->getContext(), IntVT) != 1)
328 IntVT = TLI->getTypeToTransformTo(PN->getContext(), IntVT);
329 unsigned BitWidth = IntVT.getSizeInBits();
331 unsigned DestReg = ValueMap[PN];
332 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
334 LiveOutRegInfo.grow(DestReg);
335 LiveOutInfo &DestLOI = LiveOutRegInfo[DestReg];
337 Value *V = PN->getIncomingValue(0);
338 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
339 DestLOI.NumSignBits = 1;
340 APInt Zero(BitWidth, 0);
341 DestLOI.KnownZero = Zero;
342 DestLOI.KnownOne = Zero;
346 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
347 APInt Val = CI->getValue().zextOrTrunc(BitWidth);
348 DestLOI.NumSignBits = Val.getNumSignBits();
349 DestLOI.KnownZero = ~Val;
350 DestLOI.KnownOne = Val;
352 assert(ValueMap.count(V) && "V should have been placed in ValueMap when its"
353 "CopyToReg node was created.");
354 unsigned SrcReg = ValueMap[V];
355 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
356 DestLOI.IsValid = false;
359 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
361 DestLOI.IsValid = false;
367 assert(DestLOI.KnownZero.getBitWidth() == BitWidth &&
368 DestLOI.KnownOne.getBitWidth() == BitWidth &&
369 "Masks should have the same bit width as the type.");
371 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
372 Value *V = PN->getIncomingValue(i);
373 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
374 DestLOI.NumSignBits = 1;
375 APInt Zero(BitWidth, 0);
376 DestLOI.KnownZero = Zero;
377 DestLOI.KnownOne = Zero;
381 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
382 APInt Val = CI->getValue().zextOrTrunc(BitWidth);
383 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, Val.getNumSignBits());
384 DestLOI.KnownZero &= ~Val;
385 DestLOI.KnownOne &= Val;
389 assert(ValueMap.count(V) && "V should have been placed in ValueMap when "
390 "its CopyToReg node was created.");
391 unsigned SrcReg = ValueMap[V];
392 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
393 DestLOI.IsValid = false;
396 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
398 DestLOI.IsValid = false;
401 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, SrcLOI->NumSignBits);
402 DestLOI.KnownZero &= SrcLOI->KnownZero;
403 DestLOI.KnownOne &= SrcLOI->KnownOne;
407 /// setArgumentFrameIndex - Record frame index for the byval
408 /// argument. This overrides previous frame index entry for this argument,
410 void FunctionLoweringInfo::setArgumentFrameIndex(const Argument *A,
412 ByValArgFrameIndexMap[A] = FI;
415 /// getArgumentFrameIndex - Get frame index for the byval argument.
416 /// If the argument does not have any assigned frame index then 0 is
418 int FunctionLoweringInfo::getArgumentFrameIndex(const Argument *A) {
419 DenseMap<const Argument *, int>::iterator I =
420 ByValArgFrameIndexMap.find(A);
421 if (I != ByValArgFrameIndexMap.end())
423 DEBUG(dbgs() << "Argument does not have assigned frame index!\n");
427 /// ComputeUsesVAFloatArgument - Determine if any floating-point values are
428 /// being passed to this variadic function, and set the MachineModuleInfo's
429 /// usesVAFloatArgument flag if so. This flag is used to emit an undefined
430 /// reference to _fltused on Windows, which will link in MSVCRT's
431 /// floating-point support.
432 void llvm::ComputeUsesVAFloatArgument(const CallInst &I,
433 MachineModuleInfo *MMI)
435 FunctionType *FT = cast<FunctionType>(
436 I.getCalledValue()->getType()->getContainedType(0));
437 if (FT->isVarArg() && !MMI->usesVAFloatArgument()) {
438 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
439 Type* T = I.getArgOperand(i)->getType();
440 for (po_iterator<Type*> i = po_begin(T), e = po_end(T);
442 if (i->isFloatingPointTy()) {
443 MMI->setUsesVAFloatArgument(true);
451 /// AddCatchInfo - Extract the personality and type infos from an eh.selector
452 /// call, and add them to the specified machine basic block.
453 void llvm::AddCatchInfo(const CallInst &I, MachineModuleInfo *MMI,
454 MachineBasicBlock *MBB) {
455 // Inform the MachineModuleInfo of the personality for this landing pad.
456 const ConstantExpr *CE = cast<ConstantExpr>(I.getArgOperand(1));
457 assert(CE->getOpcode() == Instruction::BitCast &&
458 isa<Function>(CE->getOperand(0)) &&
459 "Personality should be a function");
460 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
462 // Gather all the type infos for this landing pad and pass them along to
463 // MachineModuleInfo.
464 std::vector<const GlobalVariable *> TyInfo;
465 unsigned N = I.getNumArgOperands();
467 for (unsigned i = N - 1; i > 1; --i) {
468 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(i))) {
469 unsigned FilterLength = CI->getZExtValue();
470 unsigned FirstCatch = i + FilterLength + !FilterLength;
471 assert(FirstCatch <= N && "Invalid filter length");
473 if (FirstCatch < N) {
474 TyInfo.reserve(N - FirstCatch);
475 for (unsigned j = FirstCatch; j < N; ++j)
476 TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
477 MMI->addCatchTypeInfo(MBB, TyInfo);
483 MMI->addCleanup(MBB);
486 TyInfo.reserve(FilterLength - 1);
487 for (unsigned j = i + 1; j < FirstCatch; ++j)
488 TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
489 MMI->addFilterTypeInfo(MBB, TyInfo);
498 TyInfo.reserve(N - 2);
499 for (unsigned j = 2; j < N; ++j)
500 TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
501 MMI->addCatchTypeInfo(MBB, TyInfo);
505 /// AddLandingPadInfo - Extract the exception handling information from the
506 /// landingpad instruction and add them to the specified machine module info.
507 void llvm::AddLandingPadInfo(const LandingPadInst &I, MachineModuleInfo &MMI,
508 MachineBasicBlock *MBB) {
509 MMI.addPersonality(MBB,
510 cast<Function>(I.getPersonalityFn()->stripPointerCasts()));
515 // FIXME: New EH - Add the clauses in reverse order. This isn't 100% correct,
516 // but we need to do it this way because of how the DWARF EH emitter
517 // processes the clauses.
518 for (unsigned i = I.getNumClauses(); i != 0; --i) {
519 Value *Val = I.getClause(i - 1);
520 if (I.isCatch(i - 1)) {
521 MMI.addCatchTypeInfo(MBB,
522 dyn_cast<GlobalVariable>(Val->stripPointerCasts()));
524 // Add filters in a list.
525 Constant *CVal = cast<Constant>(Val);
526 SmallVector<const GlobalVariable*, 4> FilterList;
527 for (User::op_iterator
528 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II)
529 FilterList.push_back(cast<GlobalVariable>((*II)->stripPointerCasts()));
531 MMI.addFilterTypeInfo(MBB, FilterList);