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