Add a function for profiling to run at shutdown. Unlike the existing API, this
[llvm/stm8.git] / lib / CodeGen / SelectionDAG / FunctionLoweringInfo.cpp
blobd8a5770d36c08703a75e0e77d9060b7fa637cdcc
1 //===-- 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.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "function-lowering-info"
16 #include "llvm/CodeGen/FunctionLoweringInfo.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/IntrinsicInst.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Module.h"
23 #include "llvm/Analysis/DebugInfo.h"
24 #include "llvm/CodeGen/Analysis.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineModuleInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/Target/TargetRegisterInfo.h"
31 #include "llvm/Target/TargetData.h"
32 #include "llvm/Target/TargetInstrInfo.h"
33 #include "llvm/Target/TargetLowering.h"
34 #include "llvm/Target/TargetOptions.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include <algorithm>
39 using namespace llvm;
41 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
42 /// PHI nodes or outside of the basic block that defines it, or used by a
43 /// switch or atomic instruction, which may expand to multiple basic blocks.
44 static bool isUsedOutsideOfDefiningBlock(const Instruction *I) {
45 if (I->use_empty()) return false;
46 if (isa<PHINode>(I)) return true;
47 const BasicBlock *BB = I->getParent();
48 for (Value::const_use_iterator UI = I->use_begin(), E = I->use_end();
49 UI != E; ++UI) {
50 const User *U = *UI;
51 if (cast<Instruction>(U)->getParent() != BB || isa<PHINode>(U))
52 return true;
54 return false;
57 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
58 /// entry block, return true. This includes arguments used by switches, since
59 /// the switch may expand into multiple basic blocks.
60 static bool isOnlyUsedInEntryBlock(const Argument *A, bool EnableFastISel) {
61 // With FastISel active, we may be splitting blocks, so force creation
62 // of virtual registers for all non-dead arguments.
63 if (EnableFastISel)
64 return A->use_empty();
66 const BasicBlock *Entry = A->getParent()->begin();
67 for (Value::const_use_iterator UI = A->use_begin(), E = A->use_end();
68 UI != E; ++UI) {
69 const User *U = *UI;
70 if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U))
71 return false; // Use not in entry block.
73 return true;
76 FunctionLoweringInfo::FunctionLoweringInfo(const TargetLowering &tli)
77 : TLI(tli) {
80 void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf) {
81 Fn = &fn;
82 MF = &mf;
83 RegInfo = &MF->getRegInfo();
85 // Check whether the function can return without sret-demotion.
86 SmallVector<ISD::OutputArg, 4> Outs;
87 GetReturnInfo(Fn->getReturnType(),
88 Fn->getAttributes().getRetAttributes(), Outs, TLI);
89 CanLowerReturn = TLI.CanLowerReturn(Fn->getCallingConv(), Fn->isVarArg(),
90 Outs, Fn->getContext());
92 // Create a vreg for each argument register that is not dead and is used
93 // outside of the entry block for the function.
94 for (Function::const_arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
95 AI != E; ++AI)
96 if (!isOnlyUsedInEntryBlock(AI, EnableFastISel))
97 InitializeRegForValue(AI);
99 // Initialize the mapping of values to registers. This is only set up for
100 // instruction values that are used outside of the block that defines
101 // them.
102 Function::const_iterator BB = Fn->begin(), EB = Fn->end();
103 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
104 if (const AllocaInst *AI = dyn_cast<AllocaInst>(I))
105 if (const ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
106 const Type *Ty = AI->getAllocatedType();
107 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
108 unsigned Align =
109 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
110 AI->getAlignment());
112 TySize *= CUI->getZExtValue(); // Get total allocated size.
113 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
115 // The object may need to be placed onto the stack near the stack
116 // protector if one exists. Determine here if this object is a suitable
117 // candidate. I.e., it would trigger the creation of a stack protector.
118 bool MayNeedSP =
119 (AI->isArrayAllocation() ||
120 (TySize > 8 && isa<ArrayType>(Ty) &&
121 cast<ArrayType>(Ty)->getElementType()->isIntegerTy(8)));
122 StaticAllocaMap[AI] =
123 MF->getFrameInfo()->CreateStackObject(TySize, Align, false, MayNeedSP);
126 for (; BB != EB; ++BB)
127 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
128 // Mark values used outside their block as exported, by allocating
129 // a virtual register for them.
130 if (isUsedOutsideOfDefiningBlock(I))
131 if (!isa<AllocaInst>(I) ||
132 !StaticAllocaMap.count(cast<AllocaInst>(I)))
133 InitializeRegForValue(I);
135 // Collect llvm.dbg.declare information. This is done now instead of
136 // during the initial isel pass through the IR so that it is done
137 // in a predictable order.
138 if (const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(I)) {
139 MachineModuleInfo &MMI = MF->getMMI();
140 if (MMI.hasDebugInfo() &&
141 DIVariable(DI->getVariable()).Verify() &&
142 !DI->getDebugLoc().isUnknown()) {
143 // Don't handle byval struct arguments or VLAs, for example.
144 // Non-byval arguments are handled here (they refer to the stack
145 // temporary alloca at this point).
146 const Value *Address = DI->getAddress();
147 if (Address) {
148 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
149 Address = BCI->getOperand(0);
150 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
151 DenseMap<const AllocaInst *, int>::iterator SI =
152 StaticAllocaMap.find(AI);
153 if (SI != StaticAllocaMap.end()) { // Check for VLAs.
154 int FI = SI->second;
155 MMI.setVariableDbgInfo(DI->getVariable(),
156 FI, DI->getDebugLoc());
164 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
165 // also creates the initial PHI MachineInstrs, though none of the input
166 // operands are populated.
167 for (BB = Fn->begin(); BB != EB; ++BB) {
168 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
169 MBBMap[BB] = MBB;
170 MF->push_back(MBB);
172 // Transfer the address-taken flag. This is necessary because there could
173 // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
174 // the first one should be marked.
175 if (BB->hasAddressTaken())
176 MBB->setHasAddressTaken();
178 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
179 // appropriate.
180 for (BasicBlock::const_iterator I = BB->begin();
181 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
182 if (PN->use_empty()) continue;
184 DebugLoc DL = PN->getDebugLoc();
185 unsigned PHIReg = ValueMap[PN];
186 assert(PHIReg && "PHI node does not have an assigned virtual register!");
188 SmallVector<EVT, 4> ValueVTs;
189 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
190 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
191 EVT VT = ValueVTs[vti];
192 unsigned NumRegisters = TLI.getNumRegisters(Fn->getContext(), VT);
193 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
194 for (unsigned i = 0; i != NumRegisters; ++i)
195 BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i);
196 PHIReg += NumRegisters;
201 // Mark landing pad blocks.
202 for (BB = Fn->begin(); BB != EB; ++BB)
203 if (const InvokeInst *Invoke = dyn_cast<InvokeInst>(BB->getTerminator()))
204 MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
207 /// clear - Clear out all the function-specific state. This returns this
208 /// FunctionLoweringInfo to an empty state, ready to be used for a
209 /// different function.
210 void FunctionLoweringInfo::clear() {
211 assert(CatchInfoFound.size() == CatchInfoLost.size() &&
212 "Not all catch info was assigned to a landing pad!");
214 MBBMap.clear();
215 ValueMap.clear();
216 StaticAllocaMap.clear();
217 #ifndef NDEBUG
218 CatchInfoLost.clear();
219 CatchInfoFound.clear();
220 #endif
221 LiveOutRegInfo.clear();
222 VisitedBBs.clear();
223 ArgDbgValues.clear();
224 ByValArgFrameIndexMap.clear();
225 RegFixups.clear();
228 /// CreateReg - Allocate a single virtual register for the given type.
229 unsigned FunctionLoweringInfo::CreateReg(EVT VT) {
230 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
233 /// CreateRegs - Allocate the appropriate number of virtual registers of
234 /// the correctly promoted or expanded types. Assign these registers
235 /// consecutive vreg numbers and return the first assigned number.
237 /// In the case that the given value has struct or array type, this function
238 /// will assign registers for each member or element.
240 unsigned FunctionLoweringInfo::CreateRegs(const Type *Ty) {
241 SmallVector<EVT, 4> ValueVTs;
242 ComputeValueVTs(TLI, Ty, ValueVTs);
244 unsigned FirstReg = 0;
245 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
246 EVT ValueVT = ValueVTs[Value];
247 EVT RegisterVT = TLI.getRegisterType(Ty->getContext(), ValueVT);
249 unsigned NumRegs = TLI.getNumRegisters(Ty->getContext(), ValueVT);
250 for (unsigned i = 0; i != NumRegs; ++i) {
251 unsigned R = CreateReg(RegisterVT);
252 if (!FirstReg) FirstReg = R;
255 return FirstReg;
258 /// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the
259 /// register is a PHI destination and the PHI's LiveOutInfo is not valid. If
260 /// the register's LiveOutInfo is for a smaller bit width, it is extended to
261 /// the larger bit width by zero extension. The bit width must be no smaller
262 /// than the LiveOutInfo's existing bit width.
263 const FunctionLoweringInfo::LiveOutInfo *
264 FunctionLoweringInfo::GetLiveOutRegInfo(unsigned Reg, unsigned BitWidth) {
265 if (!LiveOutRegInfo.inBounds(Reg))
266 return NULL;
268 LiveOutInfo *LOI = &LiveOutRegInfo[Reg];
269 if (!LOI->IsValid)
270 return NULL;
272 if (BitWidth > LOI->KnownZero.getBitWidth()) {
273 LOI->NumSignBits = 1;
274 LOI->KnownZero = LOI->KnownZero.zextOrTrunc(BitWidth);
275 LOI->KnownOne = LOI->KnownOne.zextOrTrunc(BitWidth);
278 return LOI;
281 /// ComputePHILiveOutRegInfo - Compute LiveOutInfo for a PHI's destination
282 /// register based on the LiveOutInfo of its operands.
283 void FunctionLoweringInfo::ComputePHILiveOutRegInfo(const PHINode *PN) {
284 const Type *Ty = PN->getType();
285 if (!Ty->isIntegerTy() || Ty->isVectorTy())
286 return;
288 SmallVector<EVT, 1> ValueVTs;
289 ComputeValueVTs(TLI, Ty, ValueVTs);
290 assert(ValueVTs.size() == 1 &&
291 "PHIs with non-vector integer types should have a single VT.");
292 EVT IntVT = ValueVTs[0];
294 if (TLI.getNumRegisters(PN->getContext(), IntVT) != 1)
295 return;
296 IntVT = TLI.getTypeToTransformTo(PN->getContext(), IntVT);
297 unsigned BitWidth = IntVT.getSizeInBits();
299 unsigned DestReg = ValueMap[PN];
300 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
301 return;
302 LiveOutRegInfo.grow(DestReg);
303 LiveOutInfo &DestLOI = LiveOutRegInfo[DestReg];
305 Value *V = PN->getIncomingValue(0);
306 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
307 DestLOI.NumSignBits = 1;
308 APInt Zero(BitWidth, 0);
309 DestLOI.KnownZero = Zero;
310 DestLOI.KnownOne = Zero;
311 return;
314 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
315 APInt Val = CI->getValue().zextOrTrunc(BitWidth);
316 DestLOI.NumSignBits = Val.getNumSignBits();
317 DestLOI.KnownZero = ~Val;
318 DestLOI.KnownOne = Val;
319 } else {
320 assert(ValueMap.count(V) && "V should have been placed in ValueMap when its"
321 "CopyToReg node was created.");
322 unsigned SrcReg = ValueMap[V];
323 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
324 DestLOI.IsValid = false;
325 return;
327 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
328 if (!SrcLOI) {
329 DestLOI.IsValid = false;
330 return;
332 DestLOI = *SrcLOI;
335 assert(DestLOI.KnownZero.getBitWidth() == BitWidth &&
336 DestLOI.KnownOne.getBitWidth() == BitWidth &&
337 "Masks should have the same bit width as the type.");
339 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
340 Value *V = PN->getIncomingValue(i);
341 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
342 DestLOI.NumSignBits = 1;
343 APInt Zero(BitWidth, 0);
344 DestLOI.KnownZero = Zero;
345 DestLOI.KnownOne = Zero;
346 return;
349 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
350 APInt Val = CI->getValue().zextOrTrunc(BitWidth);
351 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, Val.getNumSignBits());
352 DestLOI.KnownZero &= ~Val;
353 DestLOI.KnownOne &= Val;
354 continue;
357 assert(ValueMap.count(V) && "V should have been placed in ValueMap when "
358 "its CopyToReg node was created.");
359 unsigned SrcReg = ValueMap[V];
360 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
361 DestLOI.IsValid = false;
362 return;
364 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
365 if (!SrcLOI) {
366 DestLOI.IsValid = false;
367 return;
369 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, SrcLOI->NumSignBits);
370 DestLOI.KnownZero &= SrcLOI->KnownZero;
371 DestLOI.KnownOne &= SrcLOI->KnownOne;
375 /// setByValArgumentFrameIndex - Record frame index for the byval
376 /// argument. This overrides previous frame index entry for this argument,
377 /// if any.
378 void FunctionLoweringInfo::setByValArgumentFrameIndex(const Argument *A,
379 int FI) {
380 assert (A->hasByValAttr() && "Argument does not have byval attribute!");
381 ByValArgFrameIndexMap[A] = FI;
384 /// getByValArgumentFrameIndex - Get frame index for the byval argument.
385 /// If the argument does not have any assigned frame index then 0 is
386 /// returned.
387 int FunctionLoweringInfo::getByValArgumentFrameIndex(const Argument *A) {
388 assert (A->hasByValAttr() && "Argument does not have byval attribute!");
389 DenseMap<const Argument *, int>::iterator I =
390 ByValArgFrameIndexMap.find(A);
391 if (I != ByValArgFrameIndexMap.end())
392 return I->second;
393 DEBUG(dbgs() << "Argument does not have assigned frame index!");
394 return 0;
397 /// AddCatchInfo - Extract the personality and type infos from an eh.selector
398 /// call, and add them to the specified machine basic block.
399 void llvm::AddCatchInfo(const CallInst &I, MachineModuleInfo *MMI,
400 MachineBasicBlock *MBB) {
401 // Inform the MachineModuleInfo of the personality for this landing pad.
402 const ConstantExpr *CE = cast<ConstantExpr>(I.getArgOperand(1));
403 assert(CE->getOpcode() == Instruction::BitCast &&
404 isa<Function>(CE->getOperand(0)) &&
405 "Personality should be a function");
406 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
408 // Gather all the type infos for this landing pad and pass them along to
409 // MachineModuleInfo.
410 std::vector<const GlobalVariable *> TyInfo;
411 unsigned N = I.getNumArgOperands();
413 for (unsigned i = N - 1; i > 1; --i) {
414 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(i))) {
415 unsigned FilterLength = CI->getZExtValue();
416 unsigned FirstCatch = i + FilterLength + !FilterLength;
417 assert(FirstCatch <= N && "Invalid filter length");
419 if (FirstCatch < N) {
420 TyInfo.reserve(N - FirstCatch);
421 for (unsigned j = FirstCatch; j < N; ++j)
422 TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
423 MMI->addCatchTypeInfo(MBB, TyInfo);
424 TyInfo.clear();
427 if (!FilterLength) {
428 // Cleanup.
429 MMI->addCleanup(MBB);
430 } else {
431 // Filter.
432 TyInfo.reserve(FilterLength - 1);
433 for (unsigned j = i + 1; j < FirstCatch; ++j)
434 TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
435 MMI->addFilterTypeInfo(MBB, TyInfo);
436 TyInfo.clear();
439 N = i;
443 if (N > 2) {
444 TyInfo.reserve(N - 2);
445 for (unsigned j = 2; j < N; ++j)
446 TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
447 MMI->addCatchTypeInfo(MBB, TyInfo);
451 void llvm::CopyCatchInfo(const BasicBlock *SuccBB, const BasicBlock *LPad,
452 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
453 SmallPtrSet<const BasicBlock*, 4> Visited;
455 // The 'eh.selector' call may not be in the direct successor of a basic block,
456 // but could be several successors deeper. If we don't find it, try going one
457 // level further. <rdar://problem/8824861>
458 while (Visited.insert(SuccBB)) {
459 for (BasicBlock::const_iterator I = SuccBB->begin(), E = --SuccBB->end();
460 I != E; ++I)
461 if (const EHSelectorInst *EHSel = dyn_cast<EHSelectorInst>(I)) {
462 // Apply the catch info to LPad.
463 AddCatchInfo(*EHSel, MMI, FLI.MBBMap[LPad]);
464 #ifndef NDEBUG
465 if (!FLI.MBBMap[SuccBB]->isLandingPad())
466 FLI.CatchInfoFound.insert(EHSel);
467 #endif
468 return;
471 const BranchInst *Br = dyn_cast<BranchInst>(SuccBB->getTerminator());
472 if (Br && Br->isUnconditional())
473 SuccBB = Br->getSuccessor(0);
474 else
475 break;