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