1 //===-- FunctionLoweringInfo.cpp ------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements routines for translating functions from LLVM IR into
13 //===----------------------------------------------------------------------===//
15 #include "llvm/CodeGen/FunctionLoweringInfo.h"
16 #include "llvm/ADT/PostOrderIterator.h"
17 #include "llvm/CodeGen/Analysis.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/WinEHFuncInfo.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/DebugInfo.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/IntrinsicInst.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetFrameLowering.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/Target/TargetLowering.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/Target/TargetSubtargetInfo.h"
45 #define DEBUG_TYPE "function-lowering-info"
47 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
48 /// PHI nodes or outside of the basic block that defines it, or used by a
49 /// switch or atomic instruction, which may expand to multiple basic blocks.
50 static bool isUsedOutsideOfDefiningBlock(const Instruction *I) {
51 if (I->use_empty()) return false;
52 if (isa<PHINode>(I)) return true;
53 const BasicBlock *BB = I->getParent();
54 for (const User *U : I->users())
55 if (cast<Instruction>(U)->getParent() != BB || isa<PHINode>(U))
61 static ISD::NodeType getPreferredExtendForValue(const Value *V) {
62 // For the users of the source value being used for compare instruction, if
63 // the number of signed predicate is greater than unsigned predicate, we
64 // prefer to use SIGN_EXTEND.
66 // With this optimization, we would be able to reduce some redundant sign or
67 // zero extension instruction, and eventually more machine CSE opportunities
69 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
70 unsigned NumOfSigned = 0, NumOfUnsigned = 0;
71 for (const User *U : V->users()) {
72 if (const auto *CI = dyn_cast<CmpInst>(U)) {
73 NumOfSigned += CI->isSigned();
74 NumOfUnsigned += CI->isUnsigned();
77 if (NumOfSigned > NumOfUnsigned)
78 ExtendKind = ISD::SIGN_EXTEND;
84 struct WinEHNumbering {
85 WinEHNumbering(WinEHFuncInfo &FuncInfo) : FuncInfo(FuncInfo),
86 CurrentBaseState(-1), NextState(0) {}
88 WinEHFuncInfo &FuncInfo;
92 SmallVector<ActionHandler *, 4> HandlerStack;
93 SmallPtrSet<const Function *, 4> VisitedHandlers;
95 int currentEHNumber() const {
96 return HandlerStack.empty() ? CurrentBaseState : HandlerStack.back()->getEHState();
99 void createUnwindMapEntry(int ToState, ActionHandler *AH);
100 void createTryBlockMapEntry(int TryLow, int TryHigh,
101 ArrayRef<CatchHandler *> Handlers);
102 void processCallSite(ArrayRef<ActionHandler *> Actions, ImmutableCallSite CS);
103 void calculateStateNumbers(const Function &F);
107 void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf,
111 TLI = MF->getSubtarget().getTargetLowering();
112 RegInfo = &MF->getRegInfo();
113 MachineModuleInfo &MMI = MF->getMMI();
115 // Check whether the function can return without sret-demotion.
116 SmallVector<ISD::OutputArg, 4> Outs;
117 GetReturnInfo(Fn->getReturnType(), Fn->getAttributes(), Outs, *TLI);
118 CanLowerReturn = TLI->CanLowerReturn(Fn->getCallingConv(), *MF,
119 Fn->isVarArg(), Outs, Fn->getContext());
121 // Initialize the mapping of values to registers. This is only set up for
122 // instruction values that are used outside of the block that defines
124 Function::const_iterator BB = Fn->begin(), EB = Fn->end();
125 for (; BB != EB; ++BB)
126 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
128 if (const AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
129 // Static allocas can be folded into the initial stack frame adjustment.
130 if (AI->isStaticAlloca()) {
131 const ConstantInt *CUI = cast<ConstantInt>(AI->getArraySize());
132 Type *Ty = AI->getAllocatedType();
133 uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty);
135 std::max((unsigned)TLI->getDataLayout()->getPrefTypeAlignment(Ty),
138 TySize *= CUI->getZExtValue(); // Get total allocated size.
139 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
141 StaticAllocaMap[AI] =
142 MF->getFrameInfo()->CreateStackObject(TySize, Align, false, AI);
145 unsigned Align = std::max(
146 (unsigned)TLI->getDataLayout()->getPrefTypeAlignment(
147 AI->getAllocatedType()),
149 unsigned StackAlign =
150 MF->getSubtarget().getFrameLowering()->getStackAlignment();
151 if (Align <= StackAlign)
153 // Inform the Frame Information that we have variable-sized objects.
154 MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1, AI);
158 // Look for inline asm that clobbers the SP register.
159 if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
160 ImmutableCallSite CS(I);
161 if (isa<InlineAsm>(CS.getCalledValue())) {
162 unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
163 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
164 std::vector<TargetLowering::AsmOperandInfo> Ops =
165 TLI->ParseConstraints(TRI, CS);
166 for (size_t I = 0, E = Ops.size(); I != E; ++I) {
167 TargetLowering::AsmOperandInfo &Op = Ops[I];
168 if (Op.Type == InlineAsm::isClobber) {
169 // Clobbers don't have SDValue operands, hence SDValue().
170 TLI->ComputeConstraintToUse(Op, SDValue(), DAG);
171 std::pair<unsigned, const TargetRegisterClass *> PhysReg =
172 TLI->getRegForInlineAsmConstraint(TRI, Op.ConstraintCode,
174 if (PhysReg.first == SP)
175 MF->getFrameInfo()->setHasInlineAsmWithSPAdjust(true);
181 // Look for calls to the @llvm.va_start intrinsic. We can omit some
182 // prologue boilerplate for variadic functions that don't examine their
184 if (const auto *II = dyn_cast<IntrinsicInst>(I)) {
185 if (II->getIntrinsicID() == Intrinsic::vastart)
186 MF->getFrameInfo()->setHasVAStart(true);
189 // If we have a musttail call in a variadic funciton, we need to ensure we
190 // forward implicit register parameters.
191 if (const auto *CI = dyn_cast<CallInst>(I)) {
192 if (CI->isMustTailCall() && Fn->isVarArg())
193 MF->getFrameInfo()->setHasMustTailInVarArgFunc(true);
196 // Mark values used outside their block as exported, by allocating
197 // a virtual register for them.
198 if (isUsedOutsideOfDefiningBlock(I))
199 if (!isa<AllocaInst>(I) ||
200 !StaticAllocaMap.count(cast<AllocaInst>(I)))
201 InitializeRegForValue(I);
203 // Collect llvm.dbg.declare information. This is done now instead of
204 // during the initial isel pass through the IR so that it is done
205 // in a predictable order.
206 if (const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(I)) {
207 assert(DI->getVariable() && "Missing variable");
208 assert(DI->getDebugLoc() && "Missing location");
209 if (MMI.hasDebugInfo()) {
210 // Don't handle byval struct arguments or VLAs, for example.
211 // Non-byval arguments are handled here (they refer to the stack
212 // temporary alloca at this point).
213 const Value *Address = DI->getAddress();
215 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
216 Address = BCI->getOperand(0);
217 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
218 DenseMap<const AllocaInst *, int>::iterator SI =
219 StaticAllocaMap.find(AI);
220 if (SI != StaticAllocaMap.end()) { // Check for VLAs.
222 MMI.setVariableDbgInfo(DI->getVariable(), DI->getExpression(),
223 FI, DI->getDebugLoc());
230 // Decide the preferred extend type for a value.
231 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 (BB = Fn->begin(); BB != EB; ++BB) {
238 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
242 // Transfer the address-taken flag. This is necessary because there could
243 // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
244 // the first one should be marked.
245 if (BB->hasAddressTaken())
246 MBB->setHasAddressTaken();
248 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
250 for (BasicBlock::const_iterator I = BB->begin();
251 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
252 if (PN->use_empty()) continue;
255 if (PN->getType()->isEmptyTy())
258 DebugLoc DL = PN->getDebugLoc();
259 unsigned PHIReg = ValueMap[PN];
260 assert(PHIReg && "PHI node does not have an assigned virtual register!");
262 SmallVector<EVT, 4> ValueVTs;
263 ComputeValueVTs(*TLI, PN->getType(), ValueVTs);
264 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
265 EVT VT = ValueVTs[vti];
266 unsigned NumRegisters = TLI->getNumRegisters(Fn->getContext(), VT);
267 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
268 for (unsigned i = 0; i != NumRegisters; ++i)
269 BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i);
270 PHIReg += NumRegisters;
275 // Mark landing pad blocks.
276 SmallVector<const LandingPadInst *, 4> LPads;
277 for (BB = Fn->begin(); BB != EB; ++BB) {
278 if (const auto *Invoke = dyn_cast<InvokeInst>(BB->getTerminator()))
279 MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
280 if (BB->isLandingPad())
281 LPads.push_back(BB->getLandingPadInst());
284 // If this is an MSVC EH personality, we need to do a bit more work.
285 EHPersonality Personality = EHPersonality::Unknown;
287 Personality = classifyEHPersonality(LPads.back()->getPersonalityFn());
288 if (!isMSVCEHPersonality(Personality))
291 WinEHFuncInfo *EHInfo = nullptr;
292 if (Personality == EHPersonality::MSVC_Win64SEH) {
293 addSEHHandlersForLPads(LPads);
294 } else if (Personality == EHPersonality::MSVC_CXX) {
295 const Function *WinEHParentFn = MMI.getWinEHParent(&fn);
296 EHInfo = &MMI.getWinEHFuncInfo(WinEHParentFn);
297 if (EHInfo->LandingPadStateMap.empty()) {
298 WinEHNumbering Num(*EHInfo);
299 Num.calculateStateNumbers(*WinEHParentFn);
300 // Pop everything on the handler stack.
301 Num.processCallSite(None, ImmutableCallSite());
304 // Copy the state numbers to LandingPadInfo for the current function, which
305 // could be a handler or the parent.
306 for (const LandingPadInst *LP : LPads) {
307 MachineBasicBlock *LPadMBB = MBBMap[LP->getParent()];
308 MMI.addWinEHState(LPadMBB, EHInfo->LandingPadStateMap[LP]);
313 void FunctionLoweringInfo::addSEHHandlersForLPads(
314 ArrayRef<const LandingPadInst *> LPads) {
315 MachineModuleInfo &MMI = MF->getMMI();
317 // Iterate over all landing pads with llvm.eh.actions calls.
318 for (const LandingPadInst *LP : LPads) {
319 const IntrinsicInst *ActionsCall =
320 dyn_cast<IntrinsicInst>(LP->getNextNode());
322 ActionsCall->getIntrinsicID() != Intrinsic::eh_actions)
325 // Parse the llvm.eh.actions call we found.
326 MachineBasicBlock *LPadMBB = MBBMap[LP->getParent()];
327 SmallVector<ActionHandler *, 4> Actions;
328 parseEHActions(ActionsCall, Actions);
330 // Iterate EH actions from most to least precedence, which means
331 // iterating in reverse.
332 for (auto I = Actions.rbegin(), E = Actions.rend(); I != E; ++I) {
333 ActionHandler *Action = *I;
334 if (auto *CH = dyn_cast<CatchHandler>(Action)) {
336 dyn_cast<Function>(CH->getSelector()->stripPointerCasts());
337 assert((Filter || CH->getSelector()->isNullValue()) &&
338 "expected function or catch-all");
339 const auto *RecoverBA =
340 cast<BlockAddress>(CH->getHandlerBlockOrFunc());
341 MMI.addSEHCatchHandler(LPadMBB, Filter, RecoverBA);
343 assert(isa<CleanupHandler>(Action));
344 const auto *Fini = cast<Function>(Action->getHandlerBlockOrFunc());
345 MMI.addSEHCleanupHandler(LPadMBB, Fini);
348 DeleteContainerPointers(Actions);
352 void WinEHNumbering::createUnwindMapEntry(int ToState, ActionHandler *AH) {
353 WinEHUnwindMapEntry UME;
354 UME.ToState = ToState;
355 if (auto *CH = dyn_cast_or_null<CleanupHandler>(AH))
356 UME.Cleanup = cast<Function>(CH->getHandlerBlockOrFunc());
358 UME.Cleanup = nullptr;
359 FuncInfo.UnwindMap.push_back(UME);
362 void WinEHNumbering::createTryBlockMapEntry(int TryLow, int TryHigh,
363 ArrayRef<CatchHandler *> Handlers) {
364 WinEHTryBlockMapEntry TBME;
365 TBME.TryLow = TryLow;
366 TBME.TryHigh = TryHigh;
367 assert(TBME.TryLow <= TBME.TryHigh);
368 for (CatchHandler *CH : Handlers) {
370 if (CH->getSelector()->isNullValue()) {
371 HT.Adjectives = 0x40;
372 HT.TypeDescriptor = nullptr;
374 auto *GV = cast<GlobalVariable>(CH->getSelector()->stripPointerCasts());
375 // Selectors are always pointers to GlobalVariables with 'struct' type.
376 // The struct has two fields, adjectives and a type descriptor.
377 auto *CS = cast<ConstantStruct>(GV->getInitializer());
379 cast<ConstantInt>(CS->getAggregateElement(0U))->getZExtValue();
381 cast<GlobalVariable>(CS->getAggregateElement(1)->stripPointerCasts());
383 HT.Handler = cast<Function>(CH->getHandlerBlockOrFunc());
384 HT.CatchObjRecoverIdx = CH->getExceptionVarIndex();
385 TBME.HandlerArray.push_back(HT);
387 FuncInfo.TryBlockMap.push_back(TBME);
390 static void print_name(const Value *V) {
393 DEBUG(dbgs() << "null");
397 if (const auto *F = dyn_cast<Function>(V))
398 DEBUG(dbgs() << F->getName());
404 void WinEHNumbering::processCallSite(ArrayRef<ActionHandler *> Actions,
405 ImmutableCallSite CS) {
406 DEBUG(dbgs() << "processCallSite (EH state = " << currentEHNumber()
408 print_name(CS ? CS.getCalledValue() : nullptr);
409 DEBUG(dbgs() << '\n');
411 DEBUG(dbgs() << "HandlerStack: \n");
412 for (int I = 0, E = HandlerStack.size(); I < E; ++I) {
413 DEBUG(dbgs() << " ");
414 print_name(HandlerStack[I]->getHandlerBlockOrFunc());
415 DEBUG(dbgs() << '\n');
417 DEBUG(dbgs() << "Actions: \n");
418 for (int I = 0, E = Actions.size(); I < E; ++I) {
419 DEBUG(dbgs() << " ");
420 print_name(Actions[I]->getHandlerBlockOrFunc());
421 DEBUG(dbgs() << '\n');
423 int FirstMismatch = 0;
424 for (int E = std::min(HandlerStack.size(), Actions.size()); FirstMismatch < E;
426 if (HandlerStack[FirstMismatch]->getHandlerBlockOrFunc() !=
427 Actions[FirstMismatch]->getHandlerBlockOrFunc())
429 // Delete any actions that are already represented on the handler stack.
430 delete Actions[FirstMismatch];
433 // Don't recurse while we are looping over the handler stack. Instead, defer
434 // the numbering of the catch handlers until we are done popping.
435 SmallVector<CatchHandler *, 4> PoppedCatches;
436 for (int I = HandlerStack.size() - 1; I >= FirstMismatch; --I) {
437 if (auto *CH = dyn_cast<CatchHandler>(HandlerStack.back())) {
438 PoppedCatches.push_back(CH);
440 // Delete cleanup handlers
441 delete HandlerStack.back();
443 HandlerStack.pop_back();
446 int TryHigh = NextState - 1;
447 int LastTryLowIdx = 0;
448 for (int I = 0, E = PoppedCatches.size(); I != E; ++I) {
449 CatchHandler *CH = PoppedCatches[I];
450 DEBUG(dbgs() << "Popped handler with state " << CH->getEHState() << "\n");
451 if (I + 1 == E || CH->getEHState() != PoppedCatches[I + 1]->getEHState()) {
452 int TryLow = CH->getEHState();
454 makeArrayRef(&PoppedCatches[LastTryLowIdx], I - LastTryLowIdx + 1);
455 DEBUG(dbgs() << "createTryBlockMapEntry(" << TryLow << ", " << TryHigh);
456 for (int J = 0; J < Handlers.size(); ++J) {
457 DEBUG(dbgs() << ", ");
458 print_name(Handlers[J]->getHandlerBlockOrFunc());
460 DEBUG(dbgs() << ")\n");
461 createTryBlockMapEntry(TryLow, TryHigh, Handlers);
462 LastTryLowIdx = I + 1;
466 for (CatchHandler *CH : PoppedCatches) {
467 if (auto *F = dyn_cast<Function>(CH->getHandlerBlockOrFunc())) {
468 DEBUG(dbgs() << "Assigning base state " << NextState << " to ");
470 DEBUG(dbgs() << '\n');
471 FuncInfo.HandlerBaseState[F] = NextState;
472 DEBUG(dbgs() << "createUnwindMapEntry(" << currentEHNumber()
474 createUnwindMapEntry(currentEHNumber(), nullptr);
476 calculateStateNumbers(*F);
481 // The handler functions may have pushed actions onto the handler stack
482 // that we expected to push here. Compare the handler stack to our
483 // actions again to check for that possibility.
484 if (HandlerStack.size() > FirstMismatch) {
485 for (int E = std::min(HandlerStack.size(), Actions.size());
486 FirstMismatch < E; ++FirstMismatch) {
487 if (HandlerStack[FirstMismatch]->getHandlerBlockOrFunc() !=
488 Actions[FirstMismatch]->getHandlerBlockOrFunc())
490 delete Actions[FirstMismatch];
494 DEBUG(dbgs() << "Pushing actions for CallSite: ");
495 print_name(CS ? CS.getCalledValue() : nullptr);
496 DEBUG(dbgs() << '\n');
498 bool LastActionWasCatch = false;
499 for (size_t I = FirstMismatch; I != Actions.size(); ++I) {
500 // We can reuse eh states when pushing two catches for the same invoke.
501 bool CurrActionIsCatch = isa<CatchHandler>(Actions[I]);
502 // FIXME: Reenable this optimization!
503 if (CurrActionIsCatch && LastActionWasCatch && false) {
504 DEBUG(dbgs() << "setEHState for handler to " << currentEHNumber()
506 Actions[I]->setEHState(currentEHNumber());
508 DEBUG(dbgs() << "createUnwindMapEntry(" << currentEHNumber() << ", ");
509 print_name(Actions[I]->getHandlerBlockOrFunc());
510 DEBUG(dbgs() << ")\n");
511 createUnwindMapEntry(currentEHNumber(), Actions[I]);
512 DEBUG(dbgs() << "setEHState for handler to " << NextState << "\n");
513 Actions[I]->setEHState(NextState);
516 HandlerStack.push_back(Actions[I]);
517 LastActionWasCatch = CurrActionIsCatch;
520 DEBUG(dbgs() << "In EHState " << currentEHNumber() << " for CallSite: ");
521 print_name(CS ? CS.getCalledValue() : nullptr);
522 DEBUG(dbgs() << '\n');
525 void WinEHNumbering::calculateStateNumbers(const Function &F) {
526 auto I = VisitedHandlers.insert(&F);
528 return; // We've already visited this handler, don't renumber it.
530 int OldBaseState = CurrentBaseState;
531 if (FuncInfo.HandlerBaseState.count(&F)) {
532 CurrentBaseState = FuncInfo.HandlerBaseState[&F];
535 DEBUG(dbgs() << "Calculating state numbers for: " << F.getName() << '\n');
536 SmallVector<ActionHandler *, 4> ActionList;
537 for (const BasicBlock &BB : F) {
538 for (const Instruction &I : BB) {
539 const auto *CI = dyn_cast<CallInst>(&I);
540 if (!CI || CI->doesNotThrow())
542 processCallSite(None, CI);
544 const auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
547 const LandingPadInst *LPI = II->getLandingPadInst();
548 auto *ActionsCall = dyn_cast<IntrinsicInst>(LPI->getNextNode());
551 assert(ActionsCall->getIntrinsicID() == Intrinsic::eh_actions);
552 parseEHActions(ActionsCall, ActionList);
553 if (ActionList.empty())
555 processCallSite(ActionList, II);
557 FuncInfo.LandingPadStateMap[LPI] = currentEHNumber();
558 DEBUG(dbgs() << "Assigning state " << currentEHNumber()
559 << " to landing pad at " << LPI->getParent()->getName()
563 FuncInfo.CatchHandlerMaxState[&F] = NextState - 1;
565 CurrentBaseState = OldBaseState;
568 /// clear - Clear out all the function-specific state. This returns this
569 /// FunctionLoweringInfo to an empty state, ready to be used for a
570 /// different function.
571 void FunctionLoweringInfo::clear() {
572 assert(CatchInfoFound.size() == CatchInfoLost.size() &&
573 "Not all catch info was assigned to a landing pad!");
577 StaticAllocaMap.clear();
579 CatchInfoLost.clear();
580 CatchInfoFound.clear();
582 LiveOutRegInfo.clear();
584 ArgDbgValues.clear();
585 ByValArgFrameIndexMap.clear();
587 StatepointStackSlots.clear();
588 PreferredExtendType.clear();
591 /// CreateReg - Allocate a single virtual register for the given type.
592 unsigned FunctionLoweringInfo::CreateReg(MVT VT) {
593 return RegInfo->createVirtualRegister(
594 MF->getSubtarget().getTargetLowering()->getRegClassFor(VT));
597 /// CreateRegs - Allocate the appropriate number of virtual registers of
598 /// the correctly promoted or expanded types. Assign these registers
599 /// consecutive vreg numbers and return the first assigned number.
601 /// In the case that the given value has struct or array type, this function
602 /// will assign registers for each member or element.
604 unsigned FunctionLoweringInfo::CreateRegs(Type *Ty) {
605 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
607 SmallVector<EVT, 4> ValueVTs;
608 ComputeValueVTs(*TLI, Ty, ValueVTs);
610 unsigned FirstReg = 0;
611 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
612 EVT ValueVT = ValueVTs[Value];
613 MVT RegisterVT = TLI->getRegisterType(Ty->getContext(), ValueVT);
615 unsigned NumRegs = TLI->getNumRegisters(Ty->getContext(), ValueVT);
616 for (unsigned i = 0; i != NumRegs; ++i) {
617 unsigned R = CreateReg(RegisterVT);
618 if (!FirstReg) FirstReg = R;
624 /// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the
625 /// register is a PHI destination and the PHI's LiveOutInfo is not valid. If
626 /// the register's LiveOutInfo is for a smaller bit width, it is extended to
627 /// the larger bit width by zero extension. The bit width must be no smaller
628 /// than the LiveOutInfo's existing bit width.
629 const FunctionLoweringInfo::LiveOutInfo *
630 FunctionLoweringInfo::GetLiveOutRegInfo(unsigned Reg, unsigned BitWidth) {
631 if (!LiveOutRegInfo.inBounds(Reg))
634 LiveOutInfo *LOI = &LiveOutRegInfo[Reg];
638 if (BitWidth > LOI->KnownZero.getBitWidth()) {
639 LOI->NumSignBits = 1;
640 LOI->KnownZero = LOI->KnownZero.zextOrTrunc(BitWidth);
641 LOI->KnownOne = LOI->KnownOne.zextOrTrunc(BitWidth);
647 /// ComputePHILiveOutRegInfo - Compute LiveOutInfo for a PHI's destination
648 /// register based on the LiveOutInfo of its operands.
649 void FunctionLoweringInfo::ComputePHILiveOutRegInfo(const PHINode *PN) {
650 Type *Ty = PN->getType();
651 if (!Ty->isIntegerTy() || Ty->isVectorTy())
654 SmallVector<EVT, 1> ValueVTs;
655 ComputeValueVTs(*TLI, Ty, ValueVTs);
656 assert(ValueVTs.size() == 1 &&
657 "PHIs with non-vector integer types should have a single VT.");
658 EVT IntVT = ValueVTs[0];
660 if (TLI->getNumRegisters(PN->getContext(), IntVT) != 1)
662 IntVT = TLI->getTypeToTransformTo(PN->getContext(), IntVT);
663 unsigned BitWidth = IntVT.getSizeInBits();
665 unsigned DestReg = ValueMap[PN];
666 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
668 LiveOutRegInfo.grow(DestReg);
669 LiveOutInfo &DestLOI = LiveOutRegInfo[DestReg];
671 Value *V = PN->getIncomingValue(0);
672 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
673 DestLOI.NumSignBits = 1;
674 APInt Zero(BitWidth, 0);
675 DestLOI.KnownZero = Zero;
676 DestLOI.KnownOne = Zero;
680 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
681 APInt Val = CI->getValue().zextOrTrunc(BitWidth);
682 DestLOI.NumSignBits = Val.getNumSignBits();
683 DestLOI.KnownZero = ~Val;
684 DestLOI.KnownOne = Val;
686 assert(ValueMap.count(V) && "V should have been placed in ValueMap when its"
687 "CopyToReg node was created.");
688 unsigned SrcReg = ValueMap[V];
689 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
690 DestLOI.IsValid = false;
693 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
695 DestLOI.IsValid = false;
701 assert(DestLOI.KnownZero.getBitWidth() == BitWidth &&
702 DestLOI.KnownOne.getBitWidth() == BitWidth &&
703 "Masks should have the same bit width as the type.");
705 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
706 Value *V = PN->getIncomingValue(i);
707 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
708 DestLOI.NumSignBits = 1;
709 APInt Zero(BitWidth, 0);
710 DestLOI.KnownZero = Zero;
711 DestLOI.KnownOne = Zero;
715 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
716 APInt Val = CI->getValue().zextOrTrunc(BitWidth);
717 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, Val.getNumSignBits());
718 DestLOI.KnownZero &= ~Val;
719 DestLOI.KnownOne &= Val;
723 assert(ValueMap.count(V) && "V should have been placed in ValueMap when "
724 "its CopyToReg node was created.");
725 unsigned SrcReg = ValueMap[V];
726 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
727 DestLOI.IsValid = false;
730 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
732 DestLOI.IsValid = false;
735 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, SrcLOI->NumSignBits);
736 DestLOI.KnownZero &= SrcLOI->KnownZero;
737 DestLOI.KnownOne &= SrcLOI->KnownOne;
741 /// setArgumentFrameIndex - Record frame index for the byval
742 /// argument. This overrides previous frame index entry for this argument,
744 void FunctionLoweringInfo::setArgumentFrameIndex(const Argument *A,
746 ByValArgFrameIndexMap[A] = FI;
749 /// getArgumentFrameIndex - Get frame index for the byval argument.
750 /// If the argument does not have any assigned frame index then 0 is
752 int FunctionLoweringInfo::getArgumentFrameIndex(const Argument *A) {
753 DenseMap<const Argument *, int>::iterator I =
754 ByValArgFrameIndexMap.find(A);
755 if (I != ByValArgFrameIndexMap.end())
757 DEBUG(dbgs() << "Argument does not have assigned frame index!\n");
761 /// ComputeUsesVAFloatArgument - Determine if any floating-point values are
762 /// being passed to this variadic function, and set the MachineModuleInfo's
763 /// usesVAFloatArgument flag if so. This flag is used to emit an undefined
764 /// reference to _fltused on Windows, which will link in MSVCRT's
765 /// floating-point support.
766 void llvm::ComputeUsesVAFloatArgument(const CallInst &I,
767 MachineModuleInfo *MMI)
769 FunctionType *FT = cast<FunctionType>(
770 I.getCalledValue()->getType()->getContainedType(0));
771 if (FT->isVarArg() && !MMI->usesVAFloatArgument()) {
772 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
773 Type* T = I.getArgOperand(i)->getType();
774 for (auto i : post_order(T)) {
775 if (i->isFloatingPointTy()) {
776 MMI->setUsesVAFloatArgument(true);
784 /// AddLandingPadInfo - Extract the exception handling information from the
785 /// landingpad instruction and add them to the specified machine module info.
786 void llvm::AddLandingPadInfo(const LandingPadInst &I, MachineModuleInfo &MMI,
787 MachineBasicBlock *MBB) {
788 MMI.addPersonality(MBB,
789 cast<Function>(I.getPersonalityFn()->stripPointerCasts()));
794 // FIXME: New EH - Add the clauses in reverse order. This isn't 100% correct,
795 // but we need to do it this way because of how the DWARF EH emitter
796 // processes the clauses.
797 for (unsigned i = I.getNumClauses(); i != 0; --i) {
798 Value *Val = I.getClause(i - 1);
799 if (I.isCatch(i - 1)) {
800 MMI.addCatchTypeInfo(MBB,
801 dyn_cast<GlobalValue>(Val->stripPointerCasts()));
803 // Add filters in a list.
804 Constant *CVal = cast<Constant>(Val);
805 SmallVector<const GlobalValue*, 4> FilterList;
806 for (User::op_iterator
807 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II)
808 FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts()));
810 MMI.addFilterTypeInfo(MBB, FilterList);