Properly emit _fltused with FastISel. Refactor to share code with SDAG.
[oota-llvm.git] / lib / CodeGen / SelectionDAG / FunctionLoweringInfo.cpp
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.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "function-lowering-info"
16 #include "llvm/ADT/PostOrderIterator.h"
17 #include "llvm/CodeGen/FunctionLoweringInfo.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Function.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/IntrinsicInst.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/Module.h"
24 #include "llvm/Analysis/DebugInfo.h"
25 #include "llvm/CodeGen/Analysis.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineModuleInfo.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
32 #include "llvm/Target/TargetData.h"
33 #include "llvm/Target/TargetInstrInfo.h"
34 #include "llvm/Target/TargetLowering.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/MathExtras.h"
39 #include <algorithm>
40 using namespace llvm;
41
42 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
43 /// PHI nodes or outside of the basic block that defines it, or used by a
44 /// switch or atomic instruction, which may expand to multiple basic blocks.
45 static bool isUsedOutsideOfDefiningBlock(const Instruction *I) {
46   if (I->use_empty()) return false;
47   if (isa<PHINode>(I)) return true;
48   const BasicBlock *BB = I->getParent();
49   for (Value::const_use_iterator UI = I->use_begin(), E = I->use_end();
50         UI != E; ++UI) {
51     const User *U = *UI;
52     if (cast<Instruction>(U)->getParent() != BB || isa<PHINode>(U))
53       return true;
54   }
55   return false;
56 }
57
58 FunctionLoweringInfo::FunctionLoweringInfo(const TargetLowering &tli)
59   : TLI(tli) {
60 }
61
62 void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf) {
63   Fn = &fn;
64   MF = &mf;
65   RegInfo = &MF->getRegInfo();
66
67   // Check whether the function can return without sret-demotion.
68   SmallVector<ISD::OutputArg, 4> Outs;
69   GetReturnInfo(Fn->getReturnType(),
70                 Fn->getAttributes().getRetAttributes(), Outs, TLI);
71   CanLowerReturn = TLI.CanLowerReturn(Fn->getCallingConv(), *MF,
72                                       Fn->isVarArg(),
73                                       Outs, Fn->getContext());
74
75   // Initialize the mapping of values to registers.  This is only set up for
76   // instruction values that are used outside of the block that defines
77   // them.
78   Function::const_iterator BB = Fn->begin(), EB = Fn->end();
79   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
80     if (const AllocaInst *AI = dyn_cast<AllocaInst>(I))
81       if (const ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
82         Type *Ty = AI->getAllocatedType();
83         uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
84         unsigned Align =
85           std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
86                    AI->getAlignment());
87
88         TySize *= CUI->getZExtValue();   // Get total allocated size.
89         if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
90
91         // The object may need to be placed onto the stack near the stack
92         // protector if one exists. Determine here if this object is a suitable
93         // candidate. I.e., it would trigger the creation of a stack protector.
94         bool MayNeedSP =
95           (AI->isArrayAllocation() ||
96            (TySize >= 8 && isa<ArrayType>(Ty) &&
97             cast<ArrayType>(Ty)->getElementType()->isIntegerTy(8)));
98         StaticAllocaMap[AI] =
99           MF->getFrameInfo()->CreateStackObject(TySize, Align, false, MayNeedSP);
100       }
101
102   for (; BB != EB; ++BB)
103     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
104       // Mark values used outside their block as exported, by allocating
105       // a virtual register for them.
106       if (isUsedOutsideOfDefiningBlock(I))
107         if (!isa<AllocaInst>(I) ||
108             !StaticAllocaMap.count(cast<AllocaInst>(I)))
109           InitializeRegForValue(I);
110
111       // Collect llvm.dbg.declare information. This is done now instead of
112       // during the initial isel pass through the IR so that it is done
113       // in a predictable order.
114       if (const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(I)) {
115         MachineModuleInfo &MMI = MF->getMMI();
116         if (MMI.hasDebugInfo() &&
117             DIVariable(DI->getVariable()).Verify() &&
118             !DI->getDebugLoc().isUnknown()) {
119           // Don't handle byval struct arguments or VLAs, for example.
120           // Non-byval arguments are handled here (they refer to the stack
121           // temporary alloca at this point).
122           const Value *Address = DI->getAddress();
123           if (Address) {
124             if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
125               Address = BCI->getOperand(0);
126             if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
127               DenseMap<const AllocaInst *, int>::iterator SI =
128                 StaticAllocaMap.find(AI);
129               if (SI != StaticAllocaMap.end()) { // Check for VLAs.
130                 int FI = SI->second;
131                 MMI.setVariableDbgInfo(DI->getVariable(),
132                                        FI, DI->getDebugLoc());
133               }
134             }
135           }
136         }
137       }
138     }
139
140   // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
141   // also creates the initial PHI MachineInstrs, though none of the input
142   // operands are populated.
143   for (BB = Fn->begin(); BB != EB; ++BB) {
144     MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
145     MBBMap[BB] = MBB;
146     MF->push_back(MBB);
147
148     // Transfer the address-taken flag. This is necessary because there could
149     // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
150     // the first one should be marked.
151     if (BB->hasAddressTaken())
152       MBB->setHasAddressTaken();
153
154     // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
155     // appropriate.
156     for (BasicBlock::const_iterator I = BB->begin();
157          const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
158       if (PN->use_empty()) continue;
159
160       // Skip empty types
161       if (PN->getType()->isEmptyTy())
162         continue;
163
164       DebugLoc DL = PN->getDebugLoc();
165       unsigned PHIReg = ValueMap[PN];
166       assert(PHIReg && "PHI node does not have an assigned virtual register!");
167
168       SmallVector<EVT, 4> ValueVTs;
169       ComputeValueVTs(TLI, PN->getType(), ValueVTs);
170       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
171         EVT VT = ValueVTs[vti];
172         unsigned NumRegisters = TLI.getNumRegisters(Fn->getContext(), VT);
173         const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
174         for (unsigned i = 0; i != NumRegisters; ++i)
175           BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i);
176         PHIReg += NumRegisters;
177       }
178     }
179   }
180
181   // Mark landing pad blocks.
182   for (BB = Fn->begin(); BB != EB; ++BB)
183     if (const InvokeInst *Invoke = dyn_cast<InvokeInst>(BB->getTerminator()))
184       MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
185 }
186
187 /// clear - Clear out all the function-specific state. This returns this
188 /// FunctionLoweringInfo to an empty state, ready to be used for a
189 /// different function.
190 void FunctionLoweringInfo::clear() {
191   assert(CatchInfoFound.size() == CatchInfoLost.size() &&
192          "Not all catch info was assigned to a landing pad!");
193
194   MBBMap.clear();
195   ValueMap.clear();
196   StaticAllocaMap.clear();
197 #ifndef NDEBUG
198   CatchInfoLost.clear();
199   CatchInfoFound.clear();
200 #endif
201   LiveOutRegInfo.clear();
202   VisitedBBs.clear();
203   ArgDbgValues.clear();
204   ByValArgFrameIndexMap.clear();
205   RegFixups.clear();
206 }
207
208 /// CreateReg - Allocate a single virtual register for the given type.
209 unsigned FunctionLoweringInfo::CreateReg(EVT VT) {
210   return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
211 }
212
213 /// CreateRegs - Allocate the appropriate number of virtual registers of
214 /// the correctly promoted or expanded types.  Assign these registers
215 /// consecutive vreg numbers and return the first assigned number.
216 ///
217 /// In the case that the given value has struct or array type, this function
218 /// will assign registers for each member or element.
219 ///
220 unsigned FunctionLoweringInfo::CreateRegs(Type *Ty) {
221   SmallVector<EVT, 4> ValueVTs;
222   ComputeValueVTs(TLI, Ty, ValueVTs);
223
224   unsigned FirstReg = 0;
225   for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
226     EVT ValueVT = ValueVTs[Value];
227     EVT RegisterVT = TLI.getRegisterType(Ty->getContext(), ValueVT);
228
229     unsigned NumRegs = TLI.getNumRegisters(Ty->getContext(), ValueVT);
230     for (unsigned i = 0; i != NumRegs; ++i) {
231       unsigned R = CreateReg(RegisterVT);
232       if (!FirstReg) FirstReg = R;
233     }
234   }
235   return FirstReg;
236 }
237
238 /// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the
239 /// register is a PHI destination and the PHI's LiveOutInfo is not valid. If
240 /// the register's LiveOutInfo is for a smaller bit width, it is extended to
241 /// the larger bit width by zero extension. The bit width must be no smaller
242 /// than the LiveOutInfo's existing bit width.
243 const FunctionLoweringInfo::LiveOutInfo *
244 FunctionLoweringInfo::GetLiveOutRegInfo(unsigned Reg, unsigned BitWidth) {
245   if (!LiveOutRegInfo.inBounds(Reg))
246     return NULL;
247
248   LiveOutInfo *LOI = &LiveOutRegInfo[Reg];
249   if (!LOI->IsValid)
250     return NULL;
251
252   if (BitWidth > LOI->KnownZero.getBitWidth()) {
253     LOI->NumSignBits = 1;
254     LOI->KnownZero = LOI->KnownZero.zextOrTrunc(BitWidth);
255     LOI->KnownOne = LOI->KnownOne.zextOrTrunc(BitWidth);
256   }
257
258   return LOI;
259 }
260
261 /// ComputePHILiveOutRegInfo - Compute LiveOutInfo for a PHI's destination
262 /// register based on the LiveOutInfo of its operands.
263 void FunctionLoweringInfo::ComputePHILiveOutRegInfo(const PHINode *PN) {
264   Type *Ty = PN->getType();
265   if (!Ty->isIntegerTy() || Ty->isVectorTy())
266     return;
267
268   SmallVector<EVT, 1> ValueVTs;
269   ComputeValueVTs(TLI, Ty, ValueVTs);
270   assert(ValueVTs.size() == 1 &&
271          "PHIs with non-vector integer types should have a single VT.");
272   EVT IntVT = ValueVTs[0];
273
274   if (TLI.getNumRegisters(PN->getContext(), IntVT) != 1)
275     return;
276   IntVT = TLI.getTypeToTransformTo(PN->getContext(), IntVT);
277   unsigned BitWidth = IntVT.getSizeInBits();
278
279   unsigned DestReg = ValueMap[PN];
280   if (!TargetRegisterInfo::isVirtualRegister(DestReg))
281     return;
282   LiveOutRegInfo.grow(DestReg);
283   LiveOutInfo &DestLOI = LiveOutRegInfo[DestReg];
284
285   Value *V = PN->getIncomingValue(0);
286   if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
287     DestLOI.NumSignBits = 1;
288     APInt Zero(BitWidth, 0);
289     DestLOI.KnownZero = Zero;
290     DestLOI.KnownOne = Zero;
291     return;
292   }
293
294   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
295     APInt Val = CI->getValue().zextOrTrunc(BitWidth);
296     DestLOI.NumSignBits = Val.getNumSignBits();
297     DestLOI.KnownZero = ~Val;
298     DestLOI.KnownOne = Val;
299   } else {
300     assert(ValueMap.count(V) && "V should have been placed in ValueMap when its"
301                                 "CopyToReg node was created.");
302     unsigned SrcReg = ValueMap[V];
303     if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
304       DestLOI.IsValid = false;
305       return;
306     }
307     const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
308     if (!SrcLOI) {
309       DestLOI.IsValid = false;
310       return;
311     }
312     DestLOI = *SrcLOI;
313   }
314
315   assert(DestLOI.KnownZero.getBitWidth() == BitWidth &&
316          DestLOI.KnownOne.getBitWidth() == BitWidth &&
317          "Masks should have the same bit width as the type.");
318
319   for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
320     Value *V = PN->getIncomingValue(i);
321     if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
322       DestLOI.NumSignBits = 1;
323       APInt Zero(BitWidth, 0);
324       DestLOI.KnownZero = Zero;
325       DestLOI.KnownOne = Zero;
326       return;
327     }
328
329     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
330       APInt Val = CI->getValue().zextOrTrunc(BitWidth);
331       DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, Val.getNumSignBits());
332       DestLOI.KnownZero &= ~Val;
333       DestLOI.KnownOne &= Val;
334       continue;
335     }
336
337     assert(ValueMap.count(V) && "V should have been placed in ValueMap when "
338                                 "its CopyToReg node was created.");
339     unsigned SrcReg = ValueMap[V];
340     if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
341       DestLOI.IsValid = false;
342       return;
343     }
344     const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
345     if (!SrcLOI) {
346       DestLOI.IsValid = false;
347       return;
348     }
349     DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, SrcLOI->NumSignBits);
350     DestLOI.KnownZero &= SrcLOI->KnownZero;
351     DestLOI.KnownOne &= SrcLOI->KnownOne;
352   }
353 }
354
355 /// setArgumentFrameIndex - Record frame index for the byval
356 /// argument. This overrides previous frame index entry for this argument,
357 /// if any.
358 void FunctionLoweringInfo::setArgumentFrameIndex(const Argument *A,
359                                                       int FI) {
360   ByValArgFrameIndexMap[A] = FI;
361 }
362
363 /// getArgumentFrameIndex - Get frame index for the byval argument.
364 /// If the argument does not have any assigned frame index then 0 is
365 /// returned.
366 int FunctionLoweringInfo::getArgumentFrameIndex(const Argument *A) {
367   DenseMap<const Argument *, int>::iterator I =
368     ByValArgFrameIndexMap.find(A);
369   if (I != ByValArgFrameIndexMap.end())
370     return I->second;
371   DEBUG(dbgs() << "Argument does not have assigned frame index!");
372   return 0;
373 }
374
375 /// ComputeUsesVAFloatArgument - Determine if any floating-point values are
376 /// being passed to this variadic function, and set the MachineModuleInfo's
377 /// usesVAFloatArgument flag if so. This flag is used to emit an undefined
378 /// reference to _fltused on Windows, which will link in MSVCRT's
379 /// floating-point support.
380 void llvm::ComputeUsesVAFloatArgument(const CallInst &I,
381                                       MachineModuleInfo *MMI)
382 {
383   FunctionType *FT = cast<FunctionType>(
384     I.getCalledValue()->getType()->getContainedType(0));
385   if (FT->isVarArg() && !MMI->usesVAFloatArgument()) {
386     for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
387       Type* T = I.getArgOperand(i)->getType();
388       for (po_iterator<Type*> i = po_begin(T), e = po_end(T);
389            i != e; ++i) {
390         if (i->isFloatingPointTy()) {
391           MMI->setUsesVAFloatArgument(true);
392           return;
393         }
394       }
395     }
396   }
397 }
398
399 /// AddCatchInfo - Extract the personality and type infos from an eh.selector
400 /// call, and add them to the specified machine basic block.
401 void llvm::AddCatchInfo(const CallInst &I, MachineModuleInfo *MMI,
402                         MachineBasicBlock *MBB) {
403   // Inform the MachineModuleInfo of the personality for this landing pad.
404   const ConstantExpr *CE = cast<ConstantExpr>(I.getArgOperand(1));
405   assert(CE->getOpcode() == Instruction::BitCast &&
406          isa<Function>(CE->getOperand(0)) &&
407          "Personality should be a function");
408   MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
409
410   // Gather all the type infos for this landing pad and pass them along to
411   // MachineModuleInfo.
412   std::vector<const GlobalVariable *> TyInfo;
413   unsigned N = I.getNumArgOperands();
414
415   for (unsigned i = N - 1; i > 1; --i) {
416     if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(i))) {
417       unsigned FilterLength = CI->getZExtValue();
418       unsigned FirstCatch = i + FilterLength + !FilterLength;
419       assert(FirstCatch <= N && "Invalid filter length");
420
421       if (FirstCatch < N) {
422         TyInfo.reserve(N - FirstCatch);
423         for (unsigned j = FirstCatch; j < N; ++j)
424           TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
425         MMI->addCatchTypeInfo(MBB, TyInfo);
426         TyInfo.clear();
427       }
428
429       if (!FilterLength) {
430         // Cleanup.
431         MMI->addCleanup(MBB);
432       } else {
433         // Filter.
434         TyInfo.reserve(FilterLength - 1);
435         for (unsigned j = i + 1; j < FirstCatch; ++j)
436           TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
437         MMI->addFilterTypeInfo(MBB, TyInfo);
438         TyInfo.clear();
439       }
440
441       N = i;
442     }
443   }
444
445   if (N > 2) {
446     TyInfo.reserve(N - 2);
447     for (unsigned j = 2; j < N; ++j)
448       TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
449     MMI->addCatchTypeInfo(MBB, TyInfo);
450   }
451 }
452
453 /// AddLandingPadInfo - Extract the exception handling information from the
454 /// landingpad instruction and add them to the specified machine module info.
455 void llvm::AddLandingPadInfo(const LandingPadInst &I, MachineModuleInfo &MMI,
456                              MachineBasicBlock *MBB) {
457   MMI.addPersonality(MBB,
458                      cast<Function>(I.getPersonalityFn()->stripPointerCasts()));
459
460   if (I.isCleanup())
461     MMI.addCleanup(MBB);
462
463   // FIXME: New EH - Add the clauses in reverse order. This isn't 100% correct,
464   //        but we need to do it this way because of how the DWARF EH emitter
465   //        processes the clauses.
466   for (unsigned i = I.getNumClauses(); i != 0; --i) {
467     Value *Val = I.getClause(i - 1);
468     if (I.isCatch(i - 1)) {
469       MMI.addCatchTypeInfo(MBB,
470                            dyn_cast<GlobalVariable>(Val->stripPointerCasts()));
471     } else {
472       // Add filters in a list.
473       Constant *CVal = cast<Constant>(Val);
474       SmallVector<const GlobalVariable*, 4> FilterList;
475       for (User::op_iterator
476              II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II)
477         FilterList.push_back(cast<GlobalVariable>((*II)->stripPointerCasts()));
478
479       MMI.addFilterTypeInfo(MBB, FilterList);
480     }
481   }
482 }