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