1 //===- Evaluator.cpp - LLVM IR evaluator ----------------------------------===//
2 //
3 // 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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Function evaluator for LLVM IR.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/Transforms/Utils/Evaluator.h"
14 #include "llvm/ADT/DenseMap.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/Analysis/ConstantFolding.h"
19 #include "llvm/IR/BasicBlock.h"
20 #include "llvm/IR/Constant.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/GlobalAlias.h"
26 #include "llvm/IR/GlobalValue.h"
27 #include "llvm/IR/GlobalVariable.h"
28 #include "llvm/IR/InstrTypes.h"
29 #include "llvm/IR/Instruction.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/IR/Operator.h"
34 #include "llvm/IR/Type.h"
35 #include "llvm/IR/User.h"
36 #include "llvm/IR/Value.h"
37 #include "llvm/Support/Casting.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include <iterator>
41 
42 #define DEBUG_TYPE "evaluator"
43 
44 using namespace llvm;
45 
46 static inline bool
47 isSimpleEnoughValueToCommit(Constant *C,
48                             SmallPtrSetImpl<Constant *> &SimpleConstants,
49                             const DataLayout &DL);
50 
51 /// Return true if the specified constant can be handled by the code generator.
52 /// We don't want to generate something like:
53 ///   void *X = &X/42;
54 /// because the code generator doesn't have a relocation that can handle that.
55 ///
56 /// This function should be called if C was not found (but just got inserted)
57 /// in SimpleConstants to avoid having to rescan the same constants all the
58 /// time.
59 static bool
60 isSimpleEnoughValueToCommitHelper(Constant *C,
61                                   SmallPtrSetImpl<Constant *> &SimpleConstants,
62                                   const DataLayout &DL) {
63   // Simple global addresses are supported, do not allow dllimport or
64   // thread-local globals.
65   if (auto *GV = dyn_cast<GlobalValue>(C))
66     return !GV->hasDLLImportStorageClass() && !GV->isThreadLocal();
67 
68   // Simple integer, undef, constant aggregate zero, etc are all supported.
69   if (C->getNumOperands() == 0 || isa<BlockAddress>(C))
70     return true;
71 
72   // Aggregate values are safe if all their elements are.
73   if (isa<ConstantAggregate>(C)) {
74     for (Value *Op : C->operands())
75       if (!isSimpleEnoughValueToCommit(cast<Constant>(Op), SimpleConstants, DL))
76         return false;
77     return true;
78   }
79 
80   // We don't know exactly what relocations are allowed in constant expressions,
81   // so we allow &global+constantoffset, which is safe and uniformly supported
82   // across targets.
83   ConstantExpr *CE = cast<ConstantExpr>(C);
84   switch (CE->getOpcode()) {
85   case Instruction::BitCast:
86     // Bitcast is fine if the casted value is fine.
87     return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
88 
89   case Instruction::IntToPtr:
90   case Instruction::PtrToInt:
91     // int <=> ptr is fine if the int type is the same size as the
92     // pointer type.
93     if (DL.getTypeSizeInBits(CE->getType()) !=
94         DL.getTypeSizeInBits(CE->getOperand(0)->getType()))
95       return false;
96     return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
97 
98   // GEP is fine if it is simple + constant offset.
99   case Instruction::GetElementPtr:
100     for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
101       if (!isa<ConstantInt>(CE->getOperand(i)))
102         return false;
103     return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
104 
105   case Instruction::Add:
106     // We allow simple+cst.
107     if (!isa<ConstantInt>(CE->getOperand(1)))
108       return false;
109     return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
110   }
111   return false;
112 }
113 
114 static inline bool
115 isSimpleEnoughValueToCommit(Constant *C,
116                             SmallPtrSetImpl<Constant *> &SimpleConstants,
117                             const DataLayout &DL) {
118   // If we already checked this constant, we win.
119   if (!SimpleConstants.insert(C).second)
120     return true;
121   // Check the constant.
122   return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, DL);
123 }
124 
125 void Evaluator::MutableValue::clear() {
126   if (auto *Agg = Val.dyn_cast<MutableAggregate *>())
127     delete Agg;
128   Val = nullptr;
129 }
130 
131 Constant *Evaluator::MutableValue::read(Type *Ty, APInt Offset,
132                                         const DataLayout &DL) const {
133   TypeSize TySize = DL.getTypeStoreSize(Ty);
134   const MutableValue *V = this;
135   while (const auto *Agg = V->Val.dyn_cast<MutableAggregate *>()) {
136     Type *AggTy = Agg->Ty;
137     Optional<APInt> Index = DL.getGEPIndexForOffset(AggTy, Offset);
138     if (!Index || Index->ugt(Agg->Elements.size()) ||
139         !TypeSize::isKnownLE(TySize, DL.getTypeStoreSize(AggTy)))
140       return nullptr;
141 
142     V = &Agg->Elements[Index->getZExtValue()];
143   }
144 
145   return ConstantFoldLoadFromConst(V->Val.get<Constant *>(), Ty, Offset, DL);
146 }
147 
148 bool Evaluator::MutableValue::makeMutable() {
149   Constant *C = Val.get<Constant *>();
150   Type *Ty = C->getType();
151   unsigned NumElements;
152   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
153     NumElements = VT->getNumElements();
154   } else if (auto *AT = dyn_cast<ArrayType>(Ty))
155     NumElements = AT->getNumElements();
156   else if (auto *ST = dyn_cast<StructType>(Ty))
157     NumElements = ST->getNumElements();
158   else
159     return false;
160 
161   MutableAggregate *MA = new MutableAggregate(Ty);
162   MA->Elements.reserve(NumElements);
163   for (unsigned I = 0; I < NumElements; ++I)
164     MA->Elements.push_back(C->getAggregateElement(I));
165   Val = MA;
166   return true;
167 }
168 
169 bool Evaluator::MutableValue::write(Constant *V, APInt Offset,
170                                     const DataLayout &DL) {
171   Type *Ty = V->getType();
172   TypeSize TySize = DL.getTypeStoreSize(Ty);
173   MutableValue *MV = this;
174   while (Offset != 0 ||
175          !CastInst::isBitOrNoopPointerCastable(Ty, MV->getType(), DL)) {
176     if (MV->Val.is<Constant *>() && !MV->makeMutable())
177       return false;
178 
179     MutableAggregate *Agg = MV->Val.get<MutableAggregate *>();
180     Type *AggTy = Agg->Ty;
181     Optional<APInt> Index = DL.getGEPIndexForOffset(AggTy, Offset);
182     if (!Index || Index->ugt(Agg->Elements.size()) ||
183         !TypeSize::isKnownLE(TySize, DL.getTypeStoreSize(AggTy)))
184       return false;
185 
186     MV = &Agg->Elements[Index->getZExtValue()];
187   }
188 
189   Type *MVType = MV->getType();
190   MV->clear();
191   if (Ty->isIntegerTy() && MVType->isPointerTy())
192     MV->Val = ConstantExpr::getIntToPtr(V, MVType);
193   else if (Ty->isPointerTy() && MVType->isIntegerTy())
194     MV->Val = ConstantExpr::getPtrToInt(V, MVType);
195   else
196     MV->Val = ConstantExpr::getBitCast(V, MVType);
197   return true;
198 }
199 
200 Constant *Evaluator::MutableAggregate::toConstant() const {
201   SmallVector<Constant *, 32> Consts;
202   for (const MutableValue &MV : Elements)
203     Consts.push_back(MV.toConstant());
204 
205   if (auto *ST = dyn_cast<StructType>(Ty))
206     return ConstantStruct::get(ST, Consts);
207   if (auto *AT = dyn_cast<ArrayType>(Ty))
208     return ConstantArray::get(AT, Consts);
209   assert(isa<FixedVectorType>(Ty) && "Must be vector");
210   return ConstantVector::get(Consts);
211 }
212 
213 /// Return the value that would be computed by a load from P after the stores
214 /// reflected by 'memory' have been performed.  If we can't decide, return null.
215 Constant *Evaluator::ComputeLoadResult(Constant *P, Type *Ty) {
216   APInt Offset(DL.getIndexTypeSizeInBits(P->getType()), 0);
217   P = cast<Constant>(P->stripAndAccumulateConstantOffsets(
218       DL, Offset, /* AllowNonInbounds */ true));
219   Offset = Offset.sextOrTrunc(DL.getIndexTypeSizeInBits(P->getType()));
220   auto *GV = dyn_cast<GlobalVariable>(P);
221   if (!GV)
222     return nullptr;
223 
224   auto It = MutatedMemory.find(GV);
225   if (It != MutatedMemory.end())
226     return It->second.read(Ty, Offset, DL);
227 
228   if (!GV->hasDefinitiveInitializer())
229     return nullptr;
230   return ConstantFoldLoadFromConst(GV->getInitializer(), Ty, Offset, DL);
231 }
232 
233 static Function *getFunction(Constant *C) {
234   if (auto *Fn = dyn_cast<Function>(C))
235     return Fn;
236 
237   if (auto *Alias = dyn_cast<GlobalAlias>(C))
238     if (auto *Fn = dyn_cast<Function>(Alias->getAliasee()))
239       return Fn;
240   return nullptr;
241 }
242 
243 Function *
244 Evaluator::getCalleeWithFormalArgs(CallBase &CB,
245                                    SmallVectorImpl<Constant *> &Formals) {
246   auto *V = CB.getCalledOperand();
247   if (auto *Fn = getFunction(getVal(V)))
248     return getFormalParams(CB, Fn, Formals) ? Fn : nullptr;
249 
250   auto *CE = dyn_cast<ConstantExpr>(V);
251   if (!CE || CE->getOpcode() != Instruction::BitCast ||
252       !getFormalParams(CB, getFunction(CE->getOperand(0)), Formals))
253     return nullptr;
254 
255   return dyn_cast<Function>(
256       ConstantFoldLoadThroughBitcast(CE, CE->getOperand(0)->getType(), DL));
257 }
258 
259 bool Evaluator::getFormalParams(CallBase &CB, Function *F,
260                                 SmallVectorImpl<Constant *> &Formals) {
261   if (!F)
262     return false;
263 
264   auto *FTy = F->getFunctionType();
265   if (FTy->getNumParams() > CB.arg_size()) {
266     LLVM_DEBUG(dbgs() << "Too few arguments for function.\n");
267     return false;
268   }
269 
270   auto ArgI = CB.arg_begin();
271   for (Type *PTy : FTy->params()) {
272     auto *ArgC = ConstantFoldLoadThroughBitcast(getVal(*ArgI), PTy, DL);
273     if (!ArgC) {
274       LLVM_DEBUG(dbgs() << "Can not convert function argument.\n");
275       return false;
276     }
277     Formals.push_back(ArgC);
278     ++ArgI;
279   }
280   return true;
281 }
282 
283 /// If call expression contains bitcast then we may need to cast
284 /// evaluated return value to a type of the call expression.
285 Constant *Evaluator::castCallResultIfNeeded(Value *CallExpr, Constant *RV) {
286   ConstantExpr *CE = dyn_cast<ConstantExpr>(CallExpr);
287   if (!RV || !CE || CE->getOpcode() != Instruction::BitCast)
288     return RV;
289 
290   if (auto *FT =
291           dyn_cast<FunctionType>(CE->getType()->getPointerElementType())) {
292     RV = ConstantFoldLoadThroughBitcast(RV, FT->getReturnType(), DL);
293     if (!RV)
294       LLVM_DEBUG(dbgs() << "Failed to fold bitcast call expr\n");
295   }
296   return RV;
297 }
298 
299 /// Evaluate all instructions in block BB, returning true if successful, false
300 /// if we can't evaluate it.  NewBB returns the next BB that control flows into,
301 /// or null upon return. StrippedPointerCastsForAliasAnalysis is set to true if
302 /// we looked through pointer casts to evaluate something.
303 bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB,
304                               bool &StrippedPointerCastsForAliasAnalysis) {
305   // This is the main evaluation loop.
306   while (true) {
307     Constant *InstResult = nullptr;
308 
309     LLVM_DEBUG(dbgs() << "Evaluating Instruction: " << *CurInst << "\n");
310 
311     if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
312       if (!SI->isSimple()) {
313         LLVM_DEBUG(dbgs() << "Store is not simple! Can not evaluate.\n");
314         return false;  // no volatile/atomic accesses.
315       }
316       Constant *Ptr = getVal(SI->getOperand(1));
317       Constant *FoldedPtr = ConstantFoldConstant(Ptr, DL, TLI);
318       if (Ptr != FoldedPtr) {
319         LLVM_DEBUG(dbgs() << "Folding constant ptr expression: " << *Ptr);
320         Ptr = FoldedPtr;
321         LLVM_DEBUG(dbgs() << "; To: " << *Ptr << "\n");
322       }
323 
324       APInt Offset(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
325       Ptr = cast<Constant>(Ptr->stripAndAccumulateConstantOffsets(
326           DL, Offset, /* AllowNonInbounds */ true));
327       Offset = Offset.sextOrTrunc(DL.getIndexTypeSizeInBits(Ptr->getType()));
328       auto *GV = dyn_cast<GlobalVariable>(Ptr);
329       if (!GV || !GV->hasUniqueInitializer()) {
330         LLVM_DEBUG(dbgs() << "Store is not to global with unique initializer: "
331                           << *Ptr << "\n");
332         return false;
333       }
334 
335       // If this might be too difficult for the backend to handle (e.g. the addr
336       // of one global variable divided by another) then we can't commit it.
337       Constant *Val = getVal(SI->getOperand(0));
338       if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, DL)) {
339         LLVM_DEBUG(dbgs() << "Store value is too complex to evaluate store. "
340                           << *Val << "\n");
341         return false;
342       }
343 
344       auto Res = MutatedMemory.try_emplace(GV, GV->getInitializer());
345       if (!Res.first->second.write(Val, Offset, DL))
346         return false;
347     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
348       InstResult = ConstantExpr::get(BO->getOpcode(),
349                                      getVal(BO->getOperand(0)),
350                                      getVal(BO->getOperand(1)));
351       LLVM_DEBUG(dbgs() << "Found a BinaryOperator! Simplifying: "
352                         << *InstResult << "\n");
353     } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
354       InstResult = ConstantExpr::getCompare(CI->getPredicate(),
355                                             getVal(CI->getOperand(0)),
356                                             getVal(CI->getOperand(1)));
357       LLVM_DEBUG(dbgs() << "Found a CmpInst! Simplifying: " << *InstResult
358                         << "\n");
359     } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
360       InstResult = ConstantExpr::getCast(CI->getOpcode(),
361                                          getVal(CI->getOperand(0)),
362                                          CI->getType());
363       LLVM_DEBUG(dbgs() << "Found a Cast! Simplifying: " << *InstResult
364                         << "\n");
365     } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
366       InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
367                                            getVal(SI->getOperand(1)),
368                                            getVal(SI->getOperand(2)));
369       LLVM_DEBUG(dbgs() << "Found a Select! Simplifying: " << *InstResult
370                         << "\n");
371     } else if (auto *EVI = dyn_cast<ExtractValueInst>(CurInst)) {
372       InstResult = ConstantExpr::getExtractValue(
373           getVal(EVI->getAggregateOperand()), EVI->getIndices());
374       LLVM_DEBUG(dbgs() << "Found an ExtractValueInst! Simplifying: "
375                         << *InstResult << "\n");
376     } else if (auto *IVI = dyn_cast<InsertValueInst>(CurInst)) {
377       InstResult = ConstantExpr::getInsertValue(
378           getVal(IVI->getAggregateOperand()),
379           getVal(IVI->getInsertedValueOperand()), IVI->getIndices());
380       LLVM_DEBUG(dbgs() << "Found an InsertValueInst! Simplifying: "
381                         << *InstResult << "\n");
382     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
383       Constant *P = getVal(GEP->getOperand(0));
384       SmallVector<Constant*, 8> GEPOps;
385       for (Use &Op : llvm::drop_begin(GEP->operands()))
386         GEPOps.push_back(getVal(Op));
387       InstResult =
388           ConstantExpr::getGetElementPtr(GEP->getSourceElementType(), P, GEPOps,
389                                          cast<GEPOperator>(GEP)->isInBounds());
390       LLVM_DEBUG(dbgs() << "Found a GEP! Simplifying: " << *InstResult << "\n");
391     } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
392       if (!LI->isSimple()) {
393         LLVM_DEBUG(
394             dbgs() << "Found a Load! Not a simple load, can not evaluate.\n");
395         return false;  // no volatile/atomic accesses.
396       }
397 
398       Constant *Ptr = getVal(LI->getOperand(0));
399       Constant *FoldedPtr = ConstantFoldConstant(Ptr, DL, TLI);
400       if (Ptr != FoldedPtr) {
401         Ptr = FoldedPtr;
402         LLVM_DEBUG(dbgs() << "Found a constant pointer expression, constant "
403                              "folding: "
404                           << *Ptr << "\n");
405       }
406       InstResult = ComputeLoadResult(Ptr, LI->getType());
407       if (!InstResult) {
408         LLVM_DEBUG(
409             dbgs() << "Failed to compute load result. Can not evaluate load."
410                       "\n");
411         return false; // Could not evaluate load.
412       }
413 
414       LLVM_DEBUG(dbgs() << "Evaluated load: " << *InstResult << "\n");
415     } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
416       if (AI->isArrayAllocation()) {
417         LLVM_DEBUG(dbgs() << "Found an array alloca. Can not evaluate.\n");
418         return false;  // Cannot handle array allocs.
419       }
420       Type *Ty = AI->getAllocatedType();
421       AllocaTmps.push_back(std::make_unique<GlobalVariable>(
422           Ty, false, GlobalValue::InternalLinkage, UndefValue::get(Ty),
423           AI->getName(), /*TLMode=*/GlobalValue::NotThreadLocal,
424           AI->getType()->getPointerAddressSpace()));
425       InstResult = AllocaTmps.back().get();
426       LLVM_DEBUG(dbgs() << "Found an alloca. Result: " << *InstResult << "\n");
427     } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
428       CallBase &CB = *cast<CallBase>(&*CurInst);
429 
430       // Debug info can safely be ignored here.
431       if (isa<DbgInfoIntrinsic>(CB)) {
432         LLVM_DEBUG(dbgs() << "Ignoring debug info.\n");
433         ++CurInst;
434         continue;
435       }
436 
437       // Cannot handle inline asm.
438       if (CB.isInlineAsm()) {
439         LLVM_DEBUG(dbgs() << "Found inline asm, can not evaluate.\n");
440         return false;
441       }
442 
443       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CB)) {
444         if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
445           if (MSI->isVolatile()) {
446             LLVM_DEBUG(dbgs() << "Can not optimize a volatile memset "
447                               << "intrinsic.\n");
448             return false;
449           }
450           Constant *Ptr = getVal(MSI->getDest());
451           Constant *Val = getVal(MSI->getValue());
452           Constant *DestVal =
453               ComputeLoadResult(getVal(Ptr), MSI->getValue()->getType());
454           if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
455             // This memset is a no-op.
456             LLVM_DEBUG(dbgs() << "Ignoring no-op memset.\n");
457             ++CurInst;
458             continue;
459           }
460         }
461 
462         if (II->isLifetimeStartOrEnd()) {
463           LLVM_DEBUG(dbgs() << "Ignoring lifetime intrinsic.\n");
464           ++CurInst;
465           continue;
466         }
467 
468         if (II->getIntrinsicID() == Intrinsic::invariant_start) {
469           // We don't insert an entry into Values, as it doesn't have a
470           // meaningful return value.
471           if (!II->use_empty()) {
472             LLVM_DEBUG(dbgs()
473                        << "Found unused invariant_start. Can't evaluate.\n");
474             return false;
475           }
476           ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
477           Value *PtrArg = getVal(II->getArgOperand(1));
478           Value *Ptr = PtrArg->stripPointerCasts();
479           if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
480             Type *ElemTy = GV->getValueType();
481             if (!Size->isMinusOne() &&
482                 Size->getValue().getLimitedValue() >=
483                     DL.getTypeStoreSize(ElemTy)) {
484               Invariants.insert(GV);
485               LLVM_DEBUG(dbgs() << "Found a global var that is an invariant: "
486                                 << *GV << "\n");
487             } else {
488               LLVM_DEBUG(dbgs()
489                          << "Found a global var, but can not treat it as an "
490                             "invariant.\n");
491             }
492           }
493           // Continue even if we do nothing.
494           ++CurInst;
495           continue;
496         } else if (II->getIntrinsicID() == Intrinsic::assume) {
497           LLVM_DEBUG(dbgs() << "Skipping assume intrinsic.\n");
498           ++CurInst;
499           continue;
500         } else if (II->getIntrinsicID() == Intrinsic::sideeffect) {
501           LLVM_DEBUG(dbgs() << "Skipping sideeffect intrinsic.\n");
502           ++CurInst;
503           continue;
504         } else if (II->getIntrinsicID() == Intrinsic::pseudoprobe) {
505           LLVM_DEBUG(dbgs() << "Skipping pseudoprobe intrinsic.\n");
506           ++CurInst;
507           continue;
508         } else {
509           Value *Stripped = CurInst->stripPointerCastsForAliasAnalysis();
510           // Only attempt to getVal() if we've actually managed to strip
511           // anything away, or else we'll call getVal() on the current
512           // instruction.
513           if (Stripped != &*CurInst) {
514             InstResult = getVal(Stripped);
515           }
516           if (InstResult) {
517             LLVM_DEBUG(dbgs()
518                        << "Stripped pointer casts for alias analysis for "
519                           "intrinsic call.\n");
520             StrippedPointerCastsForAliasAnalysis = true;
521             InstResult = ConstantExpr::getBitCast(InstResult, II->getType());
522           } else {
523             LLVM_DEBUG(dbgs() << "Unknown intrinsic. Cannot evaluate.\n");
524             return false;
525           }
526         }
527       }
528 
529       if (!InstResult) {
530         // Resolve function pointers.
531         SmallVector<Constant *, 8> Formals;
532         Function *Callee = getCalleeWithFormalArgs(CB, Formals);
533         if (!Callee || Callee->isInterposable()) {
534           LLVM_DEBUG(dbgs() << "Can not resolve function pointer.\n");
535           return false; // Cannot resolve.
536         }
537 
538         if (Callee->isDeclaration()) {
539           // If this is a function we can constant fold, do it.
540           if (Constant *C = ConstantFoldCall(&CB, Callee, Formals, TLI)) {
541             InstResult = castCallResultIfNeeded(CB.getCalledOperand(), C);
542             if (!InstResult)
543               return false;
544             LLVM_DEBUG(dbgs() << "Constant folded function call. Result: "
545                               << *InstResult << "\n");
546           } else {
547             LLVM_DEBUG(dbgs() << "Can not constant fold function call.\n");
548             return false;
549           }
550         } else {
551           if (Callee->getFunctionType()->isVarArg()) {
552             LLVM_DEBUG(dbgs()
553                        << "Can not constant fold vararg function call.\n");
554             return false;
555           }
556 
557           Constant *RetVal = nullptr;
558           // Execute the call, if successful, use the return value.
559           ValueStack.emplace_back();
560           if (!EvaluateFunction(Callee, RetVal, Formals)) {
561             LLVM_DEBUG(dbgs() << "Failed to evaluate function.\n");
562             return false;
563           }
564           ValueStack.pop_back();
565           InstResult = castCallResultIfNeeded(CB.getCalledOperand(), RetVal);
566           if (RetVal && !InstResult)
567             return false;
568 
569           if (InstResult) {
570             LLVM_DEBUG(dbgs() << "Successfully evaluated function. Result: "
571                               << *InstResult << "\n\n");
572           } else {
573             LLVM_DEBUG(dbgs()
574                        << "Successfully evaluated function. Result: 0\n\n");
575           }
576         }
577       }
578     } else if (CurInst->isTerminator()) {
579       LLVM_DEBUG(dbgs() << "Found a terminator instruction.\n");
580 
581       if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
582         if (BI->isUnconditional()) {
583           NextBB = BI->getSuccessor(0);
584         } else {
585           ConstantInt *Cond =
586             dyn_cast<ConstantInt>(getVal(BI->getCondition()));
587           if (!Cond) return false;  // Cannot determine.
588 
589           NextBB = BI->getSuccessor(!Cond->getZExtValue());
590         }
591       } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
592         ConstantInt *Val =
593           dyn_cast<ConstantInt>(getVal(SI->getCondition()));
594         if (!Val) return false;  // Cannot determine.
595         NextBB = SI->findCaseValue(Val)->getCaseSuccessor();
596       } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
597         Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
598         if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
599           NextBB = BA->getBasicBlock();
600         else
601           return false;  // Cannot determine.
602       } else if (isa<ReturnInst>(CurInst)) {
603         NextBB = nullptr;
604       } else {
605         // invoke, unwind, resume, unreachable.
606         LLVM_DEBUG(dbgs() << "Can not handle terminator.");
607         return false;  // Cannot handle this terminator.
608       }
609 
610       // We succeeded at evaluating this block!
611       LLVM_DEBUG(dbgs() << "Successfully evaluated block.\n");
612       return true;
613     } else {
614       // Did not know how to evaluate this!
615       LLVM_DEBUG(
616           dbgs() << "Failed to evaluate block due to unhandled instruction."
617                     "\n");
618       return false;
619     }
620 
621     if (!CurInst->use_empty()) {
622       InstResult = ConstantFoldConstant(InstResult, DL, TLI);
623       setVal(&*CurInst, InstResult);
624     }
625 
626     // If we just processed an invoke, we finished evaluating the block.
627     if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
628       NextBB = II->getNormalDest();
629       LLVM_DEBUG(dbgs() << "Found an invoke instruction. Finished Block.\n\n");
630       return true;
631     }
632 
633     // Advance program counter.
634     ++CurInst;
635   }
636 }
637 
638 /// Evaluate a call to function F, returning true if successful, false if we
639 /// can't evaluate it.  ActualArgs contains the formal arguments for the
640 /// function.
641 bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
642                                  const SmallVectorImpl<Constant*> &ActualArgs) {
643   // Check to see if this function is already executing (recursion).  If so,
644   // bail out.  TODO: we might want to accept limited recursion.
645   if (is_contained(CallStack, F))
646     return false;
647 
648   CallStack.push_back(F);
649 
650   // Initialize arguments to the incoming values specified.
651   unsigned ArgNo = 0;
652   for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
653        ++AI, ++ArgNo)
654     setVal(&*AI, ActualArgs[ArgNo]);
655 
656   // ExecutedBlocks - We only handle non-looping, non-recursive code.  As such,
657   // we can only evaluate any one basic block at most once.  This set keeps
658   // track of what we have executed so we can detect recursive cases etc.
659   SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
660 
661   // CurBB - The current basic block we're evaluating.
662   BasicBlock *CurBB = &F->front();
663 
664   BasicBlock::iterator CurInst = CurBB->begin();
665 
666   while (true) {
667     BasicBlock *NextBB = nullptr; // Initialized to avoid compiler warnings.
668     LLVM_DEBUG(dbgs() << "Trying to evaluate BB: " << *CurBB << "\n");
669 
670     bool StrippedPointerCastsForAliasAnalysis = false;
671 
672     if (!EvaluateBlock(CurInst, NextBB, StrippedPointerCastsForAliasAnalysis))
673       return false;
674 
675     if (!NextBB) {
676       // Successfully running until there's no next block means that we found
677       // the return.  Fill it the return value and pop the call stack.
678       ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
679       if (RI->getNumOperands()) {
680         // The Evaluator can look through pointer casts as long as alias
681         // analysis holds because it's just a simple interpreter and doesn't
682         // skip memory accesses due to invariant group metadata, but we can't
683         // let users of Evaluator use a value that's been gleaned looking
684         // through stripping pointer casts.
685         if (StrippedPointerCastsForAliasAnalysis &&
686             !RI->getReturnValue()->getType()->isVoidTy()) {
687           return false;
688         }
689         RetVal = getVal(RI->getOperand(0));
690       }
691       CallStack.pop_back();
692       return true;
693     }
694 
695     // Okay, we succeeded in evaluating this control flow.  See if we have
696     // executed the new block before.  If so, we have a looping function,
697     // which we cannot evaluate in reasonable time.
698     if (!ExecutedBlocks.insert(NextBB).second)
699       return false;  // looped!
700 
701     // Okay, we have never been in this block before.  Check to see if there
702     // are any PHI nodes.  If so, evaluate them with information about where
703     // we came from.
704     PHINode *PN = nullptr;
705     for (CurInst = NextBB->begin();
706          (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
707       setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
708 
709     // Advance to the next block.
710     CurBB = NextBB;
711   }
712 }
713