blob: 51fc423546d075da4a1e44d70ea08dc35f72ca16 [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:
206 if (auto *I = getInitializer(CE->getOperand(0)))
207 return ConstantFoldLoadThroughBitcast(
208 I, P->getType()->getPointerElementType(), DL);
209 break;
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000210 }
Eugene Leviant6f42a2c2018-03-13 10:19:50 +0000211 }
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000212
213 return nullptr; // don't know how to evaluate.
214}
215
216/// Evaluate all instructions in block BB, returning true if successful, false
217/// if we can't evaluate it. NewBB returns the next BB that control flows into,
218/// or null upon return.
219bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
220 BasicBlock *&NextBB) {
221 // This is the main evaluation loop.
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000222 while (true) {
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000223 Constant *InstResult = nullptr;
224
225 DEBUG(dbgs() << "Evaluating Instruction: " << *CurInst << "\n");
226
227 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
228 if (!SI->isSimple()) {
229 DEBUG(dbgs() << "Store is not simple! Can not evaluate.\n");
230 return false; // no volatile/atomic accesses.
231 }
232 Constant *Ptr = getVal(SI->getOperand(1));
David Majnemerd536f232016-07-29 03:27:26 +0000233 if (auto *FoldedPtr = ConstantFoldConstant(Ptr, DL, TLI)) {
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000234 DEBUG(dbgs() << "Folding constant ptr expression: " << *Ptr);
David Majnemerd536f232016-07-29 03:27:26 +0000235 Ptr = FoldedPtr;
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000236 DEBUG(dbgs() << "; To: " << *Ptr << "\n");
237 }
238 if (!isSimpleEnoughPointerToCommit(Ptr)) {
239 // If this is too complex for us to commit, reject it.
240 DEBUG(dbgs() << "Pointer is too complex for us to evaluate store.");
241 return false;
242 }
243
244 Constant *Val = getVal(SI->getOperand(0));
245
246 // If this might be too difficult for the backend to handle (e.g. the addr
247 // of one global variable divided by another) then we can't commit it.
248 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, DL)) {
249 DEBUG(dbgs() << "Store value is too complex to evaluate store. " << *Val
250 << "\n");
251 return false;
252 }
253
254 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
255 if (CE->getOpcode() == Instruction::BitCast) {
256 DEBUG(dbgs() << "Attempting to resolve bitcast on constant ptr.\n");
257 // If we're evaluating a store through a bitcast, then we need
258 // to pull the bitcast off the pointer type and push it onto the
259 // stored value.
260 Ptr = CE->getOperand(0);
261
262 Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
263
264 // In order to push the bitcast onto the stored value, a bitcast
265 // from NewTy to Val's type must be legal. If it's not, we can try
266 // introspecting NewTy to find a legal conversion.
Eugene Leviant6f42a2c2018-03-13 10:19:50 +0000267 Constant *NewVal;
268 while (!(NewVal = ConstantFoldLoadThroughBitcast(Val, NewTy, DL))) {
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000269 // If NewTy is a struct, we can convert the pointer to the struct
270 // into a pointer to its first member.
271 // FIXME: This could be extended to support arrays as well.
272 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
273 NewTy = STy->getTypeAtIndex(0U);
274
275 IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
276 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
277 Constant * const IdxList[] = {IdxZero, IdxZero};
278
279 Ptr = ConstantExpr::getGetElementPtr(nullptr, Ptr, IdxList);
David Majnemerd536f232016-07-29 03:27:26 +0000280 if (auto *FoldedPtr = ConstantFoldConstant(Ptr, DL, TLI))
281 Ptr = FoldedPtr;
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000282
283 // If we can't improve the situation by introspecting NewTy,
284 // we have to give up.
285 } else {
286 DEBUG(dbgs() << "Failed to bitcast constant ptr, can not "
287 "evaluate.\n");
288 return false;
289 }
290 }
291
Eugene Leviant6f42a2c2018-03-13 10:19:50 +0000292 Val = NewVal;
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000293 DEBUG(dbgs() << "Evaluated bitcast: " << *Val << "\n");
294 }
295 }
296
297 MutatedMemory[Ptr] = Val;
298 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
299 InstResult = ConstantExpr::get(BO->getOpcode(),
300 getVal(BO->getOperand(0)),
301 getVal(BO->getOperand(1)));
302 DEBUG(dbgs() << "Found a BinaryOperator! Simplifying: " << *InstResult
303 << "\n");
304 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
305 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
306 getVal(CI->getOperand(0)),
307 getVal(CI->getOperand(1)));
308 DEBUG(dbgs() << "Found a CmpInst! Simplifying: " << *InstResult
309 << "\n");
310 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
311 InstResult = ConstantExpr::getCast(CI->getOpcode(),
312 getVal(CI->getOperand(0)),
313 CI->getType());
314 DEBUG(dbgs() << "Found a Cast! Simplifying: " << *InstResult
315 << "\n");
316 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
317 InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
318 getVal(SI->getOperand(1)),
319 getVal(SI->getOperand(2)));
320 DEBUG(dbgs() << "Found a Select! Simplifying: " << *InstResult
321 << "\n");
322 } else if (auto *EVI = dyn_cast<ExtractValueInst>(CurInst)) {
323 InstResult = ConstantExpr::getExtractValue(
324 getVal(EVI->getAggregateOperand()), EVI->getIndices());
325 DEBUG(dbgs() << "Found an ExtractValueInst! Simplifying: " << *InstResult
326 << "\n");
327 } else if (auto *IVI = dyn_cast<InsertValueInst>(CurInst)) {
328 InstResult = ConstantExpr::getInsertValue(
329 getVal(IVI->getAggregateOperand()),
330 getVal(IVI->getInsertedValueOperand()), IVI->getIndices());
331 DEBUG(dbgs() << "Found an InsertValueInst! Simplifying: " << *InstResult
332 << "\n");
333 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
334 Constant *P = getVal(GEP->getOperand(0));
335 SmallVector<Constant*, 8> GEPOps;
336 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
337 i != e; ++i)
338 GEPOps.push_back(getVal(*i));
339 InstResult =
340 ConstantExpr::getGetElementPtr(GEP->getSourceElementType(), P, GEPOps,
341 cast<GEPOperator>(GEP)->isInBounds());
342 DEBUG(dbgs() << "Found a GEP! Simplifying: " << *InstResult
343 << "\n");
344 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000345 if (!LI->isSimple()) {
346 DEBUG(dbgs() << "Found a Load! Not a simple load, can not evaluate.\n");
347 return false; // no volatile/atomic accesses.
348 }
349
350 Constant *Ptr = getVal(LI->getOperand(0));
David Majnemerd536f232016-07-29 03:27:26 +0000351 if (auto *FoldedPtr = ConstantFoldConstant(Ptr, DL, TLI)) {
352 Ptr = FoldedPtr;
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000353 DEBUG(dbgs() << "Found a constant pointer expression, constant "
354 "folding: " << *Ptr << "\n");
355 }
356 InstResult = ComputeLoadResult(Ptr);
357 if (!InstResult) {
358 DEBUG(dbgs() << "Failed to compute load result. Can not evaluate load."
359 "\n");
360 return false; // Could not evaluate load.
361 }
362
363 DEBUG(dbgs() << "Evaluated load: " << *InstResult << "\n");
364 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
365 if (AI->isArrayAllocation()) {
366 DEBUG(dbgs() << "Found an array alloca. Can not evaluate.\n");
367 return false; // Cannot handle array allocs.
368 }
369 Type *Ty = AI->getAllocatedType();
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000370 AllocaTmps.push_back(llvm::make_unique<GlobalVariable>(
371 Ty, false, GlobalValue::InternalLinkage, UndefValue::get(Ty),
372 AI->getName()));
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000373 InstResult = AllocaTmps.back().get();
374 DEBUG(dbgs() << "Found an alloca. Result: " << *InstResult << "\n");
375 } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
376 CallSite CS(&*CurInst);
377
378 // Debug info can safely be ignored here.
379 if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
380 DEBUG(dbgs() << "Ignoring debug info.\n");
381 ++CurInst;
382 continue;
383 }
384
385 // Cannot handle inline asm.
386 if (isa<InlineAsm>(CS.getCalledValue())) {
387 DEBUG(dbgs() << "Found inline asm, can not evaluate.\n");
388 return false;
389 }
390
391 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
392 if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
393 if (MSI->isVolatile()) {
394 DEBUG(dbgs() << "Can not optimize a volatile memset " <<
395 "intrinsic.\n");
396 return false;
397 }
398 Constant *Ptr = getVal(MSI->getDest());
399 Constant *Val = getVal(MSI->getValue());
400 Constant *DestVal = ComputeLoadResult(getVal(Ptr));
401 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
402 // This memset is a no-op.
403 DEBUG(dbgs() << "Ignoring no-op memset.\n");
404 ++CurInst;
405 continue;
406 }
407 }
408
409 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
410 II->getIntrinsicID() == Intrinsic::lifetime_end) {
411 DEBUG(dbgs() << "Ignoring lifetime intrinsic.\n");
412 ++CurInst;
413 continue;
414 }
415
416 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
417 // We don't insert an entry into Values, as it doesn't have a
418 // meaningful return value.
419 if (!II->use_empty()) {
420 DEBUG(dbgs() << "Found unused invariant_start. Can't evaluate.\n");
421 return false;
422 }
423 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
424 Value *PtrArg = getVal(II->getArgOperand(1));
425 Value *Ptr = PtrArg->stripPointerCasts();
426 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
427 Type *ElemTy = GV->getValueType();
Craig Topper79ab6432017-07-06 18:39:47 +0000428 if (!Size->isMinusOne() &&
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000429 Size->getValue().getLimitedValue() >=
430 DL.getTypeStoreSize(ElemTy)) {
431 Invariants.insert(GV);
432 DEBUG(dbgs() << "Found a global var that is an invariant: " << *GV
433 << "\n");
434 } else {
435 DEBUG(dbgs() << "Found a global var, but can not treat it as an "
436 "invariant.\n");
437 }
438 }
439 // Continue even if we do nothing.
440 ++CurInst;
441 continue;
442 } else if (II->getIntrinsicID() == Intrinsic::assume) {
443 DEBUG(dbgs() << "Skipping assume intrinsic.\n");
444 ++CurInst;
445 continue;
Dan Gohman2c74fe92017-11-08 21:59:51 +0000446 } else if (II->getIntrinsicID() == Intrinsic::sideeffect) {
447 DEBUG(dbgs() << "Skipping sideeffect intrinsic.\n");
448 ++CurInst;
449 continue;
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000450 }
451
452 DEBUG(dbgs() << "Unknown intrinsic. Can not evaluate.\n");
453 return false;
454 }
455
456 // Resolve function pointers.
457 Function *Callee = dyn_cast<Function>(getVal(CS.getCalledValue()));
Sanjoy Das5ce32722016-04-08 00:48:30 +0000458 if (!Callee || Callee->isInterposable()) {
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000459 DEBUG(dbgs() << "Can not resolve function pointer.\n");
460 return false; // Cannot resolve.
461 }
462
463 SmallVector<Constant*, 8> Formals;
464 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i)
465 Formals.push_back(getVal(*i));
466
467 if (Callee->isDeclaration()) {
468 // If this is a function we can constant fold, do it.
Andrew Kaylor647025f2017-06-09 23:18:11 +0000469 if (Constant *C = ConstantFoldCall(CS, Callee, Formals, TLI)) {
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000470 InstResult = C;
471 DEBUG(dbgs() << "Constant folded function call. Result: " <<
472 *InstResult << "\n");
473 } else {
474 DEBUG(dbgs() << "Can not constant fold function call.\n");
475 return false;
476 }
477 } else {
478 if (Callee->getFunctionType()->isVarArg()) {
479 DEBUG(dbgs() << "Can not constant fold vararg function call.\n");
480 return false;
481 }
482
483 Constant *RetVal = nullptr;
484 // Execute the call, if successful, use the return value.
485 ValueStack.emplace_back();
486 if (!EvaluateFunction(Callee, RetVal, Formals)) {
487 DEBUG(dbgs() << "Failed to evaluate function.\n");
488 return false;
489 }
490 ValueStack.pop_back();
491 InstResult = RetVal;
492
493 if (InstResult) {
494 DEBUG(dbgs() << "Successfully evaluated function. Result: "
495 << *InstResult << "\n\n");
496 } else {
497 DEBUG(dbgs() << "Successfully evaluated function. Result: 0\n\n");
498 }
499 }
500 } else if (isa<TerminatorInst>(CurInst)) {
501 DEBUG(dbgs() << "Found a terminator instruction.\n");
502
503 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
504 if (BI->isUnconditional()) {
505 NextBB = BI->getSuccessor(0);
506 } else {
507 ConstantInt *Cond =
508 dyn_cast<ConstantInt>(getVal(BI->getCondition()));
509 if (!Cond) return false; // Cannot determine.
510
511 NextBB = BI->getSuccessor(!Cond->getZExtValue());
512 }
513 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
514 ConstantInt *Val =
515 dyn_cast<ConstantInt>(getVal(SI->getCondition()));
516 if (!Val) return false; // Cannot determine.
Chandler Carruth927d8e62017-04-12 07:27:28 +0000517 NextBB = SI->findCaseValue(Val)->getCaseSuccessor();
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000518 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
519 Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
520 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
521 NextBB = BA->getBasicBlock();
522 else
523 return false; // Cannot determine.
524 } else if (isa<ReturnInst>(CurInst)) {
525 NextBB = nullptr;
526 } else {
527 // invoke, unwind, resume, unreachable.
528 DEBUG(dbgs() << "Can not handle terminator.");
529 return false; // Cannot handle this terminator.
530 }
531
532 // We succeeded at evaluating this block!
533 DEBUG(dbgs() << "Successfully evaluated block.\n");
534 return true;
535 } else {
536 // Did not know how to evaluate this!
537 DEBUG(dbgs() << "Failed to evaluate block due to unhandled instruction."
538 "\n");
539 return false;
540 }
541
542 if (!CurInst->use_empty()) {
David Majnemerd536f232016-07-29 03:27:26 +0000543 if (auto *FoldedInstResult = ConstantFoldConstant(InstResult, DL, TLI))
544 InstResult = FoldedInstResult;
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000545
546 setVal(&*CurInst, InstResult);
547 }
548
549 // If we just processed an invoke, we finished evaluating the block.
550 if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
551 NextBB = II->getNormalDest();
552 DEBUG(dbgs() << "Found an invoke instruction. Finished Block.\n\n");
553 return true;
554 }
555
556 // Advance program counter.
557 ++CurInst;
558 }
559}
560
561/// Evaluate a call to function F, returning true if successful, false if we
562/// can't evaluate it. ActualArgs contains the formal arguments for the
563/// function.
564bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
565 const SmallVectorImpl<Constant*> &ActualArgs) {
566 // Check to see if this function is already executing (recursion). If so,
567 // bail out. TODO: we might want to accept limited recursion.
David Majnemer0d955d02016-08-11 22:21:41 +0000568 if (is_contained(CallStack, F))
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000569 return false;
570
571 CallStack.push_back(F);
572
573 // Initialize arguments to the incoming values specified.
574 unsigned ArgNo = 0;
575 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
576 ++AI, ++ArgNo)
577 setVal(&*AI, ActualArgs[ArgNo]);
578
579 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
580 // we can only evaluate any one basic block at most once. This set keeps
581 // track of what we have executed so we can detect recursive cases etc.
582 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
583
584 // CurBB - The current basic block we're evaluating.
585 BasicBlock *CurBB = &F->front();
586
587 BasicBlock::iterator CurInst = CurBB->begin();
588
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000589 while (true) {
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000590 BasicBlock *NextBB = nullptr; // Initialized to avoid compiler warnings.
591 DEBUG(dbgs() << "Trying to evaluate BB: " << *CurBB << "\n");
592
593 if (!EvaluateBlock(CurInst, NextBB))
594 return false;
595
596 if (!NextBB) {
597 // Successfully running until there's no next block means that we found
598 // the return. Fill it the return value and pop the call stack.
599 ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
600 if (RI->getNumOperands())
601 RetVal = getVal(RI->getOperand(0));
602 CallStack.pop_back();
603 return true;
604 }
605
606 // Okay, we succeeded in evaluating this control flow. See if we have
607 // executed the new block before. If so, we have a looping function,
608 // which we cannot evaluate in reasonable time.
609 if (!ExecutedBlocks.insert(NextBB).second)
610 return false; // looped!
611
612 // Okay, we have never been in this block before. Check to see if there
613 // are any PHI nodes. If so, evaluate them with information about where
614 // we came from.
615 PHINode *PN = nullptr;
616 for (CurInst = NextBB->begin();
617 (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
618 setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
619
620 // Advance to the next block.
621 CurBB = NextBB;
622 }
623}