1//===-- FunctionLoweringInfo.cpp ------------------------------------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// This implements routines for translating functions from LLVM IR into
10// Machine IR.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/CodeGen/FunctionLoweringInfo.h"
15#include "llvm/ADT/APInt.h"
16#include "llvm/Analysis/UniformityAnalysis.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/MachineRegisterInfo.h"
22#include "llvm/CodeGen/TargetFrameLowering.h"
23#include "llvm/CodeGen/TargetInstrInfo.h"
24#include "llvm/CodeGen/TargetLowering.h"
25#include "llvm/CodeGen/TargetRegisterInfo.h"
26#include "llvm/CodeGen/TargetSubtargetInfo.h"
27#include "llvm/CodeGen/WinEHFuncInfo.h"
28#include "llvm/IR/Constants.h"
29#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/DerivedTypes.h"
31#include "llvm/IR/EHPersonalities.h"
32#include "llvm/IR/Function.h"
33#include "llvm/IR/Instructions.h"
34#include "llvm/IR/IntrinsicInst.h"
35#include "llvm/IR/Intrinsics.h"
36#include "llvm/IR/Module.h"
37#include "llvm/Support/Debug.h"
38#include "llvm/Support/ErrorHandling.h"
39#include "llvm/Support/raw_ostream.h"
40#include "llvm/Target/TargetMachine.h"
41#include <algorithm>
42using namespace llvm;
43
44#define DEBUG_TYPE "function-lowering-info"
45
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.
49static bool isUsedOutsideOfDefiningBlock(const Instruction *I) {
50 if (I->use_empty()) return false;
51 if (isa<PHINode>(Val: I)) return true;
52 const BasicBlock *BB = I->getParent();
53 for (const User *U : I->users())
54 if (cast<Instruction>(Val: U)->getParent() != BB || isa<PHINode>(Val: U))
55 return true;
56
57 return false;
58}
59
60static ISD::NodeType getPreferredExtendForValue(const Instruction *I) {
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.
64 //
65 // With this optimization, we would be able to reduce some redundant sign or
66 // zero extension instruction, and eventually more machine CSE opportunities
67 // can be exposed.
68 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
69 unsigned NumOfSigned = 0, NumOfUnsigned = 0;
70 for (const Use &U : I->uses()) {
71 if (const auto *CI = dyn_cast<CmpInst>(Val: U.getUser())) {
72 NumOfSigned += CI->isSigned();
73 NumOfUnsigned += CI->isUnsigned();
74 }
75 if (const auto *CallI = dyn_cast<CallBase>(Val: U.getUser())) {
76 if (!CallI->isArgOperand(U: &U))
77 continue;
78 unsigned ArgNo = CallI->getArgOperandNo(U: &U);
79 NumOfUnsigned += CallI->paramHasAttr(ArgNo, Kind: Attribute::ZExt);
80 NumOfSigned += CallI->paramHasAttr(ArgNo, Kind: Attribute::SExt);
81 }
82 }
83 if (NumOfSigned > NumOfUnsigned)
84 ExtendKind = ISD::SIGN_EXTEND;
85
86 return ExtendKind;
87}
88
89void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf,
90 SelectionDAG *DAG) {
91 Fn = &fn;
92 MF = &mf;
93 TLI = MF->getSubtarget().getTargetLowering();
94 RegInfo = &MF->getRegInfo();
95 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
96 UA = DAG->getUniformityInfo();
97 // Prefer the "exception-model" module flag, else the TargetOptions default.
98 ExceptionModel = Fn->getParent()->getExceptionModel();
99 if (ExceptionModel == ExceptionHandling::Default)
100 ExceptionModel = MF->getTarget().getExceptionModel();
101
102 // Check whether the function can return without sret-demotion.
103 SmallVector<ISD::OutputArg, 4> Outs;
104 CallingConv::ID CC = Fn->getCallingConv();
105
106 GetReturnInfo(CC, ReturnType: Fn->getReturnType(), attr: Fn->getAttributes(), Outs, TLI: *TLI,
107 DL: mf.getDataLayout());
108 CanLowerReturn =
109 TLI->CanLowerReturn(CC, *MF, Fn->isVarArg(), Outs, Fn->getContext(), RetTy: Fn->getReturnType());
110
111 // If this personality uses funclets, we need to do a bit more work.
112 DenseMap<const AllocaInst *, TinyPtrVector<int *>> CatchObjects;
113 EHPersonality Personality = classifyEHPersonality(
114 Pers: Fn->hasPersonalityFn() ? Fn->getPersonalityFn() : nullptr);
115 if (isFuncletEHPersonality(Pers: Personality)) {
116 // Calculate state numbers if we haven't already.
117 WinEHFuncInfo &EHInfo = *MF->getWinEHFuncInfo();
118 if (Personality == EHPersonality::MSVC_CXX)
119 calculateWinCXXEHStateNumbers(ParentFn: &fn, FuncInfo&: EHInfo);
120 else if (isAsynchronousEHPersonality(Pers: Personality))
121 calculateSEHStateNumbers(ParentFn: &fn, FuncInfo&: EHInfo);
122 else if (Personality == EHPersonality::CoreCLR)
123 calculateClrEHStateNumbers(Fn: &fn, FuncInfo&: EHInfo);
124
125 // Map all BB references in the WinEH data to MBBs.
126 for (WinEHTryBlockMapEntry &TBME : EHInfo.TryBlockMap) {
127 for (WinEHHandlerType &H : TBME.HandlerArray) {
128 if (const AllocaInst *AI = H.CatchObj.Alloca)
129 CatchObjects[AI].push_back(NewVal: &H.CatchObj.FrameIndex);
130 else
131 H.CatchObj.FrameIndex = INT_MAX;
132 }
133 }
134 }
135
136 // Initialize the mapping of values to registers. This is only set up for
137 // instruction values that are used outside of the block that defines
138 // them.
139 const Align StackAlign = TFI->getStackAlign();
140 for (const BasicBlock &BB : *Fn) {
141 for (const Instruction &I : BB) {
142 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Val: &I)) {
143 Align Alignment = AI->getAlign();
144
145 // Static allocas can be folded into the initial stack frame
146 // adjustment. For targets that don't realign the stack, don't
147 // do this if there is an extra alignment requirement.
148 if (AI->isStaticAlloca() &&
149 (TFI->isStackRealignable() || (Alignment <= StackAlign))) {
150 TypeSize AllocaSize = AI->getAllocationSize(DL: MF->getDataLayout())
151 .value_or(u: TypeSize::getZero());
152 uint64_t TySize = AllocaSize.getKnownMinValue();
153 if (TySize == 0)
154 TySize = 1; // Don't create zero-sized stack objects.
155 int FrameIndex = INT_MAX;
156 auto Iter = CatchObjects.find(Val: AI);
157 if (Iter != CatchObjects.end() && TLI->needsFixedCatchObjects()) {
158 FrameIndex = MF->getFrameInfo().CreateFixedObject(
159 Size: TySize, SPOffset: 0, /*IsImmutable=*/false, /*isAliased=*/true);
160 MF->getFrameInfo().setObjectAlignment(ObjectIdx: FrameIndex, Alignment);
161 } else {
162 FrameIndex = MF->getFrameInfo().CreateStackObject(Size: TySize, Alignment,
163 isSpillSlot: false, Alloca: AI);
164 }
165
166 // Scalable vectors and structures that contain scalable vectors may
167 // need a special StackID to distinguish them from other (fixed size)
168 // stack objects.
169 if (AllocaSize.isScalable())
170 MF->getFrameInfo().setStackID(ObjectIdx: FrameIndex,
171 ID: TFI->getStackIDForScalableVectors());
172
173 StaticAllocaMap[AI] = FrameIndex;
174 // Update the catch handler information.
175 if (Iter != CatchObjects.end()) {
176 for (int *CatchObjPtr : Iter->second)
177 *CatchObjPtr = FrameIndex;
178 }
179 } else {
180 // FIXME: Overaligned static allocas should be grouped into
181 // a single dynamic allocation instead of using a separate
182 // stack allocation for each one.
183 // Inform the Frame Information that we have variable-sized objects.
184 MF->getFrameInfo().CreateVariableSizedObject(
185 Alignment: Alignment <= StackAlign ? Align(1) : Alignment, Alloca: AI);
186 }
187 } else if (auto *Call = dyn_cast<CallBase>(Val: &I)) {
188 // Look for inline asm that clobbers the SP register.
189 if (Call->isInlineAsm()) {
190 Register SP = TLI->getStackPointerRegisterToSaveRestore();
191 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
192 std::vector<TargetLowering::AsmOperandInfo> Ops =
193 TLI->ParseConstraints(DL: Fn->getDataLayout(), TRI,
194 Call: *Call);
195 for (TargetLowering::AsmOperandInfo &Op : Ops) {
196 if (Op.Type == InlineAsm::isClobber) {
197 // Clobbers don't have SDValue operands, hence SDValue().
198 TLI->ComputeConstraintToUse(OpInfo&: Op, Op: SDValue(), DAG);
199 std::pair<unsigned, const TargetRegisterClass *> PhysReg =
200 TLI->getRegForInlineAsmConstraint(TRI, Constraint: Op.ConstraintCode,
201 VT: Op.ConstraintVT);
202 if (PhysReg.first == SP)
203 MF->getFrameInfo().setHasOpaqueSPAdjustment(true);
204 }
205 }
206 }
207 if (const auto *II = dyn_cast<IntrinsicInst>(Val: &I)) {
208 switch (II->getIntrinsicID()) {
209 case Intrinsic::vastart:
210 // Look for calls to the @llvm.va_start intrinsic. We can omit
211 // some prologue boilerplate for variadic functions that don't
212 // examine their arguments.
213 MF->getFrameInfo().setHasVAStart(true);
214 break;
215 case Intrinsic::fake_use:
216 // Look for llvm.fake.uses, so that we can remove loads into fake
217 // uses later if necessary.
218 MF->setHasFakeUses(true);
219 break;
220 default:
221 break;
222 }
223 }
224
225 // If we have a musttail call in a variadic function, we need to ensure
226 // we forward implicit register parameters.
227 if (const auto *CI = dyn_cast<CallInst>(Val: &I)) {
228 if (CI->isMustTailCall() && Fn->isVarArg())
229 MF->getFrameInfo().setHasMustTailInVarArgFunc(true);
230 }
231
232 // Determine if there is a call to setjmp in the machine function.
233 if (Call->hasFnAttr(Kind: Attribute::ReturnsTwice))
234 MF->setExposesReturnsTwice(true);
235 }
236
237 // Mark values used outside their block as exported, by allocating
238 // a virtual register for them.
239 if (isUsedOutsideOfDefiningBlock(I: &I))
240 if (!isa<AllocaInst>(Val: I) || !StaticAllocaMap.count(Val: cast<AllocaInst>(Val: &I)))
241 InitializeRegForValue(V: &I);
242
243 // Decide the preferred extend type for a value. This iterates over all
244 // users and therefore isn't cheap, so don't do this at O0.
245 if (DAG->getOptLevel() != CodeGenOptLevel::None)
246 PreferredExtendType[&I] = getPreferredExtendForValue(I: &I);
247 }
248 }
249
250 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
251 // also creates the initial PHI MachineInstrs, though none of the input
252 // operands are populated.
253 MBBMap.resize(N: Fn->getMaxBlockNumber());
254 for (const BasicBlock &BB : *Fn) {
255 // Don't create MachineBasicBlocks for imaginary EH pad blocks. These blocks
256 // are really data, and no instructions can live here.
257 if (BB.isEHPad()) {
258 BasicBlock::const_iterator PadInst = BB.getFirstNonPHIIt();
259 // If this is a non-landingpad EH pad, mark this function as using
260 // funclets.
261 // FIXME: SEH catchpads do not create EH scope/funclets, so we could avoid
262 // setting this in such cases in order to improve frame layout.
263 if (!isa<LandingPadInst>(Val: PadInst)) {
264 MF->setHasEHScopes(true);
265 MF->setHasEHFunclets(true);
266 MF->getFrameInfo().setHasOpaqueSPAdjustment(true);
267 }
268 if (isa<CatchSwitchInst>(Val: PadInst)) {
269 assert(BB.begin() == PadInst &&
270 "WinEHPrepare failed to remove PHIs from imaginary BBs");
271 continue;
272 }
273 if (isa<FuncletPadInst>(Val: PadInst) &&
274 Personality != EHPersonality::Wasm_CXX &&
275 Personality != EHPersonality::Wasm_D)
276 assert(BB.begin() == PadInst && "WinEHPrepare failed to demote PHIs");
277 }
278
279 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB: &BB);
280 MBBMap[BB.getNumber()] = MBB;
281 MF->push_back(MBB);
282
283 // Transfer the address-taken flag. This is necessary because there could
284 // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
285 // the first one should be marked.
286 // Only mark the block if the BlockAddress actually has users. The
287 // hasAddressTaken flag may be stale if the BlockAddress was optimized away
288 // but the constant still exists in the uniquing table.
289 if (BB.hasAddressTaken()) {
290 if (BlockAddress *BA = BlockAddress::lookup(BB: &BB))
291 if (!BA->hasZeroLiveUses())
292 MBB->setAddressTakenIRBlock(const_cast<BasicBlock *>(&BB));
293 }
294
295 // Mark landing pad blocks.
296 if (BB.isEHPad())
297 MBB->setIsEHPad();
298
299 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
300 // appropriate.
301 for (const PHINode &PN : BB.phis()) {
302 if (PN.use_empty())
303 continue;
304
305 // Skip empty types
306 if (PN.getType()->isEmptyTy())
307 continue;
308
309 DebugLoc DL = PN.getDebugLoc();
310 Register PHIReg = ValueMap[&PN];
311 assert(PHIReg && "PHI node does not have an assigned virtual register!");
312
313 SmallVector<EVT, 4> ValueVTs;
314 ComputeValueVTs(TLI: *TLI, DL: MF->getDataLayout(), Ty: PN.getType(), ValueVTs);
315 for (EVT VT : ValueVTs) {
316 unsigned NumRegisters = TLI->getNumRegisters(Context&: Fn->getContext(), VT);
317 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
318 for (unsigned i = 0; i != NumRegisters; ++i)
319 BuildMI(BB: MBB, MIMD: DL, MCID: TII->get(Opcode: TargetOpcode::PHI), DestReg: PHIReg + i);
320 PHIReg += NumRegisters;
321 }
322 }
323 }
324
325 if (isFuncletEHPersonality(Pers: Personality)) {
326 WinEHFuncInfo &EHInfo = *MF->getWinEHFuncInfo();
327
328 // Map all BB references in the WinEH data to MBBs.
329 for (WinEHTryBlockMapEntry &TBME : EHInfo.TryBlockMap) {
330 for (WinEHHandlerType &H : TBME.HandlerArray) {
331 if (H.Handler)
332 H.Handler = getMBB(BB: cast<const BasicBlock *>(Val&: H.Handler));
333 }
334 }
335 for (CxxUnwindMapEntry &UME : EHInfo.CxxUnwindMap)
336 if (UME.Cleanup)
337 UME.Cleanup = getMBB(BB: cast<const BasicBlock *>(Val&: UME.Cleanup));
338 for (SEHUnwindMapEntry &UME : EHInfo.SEHUnwindMap)
339 UME.Handler = getMBB(BB: cast<const BasicBlock *>(Val&: UME.Handler));
340 for (ClrEHUnwindMapEntry &CME : EHInfo.ClrEHUnwindMap)
341 CME.Handler = getMBB(BB: cast<const BasicBlock *>(Val&: CME.Handler));
342 }
343}
344
345/// clear - Clear out all the function-specific state. This returns this
346/// FunctionLoweringInfo to an empty state, ready to be used for a
347/// different function.
348void FunctionLoweringInfo::clear() {
349 MBBMap.clear();
350 ValueMap.clear();
351 VirtReg2Value.clear();
352 StaticAllocaMap.clear();
353 LiveOutRegInfo.clear();
354 VisitedBBs.clear();
355 ArgDbgValues.clear();
356 DescribedArgs.clear();
357 ByValArgFrameIndexMap.clear();
358 RegFixups.clear();
359 RegsWithFixups.clear();
360 StatepointStackSlots.clear();
361 StatepointRelocationMaps.clear();
362 PreferredExtendType.clear();
363 PreprocessedDVRDeclares.clear();
364}
365
366/// CreateReg - Allocate a single virtual register for the given type.
367Register FunctionLoweringInfo::CreateReg(MVT VT, bool isDivergent) {
368 return RegInfo->createVirtualRegister(RegClass: TLI->getRegClassFor(VT, isDivergent));
369}
370
371/// CreateRegs - Allocate the appropriate number of virtual registers of
372/// the correctly promoted or expanded types. Assign these registers
373/// consecutive vreg numbers and return the first assigned number.
374///
375/// In the case that the given value has struct or array type, this function
376/// will assign registers for each member or element.
377///
378Register FunctionLoweringInfo::CreateRegs(Type *Ty, bool isDivergent) {
379 SmallVector<EVT, 4> ValueVTs;
380 ComputeValueVTs(TLI: *TLI, DL: MF->getDataLayout(), Ty, ValueVTs);
381
382 Register FirstReg;
383 for (EVT ValueVT : ValueVTs) {
384 MVT RegisterVT = TLI->getRegisterType(Context&: Ty->getContext(), VT: ValueVT);
385
386 unsigned NumRegs = TLI->getNumRegisters(Context&: Ty->getContext(), VT: ValueVT);
387 for (unsigned i = 0; i != NumRegs; ++i) {
388 Register R = CreateReg(VT: RegisterVT, isDivergent);
389 if (!FirstReg) FirstReg = R;
390 }
391 }
392 return FirstReg;
393}
394
395Register FunctionLoweringInfo::CreateRegs(const Value *V) {
396 return CreateRegs(Ty: V->getType(), isDivergent: UA && UA->isDivergentAtDef(V) &&
397 !TLI->requiresUniformRegister(MF&: *MF, V));
398}
399
400Register FunctionLoweringInfo::InitializeRegForValue(const Value *V) {
401 // Tokens live in vregs only when used for convergence control.
402 if (V->getType()->isTokenTy() && !isa<ConvergenceControlInst>(Val: V))
403 return 0;
404 Register &R = ValueMap[V];
405 assert(R == Register() && "Already initialized this value register!");
406 assert(VirtReg2Value.empty());
407 return R = CreateRegs(V);
408}
409
410/// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the
411/// register is a PHI destination and the PHI's LiveOutInfo is not valid. If
412/// the register's LiveOutInfo is for a smaller bit width, it is extended to
413/// the larger bit width by zero extension. The bit width must be no smaller
414/// than the LiveOutInfo's existing bit width.
415const FunctionLoweringInfo::LiveOutInfo *
416FunctionLoweringInfo::GetLiveOutRegInfo(Register Reg, unsigned BitWidth) {
417 if (!LiveOutRegInfo.inBounds(N: Reg))
418 return nullptr;
419
420 LiveOutInfo *LOI = &LiveOutRegInfo[Reg];
421 if (!LOI->IsValid)
422 return nullptr;
423
424 if (BitWidth > LOI->Known.getBitWidth()) {
425 LOI->NumSignBits = 1;
426 LOI->Known = LOI->Known.anyext(BitWidth);
427 }
428
429 return LOI;
430}
431
432/// ComputePHILiveOutRegInfo - Compute LiveOutInfo for a PHI's destination
433/// register based on the LiveOutInfo of its operands.
434void FunctionLoweringInfo::ComputePHILiveOutRegInfo(const PHINode *PN) {
435 Type *Ty = PN->getType();
436 if (!Ty->isIntegerTy())
437 return;
438
439 SmallVector<EVT, 1> ValueVTs;
440 ComputeValueVTs(TLI: *TLI, DL: MF->getDataLayout(), Ty, ValueVTs);
441 assert(ValueVTs.size() == 1 &&
442 "PHIs with non-vector integer types should have a single VT.");
443 EVT IntVT = ValueVTs[0];
444
445 unsigned NumRegisters = TLI->getNumRegisters(Context&: PN->getContext(), VT: IntVT);
446 // FIXME: Support multiple registers for big endian targets.
447 if (NumRegisters != 1 && MF->getDataLayout().isBigEndian())
448 return;
449 IntVT = TLI->getRegisterType(Context&: PN->getContext(), VT: IntVT);
450 unsigned BitWidth = IntVT.getSizeInBits();
451
452 auto It = ValueMap.find(Val: PN);
453 if (It == ValueMap.end())
454 return;
455
456 Register BaseReg = It->second;
457 if (!BaseReg)
458 return;
459 assert(BaseReg.isVirtual() && "Expected a virtual reg");
460
461 for (unsigned RegIdx = 0; RegIdx < NumRegisters; ++RegIdx) {
462 // Split registers are assigned sequentially.
463 Register DestReg = BaseReg.id() + RegIdx;
464 LiveOutRegInfo.grow(N: DestReg);
465 LiveOutInfo &DestLOI = LiveOutRegInfo[DestReg];
466
467 Value *V = PN->getIncomingValue(i: 0);
468 if (isa<UndefValue>(Val: V) || isa<ConstantExpr>(Val: V)) {
469 DestLOI.NumSignBits = 1;
470 DestLOI.Known = KnownBits(BitWidth);
471 continue;
472 }
473
474 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val: V)) {
475 APInt Val;
476 if (TLI->signExtendConstant(C: CI))
477 Val = CI->getValue().sext(width: BitWidth * NumRegisters);
478 else
479 Val = CI->getValue().zext(width: BitWidth * NumRegisters);
480 APInt Extracted = Val.extractBits(numBits: BitWidth, bitPosition: BitWidth * RegIdx);
481 DestLOI.NumSignBits = Extracted.getNumSignBits();
482 DestLOI.Known = KnownBits::makeConstant(C: Extracted);
483 } else {
484 assert(ValueMap.count(V) &&
485 "V should have been placed in ValueMap when its"
486 "CopyToReg node was created.");
487 Register SrcReg = ValueMap[V];
488 if (!SrcReg.isVirtual()) {
489 DestLOI.IsValid = false;
490 continue;
491 }
492 // Split registers are assigned sequentially.
493 SrcReg = SrcReg.id() + RegIdx;
494 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(Reg: SrcReg, BitWidth);
495 if (!SrcLOI) {
496 DestLOI.IsValid = false;
497 continue;
498 }
499 DestLOI = *SrcLOI;
500 }
501
502 assert(DestLOI.Known.Zero.getBitWidth() == BitWidth &&
503 DestLOI.Known.One.getBitWidth() == BitWidth &&
504 "Masks should have the same bit width as the type.");
505
506 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
507 Value *V = PN->getIncomingValue(i);
508 if (isa<UndefValue>(Val: V) || isa<ConstantExpr>(Val: V)) {
509 DestLOI.NumSignBits = 1;
510 DestLOI.Known = KnownBits(BitWidth);
511 break;
512 }
513
514 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val: V)) {
515 APInt Val;
516 if (TLI->signExtendConstant(C: CI))
517 Val = CI->getValue().sext(width: BitWidth * NumRegisters);
518 else
519 Val = CI->getValue().zext(width: BitWidth * NumRegisters);
520 APInt Extracted = Val.extractBits(numBits: BitWidth, bitPosition: BitWidth * RegIdx);
521 DestLOI.NumSignBits =
522 std::min(a: DestLOI.NumSignBits, b: Extracted.getNumSignBits());
523 DestLOI.Known =
524 DestLOI.Known.intersectWith(RHS: KnownBits::makeConstant(C: Extracted));
525 continue;
526 }
527
528 assert(ValueMap.count(V) && "V should have been placed in ValueMap when "
529 "its CopyToReg node was created.");
530 Register SrcReg = ValueMap[V];
531 if (!SrcReg.isVirtual()) {
532 DestLOI.IsValid = false;
533 break;
534 }
535 // Split registers are assigned sequentially.
536 SrcReg = SrcReg.id() + RegIdx;
537 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(Reg: SrcReg, BitWidth);
538 if (!SrcLOI) {
539 DestLOI.IsValid = false;
540 break;
541 }
542 DestLOI.NumSignBits = std::min(a: DestLOI.NumSignBits, b: SrcLOI->NumSignBits);
543 DestLOI.Known = DestLOI.Known.intersectWith(RHS: SrcLOI->Known);
544 }
545 }
546}
547
548/// setArgumentFrameIndex - Record frame index for the byval
549/// argument. This overrides previous frame index entry for this argument,
550/// if any.
551void FunctionLoweringInfo::setArgumentFrameIndex(const Argument *A,
552 int FI) {
553 ByValArgFrameIndexMap[A] = FI;
554}
555
556/// getArgumentFrameIndex - Get frame index for the byval argument.
557/// If the argument does not have any assigned frame index then 0 is
558/// returned.
559int FunctionLoweringInfo::getArgumentFrameIndex(const Argument *A) {
560 auto I = ByValArgFrameIndexMap.find(Val: A);
561 if (I != ByValArgFrameIndexMap.end())
562 return I->second;
563 LLVM_DEBUG(dbgs() << "Argument does not have assigned frame index!\n");
564 return INT_MAX;
565}
566
567Register FunctionLoweringInfo::getCatchPadExceptionPointerVReg(
568 const Value *CPI, const TargetRegisterClass *RC) {
569 MachineRegisterInfo &MRI = MF->getRegInfo();
570 auto I = CatchPadExceptionPointers.insert(KV: {CPI, 0});
571 Register &VReg = I.first->second;
572 if (I.second)
573 VReg = MRI.createVirtualRegister(RegClass: RC);
574 assert(VReg && "null vreg in exception pointer table!");
575 return VReg;
576}
577
578const Value *
579FunctionLoweringInfo::getValueFromVirtualReg(Register Vreg) {
580 if (VirtReg2Value.empty()) {
581 SmallVector<EVT, 4> ValueVTs;
582 for (auto &P : ValueMap) {
583 ValueVTs.clear();
584 ComputeValueVTs(TLI: *TLI, DL: Fn->getDataLayout(),
585 Ty: P.first->getType(), ValueVTs);
586 Register Reg = P.second;
587 for (EVT VT : ValueVTs) {
588 unsigned NumRegisters = TLI->getNumRegisters(Context&: Fn->getContext(), VT);
589 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
590 VirtReg2Value[Reg++] = P.first;
591 }
592 }
593 }
594 return VirtReg2Value.lookup(Val: Vreg);
595}
596