blob: f49fba5d49b0e606d504f5b0db694d60b1a3ee99 [file] [log] [blame]
Peter Collingbourne9f7ec142016-02-03 02:51:00 +00001//===- Evaluator.cpp - LLVM IR evaluator ----------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Peter Collingbourne9f7ec142016-02-03 02:51:00 +00006//
7//===----------------------------------------------------------------------===//
8//
9// Function evaluator for LLVM IR.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/Transforms/Utils/Evaluator.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000014#include "llvm/ADT/DenseMap.h"
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/SmallPtrSet.h"
17#include "llvm/ADT/SmallVector.h"
Peter Collingbourne9f7ec142016-02-03 02:51:00 +000018#include "llvm/Analysis/ConstantFolding.h"
19#include "llvm/IR/BasicBlock.h"
20#include "llvm/IR/CallSite.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000021#include "llvm/IR/Constant.h"
Peter Collingbourne9f7ec142016-02-03 02:51:00 +000022#include "llvm/IR/Constants.h"
Craig Topperb5c2bfa2017-03-20 05:08:41 +000023#include "llvm/IR/DataLayout.h"
Peter Collingbourne9f7ec142016-02-03 02:51:00 +000024#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000025#include "llvm/IR/Function.h"
Eugene Leviant6a572b82018-07-10 16:34:23 +000026#include "llvm/IR/GlobalAlias.h"
Eugene Zelenko5adb96c2017-10-26 00:55:39 +000027#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 Leviant6a572b82018-07-10 16:34:23 +0000220static Function *getFunction(Constant *C) {
221 if (auto *Fn = dyn_cast<Function>(C))
222 return Fn;
223
224 if (auto *Alias = dyn_cast<GlobalAlias>(C))
225 if (auto *Fn = dyn_cast<Function>(Alias->getAliasee()))
226 return Fn;
227 return nullptr;
228}
229
Eugene Leviant6e413442018-07-01 11:02:07 +0000230Function *
231Evaluator::getCalleeWithFormalArgs(CallSite &CS,
232 SmallVector<Constant *, 8> &Formals) {
233 auto *V = CS.getCalledValue();
Eugene Leviant6a572b82018-07-10 16:34:23 +0000234 if (auto *Fn = getFunction(getVal(V)))
Eugene Leviant6e413442018-07-01 11:02:07 +0000235 return getFormalParams(CS, Fn, Formals) ? Fn : nullptr;
236
237 auto *CE = dyn_cast<ConstantExpr>(V);
238 if (!CE || CE->getOpcode() != Instruction::BitCast ||
Eugene Leviant6a572b82018-07-10 16:34:23 +0000239 !getFormalParams(CS, getFunction(CE->getOperand(0)), Formals))
Eugene Leviant6e413442018-07-01 11:02:07 +0000240 return nullptr;
241
242 return dyn_cast<Function>(
243 ConstantFoldLoadThroughBitcast(CE, CE->getOperand(0)->getType(), DL));
244}
245
246bool Evaluator::getFormalParams(CallSite &CS, Function *F,
247 SmallVector<Constant *, 8> &Formals) {
Eugene Leviant6a572b82018-07-10 16:34:23 +0000248 if (!F)
249 return false;
250
Eugene Leviant6e413442018-07-01 11:02:07 +0000251 auto *FTy = F->getFunctionType();
252 if (FTy->getNumParams() > CS.getNumArgOperands()) {
253 LLVM_DEBUG(dbgs() << "Too few arguments for function.\n");
254 return false;
255 }
256
257 auto ArgI = CS.arg_begin();
258 for (auto ParI = FTy->param_begin(), ParE = FTy->param_end(); ParI != ParE;
259 ++ParI) {
260 auto *ArgC = ConstantFoldLoadThroughBitcast(getVal(*ArgI), *ParI, DL);
261 if (!ArgC) {
262 LLVM_DEBUG(dbgs() << "Can not convert function argument.\n");
263 return false;
264 }
265 Formals.push_back(ArgC);
266 ++ArgI;
267 }
268 return true;
269}
270
271/// If call expression contains bitcast then we may need to cast
272/// evaluated return value to a type of the call expression.
273Constant *Evaluator::castCallResultIfNeeded(Value *CallExpr, Constant *RV) {
274 ConstantExpr *CE = dyn_cast<ConstantExpr>(CallExpr);
275 if (!RV || !CE || CE->getOpcode() != Instruction::BitCast)
276 return RV;
277
278 if (auto *FT =
279 dyn_cast<FunctionType>(CE->getType()->getPointerElementType())) {
280 RV = ConstantFoldLoadThroughBitcast(RV, FT->getReturnType(), DL);
281 if (!RV)
282 LLVM_DEBUG(dbgs() << "Failed to fold bitcast call expr\n");
283 }
284 return RV;
285}
286
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000287/// Evaluate all instructions in block BB, returning true if successful, false
288/// if we can't evaluate it. NewBB returns the next BB that control flows into,
289/// or null upon return.
290bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
291 BasicBlock *&NextBB) {
292 // This is the main evaluation loop.
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000293 while (true) {
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000294 Constant *InstResult = nullptr;
295
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000296 LLVM_DEBUG(dbgs() << "Evaluating Instruction: " << *CurInst << "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000297
298 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
299 if (!SI->isSimple()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000300 LLVM_DEBUG(dbgs() << "Store is not simple! Can not evaluate.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000301 return false; // no volatile/atomic accesses.
302 }
303 Constant *Ptr = getVal(SI->getOperand(1));
David Majnemerd536f232016-07-29 03:27:26 +0000304 if (auto *FoldedPtr = ConstantFoldConstant(Ptr, DL, TLI)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000305 LLVM_DEBUG(dbgs() << "Folding constant ptr expression: " << *Ptr);
David Majnemerd536f232016-07-29 03:27:26 +0000306 Ptr = FoldedPtr;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000307 LLVM_DEBUG(dbgs() << "; To: " << *Ptr << "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000308 }
309 if (!isSimpleEnoughPointerToCommit(Ptr)) {
310 // If this is too complex for us to commit, reject it.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000311 LLVM_DEBUG(
312 dbgs() << "Pointer is too complex for us to evaluate store.");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000313 return false;
314 }
315
316 Constant *Val = getVal(SI->getOperand(0));
317
318 // If this might be too difficult for the backend to handle (e.g. the addr
319 // of one global variable divided by another) then we can't commit it.
320 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, DL)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000321 LLVM_DEBUG(dbgs() << "Store value is too complex to evaluate store. "
322 << *Val << "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000323 return false;
324 }
325
326 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
327 if (CE->getOpcode() == Instruction::BitCast) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000328 LLVM_DEBUG(dbgs()
329 << "Attempting to resolve bitcast on constant ptr.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000330 // If we're evaluating a store through a bitcast, then we need
331 // to pull the bitcast off the pointer type and push it onto the
332 // stored value.
333 Ptr = CE->getOperand(0);
334
335 Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
336
337 // In order to push the bitcast onto the stored value, a bitcast
338 // from NewTy to Val's type must be legal. If it's not, we can try
339 // introspecting NewTy to find a legal conversion.
Eugene Leviant6f42a2c2018-03-13 10:19:50 +0000340 Constant *NewVal;
341 while (!(NewVal = ConstantFoldLoadThroughBitcast(Val, NewTy, DL))) {
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000342 // If NewTy is a struct, we can convert the pointer to the struct
343 // into a pointer to its first member.
344 // FIXME: This could be extended to support arrays as well.
345 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
346 NewTy = STy->getTypeAtIndex(0U);
347
348 IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
349 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
350 Constant * const IdxList[] = {IdxZero, IdxZero};
351
352 Ptr = ConstantExpr::getGetElementPtr(nullptr, Ptr, IdxList);
David Majnemerd536f232016-07-29 03:27:26 +0000353 if (auto *FoldedPtr = ConstantFoldConstant(Ptr, DL, TLI))
354 Ptr = FoldedPtr;
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000355
356 // If we can't improve the situation by introspecting NewTy,
357 // we have to give up.
358 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000359 LLVM_DEBUG(dbgs() << "Failed to bitcast constant ptr, can not "
360 "evaluate.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000361 return false;
362 }
363 }
364
Eugene Leviant6f42a2c2018-03-13 10:19:50 +0000365 Val = NewVal;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000366 LLVM_DEBUG(dbgs() << "Evaluated bitcast: " << *Val << "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000367 }
368 }
369
370 MutatedMemory[Ptr] = Val;
371 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
372 InstResult = ConstantExpr::get(BO->getOpcode(),
373 getVal(BO->getOperand(0)),
374 getVal(BO->getOperand(1)));
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000375 LLVM_DEBUG(dbgs() << "Found a BinaryOperator! Simplifying: "
376 << *InstResult << "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000377 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
378 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
379 getVal(CI->getOperand(0)),
380 getVal(CI->getOperand(1)));
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000381 LLVM_DEBUG(dbgs() << "Found a CmpInst! Simplifying: " << *InstResult
382 << "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000383 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
384 InstResult = ConstantExpr::getCast(CI->getOpcode(),
385 getVal(CI->getOperand(0)),
386 CI->getType());
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000387 LLVM_DEBUG(dbgs() << "Found a Cast! Simplifying: " << *InstResult
388 << "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000389 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
390 InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
391 getVal(SI->getOperand(1)),
392 getVal(SI->getOperand(2)));
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000393 LLVM_DEBUG(dbgs() << "Found a Select! Simplifying: " << *InstResult
394 << "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000395 } else if (auto *EVI = dyn_cast<ExtractValueInst>(CurInst)) {
396 InstResult = ConstantExpr::getExtractValue(
397 getVal(EVI->getAggregateOperand()), EVI->getIndices());
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000398 LLVM_DEBUG(dbgs() << "Found an ExtractValueInst! Simplifying: "
399 << *InstResult << "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000400 } else if (auto *IVI = dyn_cast<InsertValueInst>(CurInst)) {
401 InstResult = ConstantExpr::getInsertValue(
402 getVal(IVI->getAggregateOperand()),
403 getVal(IVI->getInsertedValueOperand()), IVI->getIndices());
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000404 LLVM_DEBUG(dbgs() << "Found an InsertValueInst! Simplifying: "
405 << *InstResult << "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000406 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
407 Constant *P = getVal(GEP->getOperand(0));
408 SmallVector<Constant*, 8> GEPOps;
409 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
410 i != e; ++i)
411 GEPOps.push_back(getVal(*i));
412 InstResult =
413 ConstantExpr::getGetElementPtr(GEP->getSourceElementType(), P, GEPOps,
414 cast<GEPOperator>(GEP)->isInBounds());
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000415 LLVM_DEBUG(dbgs() << "Found a GEP! Simplifying: " << *InstResult << "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000416 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000417 if (!LI->isSimple()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000418 LLVM_DEBUG(
419 dbgs() << "Found a Load! Not a simple load, can not evaluate.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000420 return false; // no volatile/atomic accesses.
421 }
422
423 Constant *Ptr = getVal(LI->getOperand(0));
David Majnemerd536f232016-07-29 03:27:26 +0000424 if (auto *FoldedPtr = ConstantFoldConstant(Ptr, DL, TLI)) {
425 Ptr = FoldedPtr;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000426 LLVM_DEBUG(dbgs() << "Found a constant pointer expression, constant "
427 "folding: "
428 << *Ptr << "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000429 }
430 InstResult = ComputeLoadResult(Ptr);
431 if (!InstResult) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000432 LLVM_DEBUG(
433 dbgs() << "Failed to compute load result. Can not evaluate load."
434 "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000435 return false; // Could not evaluate load.
436 }
437
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000438 LLVM_DEBUG(dbgs() << "Evaluated load: " << *InstResult << "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000439 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
440 if (AI->isArrayAllocation()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000441 LLVM_DEBUG(dbgs() << "Found an array alloca. Can not evaluate.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000442 return false; // Cannot handle array allocs.
443 }
444 Type *Ty = AI->getAllocatedType();
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000445 AllocaTmps.push_back(llvm::make_unique<GlobalVariable>(
446 Ty, false, GlobalValue::InternalLinkage, UndefValue::get(Ty),
Yaxun Liuea988f12018-05-19 02:58:16 +0000447 AI->getName(), /*TLMode=*/GlobalValue::NotThreadLocal,
448 AI->getType()->getPointerAddressSpace()));
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000449 InstResult = AllocaTmps.back().get();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000450 LLVM_DEBUG(dbgs() << "Found an alloca. Result: " << *InstResult << "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000451 } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
452 CallSite CS(&*CurInst);
453
454 // Debug info can safely be ignored here.
455 if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000456 LLVM_DEBUG(dbgs() << "Ignoring debug info.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000457 ++CurInst;
458 continue;
459 }
460
461 // Cannot handle inline asm.
462 if (isa<InlineAsm>(CS.getCalledValue())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000463 LLVM_DEBUG(dbgs() << "Found inline asm, can not evaluate.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000464 return false;
465 }
466
467 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
468 if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
469 if (MSI->isVolatile()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000470 LLVM_DEBUG(dbgs() << "Can not optimize a volatile memset "
471 << "intrinsic.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000472 return false;
473 }
474 Constant *Ptr = getVal(MSI->getDest());
475 Constant *Val = getVal(MSI->getValue());
476 Constant *DestVal = ComputeLoadResult(getVal(Ptr));
477 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
478 // This memset is a no-op.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000479 LLVM_DEBUG(dbgs() << "Ignoring no-op memset.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000480 ++CurInst;
481 continue;
482 }
483 }
484
Vedant Kumarb264d692018-12-21 21:49:40 +0000485 if (II->isLifetimeStartOrEnd()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000486 LLVM_DEBUG(dbgs() << "Ignoring lifetime intrinsic.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000487 ++CurInst;
488 continue;
489 }
490
491 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
492 // We don't insert an entry into Values, as it doesn't have a
493 // meaningful return value.
494 if (!II->use_empty()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000495 LLVM_DEBUG(dbgs()
496 << "Found unused invariant_start. Can't evaluate.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000497 return false;
498 }
499 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
500 Value *PtrArg = getVal(II->getArgOperand(1));
501 Value *Ptr = PtrArg->stripPointerCasts();
502 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
503 Type *ElemTy = GV->getValueType();
Craig Topper79ab6432017-07-06 18:39:47 +0000504 if (!Size->isMinusOne() &&
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000505 Size->getValue().getLimitedValue() >=
506 DL.getTypeStoreSize(ElemTy)) {
507 Invariants.insert(GV);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000508 LLVM_DEBUG(dbgs() << "Found a global var that is an invariant: "
509 << *GV << "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000510 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000511 LLVM_DEBUG(dbgs()
512 << "Found a global var, but can not treat it as an "
513 "invariant.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000514 }
515 }
516 // Continue even if we do nothing.
517 ++CurInst;
518 continue;
519 } else if (II->getIntrinsicID() == Intrinsic::assume) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000520 LLVM_DEBUG(dbgs() << "Skipping assume intrinsic.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000521 ++CurInst;
522 continue;
Dan Gohman2c74fe92017-11-08 21:59:51 +0000523 } else if (II->getIntrinsicID() == Intrinsic::sideeffect) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000524 LLVM_DEBUG(dbgs() << "Skipping sideeffect intrinsic.\n");
Dan Gohman2c74fe92017-11-08 21:59:51 +0000525 ++CurInst;
526 continue;
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000527 }
528
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000529 LLVM_DEBUG(dbgs() << "Unknown intrinsic. Can not evaluate.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000530 return false;
531 }
532
533 // Resolve function pointers.
Eugene Leviant6e413442018-07-01 11:02:07 +0000534 SmallVector<Constant *, 8> Formals;
535 Function *Callee = getCalleeWithFormalArgs(CS, Formals);
Sanjoy Das5ce32722016-04-08 00:48:30 +0000536 if (!Callee || Callee->isInterposable()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000537 LLVM_DEBUG(dbgs() << "Can not resolve function pointer.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000538 return false; // Cannot resolve.
539 }
540
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000541 if (Callee->isDeclaration()) {
542 // If this is a function we can constant fold, do it.
Andrew Kaylor647025f2017-06-09 23:18:11 +0000543 if (Constant *C = ConstantFoldCall(CS, Callee, Formals, TLI)) {
Eugene Leviant6e413442018-07-01 11:02:07 +0000544 InstResult = castCallResultIfNeeded(CS.getCalledValue(), C);
545 if (!InstResult)
546 return false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000547 LLVM_DEBUG(dbgs() << "Constant folded function call. Result: "
548 << *InstResult << "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000549 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000550 LLVM_DEBUG(dbgs() << "Can not constant fold function call.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000551 return false;
552 }
553 } else {
554 if (Callee->getFunctionType()->isVarArg()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000555 LLVM_DEBUG(dbgs() << "Can not constant fold vararg function call.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000556 return false;
557 }
558
559 Constant *RetVal = nullptr;
560 // Execute the call, if successful, use the return value.
561 ValueStack.emplace_back();
562 if (!EvaluateFunction(Callee, RetVal, Formals)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000563 LLVM_DEBUG(dbgs() << "Failed to evaluate function.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000564 return false;
565 }
566 ValueStack.pop_back();
Eugene Leviant6e413442018-07-01 11:02:07 +0000567 InstResult = castCallResultIfNeeded(CS.getCalledValue(), RetVal);
568 if (RetVal && !InstResult)
569 return false;
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000570
571 if (InstResult) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000572 LLVM_DEBUG(dbgs() << "Successfully evaluated function. Result: "
573 << *InstResult << "\n\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000574 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000575 LLVM_DEBUG(dbgs()
576 << "Successfully evaluated function. Result: 0\n\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000577 }
578 }
Chandler Carruth9ae926b2018-08-26 09:51:22 +0000579 } else if (CurInst->isTerminator()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000580 LLVM_DEBUG(dbgs() << "Found a terminator instruction.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000581
582 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
583 if (BI->isUnconditional()) {
584 NextBB = BI->getSuccessor(0);
585 } else {
586 ConstantInt *Cond =
587 dyn_cast<ConstantInt>(getVal(BI->getCondition()));
588 if (!Cond) return false; // Cannot determine.
589
590 NextBB = BI->getSuccessor(!Cond->getZExtValue());
591 }
592 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
593 ConstantInt *Val =
594 dyn_cast<ConstantInt>(getVal(SI->getCondition()));
595 if (!Val) return false; // Cannot determine.
Chandler Carruth927d8e62017-04-12 07:27:28 +0000596 NextBB = SI->findCaseValue(Val)->getCaseSuccessor();
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000597 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
598 Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
599 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
600 NextBB = BA->getBasicBlock();
601 else
602 return false; // Cannot determine.
603 } else if (isa<ReturnInst>(CurInst)) {
604 NextBB = nullptr;
605 } else {
606 // invoke, unwind, resume, unreachable.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000607 LLVM_DEBUG(dbgs() << "Can not handle terminator.");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000608 return false; // Cannot handle this terminator.
609 }
610
611 // We succeeded at evaluating this block!
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000612 LLVM_DEBUG(dbgs() << "Successfully evaluated block.\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000613 return true;
614 } else {
615 // Did not know how to evaluate this!
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000616 LLVM_DEBUG(
617 dbgs() << "Failed to evaluate block due to unhandled instruction."
618 "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000619 return false;
620 }
621
622 if (!CurInst->use_empty()) {
David Majnemerd536f232016-07-29 03:27:26 +0000623 if (auto *FoldedInstResult = ConstantFoldConstant(InstResult, DL, TLI))
624 InstResult = FoldedInstResult;
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000625
626 setVal(&*CurInst, InstResult);
627 }
628
629 // If we just processed an invoke, we finished evaluating the block.
630 if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
631 NextBB = II->getNormalDest();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000632 LLVM_DEBUG(dbgs() << "Found an invoke instruction. Finished Block.\n\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000633 return true;
634 }
635
636 // Advance program counter.
637 ++CurInst;
638 }
639}
640
641/// Evaluate a call to function F, returning true if successful, false if we
642/// can't evaluate it. ActualArgs contains the formal arguments for the
643/// function.
644bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
645 const SmallVectorImpl<Constant*> &ActualArgs) {
646 // Check to see if this function is already executing (recursion). If so,
647 // bail out. TODO: we might want to accept limited recursion.
David Majnemer0d955d02016-08-11 22:21:41 +0000648 if (is_contained(CallStack, F))
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000649 return false;
650
651 CallStack.push_back(F);
652
653 // Initialize arguments to the incoming values specified.
654 unsigned ArgNo = 0;
655 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
656 ++AI, ++ArgNo)
657 setVal(&*AI, ActualArgs[ArgNo]);
658
659 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
660 // we can only evaluate any one basic block at most once. This set keeps
661 // track of what we have executed so we can detect recursive cases etc.
662 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
663
664 // CurBB - The current basic block we're evaluating.
665 BasicBlock *CurBB = &F->front();
666
667 BasicBlock::iterator CurInst = CurBB->begin();
668
Eugene Zelenko5adb96c2017-10-26 00:55:39 +0000669 while (true) {
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000670 BasicBlock *NextBB = nullptr; // Initialized to avoid compiler warnings.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000671 LLVM_DEBUG(dbgs() << "Trying to evaluate BB: " << *CurBB << "\n");
Peter Collingbourne9f7ec142016-02-03 02:51:00 +0000672
673 if (!EvaluateBlock(CurInst, NextBB))
674 return false;
675
676 if (!NextBB) {
677 // Successfully running until there's no next block means that we found
678 // the return. Fill it the return value and pop the call stack.
679 ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
680 if (RI->getNumOperands())
681 RetVal = getVal(RI->getOperand(0));
682 CallStack.pop_back();
683 return true;
684 }
685
686 // Okay, we succeeded in evaluating this control flow. See if we have
687 // executed the new block before. If so, we have a looping function,
688 // which we cannot evaluate in reasonable time.
689 if (!ExecutedBlocks.insert(NextBB).second)
690 return false; // looped!
691
692 // Okay, we have never been in this block before. Check to see if there
693 // are any PHI nodes. If so, evaluate them with information about where
694 // we came from.
695 PHINode *PN = nullptr;
696 for (CurInst = NextBB->begin();
697 (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
698 setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
699
700 // Advance to the next block.
701 CurBB = NextBB;
702 }
703}