10b57cec5SDimitry Andric //===- Evaluator.cpp - LLVM IR evaluator ----------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // Function evaluator for LLVM IR.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric
130b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Evaluator.h"
140b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
150b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
160b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
170b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
180b57cec5SDimitry Andric #include "llvm/Analysis/ConstantFolding.h"
190b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
200b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
210b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
220b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
230b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
240b57cec5SDimitry Andric #include "llvm/IR/Function.h"
250b57cec5SDimitry Andric #include "llvm/IR/GlobalAlias.h"
260b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
270b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
280b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
290b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
300b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
310b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
320b57cec5SDimitry Andric #include "llvm/IR/Operator.h"
330b57cec5SDimitry Andric #include "llvm/IR/Type.h"
340b57cec5SDimitry Andric #include "llvm/IR/User.h"
350b57cec5SDimitry Andric #include "llvm/IR/Value.h"
360b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
370b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
380b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
390b57cec5SDimitry Andric
400b57cec5SDimitry Andric #define DEBUG_TYPE "evaluator"
410b57cec5SDimitry Andric
420b57cec5SDimitry Andric using namespace llvm;
430b57cec5SDimitry Andric
440b57cec5SDimitry Andric static inline bool
450b57cec5SDimitry Andric isSimpleEnoughValueToCommit(Constant *C,
460b57cec5SDimitry Andric SmallPtrSetImpl<Constant *> &SimpleConstants,
470b57cec5SDimitry Andric const DataLayout &DL);
480b57cec5SDimitry Andric
490b57cec5SDimitry Andric /// Return true if the specified constant can be handled by the code generator.
500b57cec5SDimitry Andric /// We don't want to generate something like:
510b57cec5SDimitry Andric /// void *X = &X/42;
520b57cec5SDimitry Andric /// because the code generator doesn't have a relocation that can handle that.
530b57cec5SDimitry Andric ///
540b57cec5SDimitry Andric /// This function should be called if C was not found (but just got inserted)
550b57cec5SDimitry Andric /// in SimpleConstants to avoid having to rescan the same constants all the
560b57cec5SDimitry Andric /// time.
570b57cec5SDimitry Andric static bool
isSimpleEnoughValueToCommitHelper(Constant * C,SmallPtrSetImpl<Constant * > & SimpleConstants,const DataLayout & DL)580b57cec5SDimitry Andric isSimpleEnoughValueToCommitHelper(Constant *C,
590b57cec5SDimitry Andric SmallPtrSetImpl<Constant *> &SimpleConstants,
600b57cec5SDimitry Andric const DataLayout &DL) {
610b57cec5SDimitry Andric // Simple global addresses are supported, do not allow dllimport or
620b57cec5SDimitry Andric // thread-local globals.
630b57cec5SDimitry Andric if (auto *GV = dyn_cast<GlobalValue>(C))
640b57cec5SDimitry Andric return !GV->hasDLLImportStorageClass() && !GV->isThreadLocal();
650b57cec5SDimitry Andric
660b57cec5SDimitry Andric // Simple integer, undef, constant aggregate zero, etc are all supported.
670b57cec5SDimitry Andric if (C->getNumOperands() == 0 || isa<BlockAddress>(C))
680b57cec5SDimitry Andric return true;
690b57cec5SDimitry Andric
700b57cec5SDimitry Andric // Aggregate values are safe if all their elements are.
710b57cec5SDimitry Andric if (isa<ConstantAggregate>(C)) {
720b57cec5SDimitry Andric for (Value *Op : C->operands())
730b57cec5SDimitry Andric if (!isSimpleEnoughValueToCommit(cast<Constant>(Op), SimpleConstants, DL))
740b57cec5SDimitry Andric return false;
750b57cec5SDimitry Andric return true;
760b57cec5SDimitry Andric }
770b57cec5SDimitry Andric
780b57cec5SDimitry Andric // We don't know exactly what relocations are allowed in constant expressions,
790b57cec5SDimitry Andric // so we allow &global+constantoffset, which is safe and uniformly supported
800b57cec5SDimitry Andric // across targets.
810b57cec5SDimitry Andric ConstantExpr *CE = cast<ConstantExpr>(C);
820b57cec5SDimitry Andric switch (CE->getOpcode()) {
830b57cec5SDimitry Andric case Instruction::BitCast:
840b57cec5SDimitry Andric // Bitcast is fine if the casted value is fine.
850b57cec5SDimitry Andric return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
860b57cec5SDimitry Andric
870b57cec5SDimitry Andric case Instruction::IntToPtr:
880b57cec5SDimitry Andric case Instruction::PtrToInt:
890b57cec5SDimitry Andric // int <=> ptr is fine if the int type is the same size as the
900b57cec5SDimitry Andric // pointer type.
910b57cec5SDimitry Andric if (DL.getTypeSizeInBits(CE->getType()) !=
920b57cec5SDimitry Andric DL.getTypeSizeInBits(CE->getOperand(0)->getType()))
930b57cec5SDimitry Andric return false;
940b57cec5SDimitry Andric return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
950b57cec5SDimitry Andric
960b57cec5SDimitry Andric // GEP is fine if it is simple + constant offset.
970b57cec5SDimitry Andric case Instruction::GetElementPtr:
980b57cec5SDimitry Andric for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
990b57cec5SDimitry Andric if (!isa<ConstantInt>(CE->getOperand(i)))
1000b57cec5SDimitry Andric return false;
1010b57cec5SDimitry Andric return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
1020b57cec5SDimitry Andric
1030b57cec5SDimitry Andric case Instruction::Add:
1040b57cec5SDimitry Andric // We allow simple+cst.
1050b57cec5SDimitry Andric if (!isa<ConstantInt>(CE->getOperand(1)))
1060b57cec5SDimitry Andric return false;
1070b57cec5SDimitry Andric return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
1080b57cec5SDimitry Andric }
1090b57cec5SDimitry Andric return false;
1100b57cec5SDimitry Andric }
1110b57cec5SDimitry Andric
1120b57cec5SDimitry Andric static inline bool
isSimpleEnoughValueToCommit(Constant * C,SmallPtrSetImpl<Constant * > & SimpleConstants,const DataLayout & DL)1130b57cec5SDimitry Andric isSimpleEnoughValueToCommit(Constant *C,
1140b57cec5SDimitry Andric SmallPtrSetImpl<Constant *> &SimpleConstants,
1150b57cec5SDimitry Andric const DataLayout &DL) {
1160b57cec5SDimitry Andric // If we already checked this constant, we win.
1170b57cec5SDimitry Andric if (!SimpleConstants.insert(C).second)
1180b57cec5SDimitry Andric return true;
1190b57cec5SDimitry Andric // Check the constant.
1200b57cec5SDimitry Andric return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, DL);
1210b57cec5SDimitry Andric }
1220b57cec5SDimitry Andric
clear()12304eeddc0SDimitry Andric void Evaluator::MutableValue::clear() {
124*06c3fb27SDimitry Andric if (auto *Agg = dyn_cast_if_present<MutableAggregate *>(Val))
12504eeddc0SDimitry Andric delete Agg;
12604eeddc0SDimitry Andric Val = nullptr;
12704eeddc0SDimitry Andric }
1280b57cec5SDimitry Andric
read(Type * Ty,APInt Offset,const DataLayout & DL) const12904eeddc0SDimitry Andric Constant *Evaluator::MutableValue::read(Type *Ty, APInt Offset,
13004eeddc0SDimitry Andric const DataLayout &DL) const {
13104eeddc0SDimitry Andric TypeSize TySize = DL.getTypeStoreSize(Ty);
13204eeddc0SDimitry Andric const MutableValue *V = this;
133*06c3fb27SDimitry Andric while (const auto *Agg = dyn_cast_if_present<MutableAggregate *>(V->Val)) {
13404eeddc0SDimitry Andric Type *AggTy = Agg->Ty;
135bdd1243dSDimitry Andric std::optional<APInt> Index = DL.getGEPIndexForOffset(AggTy, Offset);
13604eeddc0SDimitry Andric if (!Index || Index->uge(Agg->Elements.size()) ||
13704eeddc0SDimitry Andric !TypeSize::isKnownLE(TySize, DL.getTypeStoreSize(AggTy)))
13804eeddc0SDimitry Andric return nullptr;
13904eeddc0SDimitry Andric
14004eeddc0SDimitry Andric V = &Agg->Elements[Index->getZExtValue()];
14104eeddc0SDimitry Andric }
14204eeddc0SDimitry Andric
143*06c3fb27SDimitry Andric return ConstantFoldLoadFromConst(cast<Constant *>(V->Val), Ty, Offset, DL);
14404eeddc0SDimitry Andric }
14504eeddc0SDimitry Andric
makeMutable()14604eeddc0SDimitry Andric bool Evaluator::MutableValue::makeMutable() {
147*06c3fb27SDimitry Andric Constant *C = cast<Constant *>(Val);
14804eeddc0SDimitry Andric Type *Ty = C->getType();
14904eeddc0SDimitry Andric unsigned NumElements;
15004eeddc0SDimitry Andric if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
15104eeddc0SDimitry Andric NumElements = VT->getNumElements();
15204eeddc0SDimitry Andric } else if (auto *AT = dyn_cast<ArrayType>(Ty))
15304eeddc0SDimitry Andric NumElements = AT->getNumElements();
15404eeddc0SDimitry Andric else if (auto *ST = dyn_cast<StructType>(Ty))
15504eeddc0SDimitry Andric NumElements = ST->getNumElements();
15604eeddc0SDimitry Andric else
1570b57cec5SDimitry Andric return false;
1580b57cec5SDimitry Andric
15904eeddc0SDimitry Andric MutableAggregate *MA = new MutableAggregate(Ty);
16004eeddc0SDimitry Andric MA->Elements.reserve(NumElements);
16104eeddc0SDimitry Andric for (unsigned I = 0; I < NumElements; ++I)
16204eeddc0SDimitry Andric MA->Elements.push_back(C->getAggregateElement(I));
16304eeddc0SDimitry Andric Val = MA;
16404eeddc0SDimitry Andric return true;
16504eeddc0SDimitry Andric }
1660b57cec5SDimitry Andric
write(Constant * V,APInt Offset,const DataLayout & DL)16704eeddc0SDimitry Andric bool Evaluator::MutableValue::write(Constant *V, APInt Offset,
16804eeddc0SDimitry Andric const DataLayout &DL) {
16904eeddc0SDimitry Andric Type *Ty = V->getType();
17004eeddc0SDimitry Andric TypeSize TySize = DL.getTypeStoreSize(Ty);
17104eeddc0SDimitry Andric MutableValue *MV = this;
17204eeddc0SDimitry Andric while (Offset != 0 ||
17304eeddc0SDimitry Andric !CastInst::isBitOrNoopPointerCastable(Ty, MV->getType(), DL)) {
174*06c3fb27SDimitry Andric if (isa<Constant *>(MV->Val) && !MV->makeMutable())
1750b57cec5SDimitry Andric return false;
1760b57cec5SDimitry Andric
177*06c3fb27SDimitry Andric MutableAggregate *Agg = cast<MutableAggregate *>(MV->Val);
17804eeddc0SDimitry Andric Type *AggTy = Agg->Ty;
179bdd1243dSDimitry Andric std::optional<APInt> Index = DL.getGEPIndexForOffset(AggTy, Offset);
18004eeddc0SDimitry Andric if (!Index || Index->uge(Agg->Elements.size()) ||
18104eeddc0SDimitry Andric !TypeSize::isKnownLE(TySize, DL.getTypeStoreSize(AggTy)))
1820b57cec5SDimitry Andric return false;
18304eeddc0SDimitry Andric
18404eeddc0SDimitry Andric MV = &Agg->Elements[Index->getZExtValue()];
1850b57cec5SDimitry Andric }
1860b57cec5SDimitry Andric
18704eeddc0SDimitry Andric Type *MVType = MV->getType();
18804eeddc0SDimitry Andric MV->clear();
18904eeddc0SDimitry Andric if (Ty->isIntegerTy() && MVType->isPointerTy())
19004eeddc0SDimitry Andric MV->Val = ConstantExpr::getIntToPtr(V, MVType);
19104eeddc0SDimitry Andric else if (Ty->isPointerTy() && MVType->isIntegerTy())
19204eeddc0SDimitry Andric MV->Val = ConstantExpr::getPtrToInt(V, MVType);
19304eeddc0SDimitry Andric else if (Ty != MVType)
19404eeddc0SDimitry Andric MV->Val = ConstantExpr::getBitCast(V, MVType);
19504eeddc0SDimitry Andric else
19604eeddc0SDimitry Andric MV->Val = V;
19704eeddc0SDimitry Andric return true;
1980b57cec5SDimitry Andric }
1990b57cec5SDimitry Andric
toConstant() const20004eeddc0SDimitry Andric Constant *Evaluator::MutableAggregate::toConstant() const {
20104eeddc0SDimitry Andric SmallVector<Constant *, 32> Consts;
20204eeddc0SDimitry Andric for (const MutableValue &MV : Elements)
20304eeddc0SDimitry Andric Consts.push_back(MV.toConstant());
20404eeddc0SDimitry Andric
20504eeddc0SDimitry Andric if (auto *ST = dyn_cast<StructType>(Ty))
20604eeddc0SDimitry Andric return ConstantStruct::get(ST, Consts);
20704eeddc0SDimitry Andric if (auto *AT = dyn_cast<ArrayType>(Ty))
20804eeddc0SDimitry Andric return ConstantArray::get(AT, Consts);
20904eeddc0SDimitry Andric assert(isa<FixedVectorType>(Ty) && "Must be vector");
21004eeddc0SDimitry Andric return ConstantVector::get(Consts);
2110b57cec5SDimitry Andric }
2120b57cec5SDimitry Andric
2130b57cec5SDimitry Andric /// Return the value that would be computed by a load from P after the stores
2140b57cec5SDimitry Andric /// reflected by 'memory' have been performed. If we can't decide, return null.
ComputeLoadResult(Constant * P,Type * Ty)215fe6060f1SDimitry Andric Constant *Evaluator::ComputeLoadResult(Constant *P, Type *Ty) {
21604eeddc0SDimitry Andric APInt Offset(DL.getIndexTypeSizeInBits(P->getType()), 0);
21704eeddc0SDimitry Andric P = cast<Constant>(P->stripAndAccumulateConstantOffsets(
21804eeddc0SDimitry Andric DL, Offset, /* AllowNonInbounds */ true));
21904eeddc0SDimitry Andric Offset = Offset.sextOrTrunc(DL.getIndexTypeSizeInBits(P->getType()));
22081ad6265SDimitry Andric if (auto *GV = dyn_cast<GlobalVariable>(P))
22181ad6265SDimitry Andric return ComputeLoadResult(GV, Ty, Offset);
2220b57cec5SDimitry Andric return nullptr;
22381ad6265SDimitry Andric }
2240b57cec5SDimitry Andric
ComputeLoadResult(GlobalVariable * GV,Type * Ty,const APInt & Offset)22581ad6265SDimitry Andric Constant *Evaluator::ComputeLoadResult(GlobalVariable *GV, Type *Ty,
22681ad6265SDimitry Andric const APInt &Offset) {
22704eeddc0SDimitry Andric auto It = MutatedMemory.find(GV);
22804eeddc0SDimitry Andric if (It != MutatedMemory.end())
22904eeddc0SDimitry Andric return It->second.read(Ty, Offset, DL);
2300b57cec5SDimitry Andric
23104eeddc0SDimitry Andric if (!GV->hasDefinitiveInitializer())
23204eeddc0SDimitry Andric return nullptr;
23304eeddc0SDimitry Andric return ConstantFoldLoadFromConst(GV->getInitializer(), Ty, Offset, DL);
2340b57cec5SDimitry Andric }
2350b57cec5SDimitry Andric
getFunction(Constant * C)2360b57cec5SDimitry Andric static Function *getFunction(Constant *C) {
2370b57cec5SDimitry Andric if (auto *Fn = dyn_cast<Function>(C))
2380b57cec5SDimitry Andric return Fn;
2390b57cec5SDimitry Andric
2400b57cec5SDimitry Andric if (auto *Alias = dyn_cast<GlobalAlias>(C))
2410b57cec5SDimitry Andric if (auto *Fn = dyn_cast<Function>(Alias->getAliasee()))
2420b57cec5SDimitry Andric return Fn;
2430b57cec5SDimitry Andric return nullptr;
2440b57cec5SDimitry Andric }
2450b57cec5SDimitry Andric
2460b57cec5SDimitry Andric Function *
getCalleeWithFormalArgs(CallBase & CB,SmallVectorImpl<Constant * > & Formals)2475ffd83dbSDimitry Andric Evaluator::getCalleeWithFormalArgs(CallBase &CB,
2485ffd83dbSDimitry Andric SmallVectorImpl<Constant *> &Formals) {
24904eeddc0SDimitry Andric auto *V = CB.getCalledOperand()->stripPointerCasts();
2500b57cec5SDimitry Andric if (auto *Fn = getFunction(getVal(V)))
2515ffd83dbSDimitry Andric return getFormalParams(CB, Fn, Formals) ? Fn : nullptr;
2520b57cec5SDimitry Andric return nullptr;
2530b57cec5SDimitry Andric }
2540b57cec5SDimitry Andric
getFormalParams(CallBase & CB,Function * F,SmallVectorImpl<Constant * > & Formals)2555ffd83dbSDimitry Andric bool Evaluator::getFormalParams(CallBase &CB, Function *F,
2565ffd83dbSDimitry Andric SmallVectorImpl<Constant *> &Formals) {
2570b57cec5SDimitry Andric if (!F)
2580b57cec5SDimitry Andric return false;
2590b57cec5SDimitry Andric
2600b57cec5SDimitry Andric auto *FTy = F->getFunctionType();
261349cc55cSDimitry Andric if (FTy->getNumParams() > CB.arg_size()) {
2620b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Too few arguments for function.\n");
2630b57cec5SDimitry Andric return false;
2640b57cec5SDimitry Andric }
2650b57cec5SDimitry Andric
2665ffd83dbSDimitry Andric auto ArgI = CB.arg_begin();
2675e801ac6SDimitry Andric for (Type *PTy : FTy->params()) {
2685e801ac6SDimitry Andric auto *ArgC = ConstantFoldLoadThroughBitcast(getVal(*ArgI), PTy, DL);
2690b57cec5SDimitry Andric if (!ArgC) {
2700b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Can not convert function argument.\n");
2710b57cec5SDimitry Andric return false;
2720b57cec5SDimitry Andric }
2730b57cec5SDimitry Andric Formals.push_back(ArgC);
2740b57cec5SDimitry Andric ++ArgI;
2750b57cec5SDimitry Andric }
2760b57cec5SDimitry Andric return true;
2770b57cec5SDimitry Andric }
2780b57cec5SDimitry Andric
2790b57cec5SDimitry Andric /// If call expression contains bitcast then we may need to cast
2800b57cec5SDimitry Andric /// evaluated return value to a type of the call expression.
castCallResultIfNeeded(Type * ReturnType,Constant * RV)28104eeddc0SDimitry Andric Constant *Evaluator::castCallResultIfNeeded(Type *ReturnType, Constant *RV) {
28204eeddc0SDimitry Andric if (!RV || RV->getType() == ReturnType)
2830b57cec5SDimitry Andric return RV;
2840b57cec5SDimitry Andric
28504eeddc0SDimitry Andric RV = ConstantFoldLoadThroughBitcast(RV, ReturnType, DL);
2860b57cec5SDimitry Andric if (!RV)
2870b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Failed to fold bitcast call expr\n");
2880b57cec5SDimitry Andric return RV;
2890b57cec5SDimitry Andric }
2900b57cec5SDimitry Andric
2910b57cec5SDimitry Andric /// Evaluate all instructions in block BB, returning true if successful, false
2920b57cec5SDimitry Andric /// if we can't evaluate it. NewBB returns the next BB that control flows into,
293fe6060f1SDimitry Andric /// or null upon return. StrippedPointerCastsForAliasAnalysis is set to true if
294fe6060f1SDimitry Andric /// we looked through pointer casts to evaluate something.
EvaluateBlock(BasicBlock::iterator CurInst,BasicBlock * & NextBB,bool & StrippedPointerCastsForAliasAnalysis)295fe6060f1SDimitry Andric bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB,
296fe6060f1SDimitry Andric bool &StrippedPointerCastsForAliasAnalysis) {
2970b57cec5SDimitry Andric // This is the main evaluation loop.
2980b57cec5SDimitry Andric while (true) {
2990b57cec5SDimitry Andric Constant *InstResult = nullptr;
3000b57cec5SDimitry Andric
3010b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Evaluating Instruction: " << *CurInst << "\n");
3020b57cec5SDimitry Andric
3030b57cec5SDimitry Andric if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
304fcaf7f86SDimitry Andric if (SI->isVolatile()) {
305fcaf7f86SDimitry Andric LLVM_DEBUG(dbgs() << "Store is volatile! Can not evaluate.\n");
306fcaf7f86SDimitry Andric return false; // no volatile accesses.
3070b57cec5SDimitry Andric }
3080b57cec5SDimitry Andric Constant *Ptr = getVal(SI->getOperand(1));
3095ffd83dbSDimitry Andric Constant *FoldedPtr = ConstantFoldConstant(Ptr, DL, TLI);
3105ffd83dbSDimitry Andric if (Ptr != FoldedPtr) {
3110b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Folding constant ptr expression: " << *Ptr);
3120b57cec5SDimitry Andric Ptr = FoldedPtr;
3130b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "; To: " << *Ptr << "\n");
3140b57cec5SDimitry Andric }
31504eeddc0SDimitry Andric
31604eeddc0SDimitry Andric APInt Offset(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
31704eeddc0SDimitry Andric Ptr = cast<Constant>(Ptr->stripAndAccumulateConstantOffsets(
31804eeddc0SDimitry Andric DL, Offset, /* AllowNonInbounds */ true));
31904eeddc0SDimitry Andric Offset = Offset.sextOrTrunc(DL.getIndexTypeSizeInBits(Ptr->getType()));
32004eeddc0SDimitry Andric auto *GV = dyn_cast<GlobalVariable>(Ptr);
32104eeddc0SDimitry Andric if (!GV || !GV->hasUniqueInitializer()) {
32204eeddc0SDimitry Andric LLVM_DEBUG(dbgs() << "Store is not to global with unique initializer: "
32304eeddc0SDimitry Andric << *Ptr << "\n");
3240b57cec5SDimitry Andric return false;
3250b57cec5SDimitry Andric }
3260b57cec5SDimitry Andric
3270b57cec5SDimitry Andric // If this might be too difficult for the backend to handle (e.g. the addr
3280b57cec5SDimitry Andric // of one global variable divided by another) then we can't commit it.
32904eeddc0SDimitry Andric Constant *Val = getVal(SI->getOperand(0));
3300b57cec5SDimitry Andric if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, DL)) {
3310b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Store value is too complex to evaluate store. "
3320b57cec5SDimitry Andric << *Val << "\n");
3330b57cec5SDimitry Andric return false;
3340b57cec5SDimitry Andric }
3350b57cec5SDimitry Andric
33604eeddc0SDimitry Andric auto Res = MutatedMemory.try_emplace(GV, GV->getInitializer());
33704eeddc0SDimitry Andric if (!Res.first->second.write(Val, Offset, DL))
3380b57cec5SDimitry Andric return false;
3390b57cec5SDimitry Andric } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
340fcaf7f86SDimitry Andric if (LI->isVolatile()) {
3410b57cec5SDimitry Andric LLVM_DEBUG(
342fcaf7f86SDimitry Andric dbgs() << "Found a Load! Volatile load, can not evaluate.\n");
343fcaf7f86SDimitry Andric return false; // no volatile accesses.
3440b57cec5SDimitry Andric }
3450b57cec5SDimitry Andric
3460b57cec5SDimitry Andric Constant *Ptr = getVal(LI->getOperand(0));
3475ffd83dbSDimitry Andric Constant *FoldedPtr = ConstantFoldConstant(Ptr, DL, TLI);
3485ffd83dbSDimitry Andric if (Ptr != FoldedPtr) {
3490b57cec5SDimitry Andric Ptr = FoldedPtr;
3500b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Found a constant pointer expression, constant "
3510b57cec5SDimitry Andric "folding: "
3520b57cec5SDimitry Andric << *Ptr << "\n");
3530b57cec5SDimitry Andric }
354fe6060f1SDimitry Andric InstResult = ComputeLoadResult(Ptr, LI->getType());
3550b57cec5SDimitry Andric if (!InstResult) {
3560b57cec5SDimitry Andric LLVM_DEBUG(
3570b57cec5SDimitry Andric dbgs() << "Failed to compute load result. Can not evaluate load."
3580b57cec5SDimitry Andric "\n");
3590b57cec5SDimitry Andric return false; // Could not evaluate load.
3600b57cec5SDimitry Andric }
3610b57cec5SDimitry Andric
3620b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Evaluated load: " << *InstResult << "\n");
3630b57cec5SDimitry Andric } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
3640b57cec5SDimitry Andric if (AI->isArrayAllocation()) {
3650b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Found an array alloca. Can not evaluate.\n");
3660b57cec5SDimitry Andric return false; // Cannot handle array allocs.
3670b57cec5SDimitry Andric }
3680b57cec5SDimitry Andric Type *Ty = AI->getAllocatedType();
3698bcb0991SDimitry Andric AllocaTmps.push_back(std::make_unique<GlobalVariable>(
3700b57cec5SDimitry Andric Ty, false, GlobalValue::InternalLinkage, UndefValue::get(Ty),
3710b57cec5SDimitry Andric AI->getName(), /*TLMode=*/GlobalValue::NotThreadLocal,
3720b57cec5SDimitry Andric AI->getType()->getPointerAddressSpace()));
3730b57cec5SDimitry Andric InstResult = AllocaTmps.back().get();
3740b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Found an alloca. Result: " << *InstResult << "\n");
3750b57cec5SDimitry Andric } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
3765ffd83dbSDimitry Andric CallBase &CB = *cast<CallBase>(&*CurInst);
3770b57cec5SDimitry Andric
3780b57cec5SDimitry Andric // Debug info can safely be ignored here.
3795ffd83dbSDimitry Andric if (isa<DbgInfoIntrinsic>(CB)) {
3800b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Ignoring debug info.\n");
3810b57cec5SDimitry Andric ++CurInst;
3820b57cec5SDimitry Andric continue;
3830b57cec5SDimitry Andric }
3840b57cec5SDimitry Andric
3850b57cec5SDimitry Andric // Cannot handle inline asm.
3865ffd83dbSDimitry Andric if (CB.isInlineAsm()) {
3870b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Found inline asm, can not evaluate.\n");
3880b57cec5SDimitry Andric return false;
3890b57cec5SDimitry Andric }
3900b57cec5SDimitry Andric
3915ffd83dbSDimitry Andric if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CB)) {
3920b57cec5SDimitry Andric if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
3930b57cec5SDimitry Andric if (MSI->isVolatile()) {
3940b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Can not optimize a volatile memset "
3950b57cec5SDimitry Andric << "intrinsic.\n");
3960b57cec5SDimitry Andric return false;
3970b57cec5SDimitry Andric }
39881ad6265SDimitry Andric
39981ad6265SDimitry Andric auto *LenC = dyn_cast<ConstantInt>(getVal(MSI->getLength()));
40081ad6265SDimitry Andric if (!LenC) {
40181ad6265SDimitry Andric LLVM_DEBUG(dbgs() << "Memset with unknown length.\n");
40281ad6265SDimitry Andric return false;
40381ad6265SDimitry Andric }
40481ad6265SDimitry Andric
4050b57cec5SDimitry Andric Constant *Ptr = getVal(MSI->getDest());
40681ad6265SDimitry Andric APInt Offset(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
40781ad6265SDimitry Andric Ptr = cast<Constant>(Ptr->stripAndAccumulateConstantOffsets(
40881ad6265SDimitry Andric DL, Offset, /* AllowNonInbounds */ true));
40981ad6265SDimitry Andric auto *GV = dyn_cast<GlobalVariable>(Ptr);
41081ad6265SDimitry Andric if (!GV) {
41181ad6265SDimitry Andric LLVM_DEBUG(dbgs() << "Memset with unknown base.\n");
41281ad6265SDimitry Andric return false;
41381ad6265SDimitry Andric }
41481ad6265SDimitry Andric
4150b57cec5SDimitry Andric Constant *Val = getVal(MSI->getValue());
416*06c3fb27SDimitry Andric // Avoid the byte-per-byte scan if we're memseting a zeroinitializer
417*06c3fb27SDimitry Andric // to zero.
418*06c3fb27SDimitry Andric if (!Val->isNullValue() || MutatedMemory.contains(GV) ||
419*06c3fb27SDimitry Andric !GV->hasDefinitiveInitializer() ||
420*06c3fb27SDimitry Andric !GV->getInitializer()->isNullValue()) {
42181ad6265SDimitry Andric APInt Len = LenC->getValue();
422*06c3fb27SDimitry Andric if (Len.ugt(64 * 1024)) {
423*06c3fb27SDimitry Andric LLVM_DEBUG(dbgs() << "Not evaluating large memset of size "
424*06c3fb27SDimitry Andric << Len << "\n");
425*06c3fb27SDimitry Andric return false;
426*06c3fb27SDimitry Andric }
427*06c3fb27SDimitry Andric
42881ad6265SDimitry Andric while (Len != 0) {
42981ad6265SDimitry Andric Constant *DestVal = ComputeLoadResult(GV, Val->getType(), Offset);
43081ad6265SDimitry Andric if (DestVal != Val) {
43181ad6265SDimitry Andric LLVM_DEBUG(dbgs() << "Memset is not a no-op at offset "
43281ad6265SDimitry Andric << Offset << " of " << *GV << ".\n");
43381ad6265SDimitry Andric return false;
43481ad6265SDimitry Andric }
43581ad6265SDimitry Andric ++Offset;
43681ad6265SDimitry Andric --Len;
43781ad6265SDimitry Andric }
438*06c3fb27SDimitry Andric }
43981ad6265SDimitry Andric
4400b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Ignoring no-op memset.\n");
4410b57cec5SDimitry Andric ++CurInst;
4420b57cec5SDimitry Andric continue;
4430b57cec5SDimitry Andric }
4440b57cec5SDimitry Andric
4450b57cec5SDimitry Andric if (II->isLifetimeStartOrEnd()) {
4460b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Ignoring lifetime intrinsic.\n");
4470b57cec5SDimitry Andric ++CurInst;
4480b57cec5SDimitry Andric continue;
4490b57cec5SDimitry Andric }
4500b57cec5SDimitry Andric
4510b57cec5SDimitry Andric if (II->getIntrinsicID() == Intrinsic::invariant_start) {
4520b57cec5SDimitry Andric // We don't insert an entry into Values, as it doesn't have a
4530b57cec5SDimitry Andric // meaningful return value.
4540b57cec5SDimitry Andric if (!II->use_empty()) {
4550b57cec5SDimitry Andric LLVM_DEBUG(dbgs()
4560b57cec5SDimitry Andric << "Found unused invariant_start. Can't evaluate.\n");
4570b57cec5SDimitry Andric return false;
4580b57cec5SDimitry Andric }
4590b57cec5SDimitry Andric ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
4600b57cec5SDimitry Andric Value *PtrArg = getVal(II->getArgOperand(1));
4610b57cec5SDimitry Andric Value *Ptr = PtrArg->stripPointerCasts();
4620b57cec5SDimitry Andric if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
4630b57cec5SDimitry Andric Type *ElemTy = GV->getValueType();
4640b57cec5SDimitry Andric if (!Size->isMinusOne() &&
4650b57cec5SDimitry Andric Size->getValue().getLimitedValue() >=
4660b57cec5SDimitry Andric DL.getTypeStoreSize(ElemTy)) {
4670b57cec5SDimitry Andric Invariants.insert(GV);
4680b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Found a global var that is an invariant: "
4690b57cec5SDimitry Andric << *GV << "\n");
4700b57cec5SDimitry Andric } else {
4710b57cec5SDimitry Andric LLVM_DEBUG(dbgs()
4720b57cec5SDimitry Andric << "Found a global var, but can not treat it as an "
4730b57cec5SDimitry Andric "invariant.\n");
4740b57cec5SDimitry Andric }
4750b57cec5SDimitry Andric }
4760b57cec5SDimitry Andric // Continue even if we do nothing.
4770b57cec5SDimitry Andric ++CurInst;
4780b57cec5SDimitry Andric continue;
4790b57cec5SDimitry Andric } else if (II->getIntrinsicID() == Intrinsic::assume) {
4800b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Skipping assume intrinsic.\n");
4810b57cec5SDimitry Andric ++CurInst;
4820b57cec5SDimitry Andric continue;
4830b57cec5SDimitry Andric } else if (II->getIntrinsicID() == Intrinsic::sideeffect) {
4840b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Skipping sideeffect intrinsic.\n");
4850b57cec5SDimitry Andric ++CurInst;
4860b57cec5SDimitry Andric continue;
487e8d8bef9SDimitry Andric } else if (II->getIntrinsicID() == Intrinsic::pseudoprobe) {
488e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Skipping pseudoprobe intrinsic.\n");
489e8d8bef9SDimitry Andric ++CurInst;
490e8d8bef9SDimitry Andric continue;
491fe6060f1SDimitry Andric } else {
492fe6060f1SDimitry Andric Value *Stripped = CurInst->stripPointerCastsForAliasAnalysis();
493fe6060f1SDimitry Andric // Only attempt to getVal() if we've actually managed to strip
494fe6060f1SDimitry Andric // anything away, or else we'll call getVal() on the current
495fe6060f1SDimitry Andric // instruction.
496fe6060f1SDimitry Andric if (Stripped != &*CurInst) {
497fe6060f1SDimitry Andric InstResult = getVal(Stripped);
4980b57cec5SDimitry Andric }
499fe6060f1SDimitry Andric if (InstResult) {
500fe6060f1SDimitry Andric LLVM_DEBUG(dbgs()
501fe6060f1SDimitry Andric << "Stripped pointer casts for alias analysis for "
502fe6060f1SDimitry Andric "intrinsic call.\n");
503fe6060f1SDimitry Andric StrippedPointerCastsForAliasAnalysis = true;
504fe6060f1SDimitry Andric InstResult = ConstantExpr::getBitCast(InstResult, II->getType());
505fe6060f1SDimitry Andric } else {
5060b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Unknown intrinsic. Cannot evaluate.\n");
5070b57cec5SDimitry Andric return false;
5080b57cec5SDimitry Andric }
509fe6060f1SDimitry Andric }
510fe6060f1SDimitry Andric }
5110b57cec5SDimitry Andric
512fe6060f1SDimitry Andric if (!InstResult) {
5130b57cec5SDimitry Andric // Resolve function pointers.
5140b57cec5SDimitry Andric SmallVector<Constant *, 8> Formals;
5155ffd83dbSDimitry Andric Function *Callee = getCalleeWithFormalArgs(CB, Formals);
5160b57cec5SDimitry Andric if (!Callee || Callee->isInterposable()) {
5170b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Can not resolve function pointer.\n");
5180b57cec5SDimitry Andric return false; // Cannot resolve.
5190b57cec5SDimitry Andric }
5200b57cec5SDimitry Andric
5210b57cec5SDimitry Andric if (Callee->isDeclaration()) {
5220b57cec5SDimitry Andric // If this is a function we can constant fold, do it.
5235ffd83dbSDimitry Andric if (Constant *C = ConstantFoldCall(&CB, Callee, Formals, TLI)) {
52404eeddc0SDimitry Andric InstResult = castCallResultIfNeeded(CB.getType(), C);
5250b57cec5SDimitry Andric if (!InstResult)
5260b57cec5SDimitry Andric return false;
5270b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Constant folded function call. Result: "
5280b57cec5SDimitry Andric << *InstResult << "\n");
5290b57cec5SDimitry Andric } else {
5300b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Can not constant fold function call.\n");
5310b57cec5SDimitry Andric return false;
5320b57cec5SDimitry Andric }
5330b57cec5SDimitry Andric } else {
5340b57cec5SDimitry Andric if (Callee->getFunctionType()->isVarArg()) {
535fe6060f1SDimitry Andric LLVM_DEBUG(dbgs()
536fe6060f1SDimitry Andric << "Can not constant fold vararg function call.\n");
5370b57cec5SDimitry Andric return false;
5380b57cec5SDimitry Andric }
5390b57cec5SDimitry Andric
5400b57cec5SDimitry Andric Constant *RetVal = nullptr;
5410b57cec5SDimitry Andric // Execute the call, if successful, use the return value.
5420b57cec5SDimitry Andric ValueStack.emplace_back();
5430b57cec5SDimitry Andric if (!EvaluateFunction(Callee, RetVal, Formals)) {
5440b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Failed to evaluate function.\n");
5450b57cec5SDimitry Andric return false;
5460b57cec5SDimitry Andric }
5470b57cec5SDimitry Andric ValueStack.pop_back();
54804eeddc0SDimitry Andric InstResult = castCallResultIfNeeded(CB.getType(), RetVal);
5490b57cec5SDimitry Andric if (RetVal && !InstResult)
5500b57cec5SDimitry Andric return false;
5510b57cec5SDimitry Andric
5520b57cec5SDimitry Andric if (InstResult) {
5530b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Successfully evaluated function. Result: "
5540b57cec5SDimitry Andric << *InstResult << "\n\n");
5550b57cec5SDimitry Andric } else {
5560b57cec5SDimitry Andric LLVM_DEBUG(dbgs()
5570b57cec5SDimitry Andric << "Successfully evaluated function. Result: 0\n\n");
5580b57cec5SDimitry Andric }
5590b57cec5SDimitry Andric }
560fe6060f1SDimitry Andric }
5610b57cec5SDimitry Andric } else if (CurInst->isTerminator()) {
5620b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Found a terminator instruction.\n");
5630b57cec5SDimitry Andric
5640b57cec5SDimitry Andric if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
5650b57cec5SDimitry Andric if (BI->isUnconditional()) {
5660b57cec5SDimitry Andric NextBB = BI->getSuccessor(0);
5670b57cec5SDimitry Andric } else {
5680b57cec5SDimitry Andric ConstantInt *Cond =
5690b57cec5SDimitry Andric dyn_cast<ConstantInt>(getVal(BI->getCondition()));
5700b57cec5SDimitry Andric if (!Cond) return false; // Cannot determine.
5710b57cec5SDimitry Andric
5720b57cec5SDimitry Andric NextBB = BI->getSuccessor(!Cond->getZExtValue());
5730b57cec5SDimitry Andric }
5740b57cec5SDimitry Andric } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
5750b57cec5SDimitry Andric ConstantInt *Val =
5760b57cec5SDimitry Andric dyn_cast<ConstantInt>(getVal(SI->getCondition()));
5770b57cec5SDimitry Andric if (!Val) return false; // Cannot determine.
5780b57cec5SDimitry Andric NextBB = SI->findCaseValue(Val)->getCaseSuccessor();
5790b57cec5SDimitry Andric } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
5800b57cec5SDimitry Andric Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
5810b57cec5SDimitry Andric if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
5820b57cec5SDimitry Andric NextBB = BA->getBasicBlock();
5830b57cec5SDimitry Andric else
5840b57cec5SDimitry Andric return false; // Cannot determine.
5850b57cec5SDimitry Andric } else if (isa<ReturnInst>(CurInst)) {
5860b57cec5SDimitry Andric NextBB = nullptr;
5870b57cec5SDimitry Andric } else {
5880b57cec5SDimitry Andric // invoke, unwind, resume, unreachable.
5890b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Can not handle terminator.");
5900b57cec5SDimitry Andric return false; // Cannot handle this terminator.
5910b57cec5SDimitry Andric }
5920b57cec5SDimitry Andric
5930b57cec5SDimitry Andric // We succeeded at evaluating this block!
5940b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Successfully evaluated block.\n");
5950b57cec5SDimitry Andric return true;
5960b57cec5SDimitry Andric } else {
59781ad6265SDimitry Andric SmallVector<Constant *> Ops;
59881ad6265SDimitry Andric for (Value *Op : CurInst->operands())
59981ad6265SDimitry Andric Ops.push_back(getVal(Op));
60081ad6265SDimitry Andric InstResult = ConstantFoldInstOperands(&*CurInst, Ops, DL, TLI);
60181ad6265SDimitry Andric if (!InstResult) {
60281ad6265SDimitry Andric LLVM_DEBUG(dbgs() << "Cannot fold instruction: " << *CurInst << "\n");
6030b57cec5SDimitry Andric return false;
6040b57cec5SDimitry Andric }
60581ad6265SDimitry Andric LLVM_DEBUG(dbgs() << "Folded instruction " << *CurInst << " to "
60681ad6265SDimitry Andric << *InstResult << "\n");
60781ad6265SDimitry Andric }
6080b57cec5SDimitry Andric
6090b57cec5SDimitry Andric if (!CurInst->use_empty()) {
6105ffd83dbSDimitry Andric InstResult = ConstantFoldConstant(InstResult, DL, TLI);
6110b57cec5SDimitry Andric setVal(&*CurInst, InstResult);
6120b57cec5SDimitry Andric }
6130b57cec5SDimitry Andric
6140b57cec5SDimitry Andric // If we just processed an invoke, we finished evaluating the block.
6150b57cec5SDimitry Andric if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
6160b57cec5SDimitry Andric NextBB = II->getNormalDest();
6170b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Found an invoke instruction. Finished Block.\n\n");
6180b57cec5SDimitry Andric return true;
6190b57cec5SDimitry Andric }
6200b57cec5SDimitry Andric
6210b57cec5SDimitry Andric // Advance program counter.
6220b57cec5SDimitry Andric ++CurInst;
6230b57cec5SDimitry Andric }
6240b57cec5SDimitry Andric }
6250b57cec5SDimitry Andric
6260b57cec5SDimitry Andric /// Evaluate a call to function F, returning true if successful, false if we
6270b57cec5SDimitry Andric /// can't evaluate it. ActualArgs contains the formal arguments for the
6280b57cec5SDimitry Andric /// function.
EvaluateFunction(Function * F,Constant * & RetVal,const SmallVectorImpl<Constant * > & ActualArgs)6290b57cec5SDimitry Andric bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
6300b57cec5SDimitry Andric const SmallVectorImpl<Constant*> &ActualArgs) {
63181ad6265SDimitry Andric assert(ActualArgs.size() == F->arg_size() && "wrong number of arguments");
63281ad6265SDimitry Andric
6330b57cec5SDimitry Andric // Check to see if this function is already executing (recursion). If so,
6340b57cec5SDimitry Andric // bail out. TODO: we might want to accept limited recursion.
6350b57cec5SDimitry Andric if (is_contained(CallStack, F))
6360b57cec5SDimitry Andric return false;
6370b57cec5SDimitry Andric
6380b57cec5SDimitry Andric CallStack.push_back(F);
6390b57cec5SDimitry Andric
6400b57cec5SDimitry Andric // Initialize arguments to the incoming values specified.
641bdd1243dSDimitry Andric for (const auto &[ArgNo, Arg] : llvm::enumerate(F->args()))
642bdd1243dSDimitry Andric setVal(&Arg, ActualArgs[ArgNo]);
6430b57cec5SDimitry Andric
6440b57cec5SDimitry Andric // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
6450b57cec5SDimitry Andric // we can only evaluate any one basic block at most once. This set keeps
6460b57cec5SDimitry Andric // track of what we have executed so we can detect recursive cases etc.
6470b57cec5SDimitry Andric SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
6480b57cec5SDimitry Andric
6490b57cec5SDimitry Andric // CurBB - The current basic block we're evaluating.
6500b57cec5SDimitry Andric BasicBlock *CurBB = &F->front();
6510b57cec5SDimitry Andric
6520b57cec5SDimitry Andric BasicBlock::iterator CurInst = CurBB->begin();
6530b57cec5SDimitry Andric
6540b57cec5SDimitry Andric while (true) {
6550b57cec5SDimitry Andric BasicBlock *NextBB = nullptr; // Initialized to avoid compiler warnings.
6560b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Trying to evaluate BB: " << *CurBB << "\n");
6570b57cec5SDimitry Andric
658fe6060f1SDimitry Andric bool StrippedPointerCastsForAliasAnalysis = false;
659fe6060f1SDimitry Andric
660fe6060f1SDimitry Andric if (!EvaluateBlock(CurInst, NextBB, StrippedPointerCastsForAliasAnalysis))
6610b57cec5SDimitry Andric return false;
6620b57cec5SDimitry Andric
6630b57cec5SDimitry Andric if (!NextBB) {
6640b57cec5SDimitry Andric // Successfully running until there's no next block means that we found
6650b57cec5SDimitry Andric // the return. Fill it the return value and pop the call stack.
6660b57cec5SDimitry Andric ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
667fe6060f1SDimitry Andric if (RI->getNumOperands()) {
668fe6060f1SDimitry Andric // The Evaluator can look through pointer casts as long as alias
669fe6060f1SDimitry Andric // analysis holds because it's just a simple interpreter and doesn't
670fe6060f1SDimitry Andric // skip memory accesses due to invariant group metadata, but we can't
671fe6060f1SDimitry Andric // let users of Evaluator use a value that's been gleaned looking
672fe6060f1SDimitry Andric // through stripping pointer casts.
673fe6060f1SDimitry Andric if (StrippedPointerCastsForAliasAnalysis &&
674fe6060f1SDimitry Andric !RI->getReturnValue()->getType()->isVoidTy()) {
675fe6060f1SDimitry Andric return false;
676fe6060f1SDimitry Andric }
6770b57cec5SDimitry Andric RetVal = getVal(RI->getOperand(0));
678fe6060f1SDimitry Andric }
6790b57cec5SDimitry Andric CallStack.pop_back();
6800b57cec5SDimitry Andric return true;
6810b57cec5SDimitry Andric }
6820b57cec5SDimitry Andric
6830b57cec5SDimitry Andric // Okay, we succeeded in evaluating this control flow. See if we have
6840b57cec5SDimitry Andric // executed the new block before. If so, we have a looping function,
6850b57cec5SDimitry Andric // which we cannot evaluate in reasonable time.
6860b57cec5SDimitry Andric if (!ExecutedBlocks.insert(NextBB).second)
6870b57cec5SDimitry Andric return false; // looped!
6880b57cec5SDimitry Andric
6890b57cec5SDimitry Andric // Okay, we have never been in this block before. Check to see if there
6900b57cec5SDimitry Andric // are any PHI nodes. If so, evaluate them with information about where
6910b57cec5SDimitry Andric // we came from.
6920b57cec5SDimitry Andric PHINode *PN = nullptr;
6930b57cec5SDimitry Andric for (CurInst = NextBB->begin();
6940b57cec5SDimitry Andric (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
6950b57cec5SDimitry Andric setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
6960b57cec5SDimitry Andric
6970b57cec5SDimitry Andric // Advance to the next block.
6980b57cec5SDimitry Andric CurBB = NextBB;
6990b57cec5SDimitry Andric }
7000b57cec5SDimitry Andric }
701