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), NextState(0) {}
87 WinEHFuncInfo &FuncInfo;
90 SmallVector<ActionHandler *, 4> HandlerStack;
91 SmallPtrSet<const Function *, 4> VisitedHandlers;
93 int currentEHNumber() const {
94 return HandlerStack.empty() ? -1 : HandlerStack.back()->getEHState();
97 void createUnwindMapEntry(int ToState, ActionHandler *AH);
98 void createTryBlockMapEntry(int TryLow, int TryHigh,
99 ArrayRef<CatchHandler *> Handlers);
100 void processCallSite(ArrayRef<ActionHandler *> Actions, ImmutableCallSite CS);
101 void calculateStateNumbers(const Function &F);
105 void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf,
109 TLI = MF->getSubtarget().getTargetLowering();
110 RegInfo = &MF->getRegInfo();
111 MachineModuleInfo &MMI = MF->getMMI();
113 // Check whether the function can return without sret-demotion.
114 SmallVector<ISD::OutputArg, 4> Outs;
115 GetReturnInfo(Fn->getReturnType(), Fn->getAttributes(), Outs, *TLI);
116 CanLowerReturn = TLI->CanLowerReturn(Fn->getCallingConv(), *MF,
117 Fn->isVarArg(), Outs, Fn->getContext());
119 // Initialize the mapping of values to registers. This is only set up for
120 // instruction values that are used outside of the block that defines
122 Function::const_iterator BB = Fn->begin(), EB = Fn->end();
123 for (; BB != EB; ++BB)
124 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
126 if (const AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
127 // Static allocas can be folded into the initial stack frame adjustment.
128 if (AI->isStaticAlloca()) {
129 const ConstantInt *CUI = cast<ConstantInt>(AI->getArraySize());
130 Type *Ty = AI->getAllocatedType();
131 uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty);
133 std::max((unsigned)TLI->getDataLayout()->getPrefTypeAlignment(Ty),
136 TySize *= CUI->getZExtValue(); // Get total allocated size.
137 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
139 StaticAllocaMap[AI] =
140 MF->getFrameInfo()->CreateStackObject(TySize, Align, false, AI);
143 unsigned Align = std::max(
144 (unsigned)TLI->getDataLayout()->getPrefTypeAlignment(
145 AI->getAllocatedType()),
147 unsigned StackAlign =
148 MF->getSubtarget().getFrameLowering()->getStackAlignment();
149 if (Align <= StackAlign)
151 // Inform the Frame Information that we have variable-sized objects.
152 MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1, AI);
156 // Look for inline asm that clobbers the SP register.
157 if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
158 ImmutableCallSite CS(I);
159 if (isa<InlineAsm>(CS.getCalledValue())) {
160 unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
161 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
162 std::vector<TargetLowering::AsmOperandInfo> Ops =
163 TLI->ParseConstraints(TRI, CS);
164 for (size_t I = 0, E = Ops.size(); I != E; ++I) {
165 TargetLowering::AsmOperandInfo &Op = Ops[I];
166 if (Op.Type == InlineAsm::isClobber) {
167 // Clobbers don't have SDValue operands, hence SDValue().
168 TLI->ComputeConstraintToUse(Op, SDValue(), DAG);
169 std::pair<unsigned, const TargetRegisterClass *> PhysReg =
170 TLI->getRegForInlineAsmConstraint(TRI, Op.ConstraintCode,
172 if (PhysReg.first == SP)
173 MF->getFrameInfo()->setHasInlineAsmWithSPAdjust(true);
179 // Look for calls to the @llvm.va_start intrinsic. We can omit some
180 // prologue boilerplate for variadic functions that don't examine their
182 if (const auto *II = dyn_cast<IntrinsicInst>(I)) {
183 if (II->getIntrinsicID() == Intrinsic::vastart)
184 MF->getFrameInfo()->setHasVAStart(true);
187 // If we have a musttail call in a variadic funciton, we need to ensure we
188 // forward implicit register parameters.
189 if (const auto *CI = dyn_cast<CallInst>(I)) {
190 if (CI->isMustTailCall() && Fn->isVarArg())
191 MF->getFrameInfo()->setHasMustTailInVarArgFunc(true);
194 // Mark values used outside their block as exported, by allocating
195 // a virtual register for them.
196 if (isUsedOutsideOfDefiningBlock(I))
197 if (!isa<AllocaInst>(I) ||
198 !StaticAllocaMap.count(cast<AllocaInst>(I)))
199 InitializeRegForValue(I);
201 // Collect llvm.dbg.declare information. This is done now instead of
202 // during the initial isel pass through the IR so that it is done
203 // in a predictable order.
204 if (const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(I)) {
205 assert(DI->getVariable() && "Missing variable");
206 assert(DI->getDebugLoc() && "Missing location");
207 if (MMI.hasDebugInfo()) {
208 // Don't handle byval struct arguments or VLAs, for example.
209 // Non-byval arguments are handled here (they refer to the stack
210 // temporary alloca at this point).
211 const Value *Address = DI->getAddress();
213 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
214 Address = BCI->getOperand(0);
215 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
216 DenseMap<const AllocaInst *, int>::iterator SI =
217 StaticAllocaMap.find(AI);
218 if (SI != StaticAllocaMap.end()) { // Check for VLAs.
220 MMI.setVariableDbgInfo(DI->getVariable(), DI->getExpression(),
221 FI, DI->getDebugLoc());
228 // Decide the preferred extend type for a value.
229 PreferredExtendType[I] = getPreferredExtendForValue(I);
232 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
233 // also creates the initial PHI MachineInstrs, though none of the input
234 // operands are populated.
235 for (BB = Fn->begin(); BB != EB; ++BB) {
236 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
240 // Transfer the address-taken flag. This is necessary because there could
241 // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
242 // the first one should be marked.
243 if (BB->hasAddressTaken())
244 MBB->setHasAddressTaken();
246 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
248 for (BasicBlock::const_iterator I = BB->begin();
249 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
250 if (PN->use_empty()) continue;
253 if (PN->getType()->isEmptyTy())
256 DebugLoc DL = PN->getDebugLoc();
257 unsigned PHIReg = ValueMap[PN];
258 assert(PHIReg && "PHI node does not have an assigned virtual register!");
260 SmallVector<EVT, 4> ValueVTs;
261 ComputeValueVTs(*TLI, PN->getType(), ValueVTs);
262 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
263 EVT VT = ValueVTs[vti];
264 unsigned NumRegisters = TLI->getNumRegisters(Fn->getContext(), VT);
265 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
266 for (unsigned i = 0; i != NumRegisters; ++i)
267 BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i);
268 PHIReg += NumRegisters;
273 // Mark landing pad blocks.
274 const LandingPadInst *LP = nullptr;
275 for (BB = Fn->begin(); BB != EB; ++BB) {
276 if (const auto *Invoke = dyn_cast<InvokeInst>(BB->getTerminator()))
277 MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
278 if (BB->isLandingPad())
279 LP = BB->getLandingPadInst();
282 // Calculate EH numbers for MSVC C++ EH and save SEH handlers if necessary.
283 EHPersonality Personality = EHPersonality::Unknown;
285 Personality = classifyEHPersonality(LP->getPersonalityFn());
286 if (Personality == EHPersonality::MSVC_Win64SEH) {
287 addSEHHandlersForLPads();
288 } else if (Personality == EHPersonality::MSVC_CXX) {
289 const Function *WinEHParentFn = MMI.getWinEHParent(&fn);
290 WinEHFuncInfo &FI = MMI.getWinEHFuncInfo(WinEHParentFn);
291 if (FI.LandingPadStateMap.empty()) {
292 WinEHNumbering Num(FI);
293 Num.calculateStateNumbers(*WinEHParentFn);
294 // Pop everything on the handler stack.
295 Num.processCallSite(None, ImmutableCallSite());
300 void FunctionLoweringInfo::addSEHHandlersForLPads() {
301 MachineModuleInfo &MMI = MF->getMMI();
303 // Iterate over all landing pads with llvm.eh.actions calls.
304 for (const BasicBlock &BB : *Fn) {
305 const LandingPadInst *LP = BB.getLandingPadInst();
308 const IntrinsicInst *ActionsCall =
309 dyn_cast<IntrinsicInst>(LP->getNextNode());
311 ActionsCall->getIntrinsicID() != Intrinsic::eh_actions)
314 // Parse the llvm.eh.actions call we found.
315 MachineBasicBlock *LPadMBB = MBBMap[LP->getParent()];
316 SmallVector<ActionHandler *, 4> Actions;
317 parseEHActions(ActionsCall, Actions);
319 // Iterate EH actions from most to least precedence, which means
320 // iterating in reverse.
321 for (auto I = Actions.rbegin(), E = Actions.rend(); I != E; ++I) {
322 ActionHandler *Action = *I;
323 if (auto *CH = dyn_cast<CatchHandler>(Action)) {
325 dyn_cast<Function>(CH->getSelector()->stripPointerCasts());
326 assert((Filter || CH->getSelector()->isNullValue()) &&
327 "expected function or catch-all");
328 const auto *RecoverBA =
329 cast<BlockAddress>(CH->getHandlerBlockOrFunc());
330 MMI.addSEHCatchHandler(LPadMBB, Filter, RecoverBA);
332 assert(isa<CleanupHandler>(Action));
333 const auto *Fini = cast<Function>(Action->getHandlerBlockOrFunc());
334 MMI.addSEHCleanupHandler(LPadMBB, Fini);
337 DeleteContainerPointers(Actions);
341 void WinEHNumbering::createUnwindMapEntry(int ToState, ActionHandler *AH) {
342 WinEHUnwindMapEntry UME;
343 UME.ToState = ToState;
344 if (auto *CH = dyn_cast_or_null<CleanupHandler>(AH))
345 UME.Cleanup = cast<Function>(CH->getHandlerBlockOrFunc());
347 UME.Cleanup = nullptr;
348 FuncInfo.UnwindMap.push_back(UME);
351 void WinEHNumbering::createTryBlockMapEntry(int TryLow, int TryHigh,
352 ArrayRef<CatchHandler *> Handlers) {
353 WinEHTryBlockMapEntry TBME;
354 TBME.TryLow = TryLow;
355 TBME.TryHigh = TryHigh;
356 assert(TBME.TryLow <= TBME.TryHigh);
357 for (CatchHandler *CH : Handlers) {
359 if (CH->getSelector()->isNullValue()) {
360 HT.Adjectives = 0x40;
361 HT.TypeDescriptor = nullptr;
363 auto *GV = cast<GlobalVariable>(CH->getSelector()->stripPointerCasts());
364 // Selectors are always pointers to GlobalVariables with 'struct' type.
365 // The struct has two fields, adjectives and a type descriptor.
366 auto *CS = cast<ConstantStruct>(GV->getInitializer());
368 cast<ConstantInt>(CS->getAggregateElement(0U))->getZExtValue();
370 cast<GlobalVariable>(CS->getAggregateElement(1)->stripPointerCasts());
372 HT.Handler = cast<Function>(CH->getHandlerBlockOrFunc());
373 HT.CatchObjRecoverIdx = CH->getExceptionVarIndex();
374 TBME.HandlerArray.push_back(HT);
376 FuncInfo.TryBlockMap.push_back(TBME);
379 static void print_name(const Value *V) {
382 DEBUG(dbgs() << "null");
386 if (const auto *F = dyn_cast<Function>(V))
387 DEBUG(dbgs() << F->getName());
393 void WinEHNumbering::processCallSite(ArrayRef<ActionHandler *> Actions,
394 ImmutableCallSite CS) {
395 int FirstMismatch = 0;
396 for (int E = std::min(HandlerStack.size(), Actions.size()); FirstMismatch < E;
398 if (HandlerStack[FirstMismatch]->getHandlerBlockOrFunc() !=
399 Actions[FirstMismatch]->getHandlerBlockOrFunc())
401 delete Actions[FirstMismatch];
404 bool EnteringScope = (int)Actions.size() > FirstMismatch;
406 // Don't recurse while we are looping over the handler stack. Instead, defer
407 // the numbering of the catch handlers until we are done popping.
408 SmallVector<CatchHandler *, 4> PoppedCatches;
409 for (int I = HandlerStack.size() - 1; I >= FirstMismatch; --I) {
410 if (auto *CH = dyn_cast<CatchHandler>(HandlerStack.back())) {
411 PoppedCatches.push_back(CH);
413 // Delete cleanup handlers
414 delete HandlerStack.back();
416 HandlerStack.pop_back();
419 // We need to create a new state number if we are exiting a try scope and we
420 // will not push any more actions.
421 int TryHigh = NextState - 1;
422 if (!EnteringScope && !PoppedCatches.empty()) {
423 createUnwindMapEntry(currentEHNumber(), nullptr);
427 int LastTryLowIdx = 0;
428 for (int I = 0, E = PoppedCatches.size(); I != E; ++I) {
429 CatchHandler *CH = PoppedCatches[I];
430 if (I + 1 == E || CH->getEHState() != PoppedCatches[I + 1]->getEHState()) {
431 int TryLow = CH->getEHState();
433 makeArrayRef(&PoppedCatches[LastTryLowIdx], I - LastTryLowIdx + 1);
434 createTryBlockMapEntry(TryLow, TryHigh, Handlers);
435 LastTryLowIdx = I + 1;
439 for (CatchHandler *CH : PoppedCatches) {
440 if (auto *F = dyn_cast<Function>(CH->getHandlerBlockOrFunc()))
441 calculateStateNumbers(*F);
445 bool LastActionWasCatch = false;
446 for (size_t I = FirstMismatch; I != Actions.size(); ++I) {
447 // We can reuse eh states when pushing two catches for the same invoke.
448 bool CurrActionIsCatch = isa<CatchHandler>(Actions[I]);
449 // FIXME: Reenable this optimization!
450 if (CurrActionIsCatch && LastActionWasCatch && false) {
451 Actions[I]->setEHState(currentEHNumber());
453 createUnwindMapEntry(currentEHNumber(), Actions[I]);
454 Actions[I]->setEHState(NextState);
456 DEBUG(dbgs() << "Creating unwind map entry for: (");
457 print_name(Actions[I]->getHandlerBlockOrFunc());
458 DEBUG(dbgs() << ", " << currentEHNumber() << ")\n");
460 HandlerStack.push_back(Actions[I]);
461 LastActionWasCatch = CurrActionIsCatch;
464 DEBUG(dbgs() << "In EHState " << currentEHNumber() << " for CallSite: ");
465 print_name(CS ? CS.getCalledValue() : nullptr);
466 DEBUG(dbgs() << '\n');
469 void WinEHNumbering::calculateStateNumbers(const Function &F) {
470 auto I = VisitedHandlers.insert(&F);
472 return; // We've already visited this handler, don't renumber it.
474 DEBUG(dbgs() << "Calculating state numbers for: " << F.getName() << '\n');
475 SmallVector<ActionHandler *, 4> ActionList;
476 for (const BasicBlock &BB : F) {
477 for (const Instruction &I : BB) {
478 const auto *CI = dyn_cast<CallInst>(&I);
479 if (!CI || CI->doesNotThrow())
481 processCallSite(None, CI);
483 const auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
486 const LandingPadInst *LPI = II->getLandingPadInst();
487 auto *ActionsCall = dyn_cast<IntrinsicInst>(LPI->getNextNode());
490 assert(ActionsCall->getIntrinsicID() == Intrinsic::eh_actions);
491 parseEHActions(ActionsCall, ActionList);
492 processCallSite(ActionList, II);
494 FuncInfo.LandingPadStateMap[LPI] = currentEHNumber();
497 FuncInfo.CatchHandlerMaxState[&F] = NextState - 1;
500 /// clear - Clear out all the function-specific state. This returns this
501 /// FunctionLoweringInfo to an empty state, ready to be used for a
502 /// different function.
503 void FunctionLoweringInfo::clear() {
504 assert(CatchInfoFound.size() == CatchInfoLost.size() &&
505 "Not all catch info was assigned to a landing pad!");
509 StaticAllocaMap.clear();
511 CatchInfoLost.clear();
512 CatchInfoFound.clear();
514 LiveOutRegInfo.clear();
516 ArgDbgValues.clear();
517 ByValArgFrameIndexMap.clear();
519 StatepointStackSlots.clear();
520 PreferredExtendType.clear();
523 /// CreateReg - Allocate a single virtual register for the given type.
524 unsigned FunctionLoweringInfo::CreateReg(MVT VT) {
525 return RegInfo->createVirtualRegister(
526 MF->getSubtarget().getTargetLowering()->getRegClassFor(VT));
529 /// CreateRegs - Allocate the appropriate number of virtual registers of
530 /// the correctly promoted or expanded types. Assign these registers
531 /// consecutive vreg numbers and return the first assigned number.
533 /// In the case that the given value has struct or array type, this function
534 /// will assign registers for each member or element.
536 unsigned FunctionLoweringInfo::CreateRegs(Type *Ty) {
537 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
539 SmallVector<EVT, 4> ValueVTs;
540 ComputeValueVTs(*TLI, Ty, ValueVTs);
542 unsigned FirstReg = 0;
543 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
544 EVT ValueVT = ValueVTs[Value];
545 MVT RegisterVT = TLI->getRegisterType(Ty->getContext(), ValueVT);
547 unsigned NumRegs = TLI->getNumRegisters(Ty->getContext(), ValueVT);
548 for (unsigned i = 0; i != NumRegs; ++i) {
549 unsigned R = CreateReg(RegisterVT);
550 if (!FirstReg) FirstReg = R;
556 /// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the
557 /// register is a PHI destination and the PHI's LiveOutInfo is not valid. If
558 /// the register's LiveOutInfo is for a smaller bit width, it is extended to
559 /// the larger bit width by zero extension. The bit width must be no smaller
560 /// than the LiveOutInfo's existing bit width.
561 const FunctionLoweringInfo::LiveOutInfo *
562 FunctionLoweringInfo::GetLiveOutRegInfo(unsigned Reg, unsigned BitWidth) {
563 if (!LiveOutRegInfo.inBounds(Reg))
566 LiveOutInfo *LOI = &LiveOutRegInfo[Reg];
570 if (BitWidth > LOI->KnownZero.getBitWidth()) {
571 LOI->NumSignBits = 1;
572 LOI->KnownZero = LOI->KnownZero.zextOrTrunc(BitWidth);
573 LOI->KnownOne = LOI->KnownOne.zextOrTrunc(BitWidth);
579 /// ComputePHILiveOutRegInfo - Compute LiveOutInfo for a PHI's destination
580 /// register based on the LiveOutInfo of its operands.
581 void FunctionLoweringInfo::ComputePHILiveOutRegInfo(const PHINode *PN) {
582 Type *Ty = PN->getType();
583 if (!Ty->isIntegerTy() || Ty->isVectorTy())
586 SmallVector<EVT, 1> ValueVTs;
587 ComputeValueVTs(*TLI, Ty, ValueVTs);
588 assert(ValueVTs.size() == 1 &&
589 "PHIs with non-vector integer types should have a single VT.");
590 EVT IntVT = ValueVTs[0];
592 if (TLI->getNumRegisters(PN->getContext(), IntVT) != 1)
594 IntVT = TLI->getTypeToTransformTo(PN->getContext(), IntVT);
595 unsigned BitWidth = IntVT.getSizeInBits();
597 unsigned DestReg = ValueMap[PN];
598 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
600 LiveOutRegInfo.grow(DestReg);
601 LiveOutInfo &DestLOI = LiveOutRegInfo[DestReg];
603 Value *V = PN->getIncomingValue(0);
604 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
605 DestLOI.NumSignBits = 1;
606 APInt Zero(BitWidth, 0);
607 DestLOI.KnownZero = Zero;
608 DestLOI.KnownOne = Zero;
612 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
613 APInt Val = CI->getValue().zextOrTrunc(BitWidth);
614 DestLOI.NumSignBits = Val.getNumSignBits();
615 DestLOI.KnownZero = ~Val;
616 DestLOI.KnownOne = Val;
618 assert(ValueMap.count(V) && "V should have been placed in ValueMap when its"
619 "CopyToReg node was created.");
620 unsigned SrcReg = ValueMap[V];
621 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
622 DestLOI.IsValid = false;
625 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
627 DestLOI.IsValid = false;
633 assert(DestLOI.KnownZero.getBitWidth() == BitWidth &&
634 DestLOI.KnownOne.getBitWidth() == BitWidth &&
635 "Masks should have the same bit width as the type.");
637 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
638 Value *V = PN->getIncomingValue(i);
639 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
640 DestLOI.NumSignBits = 1;
641 APInt Zero(BitWidth, 0);
642 DestLOI.KnownZero = Zero;
643 DestLOI.KnownOne = Zero;
647 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
648 APInt Val = CI->getValue().zextOrTrunc(BitWidth);
649 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, Val.getNumSignBits());
650 DestLOI.KnownZero &= ~Val;
651 DestLOI.KnownOne &= Val;
655 assert(ValueMap.count(V) && "V should have been placed in ValueMap when "
656 "its CopyToReg node was created.");
657 unsigned SrcReg = ValueMap[V];
658 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
659 DestLOI.IsValid = false;
662 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
664 DestLOI.IsValid = false;
667 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, SrcLOI->NumSignBits);
668 DestLOI.KnownZero &= SrcLOI->KnownZero;
669 DestLOI.KnownOne &= SrcLOI->KnownOne;
673 /// setArgumentFrameIndex - Record frame index for the byval
674 /// argument. This overrides previous frame index entry for this argument,
676 void FunctionLoweringInfo::setArgumentFrameIndex(const Argument *A,
678 ByValArgFrameIndexMap[A] = FI;
681 /// getArgumentFrameIndex - Get frame index for the byval argument.
682 /// If the argument does not have any assigned frame index then 0 is
684 int FunctionLoweringInfo::getArgumentFrameIndex(const Argument *A) {
685 DenseMap<const Argument *, int>::iterator I =
686 ByValArgFrameIndexMap.find(A);
687 if (I != ByValArgFrameIndexMap.end())
689 DEBUG(dbgs() << "Argument does not have assigned frame index!\n");
693 /// ComputeUsesVAFloatArgument - Determine if any floating-point values are
694 /// being passed to this variadic function, and set the MachineModuleInfo's
695 /// usesVAFloatArgument flag if so. This flag is used to emit an undefined
696 /// reference to _fltused on Windows, which will link in MSVCRT's
697 /// floating-point support.
698 void llvm::ComputeUsesVAFloatArgument(const CallInst &I,
699 MachineModuleInfo *MMI)
701 FunctionType *FT = cast<FunctionType>(
702 I.getCalledValue()->getType()->getContainedType(0));
703 if (FT->isVarArg() && !MMI->usesVAFloatArgument()) {
704 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
705 Type* T = I.getArgOperand(i)->getType();
706 for (auto i : post_order(T)) {
707 if (i->isFloatingPointTy()) {
708 MMI->setUsesVAFloatArgument(true);
716 /// AddLandingPadInfo - Extract the exception handling information from the
717 /// landingpad instruction and add them to the specified machine module info.
718 void llvm::AddLandingPadInfo(const LandingPadInst &I, MachineModuleInfo &MMI,
719 MachineBasicBlock *MBB) {
720 MMI.addPersonality(MBB,
721 cast<Function>(I.getPersonalityFn()->stripPointerCasts()));
726 // FIXME: New EH - Add the clauses in reverse order. This isn't 100% correct,
727 // but we need to do it this way because of how the DWARF EH emitter
728 // processes the clauses.
729 for (unsigned i = I.getNumClauses(); i != 0; --i) {
730 Value *Val = I.getClause(i - 1);
731 if (I.isCatch(i - 1)) {
732 MMI.addCatchTypeInfo(MBB,
733 dyn_cast<GlobalValue>(Val->stripPointerCasts()));
735 // Add filters in a list.
736 Constant *CVal = cast<Constant>(Val);
737 SmallVector<const GlobalValue*, 4> FilterList;
738 for (User::op_iterator
739 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II)
740 FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts()));
742 MMI.addFilterTypeInfo(MBB, FilterList);