blob: d68bac76ce655bdfc519a885cd6b5f7316f9fee3 [file] [log] [blame]
Nick Lewycky8a8d4792011-12-02 22:16:29 +00001//===-- Analysis.cpp - CodeGen LLVM IR Analysis Utilities -----------------===//
Dan Gohman5eb6d652010-04-21 01:22:34 +00002//
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 file defines several CodeGen-specific LLVM IR analysis utilties.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/CodeGen/Analysis.h"
Dan Gohmanf0426602011-12-14 23:49:11 +000015#include "llvm/Analysis/ValueTracking.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000016#include "llvm/CodeGen/MachineFunction.h"
17#include "llvm/CodeGen/SelectionDAG.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000018#include "llvm/IR/DataLayout.h"
19#include "llvm/IR/DerivedTypes.h"
20#include "llvm/IR/Function.h"
21#include "llvm/IR/Instructions.h"
22#include "llvm/IR/IntrinsicInst.h"
23#include "llvm/IR/LLVMContext.h"
24#include "llvm/IR/Module.h"
Dan Gohman5eb6d652010-04-21 01:22:34 +000025#include "llvm/Support/ErrorHandling.h"
26#include "llvm/Support/MathExtras.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000027#include "llvm/Target/TargetLowering.h"
28#include "llvm/Target/TargetOptions.h"
Dan Gohman5eb6d652010-04-21 01:22:34 +000029using namespace llvm;
30
31/// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
32/// of insertvalue or extractvalue indices that identify a member, return
33/// the linearized index of the start of the member.
34///
Chris Lattnerdb125cf2011-07-18 04:54:35 +000035unsigned llvm::ComputeLinearIndex(Type *Ty,
Dan Gohman5eb6d652010-04-21 01:22:34 +000036 const unsigned *Indices,
37 const unsigned *IndicesEnd,
38 unsigned CurIndex) {
39 // Base case: We're done.
40 if (Indices && Indices == IndicesEnd)
41 return CurIndex;
42
43 // Given a struct type, recursively traverse the elements.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000044 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Dan Gohman5eb6d652010-04-21 01:22:34 +000045 for (StructType::element_iterator EB = STy->element_begin(),
46 EI = EB,
47 EE = STy->element_end();
48 EI != EE; ++EI) {
49 if (Indices && *Indices == unsigned(EI - EB))
Dan Gohman0dadb152010-10-06 16:18:29 +000050 return ComputeLinearIndex(*EI, Indices+1, IndicesEnd, CurIndex);
51 CurIndex = ComputeLinearIndex(*EI, 0, 0, CurIndex);
Dan Gohman5eb6d652010-04-21 01:22:34 +000052 }
53 return CurIndex;
54 }
55 // Given an array type, recursively traverse the elements.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000056 else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
57 Type *EltTy = ATy->getElementType();
Dan Gohman5eb6d652010-04-21 01:22:34 +000058 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
59 if (Indices && *Indices == i)
Dan Gohman0dadb152010-10-06 16:18:29 +000060 return ComputeLinearIndex(EltTy, Indices+1, IndicesEnd, CurIndex);
61 CurIndex = ComputeLinearIndex(EltTy, 0, 0, CurIndex);
Dan Gohman5eb6d652010-04-21 01:22:34 +000062 }
63 return CurIndex;
64 }
65 // We haven't found the type we're looking for, so keep searching.
66 return CurIndex + 1;
67}
68
69/// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
70/// EVTs that represent all the individual underlying
71/// non-aggregate types that comprise it.
72///
73/// If Offsets is non-null, it points to a vector to be filled in
74/// with the in-memory offsets of each of the individual values.
75///
Chris Lattnerdb125cf2011-07-18 04:54:35 +000076void llvm::ComputeValueVTs(const TargetLowering &TLI, Type *Ty,
Dan Gohman5eb6d652010-04-21 01:22:34 +000077 SmallVectorImpl<EVT> &ValueVTs,
78 SmallVectorImpl<uint64_t> *Offsets,
79 uint64_t StartingOffset) {
80 // Given a struct type, recursively traverse the elements.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000081 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Micah Villmow3574eca2012-10-08 16:38:25 +000082 const StructLayout *SL = TLI.getDataLayout()->getStructLayout(STy);
Dan Gohman5eb6d652010-04-21 01:22:34 +000083 for (StructType::element_iterator EB = STy->element_begin(),
84 EI = EB,
85 EE = STy->element_end();
86 EI != EE; ++EI)
87 ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
88 StartingOffset + SL->getElementOffset(EI - EB));
89 return;
90 }
91 // Given an array type, recursively traverse the elements.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000092 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
93 Type *EltTy = ATy->getElementType();
Micah Villmow3574eca2012-10-08 16:38:25 +000094 uint64_t EltSize = TLI.getDataLayout()->getTypeAllocSize(EltTy);
Dan Gohman5eb6d652010-04-21 01:22:34 +000095 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
96 ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
97 StartingOffset + i * EltSize);
98 return;
99 }
100 // Interpret void as zero return values.
101 if (Ty->isVoidTy())
102 return;
103 // Base case: we can get an EVT for this LLVM IR type.
104 ValueVTs.push_back(TLI.getValueType(Ty));
105 if (Offsets)
106 Offsets->push_back(StartingOffset);
107}
108
109/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
110GlobalVariable *llvm::ExtractTypeInfo(Value *V) {
111 V = V->stripPointerCasts();
112 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
113
Bill Wendling23295cc2010-07-26 22:36:52 +0000114 if (GV && GV->getName() == "llvm.eh.catch.all.value") {
Dan Gohman5eb6d652010-04-21 01:22:34 +0000115 assert(GV->hasInitializer() &&
116 "The EH catch-all value must have an initializer");
117 Value *Init = GV->getInitializer();
118 GV = dyn_cast<GlobalVariable>(Init);
119 if (!GV) V = cast<ConstantPointerNull>(Init);
120 }
121
122 assert((GV || isa<ConstantPointerNull>(V)) &&
123 "TypeInfo must be a global variable or NULL");
124 return GV;
125}
126
127/// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
128/// processed uses a memory 'm' constraint.
129bool
John Thompson44ab89e2010-10-29 17:29:13 +0000130llvm::hasInlineAsmMemConstraint(InlineAsm::ConstraintInfoVector &CInfos,
Dan Gohman5eb6d652010-04-21 01:22:34 +0000131 const TargetLowering &TLI) {
132 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
133 InlineAsm::ConstraintInfo &CI = CInfos[i];
134 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
135 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
136 if (CType == TargetLowering::C_Memory)
137 return true;
138 }
139
140 // Indirect operand accesses access memory.
141 if (CI.isIndirect)
142 return true;
143 }
144
145 return false;
146}
147
148/// getFCmpCondCode - Return the ISD condition code corresponding to
149/// the given LLVM IR floating-point condition code. This includes
150/// consideration of global floating-point math flags.
151///
152ISD::CondCode llvm::getFCmpCondCode(FCmpInst::Predicate Pred) {
Dan Gohman5eb6d652010-04-21 01:22:34 +0000153 switch (Pred) {
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000154 case FCmpInst::FCMP_FALSE: return ISD::SETFALSE;
155 case FCmpInst::FCMP_OEQ: return ISD::SETOEQ;
156 case FCmpInst::FCMP_OGT: return ISD::SETOGT;
157 case FCmpInst::FCMP_OGE: return ISD::SETOGE;
158 case FCmpInst::FCMP_OLT: return ISD::SETOLT;
159 case FCmpInst::FCMP_OLE: return ISD::SETOLE;
160 case FCmpInst::FCMP_ONE: return ISD::SETONE;
161 case FCmpInst::FCMP_ORD: return ISD::SETO;
162 case FCmpInst::FCMP_UNO: return ISD::SETUO;
163 case FCmpInst::FCMP_UEQ: return ISD::SETUEQ;
164 case FCmpInst::FCMP_UGT: return ISD::SETUGT;
165 case FCmpInst::FCMP_UGE: return ISD::SETUGE;
166 case FCmpInst::FCMP_ULT: return ISD::SETULT;
167 case FCmpInst::FCMP_ULE: return ISD::SETULE;
168 case FCmpInst::FCMP_UNE: return ISD::SETUNE;
169 case FCmpInst::FCMP_TRUE: return ISD::SETTRUE;
David Blaikie4d6ccb52012-01-20 21:51:11 +0000170 default: llvm_unreachable("Invalid FCmp predicate opcode!");
Dan Gohman5eb6d652010-04-21 01:22:34 +0000171 }
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000172}
173
174ISD::CondCode llvm::getFCmpCodeWithoutNaN(ISD::CondCode CC) {
175 switch (CC) {
176 case ISD::SETOEQ: case ISD::SETUEQ: return ISD::SETEQ;
177 case ISD::SETONE: case ISD::SETUNE: return ISD::SETNE;
178 case ISD::SETOLT: case ISD::SETULT: return ISD::SETLT;
179 case ISD::SETOLE: case ISD::SETULE: return ISD::SETLE;
180 case ISD::SETOGT: case ISD::SETUGT: return ISD::SETGT;
181 case ISD::SETOGE: case ISD::SETUGE: return ISD::SETGE;
David Blaikie4d6ccb52012-01-20 21:51:11 +0000182 default: return CC;
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000183 }
Dan Gohman5eb6d652010-04-21 01:22:34 +0000184}
185
186/// getICmpCondCode - Return the ISD condition code corresponding to
187/// the given LLVM IR integer condition code.
188///
189ISD::CondCode llvm::getICmpCondCode(ICmpInst::Predicate Pred) {
190 switch (Pred) {
191 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
192 case ICmpInst::ICMP_NE: return ISD::SETNE;
193 case ICmpInst::ICMP_SLE: return ISD::SETLE;
194 case ICmpInst::ICMP_ULE: return ISD::SETULE;
195 case ICmpInst::ICMP_SGE: return ISD::SETGE;
196 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
197 case ICmpInst::ICMP_SLT: return ISD::SETLT;
198 case ICmpInst::ICMP_ULT: return ISD::SETULT;
199 case ICmpInst::ICMP_SGT: return ISD::SETGT;
200 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
201 default:
202 llvm_unreachable("Invalid ICmp predicate opcode!");
Dan Gohman5eb6d652010-04-21 01:22:34 +0000203 }
204}
205
Chris Lattnercd6015c2012-06-01 05:01:15 +0000206
207/// getNoopInput - If V is a noop (i.e., lowers to no machine code), look
208/// through it (and any transitive noop operands to it) and return its input
209/// value. This is used to determine if a tail call can be formed.
210///
211static const Value *getNoopInput(const Value *V, const TargetLowering &TLI) {
212 // If V is not an instruction, it can't be looked through.
Chris Lattner5b0d9462012-06-01 05:16:33 +0000213 const Instruction *I = dyn_cast<Instruction>(V);
214 if (I == 0 || !I->hasOneUse() || I->getNumOperands() == 0) return V;
Chris Lattnercd6015c2012-06-01 05:01:15 +0000215
Chris Lattner5b0d9462012-06-01 05:16:33 +0000216 Value *Op = I->getOperand(0);
217
Chris Lattnercd6015c2012-06-01 05:01:15 +0000218 // Look through truly no-op truncates.
Chris Lattner5b0d9462012-06-01 05:16:33 +0000219 if (isa<TruncInst>(I) &&
220 TLI.isTruncateFree(I->getOperand(0)->getType(), I->getType()))
221 return getNoopInput(I->getOperand(0), TLI);
Chris Lattnercd6015c2012-06-01 05:01:15 +0000222
223 // Look through truly no-op bitcasts.
Chris Lattner5b0d9462012-06-01 05:16:33 +0000224 if (isa<BitCastInst>(I)) {
225 // No type change at all.
226 if (Op->getType() == I->getType())
227 return getNoopInput(Op, TLI);
228
229 // Pointer to pointer cast.
230 if (Op->getType()->isPointerTy() && I->getType()->isPointerTy())
231 return getNoopInput(Op, TLI);
232
233 if (isa<VectorType>(Op->getType()) && isa<VectorType>(I->getType()) &&
234 TLI.isTypeLegal(EVT::getEVT(Op->getType())) &&
235 TLI.isTypeLegal(EVT::getEVT(I->getType())))
Chris Lattnercd6015c2012-06-01 05:01:15 +0000236 return getNoopInput(Op, TLI);
237 }
Chris Lattner5b0d9462012-06-01 05:16:33 +0000238
239 // Look through inttoptr.
240 if (isa<IntToPtrInst>(I) && !isa<VectorType>(I->getType())) {
241 // Make sure this isn't a truncating or extending cast. We could support
242 // this eventually, but don't bother for now.
243 if (TLI.getPointerTy().getSizeInBits() ==
244 cast<IntegerType>(Op->getType())->getBitWidth())
245 return getNoopInput(Op, TLI);
246 }
247
248 // Look through ptrtoint.
249 if (isa<PtrToIntInst>(I) && !isa<VectorType>(I->getType())) {
250 // Make sure this isn't a truncating or extending cast. We could support
251 // this eventually, but don't bother for now.
252 if (TLI.getPointerTy().getSizeInBits() ==
253 cast<IntegerType>(I->getType())->getBitWidth())
254 return getNoopInput(Op, TLI);
255 }
256
Chris Lattnercd6015c2012-06-01 05:01:15 +0000257
258 // Otherwise it's not something we can look through.
259 return V;
260}
261
262
Dan Gohman5eb6d652010-04-21 01:22:34 +0000263/// Test if the given instruction is in a position to be optimized
264/// with a tail-call. This roughly means that it's in a block with
265/// a return and there's nothing that needs to be scheduled
266/// between it and the return.
267///
268/// This function only tests target-independent requirements.
Bill Wendling034b94b2012-12-19 07:18:57 +0000269bool llvm::isInTailCallPosition(ImmutableCallSite CS, Attribute CalleeRetAttr,
Dan Gohman5eb6d652010-04-21 01:22:34 +0000270 const TargetLowering &TLI) {
271 const Instruction *I = CS.getInstruction();
272 const BasicBlock *ExitBB = I->getParent();
273 const TerminatorInst *Term = ExitBB->getTerminator();
274 const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
Dan Gohman5eb6d652010-04-21 01:22:34 +0000275
276 // The block must end in a return statement or unreachable.
277 //
278 // FIXME: Decline tailcall if it's not guaranteed and if the block ends in
279 // an unreachable, for now. The way tailcall optimization is currently
280 // implemented means it will add an epilogue followed by a jump. That is
281 // not profitable. Also, if the callee is a special function (e.g.
282 // longjmp on x86), it can end up causing miscompilation that has not
283 // been fully understood.
284 if (!Ret &&
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000285 (!TLI.getTargetMachine().Options.GuaranteedTailCallOpt ||
Chris Lattnercd6015c2012-06-01 05:01:15 +0000286 !isa<UnreachableInst>(Term)))
287 return false;
Dan Gohman5eb6d652010-04-21 01:22:34 +0000288
289 // If I will have a chain, make sure no other instruction that will have a
290 // chain interposes between I and the return.
291 if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
Dan Gohmanf0426602011-12-14 23:49:11 +0000292 !isSafeToSpeculativelyExecute(I))
Dan Gohman5eb6d652010-04-21 01:22:34 +0000293 for (BasicBlock::const_iterator BBI = prior(prior(ExitBB->end())); ;
294 --BBI) {
295 if (&*BBI == I)
296 break;
297 // Debug info intrinsics do not get in the way of tail call optimization.
298 if (isa<DbgInfoIntrinsic>(BBI))
299 continue;
300 if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
Dan Gohmanf0426602011-12-14 23:49:11 +0000301 !isSafeToSpeculativelyExecute(BBI))
Dan Gohman5eb6d652010-04-21 01:22:34 +0000302 return false;
303 }
304
305 // If the block ends with a void return or unreachable, it doesn't matter
306 // what the call's return type is.
307 if (!Ret || Ret->getNumOperands() == 0) return true;
308
309 // If the return value is undef, it doesn't matter what the call's
310 // return type is.
311 if (isa<UndefValue>(Ret->getOperand(0))) return true;
312
313 // Conservatively require the attributes of the call to match those of
314 // the return. Ignore noalias because it doesn't affect the call sequence.
Evan Cheng9344f972011-03-19 17:03:16 +0000315 const Function *F = ExitBB->getParent();
Bill Wendling034b94b2012-12-19 07:18:57 +0000316 Attribute CallerRetAttr = F->getAttributes().getRetAttributes();
317 if (AttrBuilder(CalleeRetAttr).removeAttribute(Attribute::NoAlias) !=
318 AttrBuilder(CallerRetAttr).removeAttribute(Attribute::NoAlias))
Dan Gohman5eb6d652010-04-21 01:22:34 +0000319 return false;
320
321 // It's not safe to eliminate the sign / zero extension of the return value.
Bill Wendling034b94b2012-12-19 07:18:57 +0000322 if (CallerRetAttr.hasAttribute(Attribute::ZExt) ||
323 CallerRetAttr.hasAttribute(Attribute::SExt))
Dan Gohman5eb6d652010-04-21 01:22:34 +0000324 return false;
325
326 // Otherwise, make sure the unmodified return value of I is the return value.
Chris Lattnerf59e4e32012-06-01 05:29:15 +0000327 // We handle two cases: multiple return values + scalars.
328 Value *RetVal = Ret->getOperand(0);
329 if (!isa<InsertValueInst>(RetVal) || !isa<StructType>(RetVal->getType()))
330 // Handle scalars first.
331 return getNoopInput(Ret->getOperand(0), TLI) == I;
332
333 // If this is an aggregate return, look through the insert/extract values and
334 // see if each is transparent.
335 for (unsigned i = 0, e =cast<StructType>(RetVal->getType())->getNumElements();
336 i != e; ++i) {
Chris Lattner74ee0ef2012-06-01 15:02:52 +0000337 const Value *InScalar = FindInsertedValue(RetVal, i);
338 if (InScalar == 0) return false;
339 InScalar = getNoopInput(InScalar, TLI);
Chris Lattnerf59e4e32012-06-01 05:29:15 +0000340
341 // If the scalar value being inserted is an extractvalue of the right index
342 // from the call, then everything is good.
343 const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(InScalar);
344 if (EVI == 0 || EVI->getOperand(0) != I || EVI->getNumIndices() != 1 ||
345 EVI->getIndices()[0] != i)
346 return false;
347 }
348
349 return true;
Dan Gohman5eb6d652010-04-21 01:22:34 +0000350}
351
Evan Cheng3d2125c2010-11-30 23:55:39 +0000352bool llvm::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
Evan Chengbf010eb2012-04-10 01:51:00 +0000353 SDValue &Chain, const TargetLowering &TLI) {
Evan Cheng3d2125c2010-11-30 23:55:39 +0000354 const Function *F = DAG.getMachineFunction().getFunction();
355
356 // Conservatively require the attributes of the call to match those of
357 // the return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling034b94b2012-12-19 07:18:57 +0000358 Attribute CallerRetAttr = F->getAttributes().getRetAttributes();
Bill Wendling702cc912012-10-15 20:35:56 +0000359 if (AttrBuilder(CallerRetAttr)
Bill Wendling034b94b2012-12-19 07:18:57 +0000360 .removeAttribute(Attribute::NoAlias).hasAttributes())
Evan Cheng3d2125c2010-11-30 23:55:39 +0000361 return false;
362
363 // It's not safe to eliminate the sign / zero extension of the return value.
Bill Wendling034b94b2012-12-19 07:18:57 +0000364 if (CallerRetAttr.hasAttribute(Attribute::ZExt) ||
365 CallerRetAttr.hasAttribute(Attribute::SExt))
Evan Cheng3d2125c2010-11-30 23:55:39 +0000366 return false;
367
368 // Check if the only use is a function return node.
Evan Chengbf010eb2012-04-10 01:51:00 +0000369 return TLI.isUsedByReturnOnly(Node, Chain);
Evan Cheng3d2125c2010-11-30 23:55:39 +0000370}