1 //===-- FunctionLoweringInfo.cpp ------------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This implements routines for translating functions from LLVM IR into
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/FunctionLoweringInfo.h"
15 #include "llvm/Analysis/LegacyDivergenceAnalysis.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/MachineRegisterInfo.h"
21 #include "llvm/CodeGen/TargetFrameLowering.h"
22 #include "llvm/CodeGen/TargetInstrInfo.h"
23 #include "llvm/CodeGen/TargetLowering.h"
24 #include "llvm/CodeGen/TargetRegisterInfo.h"
25 #include "llvm/CodeGen/TargetSubtargetInfo.h"
26 #include "llvm/CodeGen/WasmEHFuncInfo.h"
27 #include "llvm/CodeGen/WinEHFuncInfo.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetOptions.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 static ISD::NodeType getPreferredExtendForValue(const Value *V) {
60 // For the users of the source value being used for compare instruction, if
61 // the number of signed predicate is greater than unsigned predicate, we
62 // prefer to use SIGN_EXTEND.
64 // With this optimization, we would be able to reduce some redundant sign or
65 // zero extension instruction, and eventually more machine CSE opportunities
67 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
68 unsigned NumOfSigned = 0, NumOfUnsigned = 0;
69 for (const User *U : V->users()) {
70 if (const auto *CI = dyn_cast<CmpInst>(U)) {
71 NumOfSigned += CI->isSigned();
72 NumOfUnsigned += CI->isUnsigned();
75 if (NumOfSigned > NumOfUnsigned)
76 ExtendKind = ISD::SIGN_EXTEND;
81 void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf,
85 TLI = MF->getSubtarget().getTargetLowering();
86 RegInfo = &MF->getRegInfo();
87 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
88 unsigned StackAlign = TFI->getStackAlignment();
89 DA = DAG->getDivergenceAnalysis();
91 // Check whether the function can return without sret-demotion.
92 SmallVector<ISD::OutputArg, 4> Outs;
93 CallingConv::ID CC = Fn->getCallingConv();
95 GetReturnInfo(CC, Fn->getReturnType(), Fn->getAttributes(), Outs, *TLI,
98 TLI->CanLowerReturn(CC, *MF, Fn->isVarArg(), Outs, Fn->getContext());
100 // If this personality uses funclets, we need to do a bit more work.
101 DenseMap<const AllocaInst *, TinyPtrVector<int *>> CatchObjects;
102 EHPersonality Personality = classifyEHPersonality(
103 Fn->hasPersonalityFn() ? Fn->getPersonalityFn() : nullptr);
104 if (isFuncletEHPersonality(Personality)) {
105 // Calculate state numbers if we haven't already.
106 WinEHFuncInfo &EHInfo = *MF->getWinEHFuncInfo();
107 if (Personality == EHPersonality::MSVC_CXX)
108 calculateWinCXXEHStateNumbers(&fn, EHInfo);
109 else if (isAsynchronousEHPersonality(Personality))
110 calculateSEHStateNumbers(&fn, EHInfo);
111 else if (Personality == EHPersonality::CoreCLR)
112 calculateClrEHStateNumbers(&fn, EHInfo);
114 // Map all BB references in the WinEH data to MBBs.
115 for (WinEHTryBlockMapEntry &TBME : EHInfo.TryBlockMap) {
116 for (WinEHHandlerType &H : TBME.HandlerArray) {
117 if (const AllocaInst *AI = H.CatchObj.Alloca)
118 CatchObjects.insert({AI, {}}).first->second.push_back(
119 &H.CatchObj.FrameIndex);
121 H.CatchObj.FrameIndex = INT_MAX;
125 if (Personality == EHPersonality::Wasm_CXX) {
126 WasmEHFuncInfo &EHInfo = *MF->getWasmEHFuncInfo();
127 calculateWasmEHInfo(&fn, EHInfo);
130 // Initialize the mapping of values to registers. This is only set up for
131 // instruction values that are used outside of the block that defines
133 for (const BasicBlock &BB : *Fn) {
134 for (const Instruction &I : BB) {
135 if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
136 Type *Ty = AI->getAllocatedType();
138 std::max((unsigned)MF->getDataLayout().getPrefTypeAlignment(Ty),
141 // Static allocas can be folded into the initial stack frame
142 // adjustment. For targets that don't realign the stack, don't
143 // do this if there is an extra alignment requirement.
144 if (AI->isStaticAlloca() &&
145 (TFI->isStackRealignable() || (Align <= StackAlign))) {
146 const ConstantInt *CUI = cast<ConstantInt>(AI->getArraySize());
148 MF->getDataLayout().getTypeAllocSize(Ty).getKnownMinSize();
150 TySize *= CUI->getZExtValue(); // Get total allocated size.
151 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
152 int FrameIndex = INT_MAX;
153 auto Iter = CatchObjects.find(AI);
154 if (Iter != CatchObjects.end() && TLI->needsFixedCatchObjects()) {
155 FrameIndex = MF->getFrameInfo().CreateFixedObject(
156 TySize, 0, /*IsImmutable=*/false, /*isAliased=*/true);
157 MF->getFrameInfo().setObjectAlignment(FrameIndex, Align);
160 MF->getFrameInfo().CreateStackObject(TySize, Align, false, AI);
163 // Scalable vectors may need a special StackID to distinguish
164 // them from other (fixed size) stack objects.
165 if (Ty->isVectorTy() && Ty->getVectorIsScalable())
166 MF->getFrameInfo().setStackID(FrameIndex,
167 TFI->getStackIDForScalableVectors());
169 StaticAllocaMap[AI] = FrameIndex;
170 // Update the catch handler information.
171 if (Iter != CatchObjects.end()) {
172 for (int *CatchObjPtr : Iter->second)
173 *CatchObjPtr = FrameIndex;
176 // FIXME: Overaligned static allocas should be grouped into
177 // a single dynamic allocation instead of using a separate
178 // stack allocation for each one.
179 if (Align <= StackAlign)
181 // Inform the Frame Information that we have variable-sized objects.
182 MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, AI);
186 // Look for inline asm that clobbers the SP register.
187 if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
188 ImmutableCallSite CS(&I);
189 if (isa<InlineAsm>(CS.getCalledValue())) {
190 unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
191 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
192 std::vector<TargetLowering::AsmOperandInfo> Ops =
193 TLI->ParseConstraints(Fn->getParent()->getDataLayout(), TRI, CS);
194 for (TargetLowering::AsmOperandInfo &Op : Ops) {
195 if (Op.Type == InlineAsm::isClobber) {
196 // Clobbers don't have SDValue operands, hence SDValue().
197 TLI->ComputeConstraintToUse(Op, SDValue(), DAG);
198 std::pair<unsigned, const TargetRegisterClass *> PhysReg =
199 TLI->getRegForInlineAsmConstraint(TRI, Op.ConstraintCode,
201 if (PhysReg.first == SP)
202 MF->getFrameInfo().setHasOpaqueSPAdjustment(true);
208 // Look for calls to the @llvm.va_start intrinsic. We can omit some
209 // prologue boilerplate for variadic functions that don't examine their
211 if (const auto *II = dyn_cast<IntrinsicInst>(&I)) {
212 if (II->getIntrinsicID() == Intrinsic::vastart)
213 MF->getFrameInfo().setHasVAStart(true);
216 // If we have a musttail call in a variadic function, we need to ensure we
217 // forward implicit register parameters.
218 if (const auto *CI = dyn_cast<CallInst>(&I)) {
219 if (CI->isMustTailCall() && Fn->isVarArg())
220 MF->getFrameInfo().setHasMustTailInVarArgFunc(true);
223 // Mark values used outside their block as exported, by allocating
224 // a virtual register for them.
225 if (isUsedOutsideOfDefiningBlock(&I))
226 if (!isa<AllocaInst>(I) || !StaticAllocaMap.count(cast<AllocaInst>(&I)))
227 InitializeRegForValue(&I);
229 // Decide the preferred extend type for a value.
230 PreferredExtendType[&I] = getPreferredExtendForValue(&I);
234 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
235 // also creates the initial PHI MachineInstrs, though none of the input
236 // operands are populated.
237 for (const BasicBlock &BB : *Fn) {
238 // Don't create MachineBasicBlocks for imaginary EH pad blocks. These blocks
239 // are really data, and no instructions can live here.
241 const Instruction *PadInst = BB.getFirstNonPHI();
242 // If this is a non-landingpad EH pad, mark this function as using
244 // FIXME: SEH catchpads do not create EH scope/funclets, so we could avoid
245 // setting this in such cases in order to improve frame layout.
246 if (!isa<LandingPadInst>(PadInst)) {
247 MF->setHasEHScopes(true);
248 MF->setHasEHFunclets(true);
249 MF->getFrameInfo().setHasOpaqueSPAdjustment(true);
251 if (isa<CatchSwitchInst>(PadInst)) {
252 assert(&*BB.begin() == PadInst &&
253 "WinEHPrepare failed to remove PHIs from imaginary BBs");
256 if (isa<FuncletPadInst>(PadInst))
257 assert(&*BB.begin() == PadInst && "WinEHPrepare failed to demote PHIs");
260 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(&BB);
264 // Transfer the address-taken flag. This is necessary because there could
265 // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
266 // the first one should be marked.
267 if (BB.hasAddressTaken())
268 MBB->setHasAddressTaken();
270 // Mark landing pad blocks.
274 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
276 for (const PHINode &PN : BB.phis()) {
281 if (PN.getType()->isEmptyTy())
284 DebugLoc DL = PN.getDebugLoc();
285 unsigned PHIReg = ValueMap[&PN];
286 assert(PHIReg && "PHI node does not have an assigned virtual register!");
288 SmallVector<EVT, 4> ValueVTs;
289 ComputeValueVTs(*TLI, MF->getDataLayout(), PN.getType(), ValueVTs);
290 for (EVT VT : ValueVTs) {
291 unsigned NumRegisters = TLI->getNumRegisters(Fn->getContext(), VT);
292 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
293 for (unsigned i = 0; i != NumRegisters; ++i)
294 BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i);
295 PHIReg += NumRegisters;
300 if (isFuncletEHPersonality(Personality)) {
301 WinEHFuncInfo &EHInfo = *MF->getWinEHFuncInfo();
303 // Map all BB references in the WinEH data to MBBs.
304 for (WinEHTryBlockMapEntry &TBME : EHInfo.TryBlockMap) {
305 for (WinEHHandlerType &H : TBME.HandlerArray) {
307 H.Handler = MBBMap[H.Handler.get<const BasicBlock *>()];
310 for (CxxUnwindMapEntry &UME : EHInfo.CxxUnwindMap)
312 UME.Cleanup = MBBMap[UME.Cleanup.get<const BasicBlock *>()];
313 for (SEHUnwindMapEntry &UME : EHInfo.SEHUnwindMap) {
314 const auto *BB = UME.Handler.get<const BasicBlock *>();
315 UME.Handler = MBBMap[BB];
317 for (ClrEHUnwindMapEntry &CME : EHInfo.ClrEHUnwindMap) {
318 const auto *BB = CME.Handler.get<const BasicBlock *>();
319 CME.Handler = MBBMap[BB];
323 else if (Personality == EHPersonality::Wasm_CXX) {
324 WasmEHFuncInfo &EHInfo = *MF->getWasmEHFuncInfo();
325 // Map all BB references in the WinEH data to MBBs.
326 DenseMap<BBOrMBB, BBOrMBB> NewMap;
327 for (auto &KV : EHInfo.EHPadUnwindMap) {
328 const auto *Src = KV.first.get<const BasicBlock *>();
329 const auto *Dst = KV.second.get<const BasicBlock *>();
330 NewMap[MBBMap[Src]] = MBBMap[Dst];
332 EHInfo.EHPadUnwindMap = std::move(NewMap);
336 /// clear - Clear out all the function-specific state. This returns this
337 /// FunctionLoweringInfo to an empty state, ready to be used for a
338 /// different function.
339 void FunctionLoweringInfo::clear() {
342 VirtReg2Value.clear();
343 StaticAllocaMap.clear();
344 LiveOutRegInfo.clear();
346 ArgDbgValues.clear();
347 DescribedArgs.clear();
348 ByValArgFrameIndexMap.clear();
350 RegsWithFixups.clear();
351 StatepointStackSlots.clear();
352 StatepointSpillMaps.clear();
353 PreferredExtendType.clear();
356 /// CreateReg - Allocate a single virtual register for the given type.
357 unsigned FunctionLoweringInfo::CreateReg(MVT VT, bool isDivergent) {
358 return RegInfo->createVirtualRegister(
359 MF->getSubtarget().getTargetLowering()->getRegClassFor(VT, isDivergent));
362 /// CreateRegs - Allocate the appropriate number of virtual registers of
363 /// the correctly promoted or expanded types. Assign these registers
364 /// consecutive vreg numbers and return the first assigned number.
366 /// In the case that the given value has struct or array type, this function
367 /// will assign registers for each member or element.
369 unsigned FunctionLoweringInfo::CreateRegs(Type *Ty, bool isDivergent) {
370 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
372 SmallVector<EVT, 4> ValueVTs;
373 ComputeValueVTs(*TLI, MF->getDataLayout(), Ty, ValueVTs);
375 unsigned FirstReg = 0;
376 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
377 EVT ValueVT = ValueVTs[Value];
378 MVT RegisterVT = TLI->getRegisterType(Ty->getContext(), ValueVT);
380 unsigned NumRegs = TLI->getNumRegisters(Ty->getContext(), ValueVT);
381 for (unsigned i = 0; i != NumRegs; ++i) {
382 unsigned R = CreateReg(RegisterVT, isDivergent);
383 if (!FirstReg) FirstReg = R;
389 unsigned FunctionLoweringInfo::CreateRegs(const Value *V) {
390 return CreateRegs(V->getType(), DA && !TLI->requiresUniformRegister(*MF, V) &&
394 /// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the
395 /// register is a PHI destination and the PHI's LiveOutInfo is not valid. If
396 /// the register's LiveOutInfo is for a smaller bit width, it is extended to
397 /// the larger bit width by zero extension. The bit width must be no smaller
398 /// than the LiveOutInfo's existing bit width.
399 const FunctionLoweringInfo::LiveOutInfo *
400 FunctionLoweringInfo::GetLiveOutRegInfo(unsigned Reg, unsigned BitWidth) {
401 if (!LiveOutRegInfo.inBounds(Reg))
404 LiveOutInfo *LOI = &LiveOutRegInfo[Reg];
408 if (BitWidth > LOI->Known.getBitWidth()) {
409 LOI->NumSignBits = 1;
410 LOI->Known = LOI->Known.zext(BitWidth, false /* => any extend */);
416 /// ComputePHILiveOutRegInfo - Compute LiveOutInfo for a PHI's destination
417 /// register based on the LiveOutInfo of its operands.
418 void FunctionLoweringInfo::ComputePHILiveOutRegInfo(const PHINode *PN) {
419 Type *Ty = PN->getType();
420 if (!Ty->isIntegerTy() || Ty->isVectorTy())
423 SmallVector<EVT, 1> ValueVTs;
424 ComputeValueVTs(*TLI, MF->getDataLayout(), Ty, ValueVTs);
425 assert(ValueVTs.size() == 1 &&
426 "PHIs with non-vector integer types should have a single VT.");
427 EVT IntVT = ValueVTs[0];
429 if (TLI->getNumRegisters(PN->getContext(), IntVT) != 1)
431 IntVT = TLI->getTypeToTransformTo(PN->getContext(), IntVT);
432 unsigned BitWidth = IntVT.getSizeInBits();
434 unsigned DestReg = ValueMap[PN];
435 if (!Register::isVirtualRegister(DestReg))
437 LiveOutRegInfo.grow(DestReg);
438 LiveOutInfo &DestLOI = LiveOutRegInfo[DestReg];
440 Value *V = PN->getIncomingValue(0);
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 = Val.getNumSignBits();
450 DestLOI.Known.Zero = ~Val;
451 DestLOI.Known.One = Val;
453 assert(ValueMap.count(V) && "V should have been placed in ValueMap when its"
454 "CopyToReg node was created.");
455 unsigned SrcReg = ValueMap[V];
456 if (!Register::isVirtualRegister(SrcReg)) {
457 DestLOI.IsValid = false;
460 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
462 DestLOI.IsValid = false;
468 assert(DestLOI.Known.Zero.getBitWidth() == BitWidth &&
469 DestLOI.Known.One.getBitWidth() == BitWidth &&
470 "Masks should have the same bit width as the type.");
472 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
473 Value *V = PN->getIncomingValue(i);
474 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
475 DestLOI.NumSignBits = 1;
476 DestLOI.Known = KnownBits(BitWidth);
480 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
481 APInt Val = CI->getValue().zextOrTrunc(BitWidth);
482 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, Val.getNumSignBits());
483 DestLOI.Known.Zero &= ~Val;
484 DestLOI.Known.One &= Val;
488 assert(ValueMap.count(V) && "V should have been placed in ValueMap when "
489 "its CopyToReg node was created.");
490 unsigned SrcReg = ValueMap[V];
491 if (!Register::isVirtualRegister(SrcReg)) {
492 DestLOI.IsValid = false;
495 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
497 DestLOI.IsValid = false;
500 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, SrcLOI->NumSignBits);
501 DestLOI.Known.Zero &= SrcLOI->Known.Zero;
502 DestLOI.Known.One &= SrcLOI->Known.One;
506 /// setArgumentFrameIndex - Record frame index for the byval
507 /// argument. This overrides previous frame index entry for this argument,
509 void FunctionLoweringInfo::setArgumentFrameIndex(const Argument *A,
511 ByValArgFrameIndexMap[A] = FI;
514 /// getArgumentFrameIndex - Get frame index for the byval argument.
515 /// If the argument does not have any assigned frame index then 0 is
517 int FunctionLoweringInfo::getArgumentFrameIndex(const Argument *A) {
518 auto I = ByValArgFrameIndexMap.find(A);
519 if (I != ByValArgFrameIndexMap.end())
521 LLVM_DEBUG(dbgs() << "Argument does not have assigned frame index!\n");
525 unsigned FunctionLoweringInfo::getCatchPadExceptionPointerVReg(
526 const Value *CPI, const TargetRegisterClass *RC) {
527 MachineRegisterInfo &MRI = MF->getRegInfo();
528 auto I = CatchPadExceptionPointers.insert({CPI, 0});
529 unsigned &VReg = I.first->second;
531 VReg = MRI.createVirtualRegister(RC);
532 assert(VReg && "null vreg in exception pointer table!");
537 FunctionLoweringInfo::getValueFromVirtualReg(unsigned Vreg) {
538 if (VirtReg2Value.empty()) {
539 SmallVector<EVT, 4> ValueVTs;
540 for (auto &P : ValueMap) {
542 ComputeValueVTs(*TLI, Fn->getParent()->getDataLayout(),
543 P.first->getType(), ValueVTs);
544 unsigned Reg = P.second;
545 for (EVT VT : ValueVTs) {
546 unsigned NumRegisters = TLI->getNumRegisters(Fn->getContext(), VT);
547 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
548 VirtReg2Value[Reg++] = P.first;
552 return VirtReg2Value.lookup(Vreg);