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