150f02cb2SNick Lewycky //===-- Analysis.cpp - CodeGen LLVM IR Analysis Utilities -----------------===//
2450aa64fSDan Gohman //
3450aa64fSDan Gohman //                     The LLVM Compiler Infrastructure
4450aa64fSDan Gohman //
5450aa64fSDan Gohman // This file is distributed under the University of Illinois Open Source
6450aa64fSDan Gohman // License. See LICENSE.TXT for details.
7450aa64fSDan Gohman //
8450aa64fSDan Gohman //===----------------------------------------------------------------------===//
9450aa64fSDan Gohman //
10450aa64fSDan Gohman // This file defines several CodeGen-specific LLVM IR analysis utilties.
11450aa64fSDan Gohman //
12450aa64fSDan Gohman //===----------------------------------------------------------------------===//
13450aa64fSDan Gohman 
14450aa64fSDan Gohman #include "llvm/CodeGen/Analysis.h"
1575d7d5e9SDan Gohman #include "llvm/Analysis/ValueTracking.h"
16450aa64fSDan Gohman #include "llvm/DerivedTypes.h"
17450aa64fSDan Gohman #include "llvm/Function.h"
18450aa64fSDan Gohman #include "llvm/Instructions.h"
19450aa64fSDan Gohman #include "llvm/IntrinsicInst.h"
20450aa64fSDan Gohman #include "llvm/LLVMContext.h"
21450aa64fSDan Gohman #include "llvm/Module.h"
22450aa64fSDan Gohman #include "llvm/CodeGen/MachineFunction.h"
23d4b0873cSEvan Cheng #include "llvm/CodeGen/SelectionDAG.h"
24450aa64fSDan Gohman #include "llvm/Target/TargetData.h"
25450aa64fSDan Gohman #include "llvm/Target/TargetLowering.h"
26450aa64fSDan Gohman #include "llvm/Target/TargetOptions.h"
27450aa64fSDan Gohman #include "llvm/Support/ErrorHandling.h"
28450aa64fSDan Gohman #include "llvm/Support/MathExtras.h"
29450aa64fSDan Gohman using namespace llvm;
30450aa64fSDan Gohman 
31450aa64fSDan Gohman /// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
32450aa64fSDan Gohman /// of insertvalue or extractvalue indices that identify a member, return
33450aa64fSDan Gohman /// the linearized index of the start of the member.
34450aa64fSDan Gohman ///
35229907cdSChris Lattner unsigned llvm::ComputeLinearIndex(Type *Ty,
36450aa64fSDan Gohman                                   const unsigned *Indices,
37450aa64fSDan Gohman                                   const unsigned *IndicesEnd,
38450aa64fSDan Gohman                                   unsigned CurIndex) {
39450aa64fSDan Gohman   // Base case: We're done.
40450aa64fSDan Gohman   if (Indices && Indices == IndicesEnd)
41450aa64fSDan Gohman     return CurIndex;
42450aa64fSDan Gohman 
43450aa64fSDan Gohman   // Given a struct type, recursively traverse the elements.
44229907cdSChris Lattner   if (StructType *STy = dyn_cast<StructType>(Ty)) {
45450aa64fSDan Gohman     for (StructType::element_iterator EB = STy->element_begin(),
46450aa64fSDan Gohman                                       EI = EB,
47450aa64fSDan Gohman                                       EE = STy->element_end();
48450aa64fSDan Gohman         EI != EE; ++EI) {
49450aa64fSDan Gohman       if (Indices && *Indices == unsigned(EI - EB))
50aadc5596SDan Gohman         return ComputeLinearIndex(*EI, Indices+1, IndicesEnd, CurIndex);
51aadc5596SDan Gohman       CurIndex = ComputeLinearIndex(*EI, 0, 0, CurIndex);
52450aa64fSDan Gohman     }
53450aa64fSDan Gohman     return CurIndex;
54450aa64fSDan Gohman   }
55450aa64fSDan Gohman   // Given an array type, recursively traverse the elements.
56229907cdSChris Lattner   else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
57229907cdSChris Lattner     Type *EltTy = ATy->getElementType();
58450aa64fSDan Gohman     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
59450aa64fSDan Gohman       if (Indices && *Indices == i)
60aadc5596SDan Gohman         return ComputeLinearIndex(EltTy, Indices+1, IndicesEnd, CurIndex);
61aadc5596SDan Gohman       CurIndex = ComputeLinearIndex(EltTy, 0, 0, CurIndex);
62450aa64fSDan Gohman     }
63450aa64fSDan Gohman     return CurIndex;
64450aa64fSDan Gohman   }
65450aa64fSDan Gohman   // We haven't found the type we're looking for, so keep searching.
66450aa64fSDan Gohman   return CurIndex + 1;
67450aa64fSDan Gohman }
68450aa64fSDan Gohman 
69450aa64fSDan Gohman /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
70450aa64fSDan Gohman /// EVTs that represent all the individual underlying
71450aa64fSDan Gohman /// non-aggregate types that comprise it.
72450aa64fSDan Gohman ///
73450aa64fSDan Gohman /// If Offsets is non-null, it points to a vector to be filled in
74450aa64fSDan Gohman /// with the in-memory offsets of each of the individual values.
75450aa64fSDan Gohman ///
76229907cdSChris Lattner void llvm::ComputeValueVTs(const TargetLowering &TLI, Type *Ty,
77450aa64fSDan Gohman                            SmallVectorImpl<EVT> &ValueVTs,
78450aa64fSDan Gohman                            SmallVectorImpl<uint64_t> *Offsets,
79450aa64fSDan Gohman                            uint64_t StartingOffset) {
80450aa64fSDan Gohman   // Given a struct type, recursively traverse the elements.
81229907cdSChris Lattner   if (StructType *STy = dyn_cast<StructType>(Ty)) {
82450aa64fSDan Gohman     const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
83450aa64fSDan Gohman     for (StructType::element_iterator EB = STy->element_begin(),
84450aa64fSDan Gohman                                       EI = EB,
85450aa64fSDan Gohman                                       EE = STy->element_end();
86450aa64fSDan Gohman          EI != EE; ++EI)
87450aa64fSDan Gohman       ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
88450aa64fSDan Gohman                       StartingOffset + SL->getElementOffset(EI - EB));
89450aa64fSDan Gohman     return;
90450aa64fSDan Gohman   }
91450aa64fSDan Gohman   // Given an array type, recursively traverse the elements.
92229907cdSChris Lattner   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
93229907cdSChris Lattner     Type *EltTy = ATy->getElementType();
94450aa64fSDan Gohman     uint64_t EltSize = TLI.getTargetData()->getTypeAllocSize(EltTy);
95450aa64fSDan Gohman     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
96450aa64fSDan Gohman       ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
97450aa64fSDan Gohman                       StartingOffset + i * EltSize);
98450aa64fSDan Gohman     return;
99450aa64fSDan Gohman   }
100450aa64fSDan Gohman   // Interpret void as zero return values.
101450aa64fSDan Gohman   if (Ty->isVoidTy())
102450aa64fSDan Gohman     return;
103450aa64fSDan Gohman   // Base case: we can get an EVT for this LLVM IR type.
104450aa64fSDan Gohman   ValueVTs.push_back(TLI.getValueType(Ty));
105450aa64fSDan Gohman   if (Offsets)
106450aa64fSDan Gohman     Offsets->push_back(StartingOffset);
107450aa64fSDan Gohman }
108450aa64fSDan Gohman 
109450aa64fSDan Gohman /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
110450aa64fSDan Gohman GlobalVariable *llvm::ExtractTypeInfo(Value *V) {
111450aa64fSDan Gohman   V = V->stripPointerCasts();
112450aa64fSDan Gohman   GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
113450aa64fSDan Gohman 
114fa60b0eeSBill Wendling   if (GV && GV->getName() == "llvm.eh.catch.all.value") {
115450aa64fSDan Gohman     assert(GV->hasInitializer() &&
116450aa64fSDan Gohman            "The EH catch-all value must have an initializer");
117450aa64fSDan Gohman     Value *Init = GV->getInitializer();
118450aa64fSDan Gohman     GV = dyn_cast<GlobalVariable>(Init);
119450aa64fSDan Gohman     if (!GV) V = cast<ConstantPointerNull>(Init);
120450aa64fSDan Gohman   }
121450aa64fSDan Gohman 
122450aa64fSDan Gohman   assert((GV || isa<ConstantPointerNull>(V)) &&
123450aa64fSDan Gohman          "TypeInfo must be a global variable or NULL");
124450aa64fSDan Gohman   return GV;
125450aa64fSDan Gohman }
126450aa64fSDan Gohman 
127450aa64fSDan Gohman /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
128450aa64fSDan Gohman /// processed uses a memory 'm' constraint.
129450aa64fSDan Gohman bool
130e8360b71SJohn Thompson llvm::hasInlineAsmMemConstraint(InlineAsm::ConstraintInfoVector &CInfos,
131450aa64fSDan Gohman                                 const TargetLowering &TLI) {
132450aa64fSDan Gohman   for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
133450aa64fSDan Gohman     InlineAsm::ConstraintInfo &CI = CInfos[i];
134450aa64fSDan Gohman     for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
135450aa64fSDan Gohman       TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
136450aa64fSDan Gohman       if (CType == TargetLowering::C_Memory)
137450aa64fSDan Gohman         return true;
138450aa64fSDan Gohman     }
139450aa64fSDan Gohman 
140450aa64fSDan Gohman     // Indirect operand accesses access memory.
141450aa64fSDan Gohman     if (CI.isIndirect)
142450aa64fSDan Gohman       return true;
143450aa64fSDan Gohman   }
144450aa64fSDan Gohman 
145450aa64fSDan Gohman   return false;
146450aa64fSDan Gohman }
147450aa64fSDan Gohman 
148450aa64fSDan Gohman /// getFCmpCondCode - Return the ISD condition code corresponding to
149450aa64fSDan Gohman /// the given LLVM IR floating-point condition code.  This includes
150450aa64fSDan Gohman /// consideration of global floating-point math flags.
151450aa64fSDan Gohman ///
152450aa64fSDan Gohman ISD::CondCode llvm::getFCmpCondCode(FCmpInst::Predicate Pred) {
153450aa64fSDan Gohman   switch (Pred) {
15450f02cb2SNick Lewycky   case FCmpInst::FCMP_FALSE: return ISD::SETFALSE;
15550f02cb2SNick Lewycky   case FCmpInst::FCMP_OEQ:   return ISD::SETOEQ;
15650f02cb2SNick Lewycky   case FCmpInst::FCMP_OGT:   return ISD::SETOGT;
15750f02cb2SNick Lewycky   case FCmpInst::FCMP_OGE:   return ISD::SETOGE;
15850f02cb2SNick Lewycky   case FCmpInst::FCMP_OLT:   return ISD::SETOLT;
15950f02cb2SNick Lewycky   case FCmpInst::FCMP_OLE:   return ISD::SETOLE;
16050f02cb2SNick Lewycky   case FCmpInst::FCMP_ONE:   return ISD::SETONE;
16150f02cb2SNick Lewycky   case FCmpInst::FCMP_ORD:   return ISD::SETO;
16250f02cb2SNick Lewycky   case FCmpInst::FCMP_UNO:   return ISD::SETUO;
16350f02cb2SNick Lewycky   case FCmpInst::FCMP_UEQ:   return ISD::SETUEQ;
16450f02cb2SNick Lewycky   case FCmpInst::FCMP_UGT:   return ISD::SETUGT;
16550f02cb2SNick Lewycky   case FCmpInst::FCMP_UGE:   return ISD::SETUGE;
16650f02cb2SNick Lewycky   case FCmpInst::FCMP_ULT:   return ISD::SETULT;
16750f02cb2SNick Lewycky   case FCmpInst::FCMP_ULE:   return ISD::SETULE;
16850f02cb2SNick Lewycky   case FCmpInst::FCMP_UNE:   return ISD::SETUNE;
16950f02cb2SNick Lewycky   case FCmpInst::FCMP_TRUE:  return ISD::SETTRUE;
17046a9f016SDavid Blaikie   default: llvm_unreachable("Invalid FCmp predicate opcode!");
171450aa64fSDan Gohman   }
17250f02cb2SNick Lewycky }
17350f02cb2SNick Lewycky 
17450f02cb2SNick Lewycky ISD::CondCode llvm::getFCmpCodeWithoutNaN(ISD::CondCode CC) {
17550f02cb2SNick Lewycky   switch (CC) {
17650f02cb2SNick Lewycky     case ISD::SETOEQ: case ISD::SETUEQ: return ISD::SETEQ;
17750f02cb2SNick Lewycky     case ISD::SETONE: case ISD::SETUNE: return ISD::SETNE;
17850f02cb2SNick Lewycky     case ISD::SETOLT: case ISD::SETULT: return ISD::SETLT;
17950f02cb2SNick Lewycky     case ISD::SETOLE: case ISD::SETULE: return ISD::SETLE;
18050f02cb2SNick Lewycky     case ISD::SETOGT: case ISD::SETUGT: return ISD::SETGT;
18150f02cb2SNick Lewycky     case ISD::SETOGE: case ISD::SETUGE: return ISD::SETGE;
18246a9f016SDavid Blaikie     default: return CC;
18350f02cb2SNick Lewycky   }
184450aa64fSDan Gohman }
185450aa64fSDan Gohman 
186450aa64fSDan Gohman /// getICmpCondCode - Return the ISD condition code corresponding to
187450aa64fSDan Gohman /// the given LLVM IR integer condition code.
188450aa64fSDan Gohman ///
189450aa64fSDan Gohman ISD::CondCode llvm::getICmpCondCode(ICmpInst::Predicate Pred) {
190450aa64fSDan Gohman   switch (Pred) {
191450aa64fSDan Gohman   case ICmpInst::ICMP_EQ:  return ISD::SETEQ;
192450aa64fSDan Gohman   case ICmpInst::ICMP_NE:  return ISD::SETNE;
193450aa64fSDan Gohman   case ICmpInst::ICMP_SLE: return ISD::SETLE;
194450aa64fSDan Gohman   case ICmpInst::ICMP_ULE: return ISD::SETULE;
195450aa64fSDan Gohman   case ICmpInst::ICMP_SGE: return ISD::SETGE;
196450aa64fSDan Gohman   case ICmpInst::ICMP_UGE: return ISD::SETUGE;
197450aa64fSDan Gohman   case ICmpInst::ICMP_SLT: return ISD::SETLT;
198450aa64fSDan Gohman   case ICmpInst::ICMP_ULT: return ISD::SETULT;
199450aa64fSDan Gohman   case ICmpInst::ICMP_SGT: return ISD::SETGT;
200450aa64fSDan Gohman   case ICmpInst::ICMP_UGT: return ISD::SETUGT;
201450aa64fSDan Gohman   default:
202450aa64fSDan Gohman     llvm_unreachable("Invalid ICmp predicate opcode!");
203450aa64fSDan Gohman   }
204450aa64fSDan Gohman }
205450aa64fSDan Gohman 
206450aa64fSDan Gohman /// Test if the given instruction is in a position to be optimized
207450aa64fSDan Gohman /// with a tail-call. This roughly means that it's in a block with
208450aa64fSDan Gohman /// a return and there's nothing that needs to be scheduled
209450aa64fSDan Gohman /// between it and the return.
210450aa64fSDan Gohman ///
211450aa64fSDan Gohman /// This function only tests target-independent requirements.
212450aa64fSDan Gohman bool llvm::isInTailCallPosition(ImmutableCallSite CS, Attributes CalleeRetAttr,
213450aa64fSDan Gohman                                 const TargetLowering &TLI) {
214450aa64fSDan Gohman   const Instruction *I = CS.getInstruction();
215450aa64fSDan Gohman   const BasicBlock *ExitBB = I->getParent();
216450aa64fSDan Gohman   const TerminatorInst *Term = ExitBB->getTerminator();
217450aa64fSDan Gohman   const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
218450aa64fSDan Gohman 
219450aa64fSDan Gohman   // The block must end in a return statement or unreachable.
220450aa64fSDan Gohman   //
221450aa64fSDan Gohman   // FIXME: Decline tailcall if it's not guaranteed and if the block ends in
222450aa64fSDan Gohman   // an unreachable, for now. The way tailcall optimization is currently
223450aa64fSDan Gohman   // implemented means it will add an epilogue followed by a jump. That is
224450aa64fSDan Gohman   // not profitable. Also, if the callee is a special function (e.g.
225450aa64fSDan Gohman   // longjmp on x86), it can end up causing miscompilation that has not
226450aa64fSDan Gohman   // been fully understood.
227450aa64fSDan Gohman   if (!Ret &&
22850f02cb2SNick Lewycky       (!TLI.getTargetMachine().Options.GuaranteedTailCallOpt ||
22950f02cb2SNick Lewycky        !isa<UnreachableInst>(Term))) return false;
230450aa64fSDan Gohman 
231450aa64fSDan Gohman   // If I will have a chain, make sure no other instruction that will have a
232450aa64fSDan Gohman   // chain interposes between I and the return.
233450aa64fSDan Gohman   if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
23475d7d5e9SDan Gohman       !isSafeToSpeculativelyExecute(I))
235450aa64fSDan Gohman     for (BasicBlock::const_iterator BBI = prior(prior(ExitBB->end())); ;
236450aa64fSDan Gohman          --BBI) {
237450aa64fSDan Gohman       if (&*BBI == I)
238450aa64fSDan Gohman         break;
239450aa64fSDan Gohman       // Debug info intrinsics do not get in the way of tail call optimization.
240450aa64fSDan Gohman       if (isa<DbgInfoIntrinsic>(BBI))
241450aa64fSDan Gohman         continue;
242450aa64fSDan Gohman       if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
24375d7d5e9SDan Gohman           !isSafeToSpeculativelyExecute(BBI))
244450aa64fSDan Gohman         return false;
245450aa64fSDan Gohman     }
246450aa64fSDan Gohman 
247450aa64fSDan Gohman   // If the block ends with a void return or unreachable, it doesn't matter
248450aa64fSDan Gohman   // what the call's return type is.
249450aa64fSDan Gohman   if (!Ret || Ret->getNumOperands() == 0) return true;
250450aa64fSDan Gohman 
251450aa64fSDan Gohman   // If the return value is undef, it doesn't matter what the call's
252450aa64fSDan Gohman   // return type is.
253450aa64fSDan Gohman   if (isa<UndefValue>(Ret->getOperand(0))) return true;
254450aa64fSDan Gohman 
255450aa64fSDan Gohman   // Conservatively require the attributes of the call to match those of
256450aa64fSDan Gohman   // the return. Ignore noalias because it doesn't affect the call sequence.
257b1f3b498SEvan Cheng   const Function *F = ExitBB->getParent();
258a5054ad2SKostya Serebryany   Attributes CallerRetAttr = F->getAttributes().getRetAttributes();
259450aa64fSDan Gohman   if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
260450aa64fSDan Gohman     return false;
261450aa64fSDan Gohman 
262450aa64fSDan Gohman   // It's not safe to eliminate the sign / zero extension of the return value.
263450aa64fSDan Gohman   if ((CallerRetAttr & Attribute::ZExt) || (CallerRetAttr & Attribute::SExt))
264450aa64fSDan Gohman     return false;
265450aa64fSDan Gohman 
266450aa64fSDan Gohman   // Otherwise, make sure the unmodified return value of I is the return value.
267450aa64fSDan Gohman   for (const Instruction *U = dyn_cast<Instruction>(Ret->getOperand(0)); ;
268450aa64fSDan Gohman        U = dyn_cast<Instruction>(U->getOperand(0))) {
269450aa64fSDan Gohman     if (!U)
270450aa64fSDan Gohman       return false;
271450aa64fSDan Gohman     if (!U->hasOneUse())
272450aa64fSDan Gohman       return false;
273450aa64fSDan Gohman     if (U == I)
274450aa64fSDan Gohman       break;
275450aa64fSDan Gohman     // Check for a truly no-op truncate.
276450aa64fSDan Gohman     if (isa<TruncInst>(U) &&
277450aa64fSDan Gohman         TLI.isTruncateFree(U->getOperand(0)->getType(), U->getType()))
278450aa64fSDan Gohman       continue;
279450aa64fSDan Gohman     // Check for a truly no-op bitcast.
280450aa64fSDan Gohman     if (isa<BitCastInst>(U) &&
281450aa64fSDan Gohman         (U->getOperand(0)->getType() == U->getType() ||
282450aa64fSDan Gohman          (U->getOperand(0)->getType()->isPointerTy() &&
283450aa64fSDan Gohman           U->getType()->isPointerTy())))
284450aa64fSDan Gohman       continue;
285450aa64fSDan Gohman     // Otherwise it's not a true no-op.
286450aa64fSDan Gohman     return false;
287450aa64fSDan Gohman   }
288450aa64fSDan Gohman 
289450aa64fSDan Gohman   return true;
290450aa64fSDan Gohman }
291450aa64fSDan Gohman 
292d4b0873cSEvan Cheng bool llvm::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
293*f8bad080SEvan Cheng                                 SDValue &Chain, const TargetLowering &TLI) {
294d4b0873cSEvan Cheng   const Function *F = DAG.getMachineFunction().getFunction();
295d4b0873cSEvan Cheng 
296d4b0873cSEvan Cheng   // Conservatively require the attributes of the call to match those of
297d4b0873cSEvan Cheng   // the return. Ignore noalias because it doesn't affect the call sequence.
298a5054ad2SKostya Serebryany   Attributes CallerRetAttr = F->getAttributes().getRetAttributes();
299d4b0873cSEvan Cheng   if (CallerRetAttr & ~Attribute::NoAlias)
300d4b0873cSEvan Cheng     return false;
301d4b0873cSEvan Cheng 
302d4b0873cSEvan Cheng   // It's not safe to eliminate the sign / zero extension of the return value.
303d4b0873cSEvan Cheng   if ((CallerRetAttr & Attribute::ZExt) || (CallerRetAttr & Attribute::SExt))
304d4b0873cSEvan Cheng     return false;
305d4b0873cSEvan Cheng 
306d4b0873cSEvan Cheng   // Check if the only use is a function return node.
307*f8bad080SEvan Cheng   return TLI.isUsedByReturnOnly(Node, Chain);
308d4b0873cSEvan Cheng }
309