xref: /src/contrib/llvm-project/llvm/lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
106f9d401SRoman Divacky //===-- FunctionLoweringInfo.cpp ------------------------------------------===//
206f9d401SRoman Divacky //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
606f9d401SRoman Divacky //
706f9d401SRoman Divacky //===----------------------------------------------------------------------===//
806f9d401SRoman Divacky //
906f9d401SRoman Divacky // This implements routines for translating functions from LLVM IR into
1006f9d401SRoman Divacky // Machine IR.
1106f9d401SRoman Divacky //
1206f9d401SRoman Divacky //===----------------------------------------------------------------------===//
1306f9d401SRoman Divacky 
1466e41e3cSRoman Divacky #include "llvm/CodeGen/FunctionLoweringInfo.h"
15cfca06d7SDimitry Andric #include "llvm/ADT/APInt.h"
167fa27ce4SDimitry Andric #include "llvm/Analysis/UniformityAnalysis.h"
17d7f7719eSRoman Divacky #include "llvm/CodeGen/Analysis.h"
1806f9d401SRoman Divacky #include "llvm/CodeGen/MachineFrameInfo.h"
194a16efa3SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
2006f9d401SRoman Divacky #include "llvm/CodeGen/MachineInstrBuilder.h"
2106f9d401SRoman Divacky #include "llvm/CodeGen/MachineRegisterInfo.h"
22044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h"
23044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
24044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
25044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
26044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
27eb11fae6SDimitry Andric #include "llvm/CodeGen/WasmEHFuncInfo.h"
285a5ac124SDimitry Andric #include "llvm/CodeGen/WinEHFuncInfo.h"
294a16efa3SDimitry Andric #include "llvm/IR/DataLayout.h"
304a16efa3SDimitry Andric #include "llvm/IR/DerivedTypes.h"
314a16efa3SDimitry Andric #include "llvm/IR/Function.h"
324a16efa3SDimitry Andric #include "llvm/IR/Instructions.h"
334a16efa3SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
344a16efa3SDimitry Andric #include "llvm/IR/Module.h"
3506f9d401SRoman Divacky #include "llvm/Support/Debug.h"
3606f9d401SRoman Divacky #include "llvm/Support/ErrorHandling.h"
375a5ac124SDimitry Andric #include "llvm/Support/raw_ostream.h"
3806f9d401SRoman Divacky #include <algorithm>
3906f9d401SRoman Divacky using namespace llvm;
4006f9d401SRoman Divacky 
415ca98fd9SDimitry Andric #define DEBUG_TYPE "function-lowering-info"
425ca98fd9SDimitry Andric 
4306f9d401SRoman Divacky /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
4406f9d401SRoman Divacky /// PHI nodes or outside of the basic block that defines it, or used by a
4506f9d401SRoman Divacky /// switch or atomic instruction, which may expand to multiple basic blocks.
isUsedOutsideOfDefiningBlock(const Instruction * I)46d7f7719eSRoman Divacky static bool isUsedOutsideOfDefiningBlock(const Instruction *I) {
47d7f7719eSRoman Divacky   if (I->use_empty()) return false;
4806f9d401SRoman Divacky   if (isa<PHINode>(I)) return true;
49d7f7719eSRoman Divacky   const BasicBlock *BB = I->getParent();
505ca98fd9SDimitry Andric   for (const User *U : I->users())
5166e41e3cSRoman Divacky     if (cast<Instruction>(U)->getParent() != BB || isa<PHINode>(U))
5206f9d401SRoman Divacky       return true;
535ca98fd9SDimitry Andric 
5406f9d401SRoman Divacky   return false;
5506f9d401SRoman Divacky }
5606f9d401SRoman Divacky 
getPreferredExtendForValue(const Instruction * I)57145449b1SDimitry Andric static ISD::NodeType getPreferredExtendForValue(const Instruction *I) {
5867c32a98SDimitry Andric   // For the users of the source value being used for compare instruction, if
5967c32a98SDimitry Andric   // the number of signed predicate is greater than unsigned predicate, we
6067c32a98SDimitry Andric   // prefer to use SIGN_EXTEND.
6167c32a98SDimitry Andric   //
6267c32a98SDimitry Andric   // With this optimization, we would be able to reduce some redundant sign or
6367c32a98SDimitry Andric   // zero extension instruction, and eventually more machine CSE opportunities
6467c32a98SDimitry Andric   // can be exposed.
6567c32a98SDimitry Andric   ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
6667c32a98SDimitry Andric   unsigned NumOfSigned = 0, NumOfUnsigned = 0;
67b1c73532SDimitry Andric   for (const Use &U : I->uses()) {
68b1c73532SDimitry Andric     if (const auto *CI = dyn_cast<CmpInst>(U.getUser())) {
6967c32a98SDimitry Andric       NumOfSigned += CI->isSigned();
7067c32a98SDimitry Andric       NumOfUnsigned += CI->isUnsigned();
7167c32a98SDimitry Andric     }
72b1c73532SDimitry Andric     if (const auto *CallI = dyn_cast<CallBase>(U.getUser())) {
73b1c73532SDimitry Andric       if (!CallI->isArgOperand(&U))
74b1c73532SDimitry Andric         continue;
75b1c73532SDimitry Andric       unsigned ArgNo = CallI->getArgOperandNo(&U);
76b1c73532SDimitry Andric       NumOfUnsigned += CallI->paramHasAttr(ArgNo, Attribute::ZExt);
77b1c73532SDimitry Andric       NumOfSigned += CallI->paramHasAttr(ArgNo, Attribute::SExt);
78b1c73532SDimitry Andric     }
7967c32a98SDimitry Andric   }
8067c32a98SDimitry Andric   if (NumOfSigned > NumOfUnsigned)
8167c32a98SDimitry Andric     ExtendKind = ISD::SIGN_EXTEND;
8267c32a98SDimitry Andric 
8367c32a98SDimitry Andric   return ExtendKind;
8467c32a98SDimitry Andric }
8567c32a98SDimitry Andric 
set(const Function & fn,MachineFunction & mf,SelectionDAG * DAG)865ca98fd9SDimitry Andric void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf,
875ca98fd9SDimitry Andric                                SelectionDAG *DAG) {
8806f9d401SRoman Divacky   Fn = &fn;
8906f9d401SRoman Divacky   MF = &mf;
9067c32a98SDimitry Andric   TLI = MF->getSubtarget().getTargetLowering();
9106f9d401SRoman Divacky   RegInfo = &MF->getRegInfo();
92dd58ef01SDimitry Andric   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
937fa27ce4SDimitry Andric   UA = DAG->getUniformityInfo();
9406f9d401SRoman Divacky 
9566e41e3cSRoman Divacky   // Check whether the function can return without sret-demotion.
9666e41e3cSRoman Divacky   SmallVector<ISD::OutputArg, 4> Outs;
97b7eb8e35SDimitry Andric   CallingConv::ID CC = Fn->getCallingConv();
98b7eb8e35SDimitry Andric 
99b7eb8e35SDimitry Andric   GetReturnInfo(CC, Fn->getReturnType(), Fn->getAttributes(), Outs, *TLI,
100ee8648bdSDimitry Andric                 mf.getDataLayout());
101b7eb8e35SDimitry Andric   CanLowerReturn =
102b7eb8e35SDimitry Andric       TLI->CanLowerReturn(CC, *MF, Fn->isVarArg(), Outs, Fn->getContext());
10366e41e3cSRoman Divacky 
10401095a5dSDimitry Andric   // If this personality uses funclets, we need to do a bit more work.
105b915e9e0SDimitry Andric   DenseMap<const AllocaInst *, TinyPtrVector<int *>> CatchObjects;
10601095a5dSDimitry Andric   EHPersonality Personality = classifyEHPersonality(
10701095a5dSDimitry Andric       Fn->hasPersonalityFn() ? Fn->getPersonalityFn() : nullptr);
10801095a5dSDimitry Andric   if (isFuncletEHPersonality(Personality)) {
10901095a5dSDimitry Andric     // Calculate state numbers if we haven't already.
11001095a5dSDimitry Andric     WinEHFuncInfo &EHInfo = *MF->getWinEHFuncInfo();
11101095a5dSDimitry Andric     if (Personality == EHPersonality::MSVC_CXX)
11201095a5dSDimitry Andric       calculateWinCXXEHStateNumbers(&fn, EHInfo);
11301095a5dSDimitry Andric     else if (isAsynchronousEHPersonality(Personality))
11401095a5dSDimitry Andric       calculateSEHStateNumbers(&fn, EHInfo);
11501095a5dSDimitry Andric     else if (Personality == EHPersonality::CoreCLR)
11601095a5dSDimitry Andric       calculateClrEHStateNumbers(&fn, EHInfo);
11701095a5dSDimitry Andric 
11801095a5dSDimitry Andric     // Map all BB references in the WinEH data to MBBs.
11901095a5dSDimitry Andric     for (WinEHTryBlockMapEntry &TBME : EHInfo.TryBlockMap) {
12001095a5dSDimitry Andric       for (WinEHHandlerType &H : TBME.HandlerArray) {
12101095a5dSDimitry Andric         if (const AllocaInst *AI = H.CatchObj.Alloca)
122b915e9e0SDimitry Andric           CatchObjects.insert({AI, {}}).first->second.push_back(
123b915e9e0SDimitry Andric               &H.CatchObj.FrameIndex);
12401095a5dSDimitry Andric         else
12501095a5dSDimitry Andric           H.CatchObj.FrameIndex = INT_MAX;
12601095a5dSDimitry Andric       }
12701095a5dSDimitry Andric     }
12801095a5dSDimitry Andric   }
12901095a5dSDimitry Andric 
13006f9d401SRoman Divacky   // Initialize the mapping of values to registers.  This is only set up for
13106f9d401SRoman Divacky   // instruction values that are used outside of the block that defines
13206f9d401SRoman Divacky   // them.
133cfca06d7SDimitry Andric   const Align StackAlign = TFI->getStackAlign();
134b915e9e0SDimitry Andric   for (const BasicBlock &BB : *Fn) {
135b915e9e0SDimitry Andric     for (const Instruction &I : BB) {
136b915e9e0SDimitry Andric       if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
13730815c53SDimitry Andric         Type *Ty = AI->getAllocatedType();
1387fa27ce4SDimitry Andric         Align Alignment = AI->getAlign();
139dd58ef01SDimitry Andric 
140dd58ef01SDimitry Andric         // Static allocas can be folded into the initial stack frame
141dd58ef01SDimitry Andric         // adjustment. For targets that don't realign the stack, don't
142dd58ef01SDimitry Andric         // do this if there is an extra alignment requirement.
143dd58ef01SDimitry Andric         if (AI->isStaticAlloca() &&
144cfca06d7SDimitry Andric             (TFI->isStackRealignable() || (Alignment <= StackAlign))) {
145dd58ef01SDimitry Andric           const ConstantInt *CUI = cast<ConstantInt>(AI->getArraySize());
146706b4fc4SDimitry Andric           uint64_t TySize =
147e3b55780SDimitry Andric               MF->getDataLayout().getTypeAllocSize(Ty).getKnownMinValue();
14806f9d401SRoman Divacky 
14906f9d401SRoman Divacky           TySize *= CUI->getZExtValue();   // Get total allocated size.
15006f9d401SRoman Divacky           if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
15101095a5dSDimitry Andric           int FrameIndex = INT_MAX;
15201095a5dSDimitry Andric           auto Iter = CatchObjects.find(AI);
15301095a5dSDimitry Andric           if (Iter != CatchObjects.end() && TLI->needsFixedCatchObjects()) {
154b915e9e0SDimitry Andric             FrameIndex = MF->getFrameInfo().CreateFixedObject(
155e6d15924SDimitry Andric                 TySize, 0, /*IsImmutable=*/false, /*isAliased=*/true);
156cfca06d7SDimitry Andric             MF->getFrameInfo().setObjectAlignment(FrameIndex, Alignment);
15701095a5dSDimitry Andric           } else {
158cfca06d7SDimitry Andric             FrameIndex = MF->getFrameInfo().CreateStackObject(TySize, Alignment,
159cfca06d7SDimitry Andric                                                               false, AI);
16001095a5dSDimitry Andric           }
16101095a5dSDimitry Andric 
1627fa27ce4SDimitry Andric           // Scalable vectors and structures that contain scalable vectors may
1637fa27ce4SDimitry Andric           // need a special StackID to distinguish them from other (fixed size)
1647fa27ce4SDimitry Andric           // stack objects.
1657fa27ce4SDimitry Andric           if (Ty->isScalableTy())
166706b4fc4SDimitry Andric             MF->getFrameInfo().setStackID(FrameIndex,
167706b4fc4SDimitry Andric                                           TFI->getStackIDForScalableVectors());
168706b4fc4SDimitry Andric 
16901095a5dSDimitry Andric           StaticAllocaMap[AI] = FrameIndex;
17001095a5dSDimitry Andric           // Update the catch handler information.
171b915e9e0SDimitry Andric           if (Iter != CatchObjects.end()) {
172b915e9e0SDimitry Andric             for (int *CatchObjPtr : Iter->second)
173b915e9e0SDimitry Andric               *CatchObjPtr = FrameIndex;
174b915e9e0SDimitry Andric           }
17567c32a98SDimitry Andric         } else {
176dd58ef01SDimitry Andric           // FIXME: Overaligned static allocas should be grouped into
177dd58ef01SDimitry Andric           // a single dynamic allocation instead of using a separate
178dd58ef01SDimitry Andric           // stack allocation for each one.
1795ca98fd9SDimitry Andric           // Inform the Frame Information that we have variable-sized objects.
180cfca06d7SDimitry Andric           MF->getFrameInfo().CreateVariableSizedObject(
181cfca06d7SDimitry Andric               Alignment <= StackAlign ? Align(1) : Alignment, AI);
1825ca98fd9SDimitry Andric         }
183344a3780SDimitry Andric       } else if (auto *Call = dyn_cast<CallBase>(&I)) {
1845ca98fd9SDimitry Andric         // Look for inline asm that clobbers the SP register.
185cfca06d7SDimitry Andric         if (Call->isInlineAsm()) {
186b60736ecSDimitry Andric           Register SP = TLI->getStackPointerRegisterToSaveRestore();
1875a5ac124SDimitry Andric           const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
1885ca98fd9SDimitry Andric           std::vector<TargetLowering::AsmOperandInfo> Ops =
189ac9a064cSDimitry Andric               TLI->ParseConstraints(Fn->getDataLayout(), TRI,
190cfca06d7SDimitry Andric                                     *Call);
191b915e9e0SDimitry Andric           for (TargetLowering::AsmOperandInfo &Op : Ops) {
1925ca98fd9SDimitry Andric             if (Op.Type == InlineAsm::isClobber) {
1935ca98fd9SDimitry Andric               // Clobbers don't have SDValue operands, hence SDValue().
1945ca98fd9SDimitry Andric               TLI->ComputeConstraintToUse(Op, SDValue(), DAG);
1955ca98fd9SDimitry Andric               std::pair<unsigned, const TargetRegisterClass *> PhysReg =
1965a5ac124SDimitry Andric                   TLI->getRegForInlineAsmConstraint(TRI, Op.ConstraintCode,
1975ca98fd9SDimitry Andric                                                     Op.ConstraintVT);
1985ca98fd9SDimitry Andric               if (PhysReg.first == SP)
199b915e9e0SDimitry Andric                 MF->getFrameInfo().setHasOpaqueSPAdjustment(true);
2005ca98fd9SDimitry Andric             }
2015ca98fd9SDimitry Andric           }
2025ca98fd9SDimitry Andric         }
20367c32a98SDimitry Andric         // Look for calls to the @llvm.va_start intrinsic. We can omit some
20467c32a98SDimitry Andric         // prologue boilerplate for variadic functions that don't examine their
20567c32a98SDimitry Andric         // arguments.
206b915e9e0SDimitry Andric         if (const auto *II = dyn_cast<IntrinsicInst>(&I)) {
20767c32a98SDimitry Andric           if (II->getIntrinsicID() == Intrinsic::vastart)
208b915e9e0SDimitry Andric             MF->getFrameInfo().setHasVAStart(true);
20967c32a98SDimitry Andric         }
21067c32a98SDimitry Andric 
211344a3780SDimitry Andric         // If we have a musttail call in a variadic function, we need to ensure
212344a3780SDimitry Andric         // we forward implicit register parameters.
213b915e9e0SDimitry Andric         if (const auto *CI = dyn_cast<CallInst>(&I)) {
21467c32a98SDimitry Andric           if (CI->isMustTailCall() && Fn->isVarArg())
215b915e9e0SDimitry Andric             MF->getFrameInfo().setHasMustTailInVarArgFunc(true);
21667c32a98SDimitry Andric         }
217ac9a064cSDimitry Andric 
218ac9a064cSDimitry Andric         // Determine if there is a call to setjmp in the machine function.
219ac9a064cSDimitry Andric         if (Call->hasFnAttr(Attribute::ReturnsTwice))
220ac9a064cSDimitry Andric           MF->setExposesReturnsTwice(true);
221344a3780SDimitry Andric       }
22267c32a98SDimitry Andric 
223d39c594dSDimitry Andric       // Mark values used outside their block as exported, by allocating
224d39c594dSDimitry Andric       // a virtual register for them.
225b915e9e0SDimitry Andric       if (isUsedOutsideOfDefiningBlock(&I))
226b915e9e0SDimitry Andric         if (!isa<AllocaInst>(I) || !StaticAllocaMap.count(cast<AllocaInst>(&I)))
227b915e9e0SDimitry Andric           InitializeRegForValue(&I);
22806f9d401SRoman Divacky 
229ac9a064cSDimitry Andric       // Decide the preferred extend type for a value. This iterates over all
230ac9a064cSDimitry Andric       // users and therefore isn't cheap, so don't do this at O0.
231ac9a064cSDimitry Andric       if (DAG->getOptLevel() != CodeGenOptLevel::None)
232b915e9e0SDimitry Andric         PreferredExtendType[&I] = getPreferredExtendForValue(&I);
233b915e9e0SDimitry Andric     }
234d39c594dSDimitry Andric   }
235d39c594dSDimitry Andric 
23606f9d401SRoman Divacky   // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
23706f9d401SRoman Divacky   // also creates the initial PHI MachineInstrs, though none of the input
23806f9d401SRoman Divacky   // operands are populated.
239b915e9e0SDimitry Andric   for (const BasicBlock &BB : *Fn) {
240dd58ef01SDimitry Andric     // Don't create MachineBasicBlocks for imaginary EH pad blocks. These blocks
241dd58ef01SDimitry Andric     // are really data, and no instructions can live here.
242b915e9e0SDimitry Andric     if (BB.isEHPad()) {
243b915e9e0SDimitry Andric       const Instruction *PadInst = BB.getFirstNonPHI();
244dd58ef01SDimitry Andric       // If this is a non-landingpad EH pad, mark this function as using
245dd58ef01SDimitry Andric       // funclets.
246eb11fae6SDimitry Andric       // FIXME: SEH catchpads do not create EH scope/funclets, so we could avoid
247eb11fae6SDimitry Andric       // setting this in such cases in order to improve frame layout.
248b915e9e0SDimitry Andric       if (!isa<LandingPadInst>(PadInst)) {
249eb11fae6SDimitry Andric         MF->setHasEHScopes(true);
250b915e9e0SDimitry Andric         MF->setHasEHFunclets(true);
251b915e9e0SDimitry Andric         MF->getFrameInfo().setHasOpaqueSPAdjustment(true);
252dd58ef01SDimitry Andric       }
253b915e9e0SDimitry Andric       if (isa<CatchSwitchInst>(PadInst)) {
254b915e9e0SDimitry Andric         assert(&*BB.begin() == PadInst &&
255dd58ef01SDimitry Andric                "WinEHPrepare failed to remove PHIs from imaginary BBs");
256dd58ef01SDimitry Andric         continue;
257dd58ef01SDimitry Andric       }
258ac9a064cSDimitry Andric       if (isa<FuncletPadInst>(PadInst) &&
259ac9a064cSDimitry Andric           Personality != EHPersonality::Wasm_CXX)
260b915e9e0SDimitry Andric         assert(&*BB.begin() == PadInst && "WinEHPrepare failed to demote PHIs");
261dd58ef01SDimitry Andric     }
262dd58ef01SDimitry Andric 
263b915e9e0SDimitry Andric     MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(&BB);
264b915e9e0SDimitry Andric     MBBMap[&BB] = MBB;
26506f9d401SRoman Divacky     MF->push_back(MBB);
26606f9d401SRoman Divacky 
26706f9d401SRoman Divacky     // Transfer the address-taken flag. This is necessary because there could
26806f9d401SRoman Divacky     // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
26906f9d401SRoman Divacky     // the first one should be marked.
270b915e9e0SDimitry Andric     if (BB.hasAddressTaken())
271e3b55780SDimitry Andric       MBB->setAddressTakenIRBlock(const_cast<BasicBlock *>(&BB));
27206f9d401SRoman Divacky 
273b915e9e0SDimitry Andric     // Mark landing pad blocks.
274b915e9e0SDimitry Andric     if (BB.isEHPad())
275b915e9e0SDimitry Andric       MBB->setIsEHPad();
276b915e9e0SDimitry Andric 
27706f9d401SRoman Divacky     // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
27806f9d401SRoman Divacky     // appropriate.
279eb11fae6SDimitry Andric     for (const PHINode &PN : BB.phis()) {
280eb11fae6SDimitry Andric       if (PN.use_empty())
28156fe8f14SDimitry Andric         continue;
28256fe8f14SDimitry Andric 
283eb11fae6SDimitry Andric       // Skip empty types
284eb11fae6SDimitry Andric       if (PN.getType()->isEmptyTy())
285eb11fae6SDimitry Andric         continue;
286eb11fae6SDimitry Andric 
287eb11fae6SDimitry Andric       DebugLoc DL = PN.getDebugLoc();
288eb11fae6SDimitry Andric       unsigned PHIReg = ValueMap[&PN];
28906f9d401SRoman Divacky       assert(PHIReg && "PHI node does not have an assigned virtual register!");
29006f9d401SRoman Divacky 
29106f9d401SRoman Divacky       SmallVector<EVT, 4> ValueVTs;
292eb11fae6SDimitry Andric       ComputeValueVTs(*TLI, MF->getDataLayout(), PN.getType(), ValueVTs);
293b915e9e0SDimitry Andric       for (EVT VT : ValueVTs) {
294f8af5cf6SDimitry Andric         unsigned NumRegisters = TLI->getNumRegisters(Fn->getContext(), VT);
29567c32a98SDimitry Andric         const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
29606f9d401SRoman Divacky         for (unsigned i = 0; i != NumRegisters; ++i)
2976fe5c7aaSRoman Divacky           BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i);
29806f9d401SRoman Divacky         PHIReg += NumRegisters;
29906f9d401SRoman Divacky       }
30006f9d401SRoman Divacky     }
30106f9d401SRoman Divacky   }
302d7f7719eSRoman Divacky 
303eb11fae6SDimitry Andric   if (isFuncletEHPersonality(Personality)) {
304dd58ef01SDimitry Andric     WinEHFuncInfo &EHInfo = *MF->getWinEHFuncInfo();
3053a0822f0SDimitry Andric 
306dd58ef01SDimitry Andric     // Map all BB references in the WinEH data to MBBs.
307dd58ef01SDimitry Andric     for (WinEHTryBlockMapEntry &TBME : EHInfo.TryBlockMap) {
308dd58ef01SDimitry Andric       for (WinEHHandlerType &H : TBME.HandlerArray) {
309dd58ef01SDimitry Andric         if (H.Handler)
3107fa27ce4SDimitry Andric           H.Handler = MBBMap[cast<const BasicBlock *>(H.Handler)];
3115a5ac124SDimitry Andric       }
3125a5ac124SDimitry Andric     }
313dd58ef01SDimitry Andric     for (CxxUnwindMapEntry &UME : EHInfo.CxxUnwindMap)
314dd58ef01SDimitry Andric       if (UME.Cleanup)
3157fa27ce4SDimitry Andric         UME.Cleanup = MBBMap[cast<const BasicBlock *>(UME.Cleanup)];
316dd58ef01SDimitry Andric     for (SEHUnwindMapEntry &UME : EHInfo.SEHUnwindMap) {
3177fa27ce4SDimitry Andric       const auto *BB = cast<const BasicBlock *>(UME.Handler);
318dd58ef01SDimitry Andric       UME.Handler = MBBMap[BB];
319dd58ef01SDimitry Andric     }
320dd58ef01SDimitry Andric     for (ClrEHUnwindMapEntry &CME : EHInfo.ClrEHUnwindMap) {
3217fa27ce4SDimitry Andric       const auto *BB = cast<const BasicBlock *>(CME.Handler);
322dd58ef01SDimitry Andric       CME.Handler = MBBMap[BB];
3235a5ac124SDimitry Andric     }
324e3b55780SDimitry Andric   } else if (Personality == EHPersonality::Wasm_CXX) {
325eb11fae6SDimitry Andric     WasmEHFuncInfo &EHInfo = *MF->getWasmEHFuncInfo();
326e3b55780SDimitry Andric     calculateWasmEHInfo(&fn, EHInfo);
327e3b55780SDimitry Andric 
328344a3780SDimitry Andric     // Map all BB references in the Wasm EH data to MBBs.
329344a3780SDimitry Andric     DenseMap<BBOrMBB, BBOrMBB> SrcToUnwindDest;
330344a3780SDimitry Andric     for (auto &KV : EHInfo.SrcToUnwindDest) {
3317fa27ce4SDimitry Andric       const auto *Src = cast<const BasicBlock *>(KV.first);
3327fa27ce4SDimitry Andric       const auto *Dest = cast<const BasicBlock *>(KV.second);
333344a3780SDimitry Andric       SrcToUnwindDest[MBBMap[Src]] = MBBMap[Dest];
334eb11fae6SDimitry Andric     }
335344a3780SDimitry Andric     EHInfo.SrcToUnwindDest = std::move(SrcToUnwindDest);
336344a3780SDimitry Andric     DenseMap<BBOrMBB, SmallPtrSet<BBOrMBB, 4>> UnwindDestToSrcs;
337344a3780SDimitry Andric     for (auto &KV : EHInfo.UnwindDestToSrcs) {
3387fa27ce4SDimitry Andric       const auto *Dest = cast<const BasicBlock *>(KV.first);
339344a3780SDimitry Andric       UnwindDestToSrcs[MBBMap[Dest]] = SmallPtrSet<BBOrMBB, 4>();
340344a3780SDimitry Andric       for (const auto P : KV.second)
341344a3780SDimitry Andric         UnwindDestToSrcs[MBBMap[Dest]].insert(
3427fa27ce4SDimitry Andric             MBBMap[cast<const BasicBlock *>(P)]);
343344a3780SDimitry Andric     }
344344a3780SDimitry Andric     EHInfo.UnwindDestToSrcs = std::move(UnwindDestToSrcs);
345eb11fae6SDimitry Andric   }
346eb11fae6SDimitry Andric }
347eb11fae6SDimitry Andric 
34806f9d401SRoman Divacky /// clear - Clear out all the function-specific state. This returns this
34906f9d401SRoman Divacky /// FunctionLoweringInfo to an empty state, ready to be used for a
35006f9d401SRoman Divacky /// different function.
clear()35106f9d401SRoman Divacky void FunctionLoweringInfo::clear() {
35206f9d401SRoman Divacky   MBBMap.clear();
35306f9d401SRoman Divacky   ValueMap.clear();
354eb11fae6SDimitry Andric   VirtReg2Value.clear();
35506f9d401SRoman Divacky   StaticAllocaMap.clear();
35606f9d401SRoman Divacky   LiveOutRegInfo.clear();
357d0e4e96dSDimitry Andric   VisitedBBs.clear();
358d7f7719eSRoman Divacky   ArgDbgValues.clear();
359e6d15924SDimitry Andric   DescribedArgs.clear();
360d39c594dSDimitry Andric   ByValArgFrameIndexMap.clear();
36166e41e3cSRoman Divacky   RegFixups.clear();
362eb11fae6SDimitry Andric   RegsWithFixups.clear();
36367c32a98SDimitry Andric   StatepointStackSlots.clear();
364b60736ecSDimitry Andric   StatepointRelocationMaps.clear();
36567c32a98SDimitry Andric   PreferredExtendType.clear();
3667fa27ce4SDimitry Andric   PreprocessedDbgDeclares.clear();
367ac9a064cSDimitry Andric   PreprocessedDVRDeclares.clear();
36806f9d401SRoman Divacky }
36906f9d401SRoman Divacky 
37066e41e3cSRoman Divacky /// CreateReg - Allocate a single virtual register for the given type.
CreateReg(MVT VT,bool isDivergent)371cfca06d7SDimitry Andric Register FunctionLoweringInfo::CreateReg(MVT VT, bool isDivergent) {
372e3b55780SDimitry Andric   return RegInfo->createVirtualRegister(TLI->getRegClassFor(VT, isDivergent));
37306f9d401SRoman Divacky }
37406f9d401SRoman Divacky 
37566e41e3cSRoman Divacky /// CreateRegs - Allocate the appropriate number of virtual registers of
37606f9d401SRoman Divacky /// the correctly promoted or expanded types.  Assign these registers
37706f9d401SRoman Divacky /// consecutive vreg numbers and return the first assigned number.
37806f9d401SRoman Divacky ///
37906f9d401SRoman Divacky /// In the case that the given value has struct or array type, this function
38006f9d401SRoman Divacky /// will assign registers for each member or element.
38106f9d401SRoman Divacky ///
CreateRegs(Type * Ty,bool isDivergent)382cfca06d7SDimitry Andric Register FunctionLoweringInfo::CreateRegs(Type *Ty, bool isDivergent) {
38306f9d401SRoman Divacky   SmallVector<EVT, 4> ValueVTs;
384ee8648bdSDimitry Andric   ComputeValueVTs(*TLI, MF->getDataLayout(), Ty, ValueVTs);
38506f9d401SRoman Divacky 
386cfca06d7SDimitry Andric   Register FirstReg;
38799aabd70SDimitry Andric   for (EVT ValueVT : ValueVTs) {
388f8af5cf6SDimitry Andric     MVT RegisterVT = TLI->getRegisterType(Ty->getContext(), ValueVT);
38906f9d401SRoman Divacky 
390f8af5cf6SDimitry Andric     unsigned NumRegs = TLI->getNumRegisters(Ty->getContext(), ValueVT);
39106f9d401SRoman Divacky     for (unsigned i = 0; i != NumRegs; ++i) {
392cfca06d7SDimitry Andric       Register R = CreateReg(RegisterVT, isDivergent);
39306f9d401SRoman Divacky       if (!FirstReg) FirstReg = R;
39406f9d401SRoman Divacky     }
39506f9d401SRoman Divacky   }
39606f9d401SRoman Divacky   return FirstReg;
39706f9d401SRoman Divacky }
39806f9d401SRoman Divacky 
CreateRegs(const Value * V)399cfca06d7SDimitry Andric Register FunctionLoweringInfo::CreateRegs(const Value *V) {
4007fa27ce4SDimitry Andric   return CreateRegs(V->getType(), UA && UA->isDivergent(V) &&
401cfca06d7SDimitry Andric                                       !TLI->requiresUniformRegister(*MF, V));
402e6d15924SDimitry Andric }
403e6d15924SDimitry Andric 
InitializeRegForValue(const Value * V)404ac9a064cSDimitry Andric Register FunctionLoweringInfo::InitializeRegForValue(const Value *V) {
405ac9a064cSDimitry Andric   // Tokens live in vregs only when used for convergence control.
406ac9a064cSDimitry Andric   if (V->getType()->isTokenTy() && !isa<ConvergenceControlInst>(V))
407ac9a064cSDimitry Andric     return 0;
408ac9a064cSDimitry Andric   Register &R = ValueMap[V];
409ac9a064cSDimitry Andric   assert(R == Register() && "Already initialized this value register!");
410ac9a064cSDimitry Andric   assert(VirtReg2Value.empty());
411ac9a064cSDimitry Andric   return R = CreateRegs(V);
412ac9a064cSDimitry Andric }
413ac9a064cSDimitry Andric 
414d0e4e96dSDimitry Andric /// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the
415d0e4e96dSDimitry Andric /// register is a PHI destination and the PHI's LiveOutInfo is not valid. If
416d0e4e96dSDimitry Andric /// the register's LiveOutInfo is for a smaller bit width, it is extended to
417d0e4e96dSDimitry Andric /// the larger bit width by zero extension. The bit width must be no smaller
418d0e4e96dSDimitry Andric /// than the LiveOutInfo's existing bit width.
419d0e4e96dSDimitry Andric const FunctionLoweringInfo::LiveOutInfo *
GetLiveOutRegInfo(Register Reg,unsigned BitWidth)420cfca06d7SDimitry Andric FunctionLoweringInfo::GetLiveOutRegInfo(Register Reg, unsigned BitWidth) {
421d0e4e96dSDimitry Andric   if (!LiveOutRegInfo.inBounds(Reg))
4225ca98fd9SDimitry Andric     return nullptr;
423d0e4e96dSDimitry Andric 
424d0e4e96dSDimitry Andric   LiveOutInfo *LOI = &LiveOutRegInfo[Reg];
425d0e4e96dSDimitry Andric   if (!LOI->IsValid)
4265ca98fd9SDimitry Andric     return nullptr;
427d0e4e96dSDimitry Andric 
428a303c417SDimitry Andric   if (BitWidth > LOI->Known.getBitWidth()) {
429d0e4e96dSDimitry Andric     LOI->NumSignBits = 1;
430cfca06d7SDimitry Andric     LOI->Known = LOI->Known.anyext(BitWidth);
431d0e4e96dSDimitry Andric   }
432d0e4e96dSDimitry Andric 
433d0e4e96dSDimitry Andric   return LOI;
434d0e4e96dSDimitry Andric }
435d0e4e96dSDimitry Andric 
436d0e4e96dSDimitry Andric /// ComputePHILiveOutRegInfo - Compute LiveOutInfo for a PHI's destination
437d0e4e96dSDimitry Andric /// register based on the LiveOutInfo of its operands.
ComputePHILiveOutRegInfo(const PHINode * PN)438d0e4e96dSDimitry Andric void FunctionLoweringInfo::ComputePHILiveOutRegInfo(const PHINode *PN) {
43930815c53SDimitry Andric   Type *Ty = PN->getType();
440d0e4e96dSDimitry Andric   if (!Ty->isIntegerTy() || Ty->isVectorTy())
441d0e4e96dSDimitry Andric     return;
442d0e4e96dSDimitry Andric 
443d0e4e96dSDimitry Andric   SmallVector<EVT, 1> ValueVTs;
444ee8648bdSDimitry Andric   ComputeValueVTs(*TLI, MF->getDataLayout(), Ty, ValueVTs);
445d0e4e96dSDimitry Andric   assert(ValueVTs.size() == 1 &&
446d0e4e96dSDimitry Andric          "PHIs with non-vector integer types should have a single VT.");
447d0e4e96dSDimitry Andric   EVT IntVT = ValueVTs[0];
448d0e4e96dSDimitry Andric 
449f8af5cf6SDimitry Andric   if (TLI->getNumRegisters(PN->getContext(), IntVT) != 1)
450d0e4e96dSDimitry Andric     return;
451ac9a064cSDimitry Andric   IntVT = TLI->getRegisterType(PN->getContext(), IntVT);
452d0e4e96dSDimitry Andric   unsigned BitWidth = IntVT.getSizeInBits();
453d0e4e96dSDimitry Andric 
454145449b1SDimitry Andric   auto It = ValueMap.find(PN);
455145449b1SDimitry Andric   if (It == ValueMap.end())
456d0e4e96dSDimitry Andric     return;
457145449b1SDimitry Andric 
458145449b1SDimitry Andric   Register DestReg = It->second;
459145449b1SDimitry Andric   if (DestReg == 0)
460e3b55780SDimitry Andric     return;
461e3b55780SDimitry Andric   assert(DestReg.isVirtual() && "Expected a virtual reg");
462d0e4e96dSDimitry Andric   LiveOutRegInfo.grow(DestReg);
463d0e4e96dSDimitry Andric   LiveOutInfo &DestLOI = LiveOutRegInfo[DestReg];
464d0e4e96dSDimitry Andric 
465d0e4e96dSDimitry Andric   Value *V = PN->getIncomingValue(0);
466d0e4e96dSDimitry Andric   if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
467d0e4e96dSDimitry Andric     DestLOI.NumSignBits = 1;
468a303c417SDimitry Andric     DestLOI.Known = KnownBits(BitWidth);
469d0e4e96dSDimitry Andric     return;
470d0e4e96dSDimitry Andric   }
471d0e4e96dSDimitry Andric 
472d0e4e96dSDimitry Andric   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
473145449b1SDimitry Andric     APInt Val;
474145449b1SDimitry Andric     if (TLI->signExtendConstant(CI))
475145449b1SDimitry Andric       Val = CI->getValue().sext(BitWidth);
476145449b1SDimitry Andric     else
477145449b1SDimitry Andric       Val = CI->getValue().zext(BitWidth);
478d0e4e96dSDimitry Andric     DestLOI.NumSignBits = Val.getNumSignBits();
479b60736ecSDimitry Andric     DestLOI.Known = KnownBits::makeConstant(Val);
480d0e4e96dSDimitry Andric   } else {
481d0e4e96dSDimitry Andric     assert(ValueMap.count(V) && "V should have been placed in ValueMap when its"
482d0e4e96dSDimitry Andric                                 "CopyToReg node was created.");
483cfca06d7SDimitry Andric     Register SrcReg = ValueMap[V];
484e3b55780SDimitry Andric     if (!SrcReg.isVirtual()) {
485d0e4e96dSDimitry Andric       DestLOI.IsValid = false;
486d0e4e96dSDimitry Andric       return;
487d0e4e96dSDimitry Andric     }
488d0e4e96dSDimitry Andric     const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
489d0e4e96dSDimitry Andric     if (!SrcLOI) {
490d0e4e96dSDimitry Andric       DestLOI.IsValid = false;
491d0e4e96dSDimitry Andric       return;
492d0e4e96dSDimitry Andric     }
493d0e4e96dSDimitry Andric     DestLOI = *SrcLOI;
494d0e4e96dSDimitry Andric   }
495d0e4e96dSDimitry Andric 
496a303c417SDimitry Andric   assert(DestLOI.Known.Zero.getBitWidth() == BitWidth &&
497a303c417SDimitry Andric          DestLOI.Known.One.getBitWidth() == BitWidth &&
498d0e4e96dSDimitry Andric          "Masks should have the same bit width as the type.");
499d0e4e96dSDimitry Andric 
500d0e4e96dSDimitry Andric   for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
501d0e4e96dSDimitry Andric     Value *V = PN->getIncomingValue(i);
502d0e4e96dSDimitry Andric     if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
503d0e4e96dSDimitry Andric       DestLOI.NumSignBits = 1;
504a303c417SDimitry Andric       DestLOI.Known = KnownBits(BitWidth);
505d0e4e96dSDimitry Andric       return;
506d0e4e96dSDimitry Andric     }
507d0e4e96dSDimitry Andric 
508d0e4e96dSDimitry Andric     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
509145449b1SDimitry Andric       APInt Val;
510145449b1SDimitry Andric       if (TLI->signExtendConstant(CI))
511145449b1SDimitry Andric         Val = CI->getValue().sext(BitWidth);
512145449b1SDimitry Andric       else
513145449b1SDimitry Andric         Val = CI->getValue().zext(BitWidth);
514d0e4e96dSDimitry Andric       DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, Val.getNumSignBits());
515a303c417SDimitry Andric       DestLOI.Known.Zero &= ~Val;
516a303c417SDimitry Andric       DestLOI.Known.One &= Val;
517d0e4e96dSDimitry Andric       continue;
518d0e4e96dSDimitry Andric     }
519d0e4e96dSDimitry Andric 
520d0e4e96dSDimitry Andric     assert(ValueMap.count(V) && "V should have been placed in ValueMap when "
521d0e4e96dSDimitry Andric                                 "its CopyToReg node was created.");
522cfca06d7SDimitry Andric     Register SrcReg = ValueMap[V];
523cfca06d7SDimitry Andric     if (!SrcReg.isVirtual()) {
524d0e4e96dSDimitry Andric       DestLOI.IsValid = false;
525d0e4e96dSDimitry Andric       return;
526d0e4e96dSDimitry Andric     }
527d0e4e96dSDimitry Andric     const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
528d0e4e96dSDimitry Andric     if (!SrcLOI) {
529d0e4e96dSDimitry Andric       DestLOI.IsValid = false;
530d0e4e96dSDimitry Andric       return;
531d0e4e96dSDimitry Andric     }
532d0e4e96dSDimitry Andric     DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, SrcLOI->NumSignBits);
5337fa27ce4SDimitry Andric     DestLOI.Known = DestLOI.Known.intersectWith(SrcLOI->Known);
534d0e4e96dSDimitry Andric   }
535d0e4e96dSDimitry Andric }
536d0e4e96dSDimitry Andric 
53730815c53SDimitry Andric /// setArgumentFrameIndex - Record frame index for the byval
538d39c594dSDimitry Andric /// argument. This overrides previous frame index entry for this argument,
539d39c594dSDimitry Andric /// if any.
setArgumentFrameIndex(const Argument * A,int FI)54030815c53SDimitry Andric void FunctionLoweringInfo::setArgumentFrameIndex(const Argument *A,
541d39c594dSDimitry Andric                                                  int FI) {
542d39c594dSDimitry Andric   ByValArgFrameIndexMap[A] = FI;
543d39c594dSDimitry Andric }
544d39c594dSDimitry Andric 
54530815c53SDimitry Andric /// getArgumentFrameIndex - Get frame index for the byval argument.
546d39c594dSDimitry Andric /// If the argument does not have any assigned frame index then 0 is
547d39c594dSDimitry Andric /// returned.
getArgumentFrameIndex(const Argument * A)54830815c53SDimitry Andric int FunctionLoweringInfo::getArgumentFrameIndex(const Argument *A) {
5496b3f41edSDimitry Andric   auto I = ByValArgFrameIndexMap.find(A);
550d39c594dSDimitry Andric   if (I != ByValArgFrameIndexMap.end())
551d39c594dSDimitry Andric     return I->second;
552eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << "Argument does not have assigned frame index!\n");
5536b3f41edSDimitry Andric   return INT_MAX;
554d39c594dSDimitry Andric }
555d39c594dSDimitry Andric 
getCatchPadExceptionPointerVReg(const Value * CPI,const TargetRegisterClass * RC)556cfca06d7SDimitry Andric Register FunctionLoweringInfo::getCatchPadExceptionPointerVReg(
557dd58ef01SDimitry Andric     const Value *CPI, const TargetRegisterClass *RC) {
558dd58ef01SDimitry Andric   MachineRegisterInfo &MRI = MF->getRegInfo();
559dd58ef01SDimitry Andric   auto I = CatchPadExceptionPointers.insert({CPI, 0});
560cfca06d7SDimitry Andric   Register &VReg = I.first->second;
561dd58ef01SDimitry Andric   if (I.second)
562dd58ef01SDimitry Andric     VReg = MRI.createVirtualRegister(RC);
563dd58ef01SDimitry Andric   assert(VReg && "null vreg in exception pointer table!");
564dd58ef01SDimitry Andric   return VReg;
565dd58ef01SDimitry Andric }
566dd58ef01SDimitry Andric 
567eb11fae6SDimitry Andric const Value *
getValueFromVirtualReg(Register Vreg)568cfca06d7SDimitry Andric FunctionLoweringInfo::getValueFromVirtualReg(Register Vreg) {
569eb11fae6SDimitry Andric   if (VirtReg2Value.empty()) {
570d8e91e46SDimitry Andric     SmallVector<EVT, 4> ValueVTs;
571eb11fae6SDimitry Andric     for (auto &P : ValueMap) {
572d8e91e46SDimitry Andric       ValueVTs.clear();
573ac9a064cSDimitry Andric       ComputeValueVTs(*TLI, Fn->getDataLayout(),
574d8e91e46SDimitry Andric                       P.first->getType(), ValueVTs);
575d8e91e46SDimitry Andric       unsigned Reg = P.second;
576d8e91e46SDimitry Andric       for (EVT VT : ValueVTs) {
577d8e91e46SDimitry Andric         unsigned NumRegisters = TLI->getNumRegisters(Fn->getContext(), VT);
578d8e91e46SDimitry Andric         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
579d8e91e46SDimitry Andric           VirtReg2Value[Reg++] = P.first;
580eb11fae6SDimitry Andric       }
581eb11fae6SDimitry Andric     }
582d8e91e46SDimitry Andric   }
583d8e91e46SDimitry Andric   return VirtReg2Value.lookup(Vreg);
584eb11fae6SDimitry Andric }
585