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