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/CodeGen/Analysis.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/CodeGen/MachineModuleInfo.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/WinEHFuncInfo.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/Support/raw_ostream.h"
35 #include "llvm/Target/TargetFrameLowering.h"
36 #include "llvm/Target/TargetInstrInfo.h"
37 #include "llvm/Target/TargetLowering.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/Target/TargetRegisterInfo.h"
40 #include "llvm/Target/TargetSubtargetInfo.h"
44 #define DEBUG_TYPE "function-lowering-info"
46 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
47 /// PHI nodes or outside of the basic block that defines it, or used by a
48 /// switch or atomic instruction, which may expand to multiple basic blocks.
49 static bool isUsedOutsideOfDefiningBlock(const Instruction *I) {
50 if (I->use_empty()) return false;
51 if (isa<PHINode>(I)) return true;
52 const BasicBlock *BB = I->getParent();
53 for (const User *U : I->users())
54 if (cast<Instruction>(U)->getParent() != BB || isa<PHINode>(U))
60 static ISD::NodeType getPreferredExtendForValue(const Value *V) {
61 // For the users of the source value being used for compare instruction, if
62 // the number of signed predicate is greater than unsigned predicate, we
63 // prefer to use SIGN_EXTEND.
65 // With this optimization, we would be able to reduce some redundant sign or
66 // zero extension instruction, and eventually more machine CSE opportunities
68 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
69 unsigned NumOfSigned = 0, NumOfUnsigned = 0;
70 for (const User *U : V->users()) {
71 if (const auto *CI = dyn_cast<CmpInst>(U)) {
72 NumOfSigned += CI->isSigned();
73 NumOfUnsigned += CI->isUnsigned();
76 if (NumOfSigned > NumOfUnsigned)
77 ExtendKind = ISD::SIGN_EXTEND;
82 void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf,
86 TLI = MF->getSubtarget().getTargetLowering();
87 RegInfo = &MF->getRegInfo();
88 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
89 unsigned StackAlign = TFI->getStackAlignment();
91 // Check whether the function can return without sret-demotion.
92 SmallVector<ISD::OutputArg, 4> Outs;
93 GetReturnInfo(Fn->getReturnType(), Fn->getAttributes(), Outs, *TLI,
95 CanLowerReturn = TLI->CanLowerReturn(Fn->getCallingConv(), *MF,
96 Fn->isVarArg(), Outs, Fn->getContext());
98 // If this personality uses funclets, we need to do a bit more work.
99 DenseMap<const AllocaInst *, TinyPtrVector<int *>> CatchObjects;
100 EHPersonality Personality = classifyEHPersonality(
101 Fn->hasPersonalityFn() ? Fn->getPersonalityFn() : nullptr);
102 if (isFuncletEHPersonality(Personality)) {
103 // Calculate state numbers if we haven't already.
104 WinEHFuncInfo &EHInfo = *MF->getWinEHFuncInfo();
105 if (Personality == EHPersonality::MSVC_CXX)
106 calculateWinCXXEHStateNumbers(&fn, EHInfo);
107 else if (isAsynchronousEHPersonality(Personality))
108 calculateSEHStateNumbers(&fn, EHInfo);
109 else if (Personality == EHPersonality::CoreCLR)
110 calculateClrEHStateNumbers(&fn, EHInfo);
112 // Map all BB references in the WinEH data to MBBs.
113 for (WinEHTryBlockMapEntry &TBME : EHInfo.TryBlockMap) {
114 for (WinEHHandlerType &H : TBME.HandlerArray) {
115 if (const AllocaInst *AI = H.CatchObj.Alloca)
116 CatchObjects.insert({AI, {}}).first->second.push_back(
117 &H.CatchObj.FrameIndex);
119 H.CatchObj.FrameIndex = INT_MAX;
124 // Initialize the mapping of values to registers. This is only set up for
125 // instruction values that are used outside of the block that defines
127 for (const BasicBlock &BB : *Fn) {
128 for (const Instruction &I : BB) {
129 if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
130 Type *Ty = AI->getAllocatedType();
132 std::max((unsigned)MF->getDataLayout().getPrefTypeAlignment(Ty),
135 // Static allocas can be folded into the initial stack frame
136 // adjustment. For targets that don't realign the stack, don't
137 // do this if there is an extra alignment requirement.
138 if (AI->isStaticAlloca() &&
139 (TFI->isStackRealignable() || (Align <= StackAlign))) {
140 const ConstantInt *CUI = cast<ConstantInt>(AI->getArraySize());
141 uint64_t TySize = MF->getDataLayout().getTypeAllocSize(Ty);
143 TySize *= CUI->getZExtValue(); // Get total allocated size.
144 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
145 int FrameIndex = INT_MAX;
146 auto Iter = CatchObjects.find(AI);
147 if (Iter != CatchObjects.end() && TLI->needsFixedCatchObjects()) {
148 FrameIndex = MF->getFrameInfo().CreateFixedObject(
149 TySize, 0, /*Immutable=*/false, /*isAliased=*/true);
150 MF->getFrameInfo().setObjectAlignment(FrameIndex, Align);
153 MF->getFrameInfo().CreateStackObject(TySize, Align, false, AI);
156 StaticAllocaMap[AI] = FrameIndex;
157 // Update the catch handler information.
158 if (Iter != CatchObjects.end()) {
159 for (int *CatchObjPtr : Iter->second)
160 *CatchObjPtr = FrameIndex;
163 // FIXME: Overaligned static allocas should be grouped into
164 // a single dynamic allocation instead of using a separate
165 // stack allocation for each one.
166 if (Align <= StackAlign)
168 // Inform the Frame Information that we have variable-sized objects.
169 MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, AI);
173 // Look for inline asm that clobbers the SP register.
174 if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
175 ImmutableCallSite CS(&I);
176 if (isa<InlineAsm>(CS.getCalledValue())) {
177 unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
178 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
179 std::vector<TargetLowering::AsmOperandInfo> Ops =
180 TLI->ParseConstraints(Fn->getParent()->getDataLayout(), TRI, CS);
181 for (TargetLowering::AsmOperandInfo &Op : Ops) {
182 if (Op.Type == InlineAsm::isClobber) {
183 // Clobbers don't have SDValue operands, hence SDValue().
184 TLI->ComputeConstraintToUse(Op, SDValue(), DAG);
185 std::pair<unsigned, const TargetRegisterClass *> PhysReg =
186 TLI->getRegForInlineAsmConstraint(TRI, Op.ConstraintCode,
188 if (PhysReg.first == SP)
189 MF->getFrameInfo().setHasOpaqueSPAdjustment(true);
195 // Look for calls to the @llvm.va_start intrinsic. We can omit some
196 // prologue boilerplate for variadic functions that don't examine their
198 if (const auto *II = dyn_cast<IntrinsicInst>(&I)) {
199 if (II->getIntrinsicID() == Intrinsic::vastart)
200 MF->getFrameInfo().setHasVAStart(true);
203 // If we have a musttail call in a variadic function, we need to ensure we
204 // forward implicit register parameters.
205 if (const auto *CI = dyn_cast<CallInst>(&I)) {
206 if (CI->isMustTailCall() && Fn->isVarArg())
207 MF->getFrameInfo().setHasMustTailInVarArgFunc(true);
210 // Mark values used outside their block as exported, by allocating
211 // a virtual register for them.
212 if (isUsedOutsideOfDefiningBlock(&I))
213 if (!isa<AllocaInst>(I) || !StaticAllocaMap.count(cast<AllocaInst>(&I)))
214 InitializeRegForValue(&I);
216 // Decide the preferred extend type for a value.
217 PreferredExtendType[&I] = getPreferredExtendForValue(&I);
221 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
222 // also creates the initial PHI MachineInstrs, though none of the input
223 // operands are populated.
224 for (const BasicBlock &BB : *Fn) {
225 // Don't create MachineBasicBlocks for imaginary EH pad blocks. These blocks
226 // are really data, and no instructions can live here.
228 const Instruction *PadInst = BB.getFirstNonPHI();
229 // If this is a non-landingpad EH pad, mark this function as using
231 // FIXME: SEH catchpads do not create funclets, so we could avoid setting
232 // this in such cases in order to improve frame layout.
233 if (!isa<LandingPadInst>(PadInst)) {
234 MF->setHasEHFunclets(true);
235 MF->getFrameInfo().setHasOpaqueSPAdjustment(true);
237 if (isa<CatchSwitchInst>(PadInst)) {
238 assert(&*BB.begin() == PadInst &&
239 "WinEHPrepare failed to remove PHIs from imaginary BBs");
242 if (isa<FuncletPadInst>(PadInst))
243 assert(&*BB.begin() == PadInst && "WinEHPrepare failed to demote PHIs");
246 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(&BB);
250 // Transfer the address-taken flag. This is necessary because there could
251 // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
252 // the first one should be marked.
253 if (BB.hasAddressTaken())
254 MBB->setHasAddressTaken();
256 // Mark landing pad blocks.
260 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
262 for (BasicBlock::const_iterator I = BB.begin();
263 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
264 if (PN->use_empty()) continue;
267 if (PN->getType()->isEmptyTy())
270 DebugLoc DL = PN->getDebugLoc();
271 unsigned PHIReg = ValueMap[PN];
272 assert(PHIReg && "PHI node does not have an assigned virtual register!");
274 SmallVector<EVT, 4> ValueVTs;
275 ComputeValueVTs(*TLI, MF->getDataLayout(), PN->getType(), ValueVTs);
276 for (EVT VT : ValueVTs) {
277 unsigned NumRegisters = TLI->getNumRegisters(Fn->getContext(), VT);
278 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
279 for (unsigned i = 0; i != NumRegisters; ++i)
280 BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i);
281 PHIReg += NumRegisters;
286 if (!isFuncletEHPersonality(Personality))
289 WinEHFuncInfo &EHInfo = *MF->getWinEHFuncInfo();
291 // Map all BB references in the WinEH data to MBBs.
292 for (WinEHTryBlockMapEntry &TBME : EHInfo.TryBlockMap) {
293 for (WinEHHandlerType &H : TBME.HandlerArray) {
295 H.Handler = MBBMap[H.Handler.get<const BasicBlock *>()];
298 for (CxxUnwindMapEntry &UME : EHInfo.CxxUnwindMap)
300 UME.Cleanup = MBBMap[UME.Cleanup.get<const BasicBlock *>()];
301 for (SEHUnwindMapEntry &UME : EHInfo.SEHUnwindMap) {
302 const BasicBlock *BB = UME.Handler.get<const BasicBlock *>();
303 UME.Handler = MBBMap[BB];
305 for (ClrEHUnwindMapEntry &CME : EHInfo.ClrEHUnwindMap) {
306 const BasicBlock *BB = CME.Handler.get<const BasicBlock *>();
307 CME.Handler = MBBMap[BB];
311 /// clear - Clear out all the function-specific state. This returns this
312 /// FunctionLoweringInfo to an empty state, ready to be used for a
313 /// different function.
314 void FunctionLoweringInfo::clear() {
317 StaticAllocaMap.clear();
318 LiveOutRegInfo.clear();
320 ArgDbgValues.clear();
321 ByValArgFrameIndexMap.clear();
323 StatepointStackSlots.clear();
324 StatepointSpillMaps.clear();
325 PreferredExtendType.clear();
328 /// CreateReg - Allocate a single virtual register for the given type.
329 unsigned FunctionLoweringInfo::CreateReg(MVT VT) {
330 return RegInfo->createVirtualRegister(
331 MF->getSubtarget().getTargetLowering()->getRegClassFor(VT));
334 /// CreateRegs - Allocate the appropriate number of virtual registers of
335 /// the correctly promoted or expanded types. Assign these registers
336 /// consecutive vreg numbers and return the first assigned number.
338 /// In the case that the given value has struct or array type, this function
339 /// will assign registers for each member or element.
341 unsigned FunctionLoweringInfo::CreateRegs(Type *Ty) {
342 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
344 SmallVector<EVT, 4> ValueVTs;
345 ComputeValueVTs(*TLI, MF->getDataLayout(), Ty, ValueVTs);
347 unsigned FirstReg = 0;
348 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
349 EVT ValueVT = ValueVTs[Value];
350 MVT RegisterVT = TLI->getRegisterType(Ty->getContext(), ValueVT);
352 unsigned NumRegs = TLI->getNumRegisters(Ty->getContext(), ValueVT);
353 for (unsigned i = 0; i != NumRegs; ++i) {
354 unsigned R = CreateReg(RegisterVT);
355 if (!FirstReg) FirstReg = R;
361 /// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the
362 /// register is a PHI destination and the PHI's LiveOutInfo is not valid. If
363 /// the register's LiveOutInfo is for a smaller bit width, it is extended to
364 /// the larger bit width by zero extension. The bit width must be no smaller
365 /// than the LiveOutInfo's existing bit width.
366 const FunctionLoweringInfo::LiveOutInfo *
367 FunctionLoweringInfo::GetLiveOutRegInfo(unsigned Reg, unsigned BitWidth) {
368 if (!LiveOutRegInfo.inBounds(Reg))
371 LiveOutInfo *LOI = &LiveOutRegInfo[Reg];
375 if (BitWidth > LOI->Known.getBitWidth()) {
376 LOI->NumSignBits = 1;
377 LOI->Known = LOI->Known.zextOrTrunc(BitWidth);
383 /// ComputePHILiveOutRegInfo - Compute LiveOutInfo for a PHI's destination
384 /// register based on the LiveOutInfo of its operands.
385 void FunctionLoweringInfo::ComputePHILiveOutRegInfo(const PHINode *PN) {
386 Type *Ty = PN->getType();
387 if (!Ty->isIntegerTy() || Ty->isVectorTy())
390 SmallVector<EVT, 1> ValueVTs;
391 ComputeValueVTs(*TLI, MF->getDataLayout(), Ty, ValueVTs);
392 assert(ValueVTs.size() == 1 &&
393 "PHIs with non-vector integer types should have a single VT.");
394 EVT IntVT = ValueVTs[0];
396 if (TLI->getNumRegisters(PN->getContext(), IntVT) != 1)
398 IntVT = TLI->getTypeToTransformTo(PN->getContext(), IntVT);
399 unsigned BitWidth = IntVT.getSizeInBits();
401 unsigned DestReg = ValueMap[PN];
402 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
404 LiveOutRegInfo.grow(DestReg);
405 LiveOutInfo &DestLOI = LiveOutRegInfo[DestReg];
407 Value *V = PN->getIncomingValue(0);
408 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
409 DestLOI.NumSignBits = 1;
410 DestLOI.Known = KnownBits(BitWidth);
414 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
415 APInt Val = CI->getValue().zextOrTrunc(BitWidth);
416 DestLOI.NumSignBits = Val.getNumSignBits();
417 DestLOI.Known.Zero = ~Val;
418 DestLOI.Known.One = Val;
420 assert(ValueMap.count(V) && "V should have been placed in ValueMap when its"
421 "CopyToReg node was created.");
422 unsigned SrcReg = ValueMap[V];
423 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
424 DestLOI.IsValid = false;
427 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
429 DestLOI.IsValid = false;
435 assert(DestLOI.Known.Zero.getBitWidth() == BitWidth &&
436 DestLOI.Known.One.getBitWidth() == BitWidth &&
437 "Masks should have the same bit width as the type.");
439 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
440 Value *V = PN->getIncomingValue(i);
441 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
442 DestLOI.NumSignBits = 1;
443 DestLOI.Known = KnownBits(BitWidth);
447 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
448 APInt Val = CI->getValue().zextOrTrunc(BitWidth);
449 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, Val.getNumSignBits());
450 DestLOI.Known.Zero &= ~Val;
451 DestLOI.Known.One &= Val;
455 assert(ValueMap.count(V) && "V should have been placed in ValueMap when "
456 "its CopyToReg node was created.");
457 unsigned SrcReg = ValueMap[V];
458 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
459 DestLOI.IsValid = false;
462 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
464 DestLOI.IsValid = false;
467 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, SrcLOI->NumSignBits);
468 DestLOI.Known.Zero &= SrcLOI->Known.Zero;
469 DestLOI.Known.One &= SrcLOI->Known.One;
473 /// setArgumentFrameIndex - Record frame index for the byval
474 /// argument. This overrides previous frame index entry for this argument,
476 void FunctionLoweringInfo::setArgumentFrameIndex(const Argument *A,
478 ByValArgFrameIndexMap[A] = FI;
481 /// getArgumentFrameIndex - Get frame index for the byval argument.
482 /// If the argument does not have any assigned frame index then 0 is
484 int FunctionLoweringInfo::getArgumentFrameIndex(const Argument *A) {
485 auto I = ByValArgFrameIndexMap.find(A);
486 if (I != ByValArgFrameIndexMap.end())
488 DEBUG(dbgs() << "Argument does not have assigned frame index!\n");
492 unsigned FunctionLoweringInfo::getCatchPadExceptionPointerVReg(
493 const Value *CPI, const TargetRegisterClass *RC) {
494 MachineRegisterInfo &MRI = MF->getRegInfo();
495 auto I = CatchPadExceptionPointers.insert({CPI, 0});
496 unsigned &VReg = I.first->second;
498 VReg = MRI.createVirtualRegister(RC);
499 assert(VReg && "null vreg in exception pointer table!");
504 FunctionLoweringInfo::getOrCreateSwiftErrorVReg(const MachineBasicBlock *MBB,
506 auto Key = std::make_pair(MBB, Val);
507 auto It = SwiftErrorVRegDefMap.find(Key);
508 // If this is the first use of this swifterror value in this basic block,
509 // create a new virtual register.
510 // After we processed all basic blocks we will satisfy this "upwards exposed
511 // use" by inserting a copy or phi at the beginning of this block.
512 if (It == SwiftErrorVRegDefMap.end()) {
513 auto &DL = MF->getDataLayout();
514 const TargetRegisterClass *RC = TLI->getRegClassFor(TLI->getPointerTy(DL));
515 auto VReg = MF->getRegInfo().createVirtualRegister(RC);
516 SwiftErrorVRegDefMap[Key] = VReg;
517 SwiftErrorVRegUpwardsUse[Key] = VReg;
519 } else return It->second;
522 void FunctionLoweringInfo::setCurrentSwiftErrorVReg(
523 const MachineBasicBlock *MBB, const Value *Val, unsigned VReg) {
524 SwiftErrorVRegDefMap[std::make_pair(MBB, Val)] = VReg;
527 std::pair<unsigned, bool>
528 FunctionLoweringInfo::getOrCreateSwiftErrorVRegDefAt(const Instruction *I) {
529 auto Key = PointerIntPair<const Instruction *, 1, bool>(I, true);
530 auto It = SwiftErrorVRegDefUses.find(Key);
531 if (It == SwiftErrorVRegDefUses.end()) {
532 auto &DL = MF->getDataLayout();
533 const TargetRegisterClass *RC = TLI->getRegClassFor(TLI->getPointerTy(DL));
534 unsigned VReg = MF->getRegInfo().createVirtualRegister(RC);
535 SwiftErrorVRegDefUses[Key] = VReg;
536 return std::make_pair(VReg, true);
538 return std::make_pair(It->second, false);
541 std::pair<unsigned, bool>
542 FunctionLoweringInfo::getOrCreateSwiftErrorVRegUseAt(const Instruction *I, const MachineBasicBlock *MBB, const Value *Val) {
543 auto Key = PointerIntPair<const Instruction *, 1, bool>(I, false);
544 auto It = SwiftErrorVRegDefUses.find(Key);
545 if (It == SwiftErrorVRegDefUses.end()) {
546 unsigned VReg = getOrCreateSwiftErrorVReg(MBB, Val);
547 SwiftErrorVRegDefUses[Key] = VReg;
548 return std::make_pair(VReg, true);
550 return std::make_pair(It->second, false);