blob: 4547906c275522e94eda97cee3d9c3a5c171e548 [file] [log] [blame]
Dan Gohmana3624b62009-11-23 17:16:22 +00001//===-- FunctionLoweringInfo.cpp ------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This implements routines for translating functions from LLVM IR into
11// Machine IR.
12//
13//===----------------------------------------------------------------------===//
14
Dan Gohmane7846162010-07-07 16:01:37 +000015#include "llvm/CodeGen/FunctionLoweringInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#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"
David Majnemercde33032015-03-30 22:58:10 +000023#include "llvm/CodeGen/WinEHFuncInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/DataLayout.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000025#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#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"
Dan Gohmana3624b62009-11-23 17:16:22 +000032#include "llvm/Support/Debug.h"
33#include "llvm/Support/ErrorHandling.h"
34#include "llvm/Support/MathExtras.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000035#include "llvm/Support/raw_ostream.h"
Hans Wennborgacb842d2014-03-05 02:43:26 +000036#include "llvm/Target/TargetFrameLowering.h"
Chandler Carruth92051402014-03-05 10:30:38 +000037#include "llvm/Target/TargetInstrInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000038#include "llvm/Target/TargetLowering.h"
39#include "llvm/Target/TargetOptions.h"
40#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000041#include "llvm/Target/TargetSubtargetInfo.h"
Dan Gohmana3624b62009-11-23 17:16:22 +000042#include <algorithm>
43using namespace llvm;
44
Chandler Carruth1b9dde02014-04-22 02:02:50 +000045#define DEBUG_TYPE "function-lowering-info"
46
Dan Gohmana3624b62009-11-23 17:16:22 +000047/// 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.
Dan Gohman913c9982010-04-15 04:33:49 +000050static bool isUsedOutsideOfDefiningBlock(const Instruction *I) {
Dan Gohman7c845e42010-04-20 14:50:13 +000051 if (I->use_empty()) return false;
Dan Gohmana3624b62009-11-23 17:16:22 +000052 if (isa<PHINode>(I)) return true;
Dan Gohman913c9982010-04-15 04:33:49 +000053 const BasicBlock *BB = I->getParent();
Chandler Carruthcdf47882014-03-09 03:16:01 +000054 for (const User *U : I->users())
Gabor Greif52617fc2010-07-09 16:08:33 +000055 if (cast<Instruction>(U)->getParent() != BB || isa<PHINode>(U))
Dan Gohmana3624b62009-11-23 17:16:22 +000056 return true;
Chandler Carruthcdf47882014-03-09 03:16:01 +000057
Dan Gohmana3624b62009-11-23 17:16:22 +000058 return false;
59}
60
Jiangning Liuffbc6902014-09-19 05:30:35 +000061static 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.
65 //
66 // With this optimization, we would be able to reduce some redundant sign or
67 // zero extension instruction, and eventually more machine CSE opportunities
68 // can be exposed.
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();
75 }
76 }
77 if (NumOfSigned > NumOfUnsigned)
78 ExtendKind = ISD::SIGN_EXTEND;
79
80 return ExtendKind;
81}
82
David Majnemercde33032015-03-30 22:58:10 +000083namespace {
84struct WinEHNumbering {
85 WinEHNumbering(WinEHFuncInfo &FuncInfo) : FuncInfo(FuncInfo), NextState(0) {}
86
87 WinEHFuncInfo &FuncInfo;
88 int NextState;
89
90 SmallVector<ActionHandler *, 4> HandlerStack;
David Majnemera225a192015-03-31 22:35:44 +000091 SmallPtrSet<const Function *, 4> VisitedHandlers;
David Majnemercde33032015-03-30 22:58:10 +000092
93 int currentEHNumber() const {
94 return HandlerStack.empty() ? -1 : HandlerStack.back()->getEHState();
95 }
96
David Majnemercde33032015-03-30 22:58:10 +000097 void createUnwindMapEntry(int ToState, ActionHandler *AH);
David Majnemera225a192015-03-31 22:35:44 +000098 void createTryBlockMapEntry(int TryLow, int TryHigh,
99 ArrayRef<CatchHandler *> Handlers);
100 void processCallSite(ArrayRef<ActionHandler *> Actions, ImmutableCallSite CS);
David Majnemercde33032015-03-30 22:58:10 +0000101 void calculateStateNumbers(const Function &F);
102};
103}
104
Hans Wennborgacb842d2014-03-05 02:43:26 +0000105void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf,
106 SelectionDAG *DAG) {
Dan Gohmana3624b62009-11-23 17:16:22 +0000107 Fn = &fn;
108 MF = &mf;
Eric Christopher2ae2de72014-10-09 00:57:31 +0000109 TLI = MF->getSubtarget().getTargetLowering();
Dan Gohmana3624b62009-11-23 17:16:22 +0000110 RegInfo = &MF->getRegInfo();
David Majnemercde33032015-03-30 22:58:10 +0000111 MachineModuleInfo &MMI = MF->getMMI();
Dan Gohmana3624b62009-11-23 17:16:22 +0000112
Dan Gohmand7b5ce32010-07-10 09:00:22 +0000113 // Check whether the function can return without sret-demotion.
114 SmallVector<ISD::OutputArg, 4> Outs;
Bill Wendling8db01cb2013-06-06 00:11:39 +0000115 GetReturnInfo(Fn->getReturnType(), Fn->getAttributes(), Outs, *TLI);
116 CanLowerReturn = TLI->CanLowerReturn(Fn->getCallingConv(), *MF,
Eric Christopher2ae2de72014-10-09 00:57:31 +0000117 Fn->isVarArg(), Outs, Fn->getContext());
Dan Gohmand7b5ce32010-07-10 09:00:22 +0000118
Dan Gohmana3624b62009-11-23 17:16:22 +0000119 // 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
121 // them.
Dan Gohman913c9982010-04-15 04:33:49 +0000122 Function::const_iterator BB = Fn->begin(), EB = Fn->end();
Dan Gohmana3624b62009-11-23 17:16:22 +0000123 for (; BB != EB; ++BB)
Eric Christopher219d51d2012-02-24 01:59:01 +0000124 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
125 I != E; ++I) {
Hans Wennborgacb842d2014-03-05 02:43:26 +0000126 if (const AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
Reid Kleckner0b2bccc2014-09-02 18:42:44 +0000127 // 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);
132 unsigned Align =
Eric Christopher2ae2de72014-10-09 00:57:31 +0000133 std::max((unsigned)TLI->getDataLayout()->getPrefTypeAlignment(Ty),
134 AI->getAlignment());
Reid Kleckner0b2bccc2014-09-02 18:42:44 +0000135
136 TySize *= CUI->getZExtValue(); // Get total allocated size.
137 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
138
139 StaticAllocaMap[AI] =
140 MF->getFrameInfo()->CreateStackObject(TySize, Align, false, AI);
141
142 } else {
Hans Wennborgacb842d2014-03-05 02:43:26 +0000143 unsigned Align = std::max(
144 (unsigned)TLI->getDataLayout()->getPrefTypeAlignment(
145 AI->getAllocatedType()),
146 AI->getAlignment());
Eric Christopherd9134482014-08-04 21:25:23 +0000147 unsigned StackAlign =
Eric Christopher2ae2de72014-10-09 00:57:31 +0000148 MF->getSubtarget().getFrameLowering()->getStackAlignment();
Hans Wennborgacb842d2014-03-05 02:43:26 +0000149 if (Align <= StackAlign)
150 Align = 0;
151 // Inform the Frame Information that we have variable-sized objects.
152 MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1, AI);
153 }
154 }
155
156 // Look for inline asm that clobbers the SP register.
157 if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
158 ImmutableCallSite CS(I);
Hans Wennborg0c72fd22014-03-05 03:21:23 +0000159 if (isa<InlineAsm>(CS.getCalledValue())) {
Hans Wennborgacb842d2014-03-05 02:43:26 +0000160 unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
Eric Christopher11e4df72015-02-26 22:38:43 +0000161 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
Hans Wennborgacb842d2014-03-05 02:43:26 +0000162 std::vector<TargetLowering::AsmOperandInfo> Ops =
Eric Christopher11e4df72015-02-26 22:38:43 +0000163 TLI->ParseConstraints(TRI, CS);
Hans Wennborgacb842d2014-03-05 02:43:26 +0000164 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);
Eric Christopher2ae2de72014-10-09 00:57:31 +0000169 std::pair<unsigned, const TargetRegisterClass *> PhysReg =
Eric Christopher11e4df72015-02-26 22:38:43 +0000170 TLI->getRegForInlineAsmConstraint(TRI, Op.ConstraintCode,
171 Op.ConstraintVT);
Hans Wennborgacb842d2014-03-05 02:43:26 +0000172 if (PhysReg.first == SP)
173 MF->getFrameInfo()->setHasInlineAsmWithSPAdjust(true);
174 }
175 }
176 }
177 }
178
Reid Kleckner2d9bb652014-08-22 21:59:26 +0000179 // Look for calls to the @llvm.va_start intrinsic. We can omit some
180 // prologue boilerplate for variadic functions that don't examine their
181 // arguments.
182 if (const auto *II = dyn_cast<IntrinsicInst>(I)) {
183 if (II->getIntrinsicID() == Intrinsic::vastart)
184 MF->getFrameInfo()->setHasVAStart(true);
185 }
186
Reid Kleckner16e55412014-08-29 21:42:08 +0000187 // If we have a musttail call in a variadic funciton, we need to ensure we
188 // forward implicit register parameters.
Reid Klecknerdccd0cb2014-08-29 21:42:21 +0000189 if (const auto *CI = dyn_cast<CallInst>(I)) {
Reid Kleckner16e55412014-08-29 21:42:08 +0000190 if (CI->isMustTailCall() && Fn->isVarArg())
191 MF->getFrameInfo()->setHasMustTailInVarArgFunc(true);
192 }
193
Dan Gohman1e9362772010-07-16 17:54:27 +0000194 // Mark values used outside their block as exported, by allocating
195 // a virtual register for them.
Cameron Zwarichf8b22b32011-02-22 03:24:52 +0000196 if (isUsedOutsideOfDefiningBlock(I))
Dan Gohmana3624b62009-11-23 17:16:22 +0000197 if (!isa<AllocaInst>(I) ||
198 !StaticAllocaMap.count(cast<AllocaInst>(I)))
199 InitializeRegForValue(I);
200
Dan Gohman1e9362772010-07-16 17:54:27 +0000201 // 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)) {
Manman Ren983a16c2013-06-28 05:43:10 +0000205 DIVariable DIVar(DI->getVariable());
206 assert((!DIVar || DIVar.isVariable()) &&
207 "Variable in DbgDeclareInst should be either null or a DIVariable.");
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +0000208 if (MMI.hasDebugInfo() && DIVar && DI->getDebugLoc()) {
Dan Gohman1e9362772010-07-16 17:54:27 +0000209 // Don't handle byval struct arguments or VLAs, for example.
210 // Non-byval arguments are handled here (they refer to the stack
211 // temporary alloca at this point).
212 const Value *Address = DI->getAddress();
213 if (Address) {
214 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
215 Address = BCI->getOperand(0);
216 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
217 DenseMap<const AllocaInst *, int>::iterator SI =
218 StaticAllocaMap.find(AI);
219 if (SI != StaticAllocaMap.end()) { // Check for VLAs.
220 int FI = SI->second;
Adrian Prantl87b7eb92014-10-01 18:55:02 +0000221 MMI.setVariableDbgInfo(DI->getVariable(), DI->getExpression(),
Dan Gohman1e9362772010-07-16 17:54:27 +0000222 FI, DI->getDebugLoc());
223 }
224 }
225 }
226 }
227 }
Jiangning Liuffbc6902014-09-19 05:30:35 +0000228
229 // Decide the preferred extend type for a value.
230 PreferredExtendType[I] = getPreferredExtendForValue(I);
Dan Gohman1e9362772010-07-16 17:54:27 +0000231 }
232
Dan Gohmana3624b62009-11-23 17:16:22 +0000233 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
234 // also creates the initial PHI MachineInstrs, though none of the input
235 // operands are populated.
Dan Gohmanf57117d2010-04-14 16:30:40 +0000236 for (BB = Fn->begin(); BB != EB; ++BB) {
Dan Gohmana3624b62009-11-23 17:16:22 +0000237 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
238 MBBMap[BB] = MBB;
239 MF->push_back(MBB);
240
241 // Transfer the address-taken flag. This is necessary because there could
242 // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
243 // the first one should be marked.
244 if (BB->hasAddressTaken())
245 MBB->setHasAddressTaken();
246
247 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
248 // appropriate.
Dan Gohman0f055d32010-04-20 14:46:25 +0000249 for (BasicBlock::const_iterator I = BB->begin();
250 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
251 if (PN->use_empty()) continue;
Dan Gohmana3624b62009-11-23 17:16:22 +0000252
Rafael Espindolae53b7d12011-05-13 15:18:06 +0000253 // Skip empty types
254 if (PN->getType()->isEmptyTy())
255 continue;
256
Dan Gohman7b7f0882010-04-20 14:48:02 +0000257 DebugLoc DL = PN->getDebugLoc();
Dan Gohmana3624b62009-11-23 17:16:22 +0000258 unsigned PHIReg = ValueMap[PN];
259 assert(PHIReg && "PHI node does not have an assigned virtual register!");
260
261 SmallVector<EVT, 4> ValueVTs;
Bill Wendling8db01cb2013-06-06 00:11:39 +0000262 ComputeValueVTs(*TLI, PN->getType(), ValueVTs);
Dan Gohmana3624b62009-11-23 17:16:22 +0000263 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
264 EVT VT = ValueVTs[vti];
Bill Wendling8db01cb2013-06-06 00:11:39 +0000265 unsigned NumRegisters = TLI->getNumRegisters(Fn->getContext(), VT);
Eric Christopherfc6de422014-08-05 02:39:49 +0000266 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
Dan Gohmana3624b62009-11-23 17:16:22 +0000267 for (unsigned i = 0; i != NumRegisters; ++i)
Chris Lattnerb06015a2010-02-09 19:54:29 +0000268 BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i);
Dan Gohmana3624b62009-11-23 17:16:22 +0000269 PHIReg += NumRegisters;
270 }
271 }
272 }
Dan Gohman69e8e322010-04-14 16:32:56 +0000273
274 // Mark landing pad blocks.
275 for (BB = Fn->begin(); BB != EB; ++BB)
David Majnemercde33032015-03-30 22:58:10 +0000276 if (const auto *Invoke = dyn_cast<InvokeInst>(BB->getTerminator()))
Dan Gohman69e8e322010-04-14 16:32:56 +0000277 MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
David Majnemercde33032015-03-30 22:58:10 +0000278
279 // Calculate EH numbers for WinEH.
David Majnemera225a192015-03-31 22:35:44 +0000280 if (fn.getFnAttribute("wineh-parent").getValueAsString() == fn.getName()) {
281 WinEHNumbering Num(MMI.getWinEHFuncInfo(&fn));
282 Num.calculateStateNumbers(fn);
283 // Pop everything on the handler stack.
284 Num.processCallSite(None, ImmutableCallSite());
285 }
David Majnemercde33032015-03-30 22:58:10 +0000286}
287
David Majnemercde33032015-03-30 22:58:10 +0000288void WinEHNumbering::createUnwindMapEntry(int ToState, ActionHandler *AH) {
289 WinEHUnwindMapEntry UME;
290 UME.ToState = ToState;
David Majnemera225a192015-03-31 22:35:44 +0000291 if (auto *CH = dyn_cast_or_null<CleanupHandler>(AH))
David Majnemercde33032015-03-30 22:58:10 +0000292 UME.Cleanup = cast<Function>(CH->getHandlerBlockOrFunc());
293 else
294 UME.Cleanup = nullptr;
295 FuncInfo.UnwindMap.push_back(UME);
296}
297
David Majnemera225a192015-03-31 22:35:44 +0000298void WinEHNumbering::createTryBlockMapEntry(int TryLow, int TryHigh,
299 ArrayRef<CatchHandler *> Handlers) {
300 WinEHTryBlockMapEntry TBME;
301 TBME.TryLow = TryLow;
302 TBME.TryHigh = TryHigh;
David Majnemera225a192015-03-31 22:35:44 +0000303 assert(TBME.TryLow <= TBME.TryHigh);
David Majnemera225a192015-03-31 22:35:44 +0000304 for (CatchHandler *CH : Handlers) {
305 WinEHHandlerType HT;
David Majnemere8eb9e62015-04-01 05:20:42 +0000306 if (CH->getSelector()->isNullValue()) {
307 HT.Adjectives = 0x40;
308 HT.TypeDescriptor = nullptr;
309 } else {
310 auto *GV = cast<GlobalVariable>(CH->getSelector()->stripPointerCasts());
311 // Selectors are always pointers to GlobalVariables with 'struct' type.
312 // The struct has two fields, adjectives and a type descriptor.
313 auto *CS = cast<ConstantStruct>(GV->getInitializer());
314 HT.Adjectives =
315 cast<ConstantInt>(CS->getAggregateElement(0U))->getZExtValue();
316 HT.TypeDescriptor =
317 cast<GlobalVariable>(CS->getAggregateElement(1)->stripPointerCasts());
318 }
David Majnemera225a192015-03-31 22:35:44 +0000319 HT.Handler = cast<Function>(CH->getHandlerBlockOrFunc());
David Majnemer69132a72015-04-03 22:49:05 +0000320 HT.CatchObjRecoverIdx = CH->getExceptionVarIndex();
David Majnemera225a192015-03-31 22:35:44 +0000321 TBME.HandlerArray.push_back(HT);
322 }
323 FuncInfo.TryBlockMap.push_back(TBME);
324}
325
David Majnemercde33032015-03-30 22:58:10 +0000326static void print_name(const Value *V) {
David Majnemer9a555392015-03-30 23:14:45 +0000327#ifndef NDEBUG
David Majnemercde33032015-03-30 22:58:10 +0000328 if (!V) {
329 DEBUG(dbgs() << "null");
330 return;
331 }
332
333 if (const auto *F = dyn_cast<Function>(V))
334 DEBUG(dbgs() << F->getName());
335 else
336 DEBUG(V->dump());
David Majnemer9a555392015-03-30 23:14:45 +0000337#endif
David Majnemercde33032015-03-30 22:58:10 +0000338}
339
David Majnemera225a192015-03-31 22:35:44 +0000340void WinEHNumbering::processCallSite(ArrayRef<ActionHandler *> Actions,
341 ImmutableCallSite CS) {
David Majnemercde33032015-03-30 22:58:10 +0000342 int FirstMismatch = 0;
343 for (int E = std::min(HandlerStack.size(), Actions.size()); FirstMismatch < E;
344 ++FirstMismatch) {
345 if (HandlerStack[FirstMismatch]->getHandlerBlockOrFunc() !=
346 Actions[FirstMismatch]->getHandlerBlockOrFunc())
347 break;
348 delete Actions[FirstMismatch];
349 }
350
David Majnemera225a192015-03-31 22:35:44 +0000351 bool EnteringScope = (int)Actions.size() > FirstMismatch;
David Majnemera225a192015-03-31 22:35:44 +0000352
David Majnemercde33032015-03-30 22:58:10 +0000353 // Don't recurse while we are looping over the handler stack. Instead, defer
354 // the numbering of the catch handlers until we are done popping.
David Majnemera225a192015-03-31 22:35:44 +0000355 SmallVector<CatchHandler *, 4> PoppedCatches;
David Majnemercde33032015-03-30 22:58:10 +0000356 for (int I = HandlerStack.size() - 1; I >= FirstMismatch; --I) {
David Majnemera225a192015-03-31 22:35:44 +0000357 if (auto *CH = dyn_cast<CatchHandler>(HandlerStack.back())) {
358 PoppedCatches.push_back(CH);
359 } else {
360 // Delete cleanup handlers
361 delete HandlerStack.back();
362 }
David Majnemercde33032015-03-30 22:58:10 +0000363 HandlerStack.pop_back();
364 }
365
David Majnemera225a192015-03-31 22:35:44 +0000366 // We need to create a new state number if we are exiting a try scope and we
367 // will not push any more actions.
368 int TryHigh = NextState - 1;
David Majnemerd1079bf2015-03-31 22:43:56 +0000369 if (!EnteringScope && !PoppedCatches.empty()) {
David Majnemera225a192015-03-31 22:35:44 +0000370 createUnwindMapEntry(currentEHNumber(), nullptr);
371 ++NextState;
372 }
David Majnemercde33032015-03-30 22:58:10 +0000373
David Majnemera225a192015-03-31 22:35:44 +0000374 int LastTryLowIdx = 0;
375 for (int I = 0, E = PoppedCatches.size(); I != E; ++I) {
376 CatchHandler *CH = PoppedCatches[I];
377 if (I + 1 == E || CH->getEHState() != PoppedCatches[I + 1]->getEHState()) {
378 int TryLow = CH->getEHState();
379 auto Handlers =
380 makeArrayRef(&PoppedCatches[LastTryLowIdx], I - LastTryLowIdx + 1);
381 createTryBlockMapEntry(TryLow, TryHigh, Handlers);
382 LastTryLowIdx = I + 1;
383 }
384 }
385
386 for (CatchHandler *CH : PoppedCatches) {
387 if (auto *F = dyn_cast<Function>(CH->getHandlerBlockOrFunc()))
388 calculateStateNumbers(*F);
389 delete CH;
390 }
391
392 bool LastActionWasCatch = false;
David Majnemercde33032015-03-30 22:58:10 +0000393 for (size_t I = FirstMismatch; I != Actions.size(); ++I) {
David Majnemera225a192015-03-31 22:35:44 +0000394 // We can reuse eh states when pushing two catches for the same invoke.
395 bool CurrActionIsCatch = isa<CatchHandler>(Actions[I]);
396 // FIXME: Reenable this optimization!
397 if (CurrActionIsCatch && LastActionWasCatch && false) {
398 Actions[I]->setEHState(currentEHNumber());
399 } else {
400 createUnwindMapEntry(currentEHNumber(), Actions[I]);
401 Actions[I]->setEHState(NextState);
402 NextState++;
403 DEBUG(dbgs() << "Creating unwind map entry for: (");
404 print_name(Actions[I]->getHandlerBlockOrFunc());
405 DEBUG(dbgs() << ", " << currentEHNumber() << ")\n");
406 }
David Majnemercde33032015-03-30 22:58:10 +0000407 HandlerStack.push_back(Actions[I]);
David Majnemera225a192015-03-31 22:35:44 +0000408 LastActionWasCatch = CurrActionIsCatch;
David Majnemercde33032015-03-30 22:58:10 +0000409 }
410
411 DEBUG(dbgs() << "In EHState " << currentEHNumber() << " for CallSite: ");
412 print_name(CS ? CS.getCalledValue() : nullptr);
413 DEBUG(dbgs() << '\n');
414}
415
416void WinEHNumbering::calculateStateNumbers(const Function &F) {
David Majnemera225a192015-03-31 22:35:44 +0000417 auto I = VisitedHandlers.insert(&F);
418 if (!I.second)
419 return; // We've already visited this handler, don't renumber it.
420
David Majnemercde33032015-03-30 22:58:10 +0000421 DEBUG(dbgs() << "Calculating state numbers for: " << F.getName() << '\n');
422 SmallVector<ActionHandler *, 4> ActionList;
423 for (const BasicBlock &BB : F) {
424 for (const Instruction &I : BB) {
425 const auto *CI = dyn_cast<CallInst>(&I);
426 if (!CI || CI->doesNotThrow())
427 continue;
David Majnemera225a192015-03-31 22:35:44 +0000428 processCallSite(None, CI);
David Majnemercde33032015-03-30 22:58:10 +0000429 }
430 const auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
431 if (!II)
432 continue;
433 const LandingPadInst *LPI = II->getLandingPadInst();
David Majnemera225a192015-03-31 22:35:44 +0000434 auto *ActionsCall = dyn_cast<IntrinsicInst>(LPI->getNextNode());
435 if (!ActionsCall)
436 continue;
437 assert(ActionsCall->getIntrinsicID() == Intrinsic::eh_actions);
438 parseEHActions(ActionsCall, ActionList);
439 processCallSite(ActionList, II);
440 ActionList.clear();
441 FuncInfo.LandingPadStateMap[LPI] = currentEHNumber();
David Majnemercde33032015-03-30 22:58:10 +0000442 }
David Majnemer7f5e7142015-04-03 23:37:34 +0000443
444 FuncInfo.CatchHandlerMaxState[&F] = NextState - 1;
Dan Gohmana3624b62009-11-23 17:16:22 +0000445}
446
447/// clear - Clear out all the function-specific state. This returns this
448/// FunctionLoweringInfo to an empty state, ready to be used for a
449/// different function.
450void FunctionLoweringInfo::clear() {
Dan Gohmanad0b3ea2010-04-14 17:11:23 +0000451 assert(CatchInfoFound.size() == CatchInfoLost.size() &&
452 "Not all catch info was assigned to a landing pad!");
453
Dan Gohmana3624b62009-11-23 17:16:22 +0000454 MBBMap.clear();
455 ValueMap.clear();
456 StaticAllocaMap.clear();
457#ifndef NDEBUG
458 CatchInfoLost.clear();
459 CatchInfoFound.clear();
460#endif
461 LiveOutRegInfo.clear();
Cameron Zwarich988faf92011-02-24 10:00:13 +0000462 VisitedBBs.clear();
Evan Cheng6e822452010-04-28 23:08:54 +0000463 ArgDbgValues.clear();
Devang Patel86ec8b32010-08-31 22:22:42 +0000464 ByValArgFrameIndexMap.clear();
Dan Gohmand7b5ce32010-07-10 09:00:22 +0000465 RegFixups.clear();
Philip Reames1a1bdb22014-12-02 18:50:36 +0000466 StatepointStackSlots.clear();
Jiangning Liu3b096172014-09-24 03:22:56 +0000467 PreferredExtendType.clear();
Dan Gohmana3624b62009-11-23 17:16:22 +0000468}
469
Dan Gohman93f59202010-07-02 00:10:16 +0000470/// CreateReg - Allocate a single virtual register for the given type.
Patrik Hagglund5e6c3612012-12-13 06:34:11 +0000471unsigned FunctionLoweringInfo::CreateReg(MVT VT) {
Eric Christopherd9134482014-08-04 21:25:23 +0000472 return RegInfo->createVirtualRegister(
Eric Christopher2ae2de72014-10-09 00:57:31 +0000473 MF->getSubtarget().getTargetLowering()->getRegClassFor(VT));
Dan Gohmana3624b62009-11-23 17:16:22 +0000474}
475
Dan Gohman93f59202010-07-02 00:10:16 +0000476/// CreateRegs - Allocate the appropriate number of virtual registers of
Dan Gohmana3624b62009-11-23 17:16:22 +0000477/// the correctly promoted or expanded types. Assign these registers
478/// consecutive vreg numbers and return the first assigned number.
479///
480/// In the case that the given value has struct or array type, this function
481/// will assign registers for each member or element.
482///
Chris Lattner229907c2011-07-18 04:54:35 +0000483unsigned FunctionLoweringInfo::CreateRegs(Type *Ty) {
Eric Christopher2ae2de72014-10-09 00:57:31 +0000484 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
Bill Wendling0ccf3102013-06-19 20:32:16 +0000485
Dan Gohmana3624b62009-11-23 17:16:22 +0000486 SmallVector<EVT, 4> ValueVTs;
Bill Wendling8db01cb2013-06-06 00:11:39 +0000487 ComputeValueVTs(*TLI, Ty, ValueVTs);
Dan Gohmana3624b62009-11-23 17:16:22 +0000488
489 unsigned FirstReg = 0;
490 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
491 EVT ValueVT = ValueVTs[Value];
Bill Wendling8db01cb2013-06-06 00:11:39 +0000492 MVT RegisterVT = TLI->getRegisterType(Ty->getContext(), ValueVT);
Dan Gohmana3624b62009-11-23 17:16:22 +0000493
Bill Wendling8db01cb2013-06-06 00:11:39 +0000494 unsigned NumRegs = TLI->getNumRegisters(Ty->getContext(), ValueVT);
Dan Gohmana3624b62009-11-23 17:16:22 +0000495 for (unsigned i = 0; i != NumRegs; ++i) {
Dan Gohman93f59202010-07-02 00:10:16 +0000496 unsigned R = CreateReg(RegisterVT);
Dan Gohmana3624b62009-11-23 17:16:22 +0000497 if (!FirstReg) FirstReg = R;
498 }
499 }
500 return FirstReg;
501}
Dan Gohmanad97b3d2009-11-23 17:42:46 +0000502
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000503/// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the
504/// register is a PHI destination and the PHI's LiveOutInfo is not valid. If
505/// the register's LiveOutInfo is for a smaller bit width, it is extended to
506/// the larger bit width by zero extension. The bit width must be no smaller
507/// than the LiveOutInfo's existing bit width.
508const FunctionLoweringInfo::LiveOutInfo *
509FunctionLoweringInfo::GetLiveOutRegInfo(unsigned Reg, unsigned BitWidth) {
510 if (!LiveOutRegInfo.inBounds(Reg))
Craig Topperc0196b12014-04-14 00:51:57 +0000511 return nullptr;
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000512
513 LiveOutInfo *LOI = &LiveOutRegInfo[Reg];
514 if (!LOI->IsValid)
Craig Topperc0196b12014-04-14 00:51:57 +0000515 return nullptr;
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000516
Cameron Zwarichd2f30412011-02-25 01:10:55 +0000517 if (BitWidth > LOI->KnownZero.getBitWidth()) {
Cameron Zwarich4c82cd22011-02-25 01:11:01 +0000518 LOI->NumSignBits = 1;
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000519 LOI->KnownZero = LOI->KnownZero.zextOrTrunc(BitWidth);
520 LOI->KnownOne = LOI->KnownOne.zextOrTrunc(BitWidth);
521 }
522
523 return LOI;
524}
525
526/// ComputePHILiveOutRegInfo - Compute LiveOutInfo for a PHI's destination
527/// register based on the LiveOutInfo of its operands.
528void FunctionLoweringInfo::ComputePHILiveOutRegInfo(const PHINode *PN) {
Chris Lattner229907c2011-07-18 04:54:35 +0000529 Type *Ty = PN->getType();
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000530 if (!Ty->isIntegerTy() || Ty->isVectorTy())
531 return;
532
533 SmallVector<EVT, 1> ValueVTs;
Bill Wendling8db01cb2013-06-06 00:11:39 +0000534 ComputeValueVTs(*TLI, Ty, ValueVTs);
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000535 assert(ValueVTs.size() == 1 &&
536 "PHIs with non-vector integer types should have a single VT.");
537 EVT IntVT = ValueVTs[0];
538
Bill Wendling8db01cb2013-06-06 00:11:39 +0000539 if (TLI->getNumRegisters(PN->getContext(), IntVT) != 1)
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000540 return;
Bill Wendling8db01cb2013-06-06 00:11:39 +0000541 IntVT = TLI->getTypeToTransformTo(PN->getContext(), IntVT);
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000542 unsigned BitWidth = IntVT.getSizeInBits();
543
544 unsigned DestReg = ValueMap[PN];
545 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
546 return;
547 LiveOutRegInfo.grow(DestReg);
548 LiveOutInfo &DestLOI = LiveOutRegInfo[DestReg];
549
550 Value *V = PN->getIncomingValue(0);
551 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
552 DestLOI.NumSignBits = 1;
553 APInt Zero(BitWidth, 0);
554 DestLOI.KnownZero = Zero;
555 DestLOI.KnownOne = Zero;
556 return;
557 }
558
559 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
560 APInt Val = CI->getValue().zextOrTrunc(BitWidth);
561 DestLOI.NumSignBits = Val.getNumSignBits();
562 DestLOI.KnownZero = ~Val;
563 DestLOI.KnownOne = Val;
564 } else {
565 assert(ValueMap.count(V) && "V should have been placed in ValueMap when its"
566 "CopyToReg node was created.");
567 unsigned SrcReg = ValueMap[V];
568 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
569 DestLOI.IsValid = false;
570 return;
571 }
572 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
573 if (!SrcLOI) {
574 DestLOI.IsValid = false;
575 return;
576 }
577 DestLOI = *SrcLOI;
578 }
579
580 assert(DestLOI.KnownZero.getBitWidth() == BitWidth &&
581 DestLOI.KnownOne.getBitWidth() == BitWidth &&
582 "Masks should have the same bit width as the type.");
583
584 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
585 Value *V = PN->getIncomingValue(i);
586 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
587 DestLOI.NumSignBits = 1;
588 APInt Zero(BitWidth, 0);
589 DestLOI.KnownZero = Zero;
590 DestLOI.KnownOne = Zero;
Eric Christopher0713a9d2011-06-08 23:55:35 +0000591 return;
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000592 }
593
594 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
595 APInt Val = CI->getValue().zextOrTrunc(BitWidth);
596 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, Val.getNumSignBits());
597 DestLOI.KnownZero &= ~Val;
598 DestLOI.KnownOne &= Val;
599 continue;
600 }
601
602 assert(ValueMap.count(V) && "V should have been placed in ValueMap when "
603 "its CopyToReg node was created.");
604 unsigned SrcReg = ValueMap[V];
605 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
606 DestLOI.IsValid = false;
607 return;
608 }
609 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
610 if (!SrcLOI) {
611 DestLOI.IsValid = false;
612 return;
613 }
614 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, SrcLOI->NumSignBits);
615 DestLOI.KnownZero &= SrcLOI->KnownZero;
616 DestLOI.KnownOne &= SrcLOI->KnownOne;
617 }
618}
619
Devang Patel9d904e12011-09-08 22:59:09 +0000620/// setArgumentFrameIndex - Record frame index for the byval
Devang Patel86ec8b32010-08-31 22:22:42 +0000621/// argument. This overrides previous frame index entry for this argument,
622/// if any.
Devang Patel9d904e12011-09-08 22:59:09 +0000623void FunctionLoweringInfo::setArgumentFrameIndex(const Argument *A,
Eric Christopher219d51d2012-02-24 01:59:01 +0000624 int FI) {
Devang Patel86ec8b32010-08-31 22:22:42 +0000625 ByValArgFrameIndexMap[A] = FI;
626}
Eric Christopher0713a9d2011-06-08 23:55:35 +0000627
Devang Patel9d904e12011-09-08 22:59:09 +0000628/// getArgumentFrameIndex - Get frame index for the byval argument.
Devang Patel86ec8b32010-08-31 22:22:42 +0000629/// If the argument does not have any assigned frame index then 0 is
630/// returned.
Devang Patel9d904e12011-09-08 22:59:09 +0000631int FunctionLoweringInfo::getArgumentFrameIndex(const Argument *A) {
Eric Christopher0713a9d2011-06-08 23:55:35 +0000632 DenseMap<const Argument *, int>::iterator I =
Devang Patel86ec8b32010-08-31 22:22:42 +0000633 ByValArgFrameIndexMap.find(A);
634 if (I != ByValArgFrameIndexMap.end())
635 return I->second;
Eric Christopher18c6be72012-02-23 03:39:43 +0000636 DEBUG(dbgs() << "Argument does not have assigned frame index!\n");
Devang Patel86ec8b32010-08-31 22:22:42 +0000637 return 0;
638}
639
Michael J. Spencer8b98bf22012-02-22 19:06:13 +0000640/// ComputeUsesVAFloatArgument - Determine if any floating-point values are
641/// being passed to this variadic function, and set the MachineModuleInfo's
642/// usesVAFloatArgument flag if so. This flag is used to emit an undefined
643/// reference to _fltused on Windows, which will link in MSVCRT's
644/// floating-point support.
645void llvm::ComputeUsesVAFloatArgument(const CallInst &I,
646 MachineModuleInfo *MMI)
647{
648 FunctionType *FT = cast<FunctionType>(
649 I.getCalledValue()->getType()->getContainedType(0));
650 if (FT->isVarArg() && !MMI->usesVAFloatArgument()) {
651 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
652 Type* T = I.getArgOperand(i)->getType();
653 for (po_iterator<Type*> i = po_begin(T), e = po_end(T);
654 i != e; ++i) {
655 if (i->isFloatingPointTy()) {
656 MMI->setUsesVAFloatArgument(true);
657 return;
658 }
659 }
660 }
661 }
662}
663
Bill Wendling247fd3b2011-08-17 21:56:44 +0000664/// AddLandingPadInfo - Extract the exception handling information from the
665/// landingpad instruction and add them to the specified machine module info.
666void llvm::AddLandingPadInfo(const LandingPadInst &I, MachineModuleInfo &MMI,
667 MachineBasicBlock *MBB) {
668 MMI.addPersonality(MBB,
669 cast<Function>(I.getPersonalityFn()->stripPointerCasts()));
670
671 if (I.isCleanup())
672 MMI.addCleanup(MBB);
673
674 // FIXME: New EH - Add the clauses in reverse order. This isn't 100% correct,
675 // but we need to do it this way because of how the DWARF EH emitter
676 // processes the clauses.
677 for (unsigned i = I.getNumClauses(); i != 0; --i) {
678 Value *Val = I.getClause(i - 1);
679 if (I.isCatch(i - 1)) {
680 MMI.addCatchTypeInfo(MBB,
Reid Kleckner283bc2e2014-11-14 00:35:50 +0000681 dyn_cast<GlobalValue>(Val->stripPointerCasts()));
Bill Wendling247fd3b2011-08-17 21:56:44 +0000682 } else {
683 // Add filters in a list.
684 Constant *CVal = cast<Constant>(Val);
Reid Kleckner283bc2e2014-11-14 00:35:50 +0000685 SmallVector<const GlobalValue*, 4> FilterList;
Bill Wendling247fd3b2011-08-17 21:56:44 +0000686 for (User::op_iterator
687 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II)
Reid Kleckner283bc2e2014-11-14 00:35:50 +0000688 FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts()));
Bill Wendling247fd3b2011-08-17 21:56:44 +0000689
690 MMI.addFilterTypeInfo(MBB, FilterList);
691 }
692 }
693}