Ignore:
Timestamp:
Apr 19, 2011, 11:12:07 PM (14 years ago)
Author:
Yuri Dario
Message:

clamav: update trunk to 0.97.

Location:
clamav/trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • clamav/trunk

  • TabularUnified clamav/trunk/libclamav/c++/llvm/lib/Transforms/Scalar/JumpThreading.cpp

    r189 r319  
    1919#include "llvm/Analysis/InstructionSimplify.h"
    2020#include "llvm/Analysis/LazyValueInfo.h"
     21#include "llvm/Analysis/Loads.h"
    2122#include "llvm/Transforms/Utils/BasicBlockUtils.h"
    2223#include "llvm/Transforms/Utils/Local.h"
     
    2425#include "llvm/Target/TargetData.h"
    2526#include "llvm/ADT/DenseMap.h"
     27#include "llvm/ADT/DenseSet.h"
    2628#include "llvm/ADT/Statistic.h"
    2729#include "llvm/ADT/STLExtras.h"
     
    4547// Turn on use of LazyValueInfo.
    4648static cl::opt<bool>
    47 EnableLVI("enable-jump-threading-lvi", cl::ReallyHidden);
     49EnableLVI("enable-jump-threading-lvi",
     50          cl::desc("Use LVI for jump threading"),
     51          cl::init(true),
     52          cl::ReallyHidden);
    4853
    4954
     
    7479    SmallSet<AssertingVH<BasicBlock>, 16> LoopHeaders;
    7580#endif
     81    DenseSet<std::pair<Value*, BasicBlock*> > RecursionSet;
     82   
     83    // RAII helper for updating the recursion stack.
     84    struct RecursionSetRemover {
     85      DenseSet<std::pair<Value*, BasicBlock*> > &TheSet;
     86      std::pair<Value*, BasicBlock*> ThePair;
     87     
     88      RecursionSetRemover(DenseSet<std::pair<Value*, BasicBlock*> > &S,
     89                          std::pair<Value*, BasicBlock*> P)
     90        : TheSet(S), ThePair(P) { }
     91     
     92      ~RecursionSetRemover() {
     93        TheSet.erase(ThePair);
     94      }
     95    };
    7696  public:
    7797    static char ID; // Pass identification
    78     JumpThreading() : FunctionPass(&ID) {}
     98    JumpThreading() : FunctionPass(ID) {}
    7999
    80100    bool runOnFunction(Function &F);
    81101   
    82102    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
    83       if (EnableLVI)
     103      if (EnableLVI) {
    84104        AU.addRequired<LazyValueInfo>();
     105        AU.addPreserved<LazyValueInfo>();
     106      }
    85107    }
    86108   
     
    111133
    112134char JumpThreading::ID = 0;
    113 static RegisterPass<JumpThreading>
    114 X("jump-threading", "Jump Threading");
     135INITIALIZE_PASS(JumpThreading, "jump-threading",
     136                "Jump Threading", false, false);
    115137
    116138// Public interface to the Jump Threading pass
     
    144166              << "' with terminator: " << *BB->getTerminator() << '\n');
    145167        LoopHeaders.erase(BB);
     168        if (LVI) LVI->eraseBlock(BB);
    146169        DeleteDeadBlock(BB);
    147170        Changed = true;
     
    164187            BasicBlock *Succ = BI->getSuccessor(0);
    165188           
     189            // FIXME: It is always conservatively correct to drop the info
     190            // for a block even if it doesn't get erased.  This isn't totally
     191            // awesome, but it allows us to use AssertingVH to prevent nasty
     192            // dangling pointer issues within LazyValueInfo.
     193            if (LVI) LVI->eraseBlock(BB);
    166194            if (TryToSimplifyUncondBranchFromEmptyBlock(BB)) {
    167195              Changed = true;
     
    251279}
    252280
     281// Helper method for ComputeValueKnownInPredecessors.  If Value is a
     282// ConstantInt, push it.  If it's an undef, push 0.  Otherwise, do nothing.
     283static void PushConstantIntOrUndef(SmallVectorImpl<std::pair<ConstantInt*,
     284                                                        BasicBlock*> > &Result,
     285                              Constant *Value, BasicBlock* BB){
     286  if (ConstantInt *FoldedCInt = dyn_cast<ConstantInt>(Value))
     287    Result.push_back(std::make_pair(FoldedCInt, BB));
     288  else if (isa<UndefValue>(Value))
     289    Result.push_back(std::make_pair((ConstantInt*)0, BB));
     290}
     291
    253292/// ComputeValueKnownInPredecessors - Given a basic block BB and a value V, see
    254293/// if we can infer that the value is a known ConstantInt in any of our
     
    260299bool JumpThreading::
    261300ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB,PredValueInfo &Result){
     301  // This method walks up use-def chains recursively.  Because of this, we could
     302  // get into an infinite loop going around loops in the use-def chain.  To
     303  // prevent this, keep track of what (value, block) pairs we've already visited
     304  // and terminate the search if we loop back to them
     305  if (!RecursionSet.insert(std::make_pair(V, BB)).second)
     306    return false;
     307 
     308  // An RAII help to remove this pair from the recursion set once the recursion
     309  // stack pops back out again.
     310  RecursionSetRemover remover(RecursionSet, std::make_pair(V, BB));
     311 
    262312  // If V is a constantint, then it is known in all predecessors.
    263313  if (isa<ConstantInt>(V) || isa<UndefValue>(V)) {
     
    266316    for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
    267317      Result.push_back(std::make_pair(CI, *PI));
     318   
    268319    return true;
    269320  }
     
    289340     
    290341      for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
     342        BasicBlock *P = *PI;
    291343        // If the value is known by LazyValueInfo to be a constant in a
    292344        // predecessor, use that information to try to thread this block.
    293         Constant *PredCst = LVI->getConstantOnEdge(V, *PI, BB);
     345        Constant *PredCst = LVI->getConstantOnEdge(V, P, BB);
    294346        if (PredCst == 0 ||
    295347            (!isa<ConstantInt>(PredCst) && !isa<UndefValue>(PredCst)))
    296348          continue;
    297349       
    298         Result.push_back(std::make_pair(dyn_cast<ConstantInt>(PredCst), *PI));
     350        Result.push_back(std::make_pair(dyn_cast<ConstantInt>(PredCst), P));
    299351      }
    300352     
     
    312364        ConstantInt *CI = dyn_cast<ConstantInt>(InVal);
    313365        Result.push_back(std::make_pair(CI, PN->getIncomingBlock(i)));
     366      } else if (LVI) {
     367        Constant *CI = LVI->getConstantOnEdge(InVal,
     368                                              PN->getIncomingBlock(i), BB);
     369        // LVI returns null is no value could be determined.
     370        if (!CI) continue;
     371        PushConstantIntOrUndef(Result, CI, PN->getIncomingBlock(i));
    314372      }
    315373    }
     374   
    316375    return !Result.empty();
    317376  }
     
    337396        InterestingVal = ConstantInt::getFalse(I->getContext());
    338397     
     398      SmallPtrSet<BasicBlock*, 4> LHSKnownBBs;
     399     
    339400      // Scan for the sentinel.  If we find an undef, force it to the
    340401      // interesting value: x|undef -> true and x&undef -> false.
     
    343404          Result.push_back(LHSVals[i]);
    344405          Result.back().first = InterestingVal;
     406          LHSKnownBBs.insert(LHSVals[i].second);
    345407        }
    346408      for (unsigned i = 0, e = RHSVals.size(); i != e; ++i)
    347409        if (RHSVals[i].first == InterestingVal || RHSVals[i].first == 0) {
    348           Result.push_back(RHSVals[i]);
    349           Result.back().first = InterestingVal;
     410          // If we already inferred a value for this block on the LHS, don't
     411          // re-add it.
     412          if (!LHSKnownBBs.count(RHSVals[i].second)) {
     413            Result.push_back(RHSVals[i]);
     414            Result.back().first = InterestingVal;
     415          }
    350416        }
     417     
    351418      return !Result.empty();
    352419    }
     
    365432          Result[i].first =
    366433            cast<ConstantInt>(ConstantExpr::getNot(Result[i].first));
     434     
    367435      return true;
    368436    }
     437 
     438  // Try to simplify some other binary operator values.
     439  } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
     440    if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
     441      SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> LHSVals;
     442      ComputeValueKnownInPredecessors(BO->getOperand(0), BB, LHSVals);
     443   
     444      // Try to use constant folding to simplify the binary operator.
     445      for (unsigned i = 0, e = LHSVals.size(); i != e; ++i) {
     446        Constant *V = LHSVals[i].first ? LHSVals[i].first :
     447                                 cast<Constant>(UndefValue::get(BO->getType()));
     448        Constant *Folded = ConstantExpr::get(BO->getOpcode(), V, CI);
     449       
     450        PushConstantIntOrUndef(Result, Folded, LHSVals[i].second);
     451      }
     452    }
     453     
     454    return !Result.empty();
    369455  }
    370456 
     
    393479        }
    394480       
    395         if (isa<UndefValue>(Res))
    396           Result.push_back(std::make_pair((ConstantInt*)0, PredBB));
    397         else if (ConstantInt *CI = dyn_cast<ConstantInt>(Res))
    398           Result.push_back(std::make_pair(CI, PredBB));
     481        if (Constant *ConstRes = dyn_cast<Constant>(Res))
     482          PushConstantIntOrUndef(Result, ConstRes, PredBB);
    399483      }
    400484     
     
    406490    // live-in value on any predecessors.
    407491    if (LVI && isa<Constant>(Cmp->getOperand(1)) &&
    408         Cmp->getType()->isIntegerTy() && // Not vector compare.
    409         (!isa<Instruction>(Cmp->getOperand(0)) ||
    410          cast<Instruction>(Cmp->getOperand(0))->getParent() != BB)) {
    411       Constant *RHSCst = cast<Constant>(Cmp->getOperand(1));
    412      
    413       for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
    414         // If the value is known by LazyValueInfo to be a constant in a
    415         // predecessor, use that information to try to thread this block.
    416         LazyValueInfo::Tristate
    417           Res = LVI->getPredicateOnEdge(Cmp->getPredicate(), Cmp->getOperand(0),
    418                                         RHSCst, *PI, BB);
    419         if (Res == LazyValueInfo::Unknown)
    420           continue;
    421 
    422         Constant *ResC = ConstantInt::get(Cmp->getType(), Res);
    423         Result.push_back(std::make_pair(cast<ConstantInt>(ResC), *PI));
     492        Cmp->getType()->isIntegerTy()) {
     493      if (!isa<Instruction>(Cmp->getOperand(0)) ||
     494          cast<Instruction>(Cmp->getOperand(0))->getParent() != BB) {
     495        Constant *RHSCst = cast<Constant>(Cmp->getOperand(1));
     496
     497        for (pred_iterator PI = pred_begin(BB), E = pred_end(BB);PI != E; ++PI){
     498          BasicBlock *P = *PI;
     499          // If the value is known by LazyValueInfo to be a constant in a
     500          // predecessor, use that information to try to thread this block.
     501          LazyValueInfo::Tristate Res =
     502            LVI->getPredicateOnEdge(Cmp->getPredicate(), Cmp->getOperand(0),
     503                                    RHSCst, P, BB);
     504          if (Res == LazyValueInfo::Unknown)
     505            continue;
     506
     507          Constant *ResC = ConstantInt::get(Cmp->getType(), Res);
     508          Result.push_back(std::make_pair(cast<ConstantInt>(ResC), P));
     509        }
     510
     511        return !Result.empty();
    424512      }
    425513     
    426       return !Result.empty();
    427     }
    428   }
     514      // Try to find a constant value for the LHS of a comparison,
     515      // and evaluate it statically if we can.
     516      if (Constant *CmpConst = dyn_cast<Constant>(Cmp->getOperand(1))) {
     517        SmallVector<std::pair<ConstantInt*, BasicBlock*>, 8> LHSVals;
     518        ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals);
     519       
     520        for (unsigned i = 0, e = LHSVals.size(); i != e; ++i) {
     521          Constant *V = LHSVals[i].first ? LHSVals[i].first :
     522                           cast<Constant>(UndefValue::get(CmpConst->getType()));
     523          Constant *Folded = ConstantExpr::getCompare(Cmp->getPredicate(),
     524                                                      V, CmpConst);
     525          PushConstantIntOrUndef(Result, Folded, LHSVals[i].second);
     526        }
     527       
     528        return !Result.empty();
     529      }
     530    }
     531  }
     532 
     533  if (LVI) {
     534    // If all else fails, see if LVI can figure out a constant value for us.
     535    Constant *CI = LVI->getConstant(V, BB);
     536    ConstantInt *CInt = dyn_cast_or_null<ConstantInt>(CI);
     537    if (CInt) {
     538      for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
     539        Result.push_back(std::make_pair(CInt, *PI));
     540    }
     541   
     542    return !Result.empty();
     543  }
     544 
    429545  return false;
    430546}
     
    477593      // will need to move BB back to the entry position.
    478594      bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
     595      if (LVI) LVI->eraseBlock(SinglePred);
    479596      MergeBasicBlockIntoOnlyPred(BB);
    480597     
     
    539656    pred_iterator PI = pred_begin(BB), E = pred_end(BB);
    540657    if (isa<BranchInst>(BB->getTerminator())) {
    541       for (; PI != E; ++PI)
    542         if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
     658      for (; PI != E; ++PI) {
     659        BasicBlock *P = *PI;
     660        if (BranchInst *PBI = dyn_cast<BranchInst>(P->getTerminator()))
    543661          if (PBI->isConditional() && PBI->getCondition() == Condition &&
    544               ProcessBranchOnDuplicateCond(*PI, BB))
     662              ProcessBranchOnDuplicateCond(P, BB))
    545663            return true;
     664      }
    546665    } else {
    547666      assert(isa<SwitchInst>(BB->getTerminator()) && "Unknown jump terminator");
    548       for (; PI != E; ++PI)
    549         if (SwitchInst *PSI = dyn_cast<SwitchInst>((*PI)->getTerminator()))
     667      for (; PI != E; ++PI) {
     668        BasicBlock *P = *PI;
     669        if (SwitchInst *PSI = dyn_cast<SwitchInst>(P->getTerminator()))
    550670          if (PSI->getCondition() == Condition &&
    551               ProcessSwitchOnDuplicateCond(*PI, BB))
     671              ProcessSwitchOnDuplicateCond(P, BB))
    552672            return true;
     673      }
    553674    }
    554675  }
     
    570691      // a condition with a lexically identical value.
    571692      pred_iterator PI = pred_begin(BB), E = pred_end(BB);
    572       for (; PI != E; ++PI)
    573         if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
    574           if (PBI->isConditional() && *PI != BB) {
     693      for (; PI != E; ++PI) {
     694        BasicBlock *P = *PI;
     695        if (BranchInst *PBI = dyn_cast<BranchInst>(P->getTerminator()))
     696          if (PBI->isConditional() && P != BB) {
    575697            if (CmpInst *CI = dyn_cast<CmpInst>(PBI->getCondition())) {
    576698              if (CI->getOperand(0) == CondCmp->getOperand(0) &&
     
    578700                  CI->getPredicate() == CondCmp->getPredicate()) {
    579701                // TODO: Could handle things like (x != 4) --> (x == 17)
    580                 if (ProcessBranchOnDuplicateCond(*PI, BB))
     702                if (ProcessBranchOnDuplicateCond(P, BB))
    581703                  return true;
    582704              }
    583705            }
    584706          }
     707      }
     708    }
     709   
     710    // For a comparison where the LHS is outside this block, it's possible
     711    // that we've branched on it before.  Used LVI to see if we can simplify
     712    // the branch based on that.
     713    BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
     714    Constant *CondConst = dyn_cast<Constant>(CondCmp->getOperand(1));
     715    pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
     716    if (LVI && CondBr && CondConst && CondBr->isConditional() && PI != PE &&
     717        (!isa<Instruction>(CondCmp->getOperand(0)) ||
     718         cast<Instruction>(CondCmp->getOperand(0))->getParent() != BB)) {
     719      // For predecessor edge, determine if the comparison is true or false
     720      // on that edge.  If they're all true or all false, we can simplify the
     721      // branch.
     722      // FIXME: We could handle mixed true/false by duplicating code.
     723      LazyValueInfo::Tristate Baseline =     
     724        LVI->getPredicateOnEdge(CondCmp->getPredicate(), CondCmp->getOperand(0),
     725                                CondConst, *PI, BB);
     726      if (Baseline != LazyValueInfo::Unknown) {
     727        // Check that all remaining incoming values match the first one.
     728        while (++PI != PE) {
     729          LazyValueInfo::Tristate Ret = LVI->getPredicateOnEdge(
     730                                          CondCmp->getPredicate(),
     731                                          CondCmp->getOperand(0),
     732                                          CondConst, *PI, BB);
     733          if (Ret != Baseline) break;
     734        }
     735       
     736        // If we terminated early, then one of the values didn't match.
     737        if (PI == PE) {
     738          unsigned ToRemove = Baseline == LazyValueInfo::True ? 1 : 0;
     739          unsigned ToKeep = Baseline == LazyValueInfo::True ? 0 : 1;
     740          RemovePredecessorAndSimplify(CondBr->getSuccessor(ToRemove), BB, TD);
     741          BranchInst::Create(CondBr->getSuccessor(ToKeep), CondBr);
     742          CondBr->eraseFromParent();
     743          return true;
     744        }
     745      }
    585746    }
    586747  }
     
    671832    DestBI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
    672833                                          BranchDir));
     834    // Delete dead instructions before we fold the branch.  Folding the branch
     835    // can eliminate edges from the CFG which can end up deleting OldCond.
     836    RecursivelyDeleteTriviallyDeadInstructions(OldCond);
    673837    ConstantFoldTerminator(BB);
    674     RecursivelyDeleteTriviallyDeadInstructions(OldCond);
    675838    return true;
    676839  }
     
    8681031    // Add all the unavailable predecessors to the PredsToSplit list.
    8691032    for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
    870          PI != PE; ++PI)
    871       if (!AvailablePredSet.count(*PI))
    872         PredsToSplit.push_back(*PI);
     1033         PI != PE; ++PI) {
     1034      BasicBlock *P = *PI;
     1035      // If the predecessor is an indirect goto, we can't split the edge.
     1036      if (isa<IndirectBrInst>(P->getTerminator()))
     1037        return false;
     1038     
     1039      if (!AvailablePredSet.count(P))
     1040        PredsToSplit.push_back(P);
     1041    }
    8731042   
    8741043    // Split them out to their own block.
     
    9021071  for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB); PI != E;
    9031072       ++PI) {
     1073    BasicBlock *P = *PI;
    9041074    AvailablePredsTy::iterator I =
    9051075      std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
    906                        std::make_pair(*PI, (Value*)0));
    907    
    908     assert(I != AvailablePreds.end() && I->first == *PI &&
     1076                       std::make_pair(P, (Value*)0));
     1077   
     1078    assert(I != AvailablePreds.end() && I->first == P &&
    9091079           "Didn't find entry for predecessor!");
    9101080   
     
    9921162  if (!ComputeValueKnownInPredecessors(Cond, BB, PredValues))
    9931163    return false;
     1164 
    9941165  assert(!PredValues.empty() &&
    9951166         "ComputeValueKnownInPredecessors returned true with no values");
     
    12861457        << *BB << "\n");
    12871458 
     1459  if (LVI)
     1460    LVI->threadEdge(PredBB, BB, SuccBB);
     1461 
    12881462  // We are going to have to map operands from the original BB block to the new
    12891463  // copy of the block 'NewBB'.  If there are PHI nodes in BB, evaluate them to
     
    13551529    // its block to be uses of the appropriate PHI node etc.  See ValuesInBlocks
    13561530    // with the two values we know.
    1357     SSAUpdate.Initialize(I);
     1531    SSAUpdate.Initialize(I->getType(), I->getName());
    13581532    SSAUpdate.AddAvailableValue(BB, I);
    13591533    SSAUpdate.AddAvailableValue(NewBB, ValueMapping[I]);
     
    15101684    // its block to be uses of the appropriate PHI node etc.  See ValuesInBlocks
    15111685    // with the two values we know.
    1512     SSAUpdate.Initialize(I);
     1686    SSAUpdate.Initialize(I->getType(), I->getName());
    15131687    SSAUpdate.AddAvailableValue(BB, I);
    15141688    SSAUpdate.AddAvailableValue(PredBB, ValueMapping[I]);
Note: See TracChangeset for help on using the changeset viewer.