blob: 264bc21d604a042d85762f27c6990d2990d051b2 [file] [log] [blame]
Peter Collingbourne9f7ec142016-02-03 02:51:00 +00001//===- Evaluator.cpp - LLVM IR evaluator ----------------------------------===//
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// Function evaluator for LLVM IR.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/Utils/Evaluator.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000015#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SmallPtrSet.h"
18#include "llvm/ADT/SmallVector.h"
Peter Collingbourne9f7ec142016-02-03 02:51:00 +000019#include "llvm/Analysis/ConstantFolding.h"
20#include "llvm/IR/BasicBlock.h"
21#include "llvm/IR/CallSite.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000022#include "llvm/IR/Constant.h"
Peter Collingbourne9f7ec142016-02-03 02:51:00 +000023#include "llvm/IR/Constants.h"
Craig Topperb5c2bfa2017-03-20 05:08:41 +000024#include "llvm/IR/DataLayout.h"
Peter Collingbourne9f7ec142016-02-03 02:51:00 +000025#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000026#include "llvm/IR/Function.h"
27#include "llvm/IR/GlobalValue.h"
Peter Collingbourne9f7ec142016-02-03 02:51:00 +000028#include "llvm/IR/GlobalVariable.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000029#include "llvm/IR/InstrTypes.h"
30#include "llvm/IR/Instruction.h"
Peter Collingbourne9f7ec142016-02-03 02:51:00 +000031#include "llvm/IR/Instructions.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000032#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000033#include "llvm/IR/Intrinsics.h"
Peter Collingbourne9f7ec142016-02-03 02:51:00 +000034#include "llvm/IR/Operator.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000035#include "llvm/IR/Type.h"
36#include "llvm/IR/User.h"
37#include "llvm/IR/Value.h"
38#include "llvm/Support/Casting.h"
Peter Collingbourne9f7ec142016-02-03 02:51:00 +000039#include "llvm/Support/Debug.h"
Peter Collingbourne83cc9812016-02-03 03:16:37 +000040#include "llvm/Support/raw_ostream.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000041#include <iterator>
Peter Collingbourne9f7ec142016-02-03 02:51:00 +000042
43#define DEBUG_TYPE "evaluator"
44
45using namespace llvm;
46
47static inline bool
48isSimpleEnoughValueToCommit(Constant *C,
49 SmallPtrSetImpl<Constant *> &SimpleConstants,
50 const DataLayout &DL);
51
52/// Return true if the specified constant can be handled by the code generator.
53/// We don't want to generate something like:
54/// void *X = &X/42;
55/// because the code generator doesn't have a relocation that can handle that.
56///
57/// This function should be called if C was not found (but just got inserted)
58/// in SimpleConstants to avoid having to rescan the same constants all the
59/// time.
60static bool
61isSimpleEnoughValueToCommitHelper(Constant *C,
62 SmallPtrSetImpl<Constant *> &SimpleConstants,
63 const DataLayout &DL) {
64 // Simple global addresses are supported, do not allow dllimport or
65 // thread-local globals.
66 if (auto *GV = dyn_cast<GlobalValue>(C))
67 return !GV->hasDLLImportStorageClass() && !GV->isThreadLocal();
68
69 // Simple integer, undef, constant aggregate zero, etc are all supported.
70 if (C->getNumOperands() == 0 || isa<BlockAddress>(C))
71 return true;
72
73 // Aggregate values are safe if all their elements are.
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +000074 if (isa<ConstantAggregate>(C)) {
Peter Collingbourne9f7ec142016-02-03 02:51:00 +000075 for (Value *Op : C->operands())
76 if (!isSimpleEnoughValueToCommit(cast<Constant>(Op), SimpleConstants, DL))
77 return false;
78 return true;
79 }
80
81 // We don't know exactly what relocations are allowed in constant expressions,
82 // so we allow &global+constantoffset, which is safe and uniformly supported
83 // across targets.
84 ConstantExpr *CE = cast<ConstantExpr>(C);
85 switch (CE->getOpcode()) {
86 case Instruction::BitCast:
87 // Bitcast is fine if the casted value is fine.
88 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
89
90 case Instruction::IntToPtr:
91 case Instruction::PtrToInt:
92 // int <=> ptr is fine if the int type is the same size as the
93 // pointer type.
94 if (DL.getTypeSizeInBits(CE->getType()) !=
95 DL.getTypeSizeInBits(CE->getOperand(0)->getType()))
96 return false;
97 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
98
99 // GEP is fine if it is simple + constant offset.
100 case Instruction::GetElementPtr:
101 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
102 if (!isa<ConstantInt>(CE->getOperand(i)))
103 return false;
104 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
105
106 case Instruction::Add:
107 // We allow simple+cst.
108 if (!isa<ConstantInt>(CE->getOperand(1)))
109 return false;
110 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
111 }
112 return false;
113}
114
115static inline bool
116isSimpleEnoughValueToCommit(Constant *C,
117 SmallPtrSetImpl<Constant *> &SimpleConstants,
118 const DataLayout &DL) {
119 // If we already checked this constant, we win.
120 if (!SimpleConstants.insert(C).second)
121 return true;
122 // Check the constant.
123 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, DL);
124}
125
126/// Return true if this constant is simple enough for us to understand. In
127/// particular, if it is a cast to anything other than from one pointer type to
128/// another pointer type, we punt. We basically just support direct accesses to
129/// globals and GEP's of globals. This should be kept up to date with
130/// CommitValueTo.
131static bool isSimpleEnoughPointerToCommit(Constant *C) {
132 // Conservatively, avoid aggregate types. This is because we don't
133 // want to worry about them partially overlapping other stores.
134 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
135 return false;
136
137 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
138 // Do not allow weak/*_odr/linkonce linkage or external globals.
139 return GV->hasUniqueInitializer();
140
141 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
142 // Handle a constantexpr gep.
143 if (CE->getOpcode() == Instruction::GetElementPtr &&
144 isa<GlobalVariable>(CE->getOperand(0)) &&
145 cast<GEPOperator>(CE)->isInBounds()) {
146 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
147 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
148 // external globals.
149 if (!GV->hasUniqueInitializer())
150 return false;
151
152 // The first index must be zero.
153 ConstantInt *CI = dyn_cast<ConstantInt>(*std::next(CE->op_begin()));
154 if (!CI || !CI->isZero()) return false;
155
156 // The remaining indices must be compile-time known integers within the
157 // notional bounds of the corresponding static array types.
158 if (!CE->isGEPWithNoNotionalOverIndexing())
159 return false;
160
161 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
162
163 // A constantexpr bitcast from a pointer to another pointer is a no-op,
164 // and we know how to evaluate it by moving the bitcast from the pointer
165 // operand to the value operand.
166 } else if (CE->getOpcode() == Instruction::BitCast &&
167 isa<GlobalVariable>(CE->getOperand(0))) {
168 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
169 // external globals.
170 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
171 }
172 }
173
174 return false;
175}
176
Eugene Leviant6f42a2c2018-03-13 10:19:50 +0000177static Constant *getInitializer(Constant *C) {
178 auto *GV = dyn_cast<GlobalVariable>(C);
179 return GV && GV->hasDefinitiveInitializer() ? GV->getInitializer() : nullptr;
180}
181
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000182/// Return the value that would be computed by a load from P after the stores
183/// reflected by 'memory' have been performed. If we can't decide, return null.
184Constant *Evaluator::ComputeLoadResult(Constant *P) {
185 // If this memory location has been recently stored, use the stored value: it
186 // is the most up-to-date.
187 DenseMap<Constant*, Constant*>::const_iterator I = MutatedMemory.find(P);
188 if (I != MutatedMemory.end()) return I->second;
189
190 // Access it.
191 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
192 if (GV->hasDefinitiveInitializer())
193 return GV->getInitializer();
194 return nullptr;
195 }
196
Eugene Leviant6f42a2c2018-03-13 10:19:50 +0000197 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P)) {
198 switch (CE->getOpcode()) {
199 // Handle a constantexpr getelementptr.
200 case Instruction::GetElementPtr:
201 if (auto *I = getInitializer(CE->getOperand(0)))
202 return ConstantFoldLoadThroughGEPConstantExpr(I, CE);
203 break;
204 // Handle a constantexpr bitcast.
205 case Instruction::BitCast:
Mircea Trofinaa3fea6c2018-04-06 15:54:47 +0000206 Constant *Val = getVal(CE->getOperand(0));
207 auto MM = MutatedMemory.find(Val);
208 auto *I = (MM != MutatedMemory.end()) ? MM->second
209 : getInitializer(CE->getOperand(0));
210 if (I)
Eugene Leviant6f42a2c2018-03-13 10:19:50 +0000211 return ConstantFoldLoadThroughBitcast(
212 I, P->getType()->getPointerElementType(), DL);
213 break;
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000214 }
Eugene Leviant6f42a2c2018-03-13 10:19:50 +0000215 }
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000216
217 return nullptr; // don't know how to evaluate.
218}
219
Eugene Leviant6e413442018-07-01 11:02:07 +0000220Function *
221Evaluator::getCalleeWithFormalArgs(CallSite &CS,
222 SmallVector<Constant *, 8> &Formals) {
223 auto *V = CS.getCalledValue();
224 if (auto *Fn = dyn_cast<Function>(getVal(V)))
225 return getFormalParams(CS, Fn, Formals) ? Fn : nullptr;
226
227 auto *CE = dyn_cast<ConstantExpr>(V);
228 if (!CE || CE->getOpcode() != Instruction::BitCast ||
229 !getFormalParams(CS, cast<Function>(CE->getOperand(0)), Formals))
230 return nullptr;
231
232 return dyn_cast<Function>(
233 ConstantFoldLoadThroughBitcast(CE, CE->getOperand(0)->getType(), DL));
234}
235
236bool Evaluator::getFormalParams(CallSite &CS, Function *F,
237 SmallVector<Constant *, 8> &Formals) {
238 auto *FTy = F->getFunctionType();
239 if (FTy->getNumParams() > CS.getNumArgOperands()) {
240 LLVM_DEBUG(dbgs() << "Too few arguments for function.\n");
241 return false;
242 }
243
244 auto ArgI = CS.arg_begin();
245 for (auto ParI = FTy->param_begin(), ParE = FTy->param_end(); ParI != ParE;
246 ++ParI) {
247 auto *ArgC = ConstantFoldLoadThroughBitcast(getVal(*ArgI), *ParI, DL);
248 if (!ArgC) {
249 LLVM_DEBUG(dbgs() << "Can not convert function argument.\n");
250 return false;
251 }
252 Formals.push_back(ArgC);
253 ++ArgI;
254 }
255 return true;
256}
257
258/// If call expression contains bitcast then we may need to cast
259/// evaluated return value to a type of the call expression.
260Constant *Evaluator::castCallResultIfNeeded(Value *CallExpr, Constant *RV) {
261 ConstantExpr *CE = dyn_cast<ConstantExpr>(CallExpr);
262 if (!RV || !CE || CE->getOpcode() != Instruction::BitCast)
263 return RV;
264
265 if (auto *FT =
266 dyn_cast<FunctionType>(CE->getType()->getPointerElementType())) {
267 RV = ConstantFoldLoadThroughBitcast(RV, FT->getReturnType(), DL);
268 if (!RV)
269 LLVM_DEBUG(dbgs() << "Failed to fold bitcast call expr\n");
270 }
271 return RV;
272}
273
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000274/// Evaluate all instructions in block BB, returning true if successful, false
275/// if we can't evaluate it. NewBB returns the next BB that control flows into,
276/// or null upon return.
277bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
278 BasicBlock *&NextBB) {
279 // This is the main evaluation loop.
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000280 while (true) {
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000281 Constant *InstResult = nullptr;
282
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000283 LLVM_DEBUG(dbgs() << "Evaluating Instruction: " << *CurInst << "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000284
285 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
286 if (!SI->isSimple()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000287 LLVM_DEBUG(dbgs() << "Store is not simple! Can not evaluate.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000288 return false; // no volatile/atomic accesses.
289 }
290 Constant *Ptr = getVal(SI->getOperand(1));
David Majnemerd536f232016-07-29 03:27:26 +0000291 if (auto *FoldedPtr = ConstantFoldConstant(Ptr, DL, TLI)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000292 LLVM_DEBUG(dbgs() << "Folding constant ptr expression: " << *Ptr);
David Majnemerd536f232016-07-29 03:27:26 +0000293 Ptr = FoldedPtr;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000294 LLVM_DEBUG(dbgs() << "; To: " << *Ptr << "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000295 }
296 if (!isSimpleEnoughPointerToCommit(Ptr)) {
297 // If this is too complex for us to commit, reject it.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000298 LLVM_DEBUG(
299 dbgs() << "Pointer is too complex for us to evaluate store.");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000300 return false;
301 }
302
303 Constant *Val = getVal(SI->getOperand(0));
304
305 // If this might be too difficult for the backend to handle (e.g. the addr
306 // of one global variable divided by another) then we can't commit it.
307 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, DL)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000308 LLVM_DEBUG(dbgs() << "Store value is too complex to evaluate store. "
309 << *Val << "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000310 return false;
311 }
312
313 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
314 if (CE->getOpcode() == Instruction::BitCast) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000315 LLVM_DEBUG(dbgs()
316 << "Attempting to resolve bitcast on constant ptr.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000317 // If we're evaluating a store through a bitcast, then we need
318 // to pull the bitcast off the pointer type and push it onto the
319 // stored value.
320 Ptr = CE->getOperand(0);
321
322 Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
323
324 // In order to push the bitcast onto the stored value, a bitcast
325 // from NewTy to Val's type must be legal. If it's not, we can try
326 // introspecting NewTy to find a legal conversion.
Eugene Leviant6f42a2c2018-03-13 10:19:50 +0000327 Constant *NewVal;
328 while (!(NewVal = ConstantFoldLoadThroughBitcast(Val, NewTy, DL))) {
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000329 // If NewTy is a struct, we can convert the pointer to the struct
330 // into a pointer to its first member.
331 // FIXME: This could be extended to support arrays as well.
332 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
333 NewTy = STy->getTypeAtIndex(0U);
334
335 IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
336 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
337 Constant * const IdxList[] = {IdxZero, IdxZero};
338
339 Ptr = ConstantExpr::getGetElementPtr(nullptr, Ptr, IdxList);
David Majnemerd536f232016-07-29 03:27:26 +0000340 if (auto *FoldedPtr = ConstantFoldConstant(Ptr, DL, TLI))
341 Ptr = FoldedPtr;
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000342
343 // If we can't improve the situation by introspecting NewTy,
344 // we have to give up.
345 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000346 LLVM_DEBUG(dbgs() << "Failed to bitcast constant ptr, can not "
347 "evaluate.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000348 return false;
349 }
350 }
351
Eugene Leviant6f42a2c2018-03-13 10:19:50 +0000352 Val = NewVal;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000353 LLVM_DEBUG(dbgs() << "Evaluated bitcast: " << *Val << "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000354 }
355 }
356
357 MutatedMemory[Ptr] = Val;
358 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
359 InstResult = ConstantExpr::get(BO->getOpcode(),
360 getVal(BO->getOperand(0)),
361 getVal(BO->getOperand(1)));
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000362 LLVM_DEBUG(dbgs() << "Found a BinaryOperator! Simplifying: "
363 << *InstResult << "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000364 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
365 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
366 getVal(CI->getOperand(0)),
367 getVal(CI->getOperand(1)));
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000368 LLVM_DEBUG(dbgs() << "Found a CmpInst! Simplifying: " << *InstResult
369 << "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000370 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
371 InstResult = ConstantExpr::getCast(CI->getOpcode(),
372 getVal(CI->getOperand(0)),
373 CI->getType());
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000374 LLVM_DEBUG(dbgs() << "Found a Cast! Simplifying: " << *InstResult
375 << "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000376 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
377 InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
378 getVal(SI->getOperand(1)),
379 getVal(SI->getOperand(2)));
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000380 LLVM_DEBUG(dbgs() << "Found a Select! Simplifying: " << *InstResult
381 << "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000382 } else if (auto *EVI = dyn_cast<ExtractValueInst>(CurInst)) {
383 InstResult = ConstantExpr::getExtractValue(
384 getVal(EVI->getAggregateOperand()), EVI->getIndices());
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000385 LLVM_DEBUG(dbgs() << "Found an ExtractValueInst! Simplifying: "
386 << *InstResult << "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000387 } else if (auto *IVI = dyn_cast<InsertValueInst>(CurInst)) {
388 InstResult = ConstantExpr::getInsertValue(
389 getVal(IVI->getAggregateOperand()),
390 getVal(IVI->getInsertedValueOperand()), IVI->getIndices());
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000391 LLVM_DEBUG(dbgs() << "Found an InsertValueInst! Simplifying: "
392 << *InstResult << "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000393 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
394 Constant *P = getVal(GEP->getOperand(0));
395 SmallVector<Constant*, 8> GEPOps;
396 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
397 i != e; ++i)
398 GEPOps.push_back(getVal(*i));
399 InstResult =
400 ConstantExpr::getGetElementPtr(GEP->getSourceElementType(), P, GEPOps,
401 cast<GEPOperator>(GEP)->isInBounds());
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000402 LLVM_DEBUG(dbgs() << "Found a GEP! Simplifying: " << *InstResult << "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000403 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000404 if (!LI->isSimple()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000405 LLVM_DEBUG(
406 dbgs() << "Found a Load! Not a simple load, can not evaluate.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000407 return false; // no volatile/atomic accesses.
408 }
409
410 Constant *Ptr = getVal(LI->getOperand(0));
David Majnemerd536f232016-07-29 03:27:26 +0000411 if (auto *FoldedPtr = ConstantFoldConstant(Ptr, DL, TLI)) {
412 Ptr = FoldedPtr;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000413 LLVM_DEBUG(dbgs() << "Found a constant pointer expression, constant "
414 "folding: "
415 << *Ptr << "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000416 }
417 InstResult = ComputeLoadResult(Ptr);
418 if (!InstResult) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000419 LLVM_DEBUG(
420 dbgs() << "Failed to compute load result. Can not evaluate load."
421 "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000422 return false; // Could not evaluate load.
423 }
424
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000425 LLVM_DEBUG(dbgs() << "Evaluated load: " << *InstResult << "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000426 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
427 if (AI->isArrayAllocation()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000428 LLVM_DEBUG(dbgs() << "Found an array alloca. Can not evaluate.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000429 return false; // Cannot handle array allocs.
430 }
431 Type *Ty = AI->getAllocatedType();
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000432 AllocaTmps.push_back(llvm::make_unique<GlobalVariable>(
433 Ty, false, GlobalValue::InternalLinkage, UndefValue::get(Ty),
Yaxun Liuea988f12018-05-19 02:58:16 +0000434 AI->getName(), /*TLMode=*/GlobalValue::NotThreadLocal,
435 AI->getType()->getPointerAddressSpace()));
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000436 InstResult = AllocaTmps.back().get();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000437 LLVM_DEBUG(dbgs() << "Found an alloca. Result: " << *InstResult << "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000438 } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
439 CallSite CS(&*CurInst);
440
441 // Debug info can safely be ignored here.
442 if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000443 LLVM_DEBUG(dbgs() << "Ignoring debug info.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000444 ++CurInst;
445 continue;
446 }
447
448 // Cannot handle inline asm.
449 if (isa<InlineAsm>(CS.getCalledValue())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000450 LLVM_DEBUG(dbgs() << "Found inline asm, can not evaluate.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000451 return false;
452 }
453
454 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
455 if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
456 if (MSI->isVolatile()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000457 LLVM_DEBUG(dbgs() << "Can not optimize a volatile memset "
458 << "intrinsic.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000459 return false;
460 }
461 Constant *Ptr = getVal(MSI->getDest());
462 Constant *Val = getVal(MSI->getValue());
463 Constant *DestVal = ComputeLoadResult(getVal(Ptr));
464 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
465 // This memset is a no-op.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000466 LLVM_DEBUG(dbgs() << "Ignoring no-op memset.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000467 ++CurInst;
468 continue;
469 }
470 }
471
472 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
473 II->getIntrinsicID() == Intrinsic::lifetime_end) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000474 LLVM_DEBUG(dbgs() << "Ignoring lifetime intrinsic.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000475 ++CurInst;
476 continue;
477 }
478
479 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
480 // We don't insert an entry into Values, as it doesn't have a
481 // meaningful return value.
482 if (!II->use_empty()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000483 LLVM_DEBUG(dbgs()
484 << "Found unused invariant_start. Can't evaluate.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000485 return false;
486 }
487 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
488 Value *PtrArg = getVal(II->getArgOperand(1));
489 Value *Ptr = PtrArg->stripPointerCasts();
490 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
491 Type *ElemTy = GV->getValueType();
Craig Topper79ab6432017-07-06 18:39:47 +0000492 if (!Size->isMinusOne() &&
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000493 Size->getValue().getLimitedValue() >=
494 DL.getTypeStoreSize(ElemTy)) {
495 Invariants.insert(GV);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000496 LLVM_DEBUG(dbgs() << "Found a global var that is an invariant: "
497 << *GV << "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000498 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000499 LLVM_DEBUG(dbgs()
500 << "Found a global var, but can not treat it as an "
501 "invariant.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000502 }
503 }
504 // Continue even if we do nothing.
505 ++CurInst;
506 continue;
507 } else if (II->getIntrinsicID() == Intrinsic::assume) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000508 LLVM_DEBUG(dbgs() << "Skipping assume intrinsic.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000509 ++CurInst;
510 continue;
Dan Gohman2c74fe92017-11-08 21:59:51 +0000511 } else if (II->getIntrinsicID() == Intrinsic::sideeffect) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000512 LLVM_DEBUG(dbgs() << "Skipping sideeffect intrinsic.\n");
Dan Gohman2c74fe92017-11-08 21:59:51 +0000513 ++CurInst;
514 continue;
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000515 }
516
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000517 LLVM_DEBUG(dbgs() << "Unknown intrinsic. Can not evaluate.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000518 return false;
519 }
520
521 // Resolve function pointers.
Eugene Leviant6e413442018-07-01 11:02:07 +0000522 SmallVector<Constant *, 8> Formals;
523 Function *Callee = getCalleeWithFormalArgs(CS, Formals);
Sanjoy Das5ce32722016-04-08 00:48:30 +0000524 if (!Callee || Callee->isInterposable()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000525 LLVM_DEBUG(dbgs() << "Can not resolve function pointer.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000526 return false; // Cannot resolve.
527 }
528
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000529 if (Callee->isDeclaration()) {
530 // If this is a function we can constant fold, do it.
Andrew Kaylor647025f2017-06-09 23:18:11 +0000531 if (Constant *C = ConstantFoldCall(CS, Callee, Formals, TLI)) {
Eugene Leviant6e413442018-07-01 11:02:07 +0000532 InstResult = castCallResultIfNeeded(CS.getCalledValue(), C);
533 if (!InstResult)
534 return false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000535 LLVM_DEBUG(dbgs() << "Constant folded function call. Result: "
536 << *InstResult << "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000537 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000538 LLVM_DEBUG(dbgs() << "Can not constant fold function call.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000539 return false;
540 }
541 } else {
542 if (Callee->getFunctionType()->isVarArg()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000543 LLVM_DEBUG(dbgs() << "Can not constant fold vararg function call.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000544 return false;
545 }
546
547 Constant *RetVal = nullptr;
548 // Execute the call, if successful, use the return value.
549 ValueStack.emplace_back();
550 if (!EvaluateFunction(Callee, RetVal, Formals)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000551 LLVM_DEBUG(dbgs() << "Failed to evaluate function.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000552 return false;
553 }
554 ValueStack.pop_back();
Eugene Leviant6e413442018-07-01 11:02:07 +0000555 InstResult = castCallResultIfNeeded(CS.getCalledValue(), RetVal);
556 if (RetVal && !InstResult)
557 return false;
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000558
559 if (InstResult) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000560 LLVM_DEBUG(dbgs() << "Successfully evaluated function. Result: "
561 << *InstResult << "\n\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000562 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000563 LLVM_DEBUG(dbgs()
564 << "Successfully evaluated function. Result: 0\n\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000565 }
566 }
567 } else if (isa<TerminatorInst>(CurInst)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000568 LLVM_DEBUG(dbgs() << "Found a terminator instruction.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000569
570 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
571 if (BI->isUnconditional()) {
572 NextBB = BI->getSuccessor(0);
573 } else {
574 ConstantInt *Cond =
575 dyn_cast<ConstantInt>(getVal(BI->getCondition()));
576 if (!Cond) return false; // Cannot determine.
577
578 NextBB = BI->getSuccessor(!Cond->getZExtValue());
579 }
580 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
581 ConstantInt *Val =
582 dyn_cast<ConstantInt>(getVal(SI->getCondition()));
583 if (!Val) return false; // Cannot determine.
Chandler Carruth927d8e62017-04-12 07:27:28 +0000584 NextBB = SI->findCaseValue(Val)->getCaseSuccessor();
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000585 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
586 Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
587 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
588 NextBB = BA->getBasicBlock();
589 else
590 return false; // Cannot determine.
591 } else if (isa<ReturnInst>(CurInst)) {
592 NextBB = nullptr;
593 } else {
594 // invoke, unwind, resume, unreachable.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000595 LLVM_DEBUG(dbgs() << "Can not handle terminator.");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000596 return false; // Cannot handle this terminator.
597 }
598
599 // We succeeded at evaluating this block!
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000600 LLVM_DEBUG(dbgs() << "Successfully evaluated block.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000601 return true;
602 } else {
603 // Did not know how to evaluate this!
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000604 LLVM_DEBUG(
605 dbgs() << "Failed to evaluate block due to unhandled instruction."
606 "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000607 return false;
608 }
609
610 if (!CurInst->use_empty()) {
David Majnemerd536f232016-07-29 03:27:26 +0000611 if (auto *FoldedInstResult = ConstantFoldConstant(InstResult, DL, TLI))
612 InstResult = FoldedInstResult;
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000613
614 setVal(&*CurInst, InstResult);
615 }
616
617 // If we just processed an invoke, we finished evaluating the block.
618 if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
619 NextBB = II->getNormalDest();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000620 LLVM_DEBUG(dbgs() << "Found an invoke instruction. Finished Block.\n\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000621 return true;
622 }
623
624 // Advance program counter.
625 ++CurInst;
626 }
627}
628
629/// Evaluate a call to function F, returning true if successful, false if we
630/// can't evaluate it. ActualArgs contains the formal arguments for the
631/// function.
632bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
633 const SmallVectorImpl<Constant*> &ActualArgs) {
634 // Check to see if this function is already executing (recursion). If so,
635 // bail out. TODO: we might want to accept limited recursion.
David Majnemer0d955d02016-08-11 22:21:41 +0000636 if (is_contained(CallStack, F))
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000637 return false;
638
639 CallStack.push_back(F);
640
641 // Initialize arguments to the incoming values specified.
642 unsigned ArgNo = 0;
643 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
644 ++AI, ++ArgNo)
645 setVal(&*AI, ActualArgs[ArgNo]);
646
647 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
648 // we can only evaluate any one basic block at most once. This set keeps
649 // track of what we have executed so we can detect recursive cases etc.
650 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
651
652 // CurBB - The current basic block we're evaluating.
653 BasicBlock *CurBB = &F->front();
654
655 BasicBlock::iterator CurInst = CurBB->begin();
656
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000657 while (true) {
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000658 BasicBlock *NextBB = nullptr; // Initialized to avoid compiler warnings.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000659 LLVM_DEBUG(dbgs() << "Trying to evaluate BB: " << *CurBB << "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000660
661 if (!EvaluateBlock(CurInst, NextBB))
662 return false;
663
664 if (!NextBB) {
665 // Successfully running until there's no next block means that we found
666 // the return. Fill it the return value and pop the call stack.
667 ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
668 if (RI->getNumOperands())
669 RetVal = getVal(RI->getOperand(0));
670 CallStack.pop_back();
671 return true;
672 }
673
674 // Okay, we succeeded in evaluating this control flow. See if we have
675 // executed the new block before. If so, we have a looping function,
676 // which we cannot evaluate in reasonable time.
677 if (!ExecutedBlocks.insert(NextBB).second)
678 return false; // looped!
679
680 // Okay, we have never been in this block before. Check to see if there
681 // are any PHI nodes. If so, evaluate them with information about where
682 // we came from.
683 PHINode *PN = nullptr;
684 for (CurInst = NextBB->begin();
685 (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
686 setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
687
688 // Advance to the next block.
689 CurBB = NextBB;
690 }
691}