1450aa64fSDan Gohman //===-- Analysis.cpp - CodeGen LLVM IR Analysis Utilities --*- C++ ------*-===//
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"
15450aa64fSDan Gohman #include "llvm/DerivedTypes.h"
16450aa64fSDan Gohman #include "llvm/Function.h"
17450aa64fSDan Gohman #include "llvm/Instructions.h"
18450aa64fSDan Gohman #include "llvm/IntrinsicInst.h"
19450aa64fSDan Gohman #include "llvm/LLVMContext.h"
20450aa64fSDan Gohman #include "llvm/Module.h"
21450aa64fSDan Gohman #include "llvm/CodeGen/MachineFunction.h"
22450aa64fSDan Gohman #include "llvm/Target/TargetData.h"
23450aa64fSDan Gohman #include "llvm/Target/TargetLowering.h"
24450aa64fSDan Gohman #include "llvm/Target/TargetOptions.h"
25450aa64fSDan Gohman #include "llvm/Support/ErrorHandling.h"
26450aa64fSDan Gohman #include "llvm/Support/MathExtras.h"
27450aa64fSDan Gohman using namespace llvm;
28450aa64fSDan Gohman 
29450aa64fSDan Gohman /// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
30450aa64fSDan Gohman /// of insertvalue or extractvalue indices that identify a member, return
31450aa64fSDan Gohman /// the linearized index of the start of the member.
32450aa64fSDan Gohman ///
33450aa64fSDan Gohman unsigned llvm::ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
34450aa64fSDan Gohman                                   const unsigned *Indices,
35450aa64fSDan Gohman                                   const unsigned *IndicesEnd,
36450aa64fSDan Gohman                                   unsigned CurIndex) {
37450aa64fSDan Gohman   // Base case: We're done.
38450aa64fSDan Gohman   if (Indices && Indices == IndicesEnd)
39450aa64fSDan Gohman     return CurIndex;
40450aa64fSDan Gohman 
41450aa64fSDan Gohman   // Given a struct type, recursively traverse the elements.
42450aa64fSDan Gohman   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
43450aa64fSDan Gohman     for (StructType::element_iterator EB = STy->element_begin(),
44450aa64fSDan Gohman                                       EI = EB,
45450aa64fSDan Gohman                                       EE = STy->element_end();
46450aa64fSDan Gohman         EI != EE; ++EI) {
47450aa64fSDan Gohman       if (Indices && *Indices == unsigned(EI - EB))
48450aa64fSDan Gohman         return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
49450aa64fSDan Gohman       CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
50450aa64fSDan Gohman     }
51450aa64fSDan Gohman     return CurIndex;
52450aa64fSDan Gohman   }
53450aa64fSDan Gohman   // Given an array type, recursively traverse the elements.
54450aa64fSDan Gohman   else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
55450aa64fSDan Gohman     const Type *EltTy = ATy->getElementType();
56450aa64fSDan Gohman     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
57450aa64fSDan Gohman       if (Indices && *Indices == i)
58450aa64fSDan Gohman         return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
59450aa64fSDan Gohman       CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
60450aa64fSDan Gohman     }
61450aa64fSDan Gohman     return CurIndex;
62450aa64fSDan Gohman   }
63450aa64fSDan Gohman   // We haven't found the type we're looking for, so keep searching.
64450aa64fSDan Gohman   return CurIndex + 1;
65450aa64fSDan Gohman }
66450aa64fSDan Gohman 
67450aa64fSDan Gohman /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
68450aa64fSDan Gohman /// EVTs that represent all the individual underlying
69450aa64fSDan Gohman /// non-aggregate types that comprise it.
70450aa64fSDan Gohman ///
71450aa64fSDan Gohman /// If Offsets is non-null, it points to a vector to be filled in
72450aa64fSDan Gohman /// with the in-memory offsets of each of the individual values.
73450aa64fSDan Gohman ///
74450aa64fSDan Gohman void llvm::ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
75450aa64fSDan Gohman                            SmallVectorImpl<EVT> &ValueVTs,
76450aa64fSDan Gohman                            SmallVectorImpl<uint64_t> *Offsets,
77450aa64fSDan Gohman                            uint64_t StartingOffset) {
78450aa64fSDan Gohman   // Given a struct type, recursively traverse the elements.
79450aa64fSDan Gohman   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
80450aa64fSDan Gohman     const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
81450aa64fSDan Gohman     for (StructType::element_iterator EB = STy->element_begin(),
82450aa64fSDan Gohman                                       EI = EB,
83450aa64fSDan Gohman                                       EE = STy->element_end();
84450aa64fSDan Gohman          EI != EE; ++EI)
85450aa64fSDan Gohman       ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
86450aa64fSDan Gohman                       StartingOffset + SL->getElementOffset(EI - EB));
87450aa64fSDan Gohman     return;
88450aa64fSDan Gohman   }
89450aa64fSDan Gohman   // Given an array type, recursively traverse the elements.
90450aa64fSDan Gohman   if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
91450aa64fSDan Gohman     const Type *EltTy = ATy->getElementType();
92450aa64fSDan Gohman     uint64_t EltSize = TLI.getTargetData()->getTypeAllocSize(EltTy);
93450aa64fSDan Gohman     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
94450aa64fSDan Gohman       ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
95450aa64fSDan Gohman                       StartingOffset + i * EltSize);
96450aa64fSDan Gohman     return;
97450aa64fSDan Gohman   }
98450aa64fSDan Gohman   // Interpret void as zero return values.
99450aa64fSDan Gohman   if (Ty->isVoidTy())
100450aa64fSDan Gohman     return;
101450aa64fSDan Gohman   // Base case: we can get an EVT for this LLVM IR type.
102450aa64fSDan Gohman   ValueVTs.push_back(TLI.getValueType(Ty));
103450aa64fSDan Gohman   if (Offsets)
104450aa64fSDan Gohman     Offsets->push_back(StartingOffset);
105450aa64fSDan Gohman }
106450aa64fSDan Gohman 
107450aa64fSDan Gohman /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
108450aa64fSDan Gohman GlobalVariable *llvm::ExtractTypeInfo(Value *V) {
109450aa64fSDan Gohman   V = V->stripPointerCasts();
110450aa64fSDan Gohman   GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
111450aa64fSDan Gohman 
112*fa60b0eeSBill Wendling   if (GV && GV->getName() == "llvm.eh.catch.all.value") {
113450aa64fSDan Gohman     assert(GV->hasInitializer() &&
114450aa64fSDan Gohman            "The EH catch-all value must have an initializer");
115450aa64fSDan Gohman     Value *Init = GV->getInitializer();
116450aa64fSDan Gohman     GV = dyn_cast<GlobalVariable>(Init);
117450aa64fSDan Gohman     if (!GV) V = cast<ConstantPointerNull>(Init);
118450aa64fSDan Gohman   }
119450aa64fSDan Gohman 
120450aa64fSDan Gohman   assert((GV || isa<ConstantPointerNull>(V)) &&
121450aa64fSDan Gohman          "TypeInfo must be a global variable or NULL");
122450aa64fSDan Gohman   return GV;
123450aa64fSDan Gohman }
124450aa64fSDan Gohman 
125450aa64fSDan Gohman /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
126450aa64fSDan Gohman /// processed uses a memory 'm' constraint.
127450aa64fSDan Gohman bool
128450aa64fSDan Gohman llvm::hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
129450aa64fSDan Gohman                                 const TargetLowering &TLI) {
130450aa64fSDan Gohman   for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
131450aa64fSDan Gohman     InlineAsm::ConstraintInfo &CI = CInfos[i];
132450aa64fSDan Gohman     for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
133450aa64fSDan Gohman       TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
134450aa64fSDan Gohman       if (CType == TargetLowering::C_Memory)
135450aa64fSDan Gohman         return true;
136450aa64fSDan Gohman     }
137450aa64fSDan Gohman 
138450aa64fSDan Gohman     // Indirect operand accesses access memory.
139450aa64fSDan Gohman     if (CI.isIndirect)
140450aa64fSDan Gohman       return true;
141450aa64fSDan Gohman   }
142450aa64fSDan Gohman 
143450aa64fSDan Gohman   return false;
144450aa64fSDan Gohman }
145450aa64fSDan Gohman 
146450aa64fSDan Gohman /// getFCmpCondCode - Return the ISD condition code corresponding to
147450aa64fSDan Gohman /// the given LLVM IR floating-point condition code.  This includes
148450aa64fSDan Gohman /// consideration of global floating-point math flags.
149450aa64fSDan Gohman ///
150450aa64fSDan Gohman ISD::CondCode llvm::getFCmpCondCode(FCmpInst::Predicate Pred) {
151450aa64fSDan Gohman   ISD::CondCode FPC, FOC;
152450aa64fSDan Gohman   switch (Pred) {
153450aa64fSDan Gohman   case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
154450aa64fSDan Gohman   case FCmpInst::FCMP_OEQ:   FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
155450aa64fSDan Gohman   case FCmpInst::FCMP_OGT:   FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
156450aa64fSDan Gohman   case FCmpInst::FCMP_OGE:   FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
157450aa64fSDan Gohman   case FCmpInst::FCMP_OLT:   FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
158450aa64fSDan Gohman   case FCmpInst::FCMP_OLE:   FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
159450aa64fSDan Gohman   case FCmpInst::FCMP_ONE:   FOC = ISD::SETNE; FPC = ISD::SETONE; break;
160450aa64fSDan Gohman   case FCmpInst::FCMP_ORD:   FOC = FPC = ISD::SETO;   break;
161450aa64fSDan Gohman   case FCmpInst::FCMP_UNO:   FOC = FPC = ISD::SETUO;  break;
162450aa64fSDan Gohman   case FCmpInst::FCMP_UEQ:   FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
163450aa64fSDan Gohman   case FCmpInst::FCMP_UGT:   FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
164450aa64fSDan Gohman   case FCmpInst::FCMP_UGE:   FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
165450aa64fSDan Gohman   case FCmpInst::FCMP_ULT:   FOC = ISD::SETLT; FPC = ISD::SETULT; break;
166450aa64fSDan Gohman   case FCmpInst::FCMP_ULE:   FOC = ISD::SETLE; FPC = ISD::SETULE; break;
167450aa64fSDan Gohman   case FCmpInst::FCMP_UNE:   FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
168450aa64fSDan Gohman   case FCmpInst::FCMP_TRUE:  FOC = FPC = ISD::SETTRUE; break;
169450aa64fSDan Gohman   default:
170450aa64fSDan Gohman     llvm_unreachable("Invalid FCmp predicate opcode!");
171450aa64fSDan Gohman     FOC = FPC = ISD::SETFALSE;
172450aa64fSDan Gohman     break;
173450aa64fSDan Gohman   }
17455f0c6b9SEvan Cheng   if (NoNaNsFPMath)
175450aa64fSDan Gohman     return FOC;
176450aa64fSDan Gohman   else
177450aa64fSDan Gohman     return FPC;
178450aa64fSDan Gohman }
179450aa64fSDan Gohman 
180450aa64fSDan Gohman /// getICmpCondCode - Return the ISD condition code corresponding to
181450aa64fSDan Gohman /// the given LLVM IR integer condition code.
182450aa64fSDan Gohman ///
183450aa64fSDan Gohman ISD::CondCode llvm::getICmpCondCode(ICmpInst::Predicate Pred) {
184450aa64fSDan Gohman   switch (Pred) {
185450aa64fSDan Gohman   case ICmpInst::ICMP_EQ:  return ISD::SETEQ;
186450aa64fSDan Gohman   case ICmpInst::ICMP_NE:  return ISD::SETNE;
187450aa64fSDan Gohman   case ICmpInst::ICMP_SLE: return ISD::SETLE;
188450aa64fSDan Gohman   case ICmpInst::ICMP_ULE: return ISD::SETULE;
189450aa64fSDan Gohman   case ICmpInst::ICMP_SGE: return ISD::SETGE;
190450aa64fSDan Gohman   case ICmpInst::ICMP_UGE: return ISD::SETUGE;
191450aa64fSDan Gohman   case ICmpInst::ICMP_SLT: return ISD::SETLT;
192450aa64fSDan Gohman   case ICmpInst::ICMP_ULT: return ISD::SETULT;
193450aa64fSDan Gohman   case ICmpInst::ICMP_SGT: return ISD::SETGT;
194450aa64fSDan Gohman   case ICmpInst::ICMP_UGT: return ISD::SETUGT;
195450aa64fSDan Gohman   default:
196450aa64fSDan Gohman     llvm_unreachable("Invalid ICmp predicate opcode!");
197450aa64fSDan Gohman     return ISD::SETNE;
198450aa64fSDan Gohman   }
199450aa64fSDan Gohman }
200450aa64fSDan Gohman 
201450aa64fSDan Gohman /// Test if the given instruction is in a position to be optimized
202450aa64fSDan Gohman /// with a tail-call. This roughly means that it's in a block with
203450aa64fSDan Gohman /// a return and there's nothing that needs to be scheduled
204450aa64fSDan Gohman /// between it and the return.
205450aa64fSDan Gohman ///
206450aa64fSDan Gohman /// This function only tests target-independent requirements.
207450aa64fSDan Gohman bool llvm::isInTailCallPosition(ImmutableCallSite CS, Attributes CalleeRetAttr,
208450aa64fSDan Gohman                                 const TargetLowering &TLI) {
209450aa64fSDan Gohman   const Instruction *I = CS.getInstruction();
210450aa64fSDan Gohman   const BasicBlock *ExitBB = I->getParent();
211450aa64fSDan Gohman   const TerminatorInst *Term = ExitBB->getTerminator();
212450aa64fSDan Gohman   const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
213450aa64fSDan Gohman   const Function *F = ExitBB->getParent();
214450aa64fSDan Gohman 
215450aa64fSDan Gohman   // The block must end in a return statement or unreachable.
216450aa64fSDan Gohman   //
217450aa64fSDan Gohman   // FIXME: Decline tailcall if it's not guaranteed and if the block ends in
218450aa64fSDan Gohman   // an unreachable, for now. The way tailcall optimization is currently
219450aa64fSDan Gohman   // implemented means it will add an epilogue followed by a jump. That is
220450aa64fSDan Gohman   // not profitable. Also, if the callee is a special function (e.g.
221450aa64fSDan Gohman   // longjmp on x86), it can end up causing miscompilation that has not
222450aa64fSDan Gohman   // been fully understood.
223450aa64fSDan Gohman   if (!Ret &&
224450aa64fSDan Gohman       (!GuaranteedTailCallOpt || !isa<UnreachableInst>(Term))) return false;
225450aa64fSDan Gohman 
226450aa64fSDan Gohman   // If I will have a chain, make sure no other instruction that will have a
227450aa64fSDan Gohman   // chain interposes between I and the return.
228450aa64fSDan Gohman   if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
229450aa64fSDan Gohman       !I->isSafeToSpeculativelyExecute())
230450aa64fSDan Gohman     for (BasicBlock::const_iterator BBI = prior(prior(ExitBB->end())); ;
231450aa64fSDan Gohman          --BBI) {
232450aa64fSDan Gohman       if (&*BBI == I)
233450aa64fSDan Gohman         break;
234450aa64fSDan Gohman       // Debug info intrinsics do not get in the way of tail call optimization.
235450aa64fSDan Gohman       if (isa<DbgInfoIntrinsic>(BBI))
236450aa64fSDan Gohman         continue;
237450aa64fSDan Gohman       if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
238450aa64fSDan Gohman           !BBI->isSafeToSpeculativelyExecute())
239450aa64fSDan Gohman         return false;
240450aa64fSDan Gohman     }
241450aa64fSDan Gohman 
242450aa64fSDan Gohman   // If the block ends with a void return or unreachable, it doesn't matter
243450aa64fSDan Gohman   // what the call's return type is.
244450aa64fSDan Gohman   if (!Ret || Ret->getNumOperands() == 0) return true;
245450aa64fSDan Gohman 
246450aa64fSDan Gohman   // If the return value is undef, it doesn't matter what the call's
247450aa64fSDan Gohman   // return type is.
248450aa64fSDan Gohman   if (isa<UndefValue>(Ret->getOperand(0))) return true;
249450aa64fSDan Gohman 
250450aa64fSDan Gohman   // Conservatively require the attributes of the call to match those of
251450aa64fSDan Gohman   // the return. Ignore noalias because it doesn't affect the call sequence.
252450aa64fSDan Gohman   unsigned CallerRetAttr = F->getAttributes().getRetAttributes();
253450aa64fSDan Gohman   if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
254450aa64fSDan Gohman     return false;
255450aa64fSDan Gohman 
256450aa64fSDan Gohman   // It's not safe to eliminate the sign / zero extension of the return value.
257450aa64fSDan Gohman   if ((CallerRetAttr & Attribute::ZExt) || (CallerRetAttr & Attribute::SExt))
258450aa64fSDan Gohman     return false;
259450aa64fSDan Gohman 
260450aa64fSDan Gohman   // Otherwise, make sure the unmodified return value of I is the return value.
261450aa64fSDan Gohman   for (const Instruction *U = dyn_cast<Instruction>(Ret->getOperand(0)); ;
262450aa64fSDan Gohman        U = dyn_cast<Instruction>(U->getOperand(0))) {
263450aa64fSDan Gohman     if (!U)
264450aa64fSDan Gohman       return false;
265450aa64fSDan Gohman     if (!U->hasOneUse())
266450aa64fSDan Gohman       return false;
267450aa64fSDan Gohman     if (U == I)
268450aa64fSDan Gohman       break;
269450aa64fSDan Gohman     // Check for a truly no-op truncate.
270450aa64fSDan Gohman     if (isa<TruncInst>(U) &&
271450aa64fSDan Gohman         TLI.isTruncateFree(U->getOperand(0)->getType(), U->getType()))
272450aa64fSDan Gohman       continue;
273450aa64fSDan Gohman     // Check for a truly no-op bitcast.
274450aa64fSDan Gohman     if (isa<BitCastInst>(U) &&
275450aa64fSDan Gohman         (U->getOperand(0)->getType() == U->getType() ||
276450aa64fSDan Gohman          (U->getOperand(0)->getType()->isPointerTy() &&
277450aa64fSDan Gohman           U->getType()->isPointerTy())))
278450aa64fSDan Gohman       continue;
279450aa64fSDan Gohman     // Otherwise it's not a true no-op.
280450aa64fSDan Gohman     return false;
281450aa64fSDan Gohman   }
282450aa64fSDan Gohman 
283450aa64fSDan Gohman   return true;
284450aa64fSDan Gohman }
285450aa64fSDan Gohman 
286