git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@206243
91177308-0d34-0410-b5e6-
96231b3b80d8
59 files changed:
const MDNode *TBAAInfo;
public:
PointerRec(Value *V)
const MDNode *TBAAInfo;
public:
PointerRec(Value *V)
- : Val(V), PrevInList(0), NextInList(0), AS(0), Size(0),
+ : Val(V), PrevInList(nullptr), NextInList(nullptr), AS(nullptr), Size(0),
TBAAInfo(DenseMapInfo<const MDNode *>::getEmptyKey()) {}
Value *getValue() const { return Val; }
PointerRec *getNext() const { return NextInList; }
TBAAInfo(DenseMapInfo<const MDNode *>::getEmptyKey()) {}
Value *getValue() const { return Val; }
PointerRec *getNext() const { return NextInList; }
- bool hasAliasSet() const { return AS != 0; }
+ bool hasAliasSet() const { return AS != nullptr; }
PointerRec** setPrevInList(PointerRec **PIL) {
PrevInList = PIL;
PointerRec** setPrevInList(PointerRec **PIL) {
PrevInList = PIL;
// If we have missing or conflicting TBAAInfo, return null.
if (TBAAInfo == DenseMapInfo<const MDNode *>::getEmptyKey() ||
TBAAInfo == DenseMapInfo<const MDNode *>::getTombstoneKey())
// If we have missing or conflicting TBAAInfo, return null.
if (TBAAInfo == DenseMapInfo<const MDNode *>::getEmptyKey() ||
TBAAInfo == DenseMapInfo<const MDNode *>::getTombstoneKey())
}
void setAliasSet(AliasSet *as) {
}
void setAliasSet(AliasSet *as) {
- assert(AS == 0 && "Already have an alias set!");
+ assert(!AS && "Already have an alias set!");
*PrevInList = NextInList;
if (AS->PtrListEnd == &NextInList) {
AS->PtrListEnd = PrevInList;
*PrevInList = NextInList;
if (AS->PtrListEnd == &NextInList) {
AS->PtrListEnd = PrevInList;
- assert(*AS->PtrListEnd == 0 && "List not terminated right!");
+ assert(*AS->PtrListEnd == nullptr && "List not terminated right!");
class iterator;
iterator begin() const { return iterator(PtrList); }
iterator end() const { return iterator(); }
class iterator;
iterator begin() const { return iterator(PtrList); }
iterator end() const { return iterator(); }
- bool empty() const { return PtrList == 0; }
+ bool empty() const { return PtrList == nullptr; }
void print(raw_ostream &OS) const;
void dump() const;
void print(raw_ostream &OS) const;
void dump() const;
PointerRec, ptrdiff_t> {
PointerRec *CurNode;
public:
PointerRec, ptrdiff_t> {
PointerRec *CurNode;
public:
- explicit iterator(PointerRec *CN = 0) : CurNode(CN) {}
+ explicit iterator(PointerRec *CN = nullptr) : CurNode(CN) {}
bool operator==(const iterator& x) const {
return CurNode == x.CurNode;
bool operator==(const iterator& x) const {
return CurNode == x.CurNode;
// Can only be created by AliasSetTracker. Also, ilist creates one
// to serve as a sentinel.
friend struct ilist_sentinel_traits<AliasSet>;
// Can only be created by AliasSetTracker. Also, ilist creates one
// to serve as a sentinel.
friend struct ilist_sentinel_traits<AliasSet>;
- AliasSet() : PtrList(0), PtrListEnd(&PtrList), Forward(0), RefCount(0),
- AccessTy(NoModRef), AliasTy(MustAlias), Volatile(false) {
+ AliasSet()
+ : PtrList(nullptr), PtrListEnd(&PtrList), Forward(nullptr), RefCount(0),
+ AccessTy(NoModRef), AliasTy(MustAlias), Volatile(false) {
}
AliasSet(const AliasSet &AS) LLVM_DELETED_FUNCTION;
}
AliasSet(const AliasSet &AS) LLVM_DELETED_FUNCTION;
void deleted() override;
void allUsesReplacedWith(Value *) override;
public:
void deleted() override;
void allUsesReplacedWith(Value *) override;
public:
- ASTCallbackVH(Value *V, AliasSetTracker *AST = 0);
+ ASTCallbackVH(Value *V, AliasSetTracker *AST = nullptr);
ASTCallbackVH &operator=(Value *V);
};
/// ASTCallbackVHDenseMapInfo - Traits to tell DenseMap that tell us how to
ASTCallbackVH &operator=(Value *V);
};
/// ASTCallbackVHDenseMapInfo - Traits to tell DenseMap that tell us how to
/// pointer didn't alias anything).
AliasSet &getAliasSetForPointer(Value *P, uint64_t Size,
const MDNode *TBAAInfo,
/// pointer didn't alias anything).
AliasSet &getAliasSetForPointer(Value *P, uint64_t Size,
const MDNode *TBAAInfo,
/// getAliasSetForPointerIfExists - Return the alias set containing the
/// location specified if one exists, otherwise return null.
/// getAliasSetForPointerIfExists - Return the alias set containing the
/// location specified if one exists, otherwise return null.
// entry for the pointer if it doesn't already exist.
AliasSet::PointerRec &getEntryFor(Value *V) {
AliasSet::PointerRec *&Entry = PointerMap[ASTCallbackVH(V, this)];
// entry for the pointer if it doesn't already exist.
AliasSet::PointerRec &getEntryFor(Value *V) {
AliasSet::PointerRec *&Entry = PointerMap[ASTCallbackVH(V, this)];
Entry = new AliasSet::PointerRec(V);
return *Entry;
}
Entry = new AliasSet::PointerRec(V);
return *Entry;
}
void getAnalysisUsage(AnalysisUsage &AU) const override;
bool runOnFunction(Function &F) override;
void getAnalysisUsage(AnalysisUsage &AU) const override;
bool runOnFunction(Function &F) override;
- void print(raw_ostream &OS, const Module *M = 0) const override;
+ void print(raw_ostream &OS, const Module *M = nullptr) const override;
/// \brief Get an edge's probability, relative to other out-edges of the Src.
///
/// \brief Get an edge's probability, relative to other out-edges of the Src.
///
/// on branchy code but not loops, and LI is most useful on code with loops but
/// does not help on branchy code outside loops.
bool isPotentiallyReachable(const Instruction *From, const Instruction *To,
/// on branchy code but not loops, and LI is most useful on code with loops but
/// does not help on branchy code outside loops.
bool isPotentiallyReachable(const Instruction *From, const Instruction *To,
- const DominatorTree *DT = 0,
- const LoopInfo *LI = 0);
+ const DominatorTree *DT = nullptr,
+ const LoopInfo *LI = nullptr);
/// \brief Determine whether block 'To' is reachable from 'From', returning
/// true if uncertain.
/// \brief Determine whether block 'To' is reachable from 'From', returning
/// true if uncertain.
/// Returns false only if we can prove that once 'From' has been reached then
/// 'To' can not be executed. Conservatively returns true.
bool isPotentiallyReachable(const BasicBlock *From, const BasicBlock *To,
/// Returns false only if we can prove that once 'From' has been reached then
/// 'To' can not be executed. Conservatively returns true.
bool isPotentiallyReachable(const BasicBlock *From, const BasicBlock *To,
- const DominatorTree *DT = 0,
- const LoopInfo *LI = 0);
+ const DominatorTree *DT = nullptr,
+ const LoopInfo *LI = nullptr);
Instruction *Destination) :
Src(Source),
Dst(Destination),
Instruction *Destination) :
Src(Source),
Dst(Destination),
- NextPredecessor(NULL),
- NextSuccessor(NULL) {}
+ NextPredecessor(nullptr),
+ NextSuccessor(nullptr) {}
virtual ~Dependence() {}
/// Dependence::DVEntry - Each level in the distance/direction vector
virtual ~Dependence() {}
/// Dependence::DVEntry - Each level in the distance/direction vector
bool Splitable : 1; // Splitting the loop will break dependence.
const SCEV *Distance; // NULL implies no distance available.
DVEntry() : Direction(ALL), Scalar(true), PeelFirst(false),
bool Splitable : 1; // Splitting the loop will break dependence.
const SCEV *Distance; // NULL implies no distance available.
DVEntry() : Direction(ALL), Scalar(true), PeelFirst(false),
- PeelLast(false), Splitable(false), Distance(NULL) { }
+ PeelLast(false), Splitable(false), Distance(nullptr) { }
};
/// getSrc - Returns the source instruction for this dependence.
};
/// getSrc - Returns the source instruction for this dependence.
/// getDistance - Returns the distance (or NULL) associated with a
/// particular level.
/// getDistance - Returns the distance (or NULL) associated with a
/// particular level.
- virtual const SCEV *getDistance(unsigned Level) const { return NULL; }
+ virtual const SCEV *getDistance(unsigned Level) const { return nullptr; }
/// isPeelFirst - Returns true if peeling the first iteration from
/// this loop will break this dependence.
/// isPeelFirst - Returns true if peeling the first iteration from
/// this loop will break this dependence.
bool runOnFunction(Function &F) override;
void releaseMemory() override;
void getAnalysisUsage(AnalysisUsage &) const override;
bool runOnFunction(Function &F) override;
void releaseMemory() override;
void getAnalysisUsage(AnalysisUsage &) const override;
- void print(raw_ostream &, const Module * = 0) const override;
+ void print(raw_ostream &, const Module * = nullptr) const override;
}; // class DependenceAnalysis
/// createDependenceAnalysisPass - This creates an instance of the
}; // class DependenceAnalysis
/// createDependenceAnalysisPass - This creates an instance of the
/// print - Convert to human readable form
///
/// print - Convert to human readable form
///
- void print(raw_ostream &OS, const Module* = 0) const override;
+ void print(raw_ostream &OS, const Module* = nullptr) const override;
/// dump - Dump the dominance frontier to dbgs().
void dump() const;
/// dump - Dump the dominance frontier to dbgs().
void dump() const;
return Processed.count(Inst);
}
return Processed.count(Inst);
}
- void print(raw_ostream &OS, const Module* = 0) const override;
+ void print(raw_ostream &OS, const Module* = nullptr) const override;
/// dump - This method is used for debugging.
void dump() const;
/// dump - This method is used for debugging.
void dump() const;
public:
static char ID; // Pass identification, replacement for typeid
public:
static char ID; // Pass identification, replacement for typeid
- IntervalPartition() : FunctionPass(ID), RootInterval(0) {
+ IntervalPartition() : FunctionPass(ID), RootInterval(nullptr) {
initializeIntervalPartitionPass(*PassRegistry::getPassRegistry());
}
initializeIntervalPartitionPass(*PassRegistry::getPassRegistry());
}
IntervalPartition(IntervalPartition &I, bool);
// print - Show contents in human readable format...
IntervalPartition(IntervalPartition &I, bool);
// print - Show contents in human readable format...
- void print(raw_ostream &O, const Module* = 0) const override;
+ void print(raw_ostream &O, const Module* = nullptr) const override;
// getRootInterval() - Return the root interval that contains the starting
// block of the function.
// getRootInterval() - Return the root interval that contains the starting
// block of the function.
// getBlockInterval - Return the interval that a basic block exists in.
inline Interval *getBlockInterval(BasicBlock *BB) {
IntervalMapTy::iterator I = IntervalMap.find(BB);
// getBlockInterval - Return the interval that a basic block exists in.
inline Interval *getBlockInterval(BasicBlock *BB) {
IntervalMapTy::iterator I = IntervalMap.find(BB);
- return I != IntervalMap.end() ? I->second : 0;
+ return I != IntervalMap.end() ? I->second : nullptr;
}
// getAnalysisUsage - Implement the Pass API
}
// getAnalysisUsage - Implement the Pass API
void operator=(const LazyValueInfo&) LLVM_DELETED_FUNCTION;
public:
static char ID;
void operator=(const LazyValueInfo&) LLVM_DELETED_FUNCTION;
public:
static char ID;
- LazyValueInfo() : FunctionPass(ID), PImpl(0) {
+ LazyValueInfo() : FunctionPass(ID), PImpl(nullptr) {
initializeLazyValueInfoPass(*PassRegistry::getPassRegistry());
}
initializeLazyValueInfoPass(*PassRegistry::getPassRegistry());
}
- ~LazyValueInfo() { assert(PImpl == 0 && "releaseMemory not called"); }
+ ~LazyValueInfo() { assert(!PImpl && "releaseMemory not called"); }
/// Tristate - This is used to return true/false/dunno results.
enum Tristate {
/// Tristate - This is used to return true/false/dunno results.
enum Tristate {
- explicit LibCallAliasAnalysis(LibCallInfo *LC = 0)
+ explicit LibCallAliasAnalysis(LibCallInfo *LC = nullptr)
: FunctionPass(ID), LCI(LC) {
initializeLibCallAliasAnalysisPass(*PassRegistry::getPassRegistry());
}
: FunctionPass(ID), LCI(LC) {
initializeLibCallAliasAnalysisPass(*PassRegistry::getPassRegistry());
}
mutable const LibCallLocationInfo *Locations;
mutable unsigned NumLocations;
public:
mutable const LibCallLocationInfo *Locations;
mutable unsigned NumLocations;
public:
- LibCallInfo() : Impl(0), Locations(0), NumLocations(0) {}
+ LibCallInfo() : Impl(nullptr), Locations(nullptr), NumLocations(0) {}
virtual ~LibCallInfo();
//===------------------------------------------------------------------===//
virtual ~LibCallInfo();
//===------------------------------------------------------------------===//
/// specified pointer, we do a quick local scan of the basic block containing
/// ScanFrom, to determine if the address is already accessed.
bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom,
/// specified pointer, we do a quick local scan of the basic block containing
/// ScanFrom, to determine if the address is already accessed.
bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom,
- unsigned Align, const DataLayout *TD = 0);
+ unsigned Align,
+ const DataLayout *TD = nullptr);
/// FindAvailableLoadedValue - Scan the ScanBB block backwards (starting at
/// the instruction before ScanFrom) checking to see if we have the value at
/// FindAvailableLoadedValue - Scan the ScanBB block backwards (starting at
/// the instruction before ScanFrom) checking to see if we have the value at
Value *FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
BasicBlock::iterator &ScanFrom,
unsigned MaxInstsToScan = 6,
Value *FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
BasicBlock::iterator &ScanFrom,
unsigned MaxInstsToScan = 6,
- AliasAnalysis *AA = 0,
- MDNode **TBAATag = 0);
+ AliasAnalysis *AA = nullptr,
+ MDNode **TBAATag = nullptr);
bool RoundToAlign;
SizeOffsetEvalType unknown() {
bool RoundToAlign;
SizeOffsetEvalType unknown() {
- return std::make_pair((Value*)0, (Value*)0);
+ return std::make_pair(nullptr, nullptr);
}
SizeOffsetEvalType compute_(Value *V);
}
SizeOffsetEvalType compute_(Value *V);
PairTy Value;
explicit MemDepResult(PairTy V) : Value(V) {}
public:
PairTy Value;
explicit MemDepResult(PairTy V) : Value(V) {}
public:
- MemDepResult() : Value(0, Invalid) {}
+ MemDepResult() : Value(nullptr, Invalid) {}
/// get methods: These are static ctor methods for creating various
/// MemDepResult kinds.
/// get methods: These are static ctor methods for creating various
/// MemDepResult kinds.
/// getInst() - If this is a normal dependency, return the instruction that
/// is depended on. Otherwise, return null.
Instruction *getInst() const {
/// getInst() - If this is a normal dependency, return the instruction that
/// is depended on. Otherwise, return null.
Instruction *getInst() const {
- if (Value.getInt() == Other) return NULL;
+ if (Value.getInt() == Other) return nullptr;
return Value.getPointer();
}
return Value.getPointer();
}
/// pointer. May be null if there are no tags or conflicting tags.
const MDNode *TBAATag;
/// pointer. May be null if there are no tags or conflicting tags.
const MDNode *TBAATag;
- NonLocalPointerInfo() : Size(AliasAnalysis::UnknownSize), TBAATag(0) {}
+ NonLocalPointerInfo()
+ : Size(AliasAnalysis::UnknownSize), TBAATag(nullptr) {}
};
/// CachedNonLocalPointerInfo - This map stores the cached results of doing
};
/// CachedNonLocalPointerInfo - This map stores the cached results of doing
bool isLoad,
BasicBlock::iterator ScanIt,
BasicBlock *BB,
bool isLoad,
BasicBlock::iterator ScanIt,
BasicBlock *BB,
- Instruction *QueryInst = 0);
+ Instruction *QueryInst = nullptr);
/// getLoadLoadClobberFullWidthSize - This is a little bit of analysis that
/// getLoadLoadClobberFullWidthSize - This is a little bit of analysis that
/// InstInputs - The inputs for our symbolic address.
SmallVector<Instruction*, 4> InstInputs;
public:
/// InstInputs - The inputs for our symbolic address.
SmallVector<Instruction*, 4> InstInputs;
public:
- PHITransAddr(Value *addr, const DataLayout *DL) : Addr(addr), DL(DL), TLI(0) {
+ PHITransAddr(Value *addr, const DataLayout *DL)
+ : Addr(addr), DL(DL), TLI(nullptr) {
// If the address is an instruction, the whole thing is considered an input.
if (Instruction *I = dyn_cast<Instruction>(Addr))
InstInputs.push_back(I);
// If the address is an instruction, the whole thing is considered an input.
if (Instruction *I = dyn_cast<Instruction>(Addr))
InstInputs.push_back(I);
/// analysis and whether the visit completed or aborted early.
class PtrInfo {
public:
/// analysis and whether the visit completed or aborted early.
class PtrInfo {
public:
- PtrInfo() : AbortedInfo(0, false), EscapedInfo(0, false) {}
+ PtrInfo() : AbortedInfo(nullptr, false), EscapedInfo(nullptr, false) {}
/// \brief Reset the pointer info, clearing all state.
void reset() {
/// \brief Reset the pointer info, clearing all state.
void reset() {
- AbortedInfo.setPointer(0);
+ AbortedInfo.setPointer(nullptr);
AbortedInfo.setInt(false);
AbortedInfo.setInt(false);
- EscapedInfo.setPointer(0);
+ EscapedInfo.setPointer(nullptr);
EscapedInfo.setInt(false);
}
EscapedInfo.setInt(false);
}
/// \brief Mark the visit as aborted. Intended for use in a void return.
/// \param I The instruction which caused the visit to abort, if available.
/// \brief Mark the visit as aborted. Intended for use in a void return.
/// \param I The instruction which caused the visit to abort, if available.
- void setAborted(Instruction *I = 0) {
+ void setAborted(Instruction *I = nullptr) {
AbortedInfo.setInt(true);
AbortedInfo.setPointer(I);
}
/// \brief Mark the pointer as escaped. Intended for use in a void return.
/// \param I The instruction which escapes the pointer, if available.
AbortedInfo.setInt(true);
AbortedInfo.setPointer(I);
}
/// \brief Mark the pointer as escaped. Intended for use in a void return.
/// \param I The instruction which escapes the pointer, if available.
- void setEscaped(Instruction *I = 0) {
+ void setEscaped(Instruction *I = nullptr) {
EscapedInfo.setInt(true);
EscapedInfo.setPointer(I);
}
EscapedInfo.setInt(true);
EscapedInfo.setPointer(I);
}
/// for use in a void return.
/// \param I The instruction which both escapes the pointer and aborts the
/// visit, if available.
/// for use in a void return.
/// \param I The instruction which both escapes the pointer and aborts the
/// visit, if available.
- void setEscapedAndAborted(Instruction *I = 0) {
+ void setEscapedAndAborted(Instruction *I = nullptr) {
setEscaped(I);
setAborted(I);
}
setEscaped(I);
setAborted(I);
}
/// @param Parent The surrounding region or NULL if this is a top level
/// region.
Region(BasicBlock *Entry, BasicBlock *Exit, RegionInfo* RI,
/// @param Parent The surrounding region or NULL if this is a top level
/// region.
Region(BasicBlock *Entry, BasicBlock *Exit, RegionInfo* RI,
- DominatorTree *DT, Region *Parent = 0);
+ DominatorTree *DT, Region *Parent = nullptr);
/// Delete the Region and all its subregions.
~Region();
/// Delete the Region and all its subregions.
~Region();
/// @brief Check if a Region is the TopLevel region.
///
/// The toplevel region represents the whole function.
/// @brief Check if a Region is the TopLevel region.
///
/// The toplevel region represents the whole function.
- bool isTopLevelRegion() const { return exit == NULL; }
+ bool isTopLevelRegion() const { return exit == nullptr; }
/// @brief Return a new (non-canonical) region, that is obtained by joining
/// this region with its predecessors.
/// @brief Return a new (non-canonical) region, that is obtained by joining
/// this region with its predecessors.
}
// Construct the end iterator.
}
// Construct the end iterator.
- block_iterator_wrapper() : super(df_end<pointer>((BasicBlock *)0)) {}
+ block_iterator_wrapper() : super(df_end<pointer>((BasicBlock *)nullptr)) {}
/*implicit*/ block_iterator_wrapper(super I) : super(I) {}
/*implicit*/ block_iterator_wrapper(super I) : super(I) {}
void deleted() override;
void allUsesReplacedWith(Value *New) override;
public:
void deleted() override;
void allUsesReplacedWith(Value *New) override;
public:
- SCEVCallbackVH(Value *V, ScalarEvolution *SE = 0);
+ SCEVCallbackVH(Value *V, ScalarEvolution *SE = nullptr);
};
friend class SCEVCallbackVH;
};
friend class SCEVCallbackVH;
const SCEV *ExactNotTaken;
PointerIntPair<ExitNotTakenInfo*, 1> NextExit;
const SCEV *ExactNotTaken;
PointerIntPair<ExitNotTakenInfo*, 1> NextExit;
- ExitNotTakenInfo() : ExitingBlock(0), ExactNotTaken(0) {}
+ ExitNotTakenInfo() : ExitingBlock(nullptr), ExactNotTaken(nullptr) {}
/// isCompleteList - Return true if all loop exits are computable.
bool isCompleteList() const {
/// isCompleteList - Return true if all loop exits are computable.
bool isCompleteList() const {
- BackedgeTakenInfo() : Max(0) {}
+ BackedgeTakenInfo() : Max(nullptr) {}
/// Initialize BackedgeTakenInfo from a list of exact exit counts.
BackedgeTakenInfo(
/// Initialize BackedgeTakenInfo from a list of exact exit counts.
BackedgeTakenInfo(
bool runOnFunction(Function &F) override;
void releaseMemory() override;
void getAnalysisUsage(AnalysisUsage &AU) const override;
bool runOnFunction(Function &F) override;
void releaseMemory() override;
void getAnalysisUsage(AnalysisUsage &AU) const override;
- void print(raw_ostream &OS, const Module* = 0) const override;
+ void print(raw_ostream &OS, const Module* = nullptr) const override;
void verifyAnalysis() const override;
private:
void verifyAnalysis() const override;
private:
public:
/// SCEVExpander - Construct a SCEVExpander in "canonical" mode.
explicit SCEVExpander(ScalarEvolution &se, const char *name)
public:
/// SCEVExpander - Construct a SCEVExpander in "canonical" mode.
explicit SCEVExpander(ScalarEvolution &se, const char *name)
- : SE(se), IVName(name), IVIncInsertLoop(0), IVIncInsertPos(0),
+ : SE(se), IVName(name), IVIncInsertLoop(nullptr), IVIncInsertPos(nullptr),
CanonicalMode(true), LSRMode(false),
Builder(se.getContext(), TargetFolder(se.DL)) {
#ifndef NDEBUG
CanonicalMode(true), LSRMode(false),
Builder(se.getContext(), TargetFolder(se.DL)) {
#ifndef NDEBUG
/// representative. Return the number of phis eliminated.
unsigned replaceCongruentIVs(Loop *L, const DominatorTree *DT,
SmallVectorImpl<WeakVH> &DeadInsts,
/// representative. Return the number of phis eliminated.
unsigned replaceCongruentIVs(Loop *L, const DominatorTree *DT,
SmallVectorImpl<WeakVH> &DeadInsts,
- const TargetTransformInfo *TTI = NULL);
+ const TargetTransformInfo *TTI = nullptr);
/// expandCodeFor - Insert code to directly compute the specified SCEV
/// expression into the program. The inserted code is inserted into the
/// expandCodeFor - Insert code to directly compute the specified SCEV
/// expression into the program. The inserted code is inserted into the
/// expression into the program. The inserted code is inserted into the
/// SCEVExpander's current insertion point. If a type is specified, the
/// result will be expanded to have that type, with a cast if necessary.
/// expression into the program. The inserted code is inserted into the
/// SCEVExpander's current insertion point. If a type is specified, the
/// result will be expanded to have that type, with a cast if necessary.
- Value *expandCodeFor(const SCEV *SH, Type *Ty = 0);
+ Value *expandCodeFor(const SCEV *SH, Type *Ty = nullptr);
/// getRelevantLoop - Determine the most "relevant" loop for the given SCEV.
const Loop *getRelevantLoop(const SCEV *);
/// getRelevantLoop - Determine the most "relevant" loop for the given SCEV.
const Loop *getRelevantLoop(const SCEV *);
/// constant value, return it. Otherwise return null. The returned value
/// must be in the same LLVM type as Val.
virtual Constant *GetConstant(LatticeVal LV, Value *Val, SparseSolver &SS) {
/// constant value, return it. Otherwise return null. The returned value
/// must be in the same LLVM type as Val.
virtual Constant *GetConstant(LatticeVal LV, Value *Val, SparseSolver &SS) {
}
/// ComputeArgument - Given a formal argument value, compute and return a
}
/// ComputeArgument - Given a formal argument value, compute and return a
if (Entry) return Entry;
SmallVector<BasicBlock*, 32> PredCache(pred_begin(BB), pred_end(BB));
if (Entry) return Entry;
SmallVector<BasicBlock*, 32> PredCache(pred_begin(BB), pred_end(BB));
- PredCache.push_back(0); // null terminator.
+ PredCache.push_back(nullptr); // null terminator.
BlockToPredCountMap[BB] = PredCache.size()-1;
BlockToPredCountMap[BB] = PredCache.size()-1;
///
void AliasAnalysis::InitializeAliasAnalysis(Pass *P) {
DataLayoutPass *DLP = P->getAnalysisIfAvailable<DataLayoutPass>();
///
void AliasAnalysis::InitializeAliasAnalysis(Pass *P) {
DataLayoutPass *DLP = P->getAnalysisIfAvailable<DataLayoutPass>();
- DL = DLP ? &DLP->getDataLayout() : 0;
+ DL = DLP ? &DLP->getDataLayout() : nullptr;
TLI = P->getAnalysisIfAvailable<TargetLibraryInfo>();
AA = &P->getAnalysis<AliasAnalysis>();
}
TLI = P->getAnalysisIfAvailable<TargetLibraryInfo>();
AA = &P->getAnalysis<AliasAnalysis>();
}
AliasAnalysisCounter::alias(const Location &LocA, const Location &LocB) {
AliasResult R = getAnalysis<AliasAnalysis>().alias(LocA, LocB);
AliasAnalysisCounter::alias(const Location &LocA, const Location &LocB) {
AliasResult R = getAnalysis<AliasAnalysis>().alias(LocA, LocB);
- const char *AliasString = 0;
+ const char *AliasString = nullptr;
switch (R) {
case NoAlias: No++; AliasString = "No alias"; break;
case MayAlias: May++; AliasString = "May alias"; break;
switch (R) {
case NoAlias: No++; AliasString = "No alias"; break;
case MayAlias: May++; AliasString = "May alias"; break;
const Location &Loc) {
ModRefResult R = getAnalysis<AliasAnalysis>().getModRefInfo(CS, Loc);
const Location &Loc) {
ModRefResult R = getAnalysis<AliasAnalysis>().getModRefInfo(CS, Loc);
- const char *MRString = 0;
+ const char *MRString = nullptr;
switch (R) {
case NoModRef: NoMR++; MRString = "NoModRef"; break;
case Ref: JustRef++; MRString = "JustRef"; break;
switch (R) {
case NoModRef: NoMR++; MRString = "NoModRef"; break;
case Ref: JustRef++; MRString = "JustRef"; break;
AS.PtrList->setPrevInList(PtrListEnd);
PtrListEnd = AS.PtrListEnd;
AS.PtrList->setPrevInList(PtrListEnd);
PtrListEnd = AS.PtrListEnd;
AS.PtrListEnd = &AS.PtrList;
AS.PtrListEnd = &AS.PtrList;
- assert(*AS.PtrListEnd == 0 && "End of list is not null?");
+ assert(*AS.PtrListEnd == nullptr && "End of list is not null?");
}
}
void AliasSetTracker::removeAliasSet(AliasSet *AS) {
if (AliasSet *Fwd = AS->Forward) {
Fwd->dropRef(*this);
}
}
void AliasSetTracker::removeAliasSet(AliasSet *AS) {
if (AliasSet *Fwd = AS->Forward) {
Fwd->dropRef(*this);
Entry.updateSizeAndTBAAInfo(Size, TBAAInfo);
// Add it to the end of the list...
Entry.updateSizeAndTBAAInfo(Size, TBAAInfo);
// Add it to the end of the list...
- assert(*PtrListEnd == 0 && "End of list is not null?");
+ assert(*PtrListEnd == nullptr && "End of list is not null?");
*PtrListEnd = &Entry;
PtrListEnd = Entry.setPrevInList(PtrListEnd);
*PtrListEnd = &Entry;
PtrListEnd = Entry.setPrevInList(PtrListEnd);
- assert(*PtrListEnd == 0 && "End of list is not null?");
+ assert(*PtrListEnd == nullptr && "End of list is not null?");
addRef(); // Entry points to alias set.
}
addRef(); // Entry points to alias set.
}
AliasSet *AliasSetTracker::findAliasSetForPointer(const Value *Ptr,
uint64_t Size,
const MDNode *TBAAInfo) {
AliasSet *AliasSetTracker::findAliasSetForPointer(const Value *Ptr,
uint64_t Size,
const MDNode *TBAAInfo) {
- AliasSet *FoundSet = 0;
+ AliasSet *FoundSet = nullptr;
for (iterator I = begin(), E = end(); I != E; ++I) {
if (I->Forward || !I->aliasesPointer(Ptr, Size, TBAAInfo, AA)) continue;
for (iterator I = begin(), E = end(); I != E; ++I) {
if (I->Forward || !I->aliasesPointer(Ptr, Size, TBAAInfo, AA)) continue;
- if (FoundSet == 0) { // If this is the first alias set ptr can go into.
+ if (!FoundSet) { // If this is the first alias set ptr can go into.
FoundSet = I; // Remember it.
} else { // Otherwise, we must merge the sets.
FoundSet->mergeSetIn(*I, *this); // Merge in contents.
FoundSet = I; // Remember it.
} else { // Otherwise, we must merge the sets.
FoundSet->mergeSetIn(*I, *this); // Merge in contents.
AliasSet *AliasSetTracker::findAliasSetForUnknownInst(Instruction *Inst) {
AliasSet *AliasSetTracker::findAliasSetForUnknownInst(Instruction *Inst) {
- AliasSet *FoundSet = 0;
+ AliasSet *FoundSet = nullptr;
for (iterator I = begin(), E = end(); I != E; ++I) {
if (I->Forward || !I->aliasesUnknownInst(Inst, AA))
continue;
for (iterator I = begin(), E = end(); I != E; ++I) {
if (I->Forward || !I->aliasesUnknownInst(Inst, AA))
continue;
- if (FoundSet == 0) // If this is the first alias set ptr can go into.
+ if (!FoundSet) // If this is the first alias set ptr can go into.
FoundSet = I; // Remember it.
else if (!I->Forward) // Otherwise, we must merge the sets.
FoundSet->mergeSetIn(*I, *this); // Merge in contents.
FoundSet = I; // Remember it.
else if (!I->Forward) // Otherwise, we must merge the sets.
FoundSet->mergeSetIn(*I, *this); // Merge in contents.
LLVMBool LLVMVerifyModule(LLVMModuleRef M, LLVMVerifierFailureAction Action,
char **OutMessages) {
LLVMBool LLVMVerifyModule(LLVMModuleRef M, LLVMVerifierFailureAction Action,
char **OutMessages) {
- raw_ostream *DebugOS = Action != LLVMReturnStatusAction ? &errs() : 0;
+ raw_ostream *DebugOS = Action != LLVMReturnStatusAction ? &errs() : nullptr;
std::string Messages;
raw_string_ostream MsgsOS(Messages);
std::string Messages;
raw_string_ostream MsgsOS(Messages);
LLVMBool LLVMVerifyFunction(LLVMValueRef Fn, LLVMVerifierFailureAction Action) {
LLVMBool Result = verifyFunction(
LLVMBool LLVMVerifyFunction(LLVMValueRef Fn, LLVMVerifierFailureAction Action) {
LLVMBool Result = verifyFunction(
- *unwrap<Function>(Fn), Action != LLVMReturnStatusAction ? &errs() : 0);
+ *unwrap<Function>(Fn), Action != LLVMReturnStatusAction ? &errs()
+ : nullptr);
if (Action == LLVMAbortProcessAction && Result)
report_fatal_error("Broken function found, compilation aborted!");
if (Action == LLVMAbortProcessAction && Result)
report_fatal_error("Broken function found, compilation aborted!");
do {
// See if this is a bitcast or GEP.
const Operator *Op = dyn_cast<Operator>(V);
do {
// See if this is a bitcast or GEP.
const Operator *Op = dyn_cast<Operator>(V);
// The only non-operator case we can handle are GlobalAliases.
if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
if (!GA->mayBeOverridden()) {
// The only non-operator case we can handle are GlobalAliases.
if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
if (!GA->mayBeOverridden()) {
}
const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
}
const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
// If it's not a GEP, hand it off to SimplifyInstruction to see if it
// can come up with something. This matches what GetUnderlyingObject does.
if (const Instruction *I = dyn_cast<Instruction>(V))
// If it's not a GEP, hand it off to SimplifyInstruction to see if it
// can come up with something. This matches what GetUnderlyingObject does.
if (const Instruction *I = dyn_cast<Instruction>(V))
// If we are lacking DataLayout information, we can't compute the offets of
// elements computed by GEPs. However, we can handle bitcast equivalent
// GEPs.
// If we are lacking DataLayout information, we can't compute the offets of
// elements computed by GEPs. However, we can handle bitcast equivalent
// GEPs.
if (!GEPOp->hasAllZeroIndices())
return V;
V = GEPOp->getOperand(0);
if (!GEPOp->hasAllZeroIndices())
return V;
V = GEPOp->getOperand(0);
if (const Argument *arg = dyn_cast<Argument>(V))
return arg->getParent();
if (const Argument *arg = dyn_cast<Argument>(V))
return arg->getParent();
}
static bool notDifferentParent(const Value *O1, const Value *O2) {
}
static bool notDifferentParent(const Value *O1, const Value *O2) {
// Finally, handle specific knowledge of intrinsics.
const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
// Finally, handle specific knowledge of intrinsics.
const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
switch (II->getIntrinsicID()) {
default: break;
case Intrinsic::memcpy:
switch (II->getIntrinsicID()) {
default: break;
case Intrinsic::memcpy:
// derived pointer.
if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
// Do the base pointers alias?
// derived pointer.
if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
// Do the base pointers alias?
- AliasResult BaseAlias = aliasCheck(UnderlyingV1, UnknownSize, 0,
- UnderlyingV2, UnknownSize, 0);
+ AliasResult BaseAlias = aliasCheck(UnderlyingV1, UnknownSize, nullptr,
+ UnderlyingV2, UnknownSize, nullptr);
// Check for geps of non-aliasing underlying pointers where the offsets are
// identical.
// Check for geps of non-aliasing underlying pointers where the offsets are
// identical.
// DecomposeGEPExpression and GetUnderlyingObject should return the
// same result except when DecomposeGEPExpression has no DataLayout.
if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
// DecomposeGEPExpression and GetUnderlyingObject should return the
// same result except when DecomposeGEPExpression has no DataLayout.
if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
- assert(DL == 0 &&
- "DecomposeGEPExpression and GetUnderlyingObject disagree!");
+ assert(!DL &&
+ "DecomposeGEPExpression and GetUnderlyingObject disagree!");
return MayAlias;
}
// If the max search depth is reached the result is undefined
return MayAlias;
}
// If the max search depth is reached the result is undefined
// DecomposeGEPExpression and GetUnderlyingObject should return the
// same result except when DecomposeGEPExpression has no DataLayout.
if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
// DecomposeGEPExpression and GetUnderlyingObject should return the
// same result except when DecomposeGEPExpression has no DataLayout.
if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
"DecomposeGEPExpression and GetUnderlyingObject disagree!");
return MayAlias;
}
"DecomposeGEPExpression and GetUnderlyingObject disagree!");
return MayAlias;
}
if (V1Size == UnknownSize && V2Size == UnknownSize)
return MayAlias;
if (V1Size == UnknownSize && V2Size == UnknownSize)
return MayAlias;
- AliasResult R = aliasCheck(UnderlyingV1, UnknownSize, 0,
+ AliasResult R = aliasCheck(UnderlyingV1, UnknownSize, nullptr,
V2, V2Size, V2TBAAInfo);
if (R != MustAlias)
// If V2 may alias GEP base pointer, conservatively returns MayAlias.
V2, V2Size, V2TBAAInfo);
if (R != MustAlias)
// If V2 may alias GEP base pointer, conservatively returns MayAlias.
// DecomposeGEPExpression and GetUnderlyingObject should return the
// same result except when DecomposeGEPExpression has no DataLayout.
if (GEP1BasePtr != UnderlyingV1) {
// DecomposeGEPExpression and GetUnderlyingObject should return the
// same result except when DecomposeGEPExpression has no DataLayout.
if (GEP1BasePtr != UnderlyingV1) {
"DecomposeGEPExpression and GetUnderlyingObject disagree!");
return MayAlias;
}
"DecomposeGEPExpression and GetUnderlyingObject disagree!");
return MayAlias;
}
// Use dominance or loop info if available.
DominatorTreeWrapperPass *DTWP =
getAnalysisIfAvailable<DominatorTreeWrapperPass>();
// Use dominance or loop info if available.
DominatorTreeWrapperPass *DTWP =
getAnalysisIfAvailable<DominatorTreeWrapperPass>();
- DominatorTree *DT = DTWP ? &DTWP->getDomTree() : 0;
+ DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
LoopInfo *LI = getAnalysisIfAvailable<LoopInfo>();
// Make sure that the visited phis cannot reach the Value. This ensures that
LoopInfo *LI = getAnalysisIfAvailable<LoopInfo>();
// Make sure that the visited phis cannot reach the Value. This ensures that
BasicBlock *BranchProbabilityInfo::getHotSucc(BasicBlock *BB) const {
uint32_t Sum = 0;
uint32_t MaxWeight = 0;
BasicBlock *BranchProbabilityInfo::getHotSucc(BasicBlock *BB) const {
uint32_t Sum = 0;
uint32_t MaxWeight = 0;
- BasicBlock *MaxSucc = 0;
+ BasicBlock *MaxSucc = nullptr;
for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
BasicBlock *Succ = *I;
for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
BasicBlock *Succ = *I;
if (BranchProbability(MaxWeight, Sum) > BranchProbability(4, 5))
return MaxSucc;
if (BranchProbability(MaxWeight, Sum) > BranchProbability(4, 5))
return MaxSucc;
}
/// Get the raw edge weight for the edge. If can't find it, return
}
/// Get the raw edge weight for the edge. If can't find it, return
const BasicBlock *BB1, const BasicBlock *BB2) {
const Loop *L1 = getOutermostLoop(LI, BB1);
const Loop *L2 = getOutermostLoop(LI, BB2);
const BasicBlock *BB1, const BasicBlock *BB2) {
const Loop *L1 = getOutermostLoop(LI, BB1);
const Loop *L2 = getOutermostLoop(LI, BB2);
- return L1 != NULL && L1 == L2;
+ return L1 != nullptr && L1 == L2;
}
static bool isPotentiallyReachableInner(SmallVectorImpl<BasicBlock *> &Worklist,
}
static bool isPotentiallyReachableInner(SmallVectorImpl<BasicBlock *> &Worklist,
// When the stop block is unreachable, it's dominated from everywhere,
// regardless of whether there's a path between the two blocks.
if (DT && !DT->isReachableFromEntry(StopBB))
// When the stop block is unreachable, it's dominated from everywhere,
// regardless of whether there's a path between the two blocks.
if (DT && !DT->isReachableFromEntry(StopBB))
// Limit the number of blocks we visit. The goal is to avoid run-away compile
// times on large CFGs without hampering sensible code. Arbitrarily chosen.
// Limit the number of blocks we visit. The goal is to avoid run-away compile
// times on large CFGs without hampering sensible code. Arbitrarily chosen.
- if (const Loop *Outer = LI ? getOutermostLoop(LI, BB) : 0) {
+ if (const Loop *Outer = LI ? getOutermostLoop(LI, BB) : nullptr) {
// All blocks in a single loop are reachable from all other blocks. From
// any of these blocks, we can skip directly to the exits of the loop,
// ignoring any other blocks inside the loop body.
// All blocks in a single loop are reachable from all other blocks. From
// any of these blocks, we can skip directly to the exits of the loop,
// ignoring any other blocks inside the loop body.
// If the block is in a loop then we can reach any instruction in the block
// from any other instruction in the block by going around a backedge.
// If the block is in a loop then we can reach any instruction in the block
// from any other instruction in the block by going around a backedge.
- if (LI && LI->getLoopFor(BB) != 0)
+ if (LI && LI->getLoopFor(BB) != nullptr)
return true;
// Linear scan, start at 'A', see whether we hit 'B' or the end first.
return true;
// Linear scan, start at 'A', see whether we hit 'B' or the end first.
- void print(raw_ostream &OS, const Module* = 0) const override {}
+ void print(raw_ostream &OS, const Module* = nullptr) const override {}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesAll();
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesAll();
- void print(raw_ostream &OS, const Module* = 0) const override {}
+ void print(raw_ostream &OS, const Module* = nullptr) const override {}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesAll();
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesAll();
- void print(raw_ostream &OS, const Module* = 0) const override {}
+ void print(raw_ostream &OS, const Module* = nullptr) const override {}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesAll();
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesAll();
errs() << "\n";
return false;
}
errs() << "\n";
return false;
}
- void print(raw_ostream &OS, const Module* = 0) const override {}
+ void print(raw_ostream &OS, const Module* = nullptr) const override {}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesAll();
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesAll();
// Handle a vector->integer cast.
if (IntegerType *IT = dyn_cast<IntegerType>(DestTy)) {
VectorType *VTy = dyn_cast<VectorType>(C->getType());
// Handle a vector->integer cast.
if (IntegerType *IT = dyn_cast<IntegerType>(DestTy)) {
VectorType *VTy = dyn_cast<VectorType>(C->getType());
return ConstantExpr::getBitCast(C, DestTy);
unsigned NumSrcElts = VTy->getNumElements();
return ConstantExpr::getBitCast(C, DestTy);
unsigned NumSrcElts = VTy->getNumElements();
}
ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
}
ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
return ConstantExpr::getBitCast(C, DestTy);
// Now that we know that the input value is a vector of integers, just shift
return ConstantExpr::getBitCast(C, DestTy);
// Now that we know that the input value is a vector of integers, just shift
// The code below only handles casts to vectors currently.
VectorType *DestVTy = dyn_cast<VectorType>(DestTy);
// The code below only handles casts to vectors currently.
VectorType *DestVTy = dyn_cast<VectorType>(DestTy);
return ConstantExpr::getBitCast(C, DestTy);
// If this is a scalar -> vector cast, convert the input into a <1 x scalar>
return ConstantExpr::getBitCast(C, DestTy);
// If this is a scalar -> vector cast, convert the input into a <1 x scalar>
TD.getTypeAllocSizeInBits(LoadTy),
AS);
} else
TD.getTypeAllocSizeInBits(LoadTy),
AS);
} else
C = FoldBitCast(C, MapTy, TD);
if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, TD))
return FoldBitCast(Res, LoadTy, TD);
C = FoldBitCast(C, MapTy, TD);
if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, TD))
return FoldBitCast(Res, LoadTy, TD);
}
unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
if (BytesLoaded > 32 || BytesLoaded == 0)
}
unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
if (BytesLoaded > 32 || BytesLoaded == 0)
GlobalValue *GVal;
APInt Offset;
if (!IsConstantOffsetFromGlobal(C, GVal, Offset, TD))
GlobalValue *GVal;
APInt Offset;
if (!IsConstantOffsetFromGlobal(C, GVal, Offset, TD))
GlobalVariable *GV = dyn_cast<GlobalVariable>(GVal);
if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
!GV->getInitializer()->getType()->isSized())
GlobalVariable *GV = dyn_cast<GlobalVariable>(GVal);
if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
!GV->getInitializer()->getType()->isSized())
// If we're loading off the beginning of the global, some bytes may be valid,
// but we don't try to handle this.
if (Offset.isNegative())
// If we're loading off the beginning of the global, some bytes may be valid,
// but we don't try to handle this.
if (Offset.isNegative())
// If we're not accessing anything in this constant, the result is undefined.
if (Offset.getZExtValue() >=
// If we're not accessing anything in this constant, the result is undefined.
if (Offset.getZExtValue() >=
unsigned char RawBytes[32] = {0};
if (!ReadDataFromGlobal(GV->getInitializer(), Offset.getZExtValue(), RawBytes,
BytesLoaded, TD))
unsigned char RawBytes[32] = {0};
if (!ReadDataFromGlobal(GV->getInitializer(), Offset.getZExtValue(), RawBytes,
BytesLoaded, TD))
APInt ResultVal = APInt(IntType->getBitWidth(), 0);
if (TD.isLittleEndian()) {
APInt ResultVal = APInt(IntType->getBitWidth(), 0);
if (TD.isLittleEndian()) {
// If the loaded value isn't a constant expr, we can't handle it.
ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
if (!CE)
// If the loaded value isn't a constant expr, we can't handle it.
ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
if (!CE)
if (CE->getOpcode() == Instruction::GetElementPtr) {
if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
if (CE->getOpcode() == Instruction::GetElementPtr) {
if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
// Try hard to fold loads from bitcasted strange and non-type-safe things.
if (TD)
return FoldReinterpretLoadFromConstPtr(CE, *TD);
// Try hard to fold loads from bitcasted strange and non-type-safe things.
if (TD)
return FoldReinterpretLoadFromConstPtr(CE, *TD);
}
static Constant *ConstantFoldLoadInst(const LoadInst *LI, const DataLayout *TD){
}
static Constant *ConstantFoldLoadInst(const LoadInst *LI, const DataLayout *TD){
- if (LI->isVolatile()) return 0;
+ if (LI->isVolatile()) return nullptr;
if (Constant *C = dyn_cast<Constant>(LI->getOperand(0)))
return ConstantFoldLoadFromConstPtr(C, TD);
if (Constant *C = dyn_cast<Constant>(LI->getOperand(0)))
return ConstantFoldLoadFromConstPtr(C, TD);
}
/// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
}
/// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
}
/// CastGEPIndices - If array indices are not pointer-sized integers,
}
/// CastGEPIndices - If array indices are not pointer-sized integers,
Type *ResultTy, const DataLayout *TD,
const TargetLibraryInfo *TLI) {
if (!TD)
Type *ResultTy, const DataLayout *TD,
const TargetLibraryInfo *TLI) {
if (!TD)
Type *IntPtrTy = TD->getIntPtrType(ResultTy);
Type *IntPtrTy = TD->getIntPtrType(ResultTy);
Constant *C = ConstantExpr::getGetElementPtr(Ops[0], NewIdxs);
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Constant *C = ConstantExpr::getGetElementPtr(Ops[0], NewIdxs);
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Constant *Ptr = Ops[0];
if (!TD || !Ptr->getType()->getPointerElementType()->isSized() ||
!Ptr->getType()->isPointerTy())
Constant *Ptr = Ops[0];
if (!TD || !Ptr->getType()->getPointerElementType()->isSized() ||
!Ptr->getType()->isPointerTy())
Type *IntPtrTy = TD->getIntPtrType(Ptr->getType());
Type *ResultElementTy = ResultTy->getPointerElementType();
Type *IntPtrTy = TD->getIntPtrType(Ptr->getType());
Type *ResultElementTy = ResultTy->getPointerElementType();
// "inttoptr (sub (ptrtoint Ptr), V)"
if (Ops.size() == 2 && ResultElementTy->isIntegerTy(8)) {
ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[1]);
// "inttoptr (sub (ptrtoint Ptr), V)"
if (Ops.size() == 2 && ResultElementTy->isIntegerTy(8)) {
ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[1]);
- assert((CE == 0 || CE->getType() == IntPtrTy) &&
+ assert((!CE || CE->getType() == IntPtrTy) &&
"CastGEPIndices didn't canonicalize index types!");
if (CE && CE->getOpcode() == Instruction::Sub &&
CE->getOperand(0)->isNullValue()) {
"CastGEPIndices didn't canonicalize index types!");
if (CE && CE->getOpcode() == Instruction::Sub &&
CE->getOperand(0)->isNullValue()) {
}
unsigned BitWidth = TD->getTypeSizeInBits(IntPtrTy);
}
unsigned BitWidth = TD->getTypeSizeInBits(IntPtrTy);
// Only handle pointers to sized types, not pointers to functions.
if (!ATy->getElementType()->isSized())
// Only handle pointers to sized types, not pointers to functions.
if (!ATy->getElementType()->isSized())
}
// Determine which element of the array the offset points into.
}
// Determine which element of the array the offset points into.
// type, then the offset is pointing into the middle of an indivisible
// member, so we can't simplify it.
if (Offset != 0)
// type, then the offset is pointing into the middle of an indivisible
// member, so we can't simplify it.
if (Offset != 0)
// Create a GEP.
Constant *C = ConstantExpr::getGetElementPtr(Ptr, NewIdxs);
// Create a GEP.
Constant *C = ConstantExpr::getGetElementPtr(Ptr, NewIdxs);
const TargetLibraryInfo *TLI) {
// Handle PHI nodes quickly here...
if (PHINode *PN = dyn_cast<PHINode>(I)) {
const TargetLibraryInfo *TLI) {
// Handle PHI nodes quickly here...
if (PHINode *PN = dyn_cast<PHINode>(I)) {
- Constant *CommonValue = 0;
+ Constant *CommonValue = nullptr;
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Value *Incoming = PN->getIncomingValue(i);
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Value *Incoming = PN->getIncomingValue(i);
// If the incoming value is not a constant, then give up.
Constant *C = dyn_cast<Constant>(Incoming);
if (!C)
// If the incoming value is not a constant, then give up.
Constant *C = dyn_cast<Constant>(Incoming);
if (!C)
// Fold the PHI's operands.
if (ConstantExpr *NewC = dyn_cast<ConstantExpr>(C))
C = ConstantFoldConstantExpression(NewC, TD, TLI);
// If the incoming value is a different constant to
// the one we saw previously, then give up.
if (CommonValue && C != CommonValue)
// Fold the PHI's operands.
if (ConstantExpr *NewC = dyn_cast<ConstantExpr>(C))
C = ConstantFoldConstantExpression(NewC, TD, TLI);
// If the incoming value is a different constant to
// the one we saw previously, then give up.
if (CommonValue && C != CommonValue)
for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
Constant *Op = dyn_cast<Constant>(*i);
if (!Op)
for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
Constant *Op = dyn_cast<Constant>(*i);
if (!Op)
- return 0; // All operands not constant!
+ return nullptr; // All operands not constant!
// Fold the Instruction's operands.
if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(Op))
// Fold the Instruction's operands.
if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(Op))
+ default: return nullptr;
case Instruction::ICmp:
case Instruction::FCmp: llvm_unreachable("Invalid for compares");
case Instruction::Call:
if (Function *F = dyn_cast<Function>(Ops.back()))
if (canConstantFoldCallTo(F))
return ConstantFoldCall(F, Ops.slice(0, Ops.size() - 1), TLI);
case Instruction::ICmp:
case Instruction::FCmp: llvm_unreachable("Invalid for compares");
case Instruction::Call:
if (Function *F = dyn_cast<Function>(Ops.back()))
if (canConstantFoldCallTo(F))
return ConstantFoldCall(F, Ops.slice(0, Ops.size() - 1), TLI);
case Instruction::PtrToInt:
// If the input is a inttoptr, eliminate the pair. This requires knowing
// the width of a pointer, so it can't be done in ConstantExpr::getCast.
case Instruction::PtrToInt:
// If the input is a inttoptr, eliminate the pair. This requires knowing
// the width of a pointer, so it can't be done in ConstantExpr::getCast.
Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
ConstantExpr *CE) {
if (!CE->getOperand(1)->isNullValue())
Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
ConstantExpr *CE) {
if (!CE->getOperand(1)->isNullValue())
- return 0; // Do not allow stepping over the value!
+ return nullptr; // Do not allow stepping over the value!
// Loop over all of the operands, tracking down which value we are
// addressing.
for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) {
C = C->getAggregateElement(CE->getOperand(i));
// Loop over all of the operands, tracking down which value we are
// addressing.
for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) {
C = C->getAggregateElement(CE->getOperand(i));
- if (C == 0)
- return 0;
+ if (!C)
+ return nullptr;
// addressing.
for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
C = C->getAggregateElement(Indices[i]);
// addressing.
for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
C = C->getAggregateElement(Indices[i]);
- if (C == 0)
- return 0;
+ if (!C)
+ return nullptr;
V = NativeFP(V);
if (sys::llvm_fenv_testexcept()) {
sys::llvm_fenv_clearexcept();
V = NativeFP(V);
if (sys::llvm_fenv_testexcept()) {
sys::llvm_fenv_clearexcept();
}
return GetConstantFoldFPValue(V, Ty);
}
return GetConstantFoldFPValue(V, Ty);
V = NativeFP(V, W);
if (sys::llvm_fenv_testexcept()) {
sys::llvm_fenv_clearexcept();
V = NativeFP(V, W);
if (sys::llvm_fenv_testexcept()) {
sys::llvm_fenv_clearexcept();
}
return GetConstantFoldFPValue(V, Ty);
}
return GetConstantFoldFPValue(V, Ty);
/*isSigned=*/true, mode,
&isExact);
if (status != APFloat::opOK && status != APFloat::opInexact)
/*isSigned=*/true, mode,
&isExact);
if (status != APFloat::opOK && status != APFloat::opInexact)
return ConstantInt::get(Ty, UIntVal, /*isSigned=*/true);
}
return ConstantInt::get(Ty, UIntVal, /*isSigned=*/true);
}
}
if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
}
if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
if (IntrinsicID == Intrinsic::round) {
APFloat V = Op->getValueAPF();
if (IntrinsicID == Intrinsic::round) {
APFloat V = Op->getValueAPF();
/// likely to be aborted with an exception anyway, and some host libms
/// have known errors raising exceptions.
if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
/// likely to be aborted with an exception anyway, and some host libms
/// have known errors raising exceptions.
if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
/// Currently APFloat versions of these functions do not exist, so we use
/// the host native double versions. Float versions are not called
/// Currently APFloat versions of these functions do not exist, so we use
/// the host native double versions. Float versions are not called
switch (Name[0]) {
case 'a':
switch (Name[0]) {
case 'a':
}
if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
}
if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
return ConstantFP::get(Ty->getContext(), Val);
}
default:
return ConstantFP::get(Ty->getContext(), Val);
}
default:
if (isa<UndefValue>(Operands[0])) {
if (IntrinsicID == Intrinsic::bswap)
return Operands[0];
if (isa<UndefValue>(Operands[0])) {
if (IntrinsicID == Intrinsic::bswap)
return Operands[0];
}
if (Operands.size() == 2) {
if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
}
if (Operands.size() == 2) {
if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
double Op1V = getValueAsDouble(Op1);
if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
if (Op2->getType() != Op1->getType())
double Op1V = getValueAsDouble(Op1);
if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
if (Op2->getType() != Op1->getType())
double Op2V = getValueAsDouble(Op2);
if (IntrinsicID == Intrinsic::pow) {
double Op2V = getValueAsDouble(Op2);
if (IntrinsicID == Intrinsic::pow) {
return ConstantFP::get(Ty->getContext(), V1);
}
if (!TLI)
return ConstantFP::get(Ty->getContext(), V1);
}
if (!TLI)
if (Name == "pow" && TLI->has(LibFunc::pow))
return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
if (Name == "fmod" && TLI->has(LibFunc::fmod))
if (Name == "pow" && TLI->has(LibFunc::pow))
return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
if (Name == "fmod" && TLI->has(LibFunc::fmod))
APFloat((double)std::pow((double)Op1V,
(int)Op2C->getZExtValue())));
}
APFloat((double)std::pow((double)Op1V,
(int)Op2C->getZExtValue())));
}
}
if (ConstantInt *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
}
if (ConstantInt *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
}
if (Operands.size() != 3)
}
if (Operands.size() != 3)
if (const ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
if (const ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
if (const ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
if (const ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
if (s != APFloat::opInvalidOp)
return ConstantFP::get(Ty->getContext(), V);
if (s != APFloat::opInvalidOp)
return ConstantFP::get(Ty->getContext(), V);
}
static Constant *ConstantFoldVectorCall(StringRef Name, unsigned IntrinsicID,
}
static Constant *ConstantFoldVectorCall(StringRef Name, unsigned IntrinsicID,
llvm::ConstantFoldCall(Function *F, ArrayRef<Constant *> Operands,
const TargetLibraryInfo *TLI) {
if (!F->hasName())
llvm::ConstantFoldCall(Function *F, ArrayRef<Constant *> Operands,
const TargetLibraryInfo *TLI) {
if (!F->hasName())
StringRef Name = F->getName();
Type *Ty = F->getReturnType();
StringRef Name = F->getName();
Type *Ty = F->getReturnType();
public:
static char ID; // Class identification, replacement for typeinfo
public:
static char ID; // Class identification, replacement for typeinfo
- CostModelAnalysis() : FunctionPass(ID), F(0), TTI(0) {
+ CostModelAnalysis() : FunctionPass(ID), F(nullptr), TTI(nullptr) {
initializeCostModelAnalysisPass(
*PassRegistry::getPassRegistry());
}
initializeCostModelAnalysisPass(
*PassRegistry::getPassRegistry());
}
// Check for a splat of a constant or for a non uniform vector of constants.
if (isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) {
OpInfo = TargetTransformInfo::OK_NonUniformConstantValue;
// Check for a splat of a constant or for a non uniform vector of constants.
if (isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) {
OpInfo = TargetTransformInfo::OK_NonUniformConstantValue;
- if (cast<Constant>(V)->getSplatValue() != NULL)
+ if (cast<Constant>(V)->getSplatValue() != nullptr)
OpInfo = TargetTransformInfo::OK_UniformConstantValue;
}
OpInfo = TargetTransformInfo::OK_UniformConstantValue;
}
// %rdx.shuf.0.1 = shufflevector <4 x float> %rdx, <4 x float> undef,
// <4 x i32> <i32 1, i32 3, i32 undef, i32 undef>
// %bin.rdx.0 = fadd <4 x float> %rdx.shuf.0.0, %rdx.shuf.0.1
// %rdx.shuf.0.1 = shufflevector <4 x float> %rdx, <4 x float> undef,
// <4 x i32> <i32 1, i32 3, i32 undef, i32 undef>
// %bin.rdx.0 = fadd <4 x float> %rdx.shuf.0.0, %rdx.shuf.0.1
return false;
assert(BinOp->getType()->isVectorTy() && "Expecting a vector type");
return false;
assert(BinOp->getType()->isVectorTy() && "Expecting a vector type");
return false;
// Shuffle inputs must match.
return false;
// Shuffle inputs must match.
- Value *NextLevelOpL = LS ? LS->getOperand(0) : 0;
- Value *NextLevelOpR = RS ? RS->getOperand(0) : 0;
- Value *NextLevelOp = 0;
+ Value *NextLevelOpL = LS ? LS->getOperand(0) : nullptr;
+ Value *NextLevelOpR = RS ? RS->getOperand(0) : nullptr;
+ Value *NextLevelOp = nullptr;
if (NextLevelOpR && NextLevelOpL) {
// If we have two shuffles their operands must match.
if (NextLevelOpL != NextLevelOpR)
if (NextLevelOpR && NextLevelOpL) {
// If we have two shuffles their operands must match.
if (NextLevelOpL != NextLevelOpR)
// Check that the next levels binary operation exists and matches with the
// current one.
// Check that the next levels binary operation exists and matches with the
// current one.
- BinaryOperator *NextLevelBinOp = 0;
+ BinaryOperator *NextLevelBinOp = nullptr;
if (Level + 1 != NumLevels) {
if (!(NextLevelBinOp = dyn_cast<BinaryOperator>(NextLevelOp)))
return false;
if (Level + 1 != NumLevels) {
if (!(NextLevelBinOp = dyn_cast<BinaryOperator>(NextLevelOp)))
return false;
Value *L = B->getOperand(0);
Value *R = B->getOperand(1);
Value *L = B->getOperand(0);
Value *R = B->getOperand(1);
- ShuffleVectorInst *S = 0;
+ ShuffleVectorInst *S = nullptr;
if ((S = dyn_cast<ShuffleVectorInst>(L)))
return std::make_pair(R, S);
if ((S = dyn_cast<ShuffleVectorInst>(L)))
return std::make_pair(R, S);
std::tie(NextRdxOp, Shuffle) = getShuffleAndOtherOprd(BinOp);
// Check the current reduction operation and the shuffle use the same value.
std::tie(NextRdxOp, Shuffle) = getShuffleAndOtherOprd(BinOp);
// Check the current reduction operation and the shuffle use the same value.
+ if (Shuffle == nullptr)
return false;
if (Shuffle->getOperand(0) != NextRdxOp)
return false;
return false;
if (Shuffle->getOperand(0) != NextRdxOp)
return false;
if (NumVecElems == Mask.size() && isReverseVectorMask(Mask))
return TTI->getShuffleCost(TargetTransformInfo::SK_Reverse, VecTypOp0, 0,
if (NumVecElems == Mask.size() && isReverseVectorMask(Mask))
return TTI->getShuffleCost(TargetTransformInfo::SK_Reverse, VecTypOp0, 0,
return -1;
}
case Instruction::Call:
return -1;
}
case Instruction::Call:
}
bool runOnFunction(Function &F) override;
void getAnalysisUsage(AnalysisUsage &AU) const override;
}
bool runOnFunction(Function &F) override;
void getAnalysisUsage(AnalysisUsage &AU) const override;
- void print(raw_ostream &O, const Module *M = 0) const override;
+ void print(raw_ostream &O, const Module *M = nullptr) const override;
};
} // end anonymous namespace
};
} // end anonymous namespace
return Store->getPointerOperand();
else if (GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(&Inst))
return Gep->getPointerOperand();
return Store->getPointerOperand();
else if (GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(&Inst))
return Gep->getPointerOperand();
}
void Delinearization::print(raw_ostream &O, const Module *) const {
}
void Delinearization::print(raw_ostream &O, const Module *) const {
const BasicBlock *BB = Inst->getParent();
// Delinearize the memory access as analyzed in all the surrounding loops.
// Do not analyze memory accesses outside loops.
const BasicBlock *BB = Inst->getParent();
// Delinearize the memory access as analyzed in all the surrounding loops.
// Do not analyze memory accesses outside loops.
- for (Loop *L = LI->getLoopFor(BB); L != NULL; L = L->getParentLoop()) {
+ for (Loop *L = LI->getLoopFor(BB); L != nullptr; L = L->getParentLoop()) {
const SCEV *AccessFn = SE->getSCEVAtScope(getPointerOperand(*Inst), L);
const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(AccessFn);
const SCEV *AccessFn = SE->getSCEVAtScope(getPointerOperand(*Inst), L);
const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(AccessFn);
Levels(CommonLevels),
LoopIndependent(PossiblyLoopIndependent) {
Consistent = true;
Levels(CommonLevels),
LoopIndependent(PossiblyLoopIndependent) {
Consistent = true;
- DV = CommonLevels ? new DVEntry[CommonLevels] : NULL;
+ DV = CommonLevels ? new DVEntry[CommonLevels] : nullptr;
}
// The rest are simple getters that hide the implementation.
}
// The rest are simple getters that hide the implementation.
if (StoreInst *SI = dyn_cast<StoreInst>(I))
return SI->getPointerOperand();
llvm_unreachable("Value is not load or store instruction");
if (StoreInst *SI = dyn_cast<StoreInst>(I))
return SI->getPointerOperand();
llvm_unreachable("Value is not load or store instruction");
const SCEV *UB = SE->getBackedgeTakenCount(L);
return SE->getNoopOrZeroExtend(UB, T);
}
const SCEV *UB = SE->getBackedgeTakenCount(L);
return SE->getNoopOrZeroExtend(UB, T);
}
) const {
if (const SCEV *UB = collectUpperBound(L, T))
return dyn_cast<SCEVConstant>(UB);
) const {
if (const SCEV *UB = collectUpperBound(L, T))
return dyn_cast<SCEVConstant>(UB);
if (const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Product->getOperand(Op)))
return Constant;
}
if (const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Product->getOperand(Op)))
return Constant;
}
CoefficientInfo *B,
BoundInfo *Bound,
unsigned K) const {
CoefficientInfo *B,
BoundInfo *Bound,
unsigned K) const {
- Bound[K].Lower[Dependence::DVEntry::ALL] = NULL; // Default value = -infinity.
- Bound[K].Upper[Dependence::DVEntry::ALL] = NULL; // Default value = +infinity.
+ Bound[K].Lower[Dependence::DVEntry::ALL] = nullptr; // Default value = -infinity.
+ Bound[K].Upper[Dependence::DVEntry::ALL] = nullptr; // Default value = +infinity.
if (Bound[K].Iterations) {
Bound[K].Lower[Dependence::DVEntry::ALL] =
SE->getMulExpr(SE->getMinusSCEV(A[K].NegPart, B[K].PosPart),
if (Bound[K].Iterations) {
Bound[K].Lower[Dependence::DVEntry::ALL] =
SE->getMulExpr(SE->getMinusSCEV(A[K].NegPart, B[K].PosPart),
CoefficientInfo *B,
BoundInfo *Bound,
unsigned K) const {
CoefficientInfo *B,
BoundInfo *Bound,
unsigned K) const {
- Bound[K].Lower[Dependence::DVEntry::EQ] = NULL; // Default value = -infinity.
- Bound[K].Upper[Dependence::DVEntry::EQ] = NULL; // Default value = +infinity.
+ Bound[K].Lower[Dependence::DVEntry::EQ] = nullptr; // Default value = -infinity.
+ Bound[K].Upper[Dependence::DVEntry::EQ] = nullptr; // Default value = +infinity.
if (Bound[K].Iterations) {
const SCEV *Delta = SE->getMinusSCEV(A[K].Coeff, B[K].Coeff);
const SCEV *NegativePart = getNegativePart(Delta);
if (Bound[K].Iterations) {
const SCEV *Delta = SE->getMinusSCEV(A[K].Coeff, B[K].Coeff);
const SCEV *NegativePart = getNegativePart(Delta);
CoefficientInfo *B,
BoundInfo *Bound,
unsigned K) const {
CoefficientInfo *B,
BoundInfo *Bound,
unsigned K) const {
- Bound[K].Lower[Dependence::DVEntry::LT] = NULL; // Default value = -infinity.
- Bound[K].Upper[Dependence::DVEntry::LT] = NULL; // Default value = +infinity.
+ Bound[K].Lower[Dependence::DVEntry::LT] = nullptr; // Default value = -infinity.
+ Bound[K].Upper[Dependence::DVEntry::LT] = nullptr; // Default value = +infinity.
if (Bound[K].Iterations) {
const SCEV *Iter_1 =
SE->getMinusSCEV(Bound[K].Iterations,
if (Bound[K].Iterations) {
const SCEV *Iter_1 =
SE->getMinusSCEV(Bound[K].Iterations,
CoefficientInfo *B,
BoundInfo *Bound,
unsigned K) const {
CoefficientInfo *B,
BoundInfo *Bound,
unsigned K) const {
- Bound[K].Lower[Dependence::DVEntry::GT] = NULL; // Default value = -infinity.
- Bound[K].Upper[Dependence::DVEntry::GT] = NULL; // Default value = +infinity.
+ Bound[K].Lower[Dependence::DVEntry::GT] = nullptr; // Default value = -infinity.
+ Bound[K].Upper[Dependence::DVEntry::GT] = nullptr; // Default value = +infinity.
if (Bound[K].Iterations) {
const SCEV *Iter_1 =
SE->getMinusSCEV(Bound[K].Iterations,
if (Bound[K].Iterations) {
const SCEV *Iter_1 =
SE->getMinusSCEV(Bound[K].Iterations,
CI[K].Coeff = Zero;
CI[K].PosPart = Zero;
CI[K].NegPart = Zero;
CI[K].Coeff = Zero;
CI[K].PosPart = Zero;
CI[K].NegPart = Zero;
- CI[K].Iterations = NULL;
+ CI[K].Iterations = nullptr;
}
while (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Subscript)) {
const Loop *L = AddRec->getLoop();
}
while (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Subscript)) {
const Loop *L = AddRec->getLoop();
if (Bound[K].Lower[Bound[K].Direction])
Sum = SE->getAddExpr(Sum, Bound[K].Lower[Bound[K].Direction]);
else
if (Bound[K].Lower[Bound[K].Direction])
Sum = SE->getAddExpr(Sum, Bound[K].Lower[Bound[K].Direction]);
else
if (Bound[K].Upper[Bound[K].Direction])
Sum = SE->getAddExpr(Sum, Bound[K].Upper[Bound[K].Direction]);
else
if (Bound[K].Upper[Bound[K].Direction])
Sum = SE->getAddExpr(Sum, Bound[K].Upper[Bound[K].Direction]);
else
}
else if (CurConstraint.isLine()) {
Level.Scalar = false;
}
else if (CurConstraint.isLine()) {
Level.Scalar = false;
+ Level.Distance = nullptr;
// direction should be accurate
}
else if (CurConstraint.isPoint()) {
Level.Scalar = false;
// direction should be accurate
}
else if (CurConstraint.isPoint()) {
Level.Scalar = false;
+ Level.Distance = nullptr;
unsigned NewDirection = Dependence::DVEntry::NONE;
if (!isKnownPredicate(CmpInst::ICMP_NE,
CurConstraint.getY(),
unsigned NewDirection = Dependence::DVEntry::NONE;
if (!isKnownPredicate(CmpInst::ICMP_NE,
CurConstraint.getY(),
if ((!Src->mayReadFromMemory() && !Src->mayWriteToMemory()) ||
(!Dst->mayReadFromMemory() && !Dst->mayWriteToMemory()))
// if both instructions don't reference memory, there's no dependence
if ((!Src->mayReadFromMemory() && !Src->mayWriteToMemory()) ||
(!Dst->mayReadFromMemory() && !Dst->mayWriteToMemory()))
// if both instructions don't reference memory, there's no dependence
if (!isLoadOrStore(Src) || !isLoadOrStore(Dst)) {
// can only analyze simple loads and stores, i.e., no calls, invokes, etc.
if (!isLoadOrStore(Src) || !isLoadOrStore(Dst)) {
// can only analyze simple loads and stores, i.e., no calls, invokes, etc.
case AliasAnalysis::NoAlias:
// If the objects noalias, they are distinct, accesses are independent.
DEBUG(dbgs() << "no alias\n");
case AliasAnalysis::NoAlias:
// If the objects noalias, they are distinct, accesses are independent.
DEBUG(dbgs() << "no alias\n");
case AliasAnalysis::MustAlias:
break; // The underlying objects alias; test accesses for dependence.
}
case AliasAnalysis::MustAlias:
break; // The underlying objects alias; test accesses for dependence.
}
case Subscript::ZIV:
DEBUG(dbgs() << ", ZIV\n");
if (testZIV(Pair[SI].Src, Pair[SI].Dst, Result))
case Subscript::ZIV:
DEBUG(dbgs() << ", ZIV\n");
if (testZIV(Pair[SI].Src, Pair[SI].Dst, Result))
break;
case Subscript::SIV: {
DEBUG(dbgs() << ", SIV\n");
unsigned Level;
break;
case Subscript::SIV: {
DEBUG(dbgs() << ", SIV\n");
unsigned Level;
- const SCEV *SplitIter = NULL;
+ const SCEV *SplitIter = nullptr;
if (testSIV(Pair[SI].Src, Pair[SI].Dst, Level,
Result, NewConstraint, SplitIter))
if (testSIV(Pair[SI].Src, Pair[SI].Dst, Level,
Result, NewConstraint, SplitIter))
break;
}
case Subscript::RDIV:
DEBUG(dbgs() << ", RDIV\n");
if (testRDIV(Pair[SI].Src, Pair[SI].Dst, Result))
break;
}
case Subscript::RDIV:
DEBUG(dbgs() << ", RDIV\n");
if (testRDIV(Pair[SI].Src, Pair[SI].Dst, Result))
break;
case Subscript::MIV:
DEBUG(dbgs() << ", MIV\n");
if (testMIV(Pair[SI].Src, Pair[SI].Dst, Pair[SI].Loops, Result))
break;
case Subscript::MIV:
DEBUG(dbgs() << ", MIV\n");
if (testMIV(Pair[SI].Src, Pair[SI].Dst, Pair[SI].Loops, Result))
break;
default:
llvm_unreachable("subscript has unexpected classification");
break;
default:
llvm_unreachable("subscript has unexpected classification");
DEBUG(dbgs() << "testing subscript " << SJ << ", SIV\n");
// SJ is an SIV subscript that's part of the current coupled group
unsigned Level;
DEBUG(dbgs() << "testing subscript " << SJ << ", SIV\n");
// SJ is an SIV subscript that's part of the current coupled group
unsigned Level;
- const SCEV *SplitIter = NULL;
+ const SCEV *SplitIter = nullptr;
DEBUG(dbgs() << "SIV\n");
if (testSIV(Pair[SJ].Src, Pair[SJ].Dst, Level,
Result, NewConstraint, SplitIter))
DEBUG(dbgs() << "SIV\n");
if (testSIV(Pair[SJ].Src, Pair[SJ].Dst, Level,
Result, NewConstraint, SplitIter))
ConstrainedLevels.set(Level);
if (intersectConstraints(&Constraints[Level], &NewConstraint)) {
if (Constraints[Level].isEmpty()) {
++DeltaIndependence;
ConstrainedLevels.set(Level);
if (intersectConstraints(&Constraints[Level], &NewConstraint)) {
if (Constraints[Level].isEmpty()) {
++DeltaIndependence;
case Subscript::ZIV:
DEBUG(dbgs() << "ZIV\n");
if (testZIV(Pair[SJ].Src, Pair[SJ].Dst, Result))
case Subscript::ZIV:
DEBUG(dbgs() << "ZIV\n");
if (testZIV(Pair[SJ].Src, Pair[SJ].Dst, Result))
Mivs.reset(SJ);
break;
case Subscript::SIV:
Mivs.reset(SJ);
break;
case Subscript::SIV:
if (Pair[SJ].Classification == Subscript::RDIV) {
DEBUG(dbgs() << "RDIV test\n");
if (testRDIV(Pair[SJ].Src, Pair[SJ].Dst, Result))
if (Pair[SJ].Classification == Subscript::RDIV) {
DEBUG(dbgs() << "RDIV test\n");
if (testRDIV(Pair[SJ].Src, Pair[SJ].Dst, Result))
// I don't yet understand how to propagate RDIV results
Mivs.reset(SJ);
}
// I don't yet understand how to propagate RDIV results
Mivs.reset(SJ);
}
if (Pair[SJ].Classification == Subscript::MIV) {
DEBUG(dbgs() << "MIV test\n");
if (testMIV(Pair[SJ].Src, Pair[SJ].Dst, Pair[SJ].Loops, Result))
if (Pair[SJ].Classification == Subscript::MIV) {
DEBUG(dbgs() << "MIV test\n");
if (testMIV(Pair[SJ].Src, Pair[SJ].Dst, Pair[SJ].Loops, Result))
}
else
llvm_unreachable("expected only MIV subscripts at this point");
}
else
llvm_unreachable("expected only MIV subscripts at this point");
SJ >= 0; SJ = ConstrainedLevels.find_next(SJ)) {
updateDirection(Result.DV[SJ - 1], Constraints[SJ]);
if (Result.DV[SJ - 1].Direction == Dependence::DVEntry::NONE)
SJ >= 0; SJ = ConstrainedLevels.find_next(SJ)) {
updateDirection(Result.DV[SJ - 1], Constraints[SJ]);
if (Result.DV[SJ - 1].Direction == Dependence::DVEntry::NONE)
}
FullDependence *Final = new FullDependence(Result);
}
FullDependence *Final = new FullDependence(Result);
switch (Pair[SI].Classification) {
case Subscript::SIV: {
unsigned Level;
switch (Pair[SI].Classification) {
case Subscript::SIV: {
unsigned Level;
- const SCEV *SplitIter = NULL;
+ const SCEV *SplitIter = nullptr;
(void) testSIV(Pair[SI].Src, Pair[SI].Dst, Level,
Result, NewConstraint, SplitIter);
if (Level == SplitLevel) {
(void) testSIV(Pair[SI].Src, Pair[SI].Dst, Level,
Result, NewConstraint, SplitIter);
if (Level == SplitLevel) {
- assert(SplitIter != NULL);
+ assert(SplitIter != nullptr);
return SplitIter;
}
break;
return SplitIter;
}
break;
for (int SJ = Sivs.find_first(); SJ >= 0; SJ = Sivs.find_next(SJ)) {
// SJ is an SIV subscript that's part of the current coupled group
unsigned Level;
for (int SJ = Sivs.find_first(); SJ >= 0; SJ = Sivs.find_next(SJ)) {
// SJ is an SIV subscript that's part of the current coupled group
unsigned Level;
- const SCEV *SplitIter = NULL;
+ const SCEV *SplitIter = nullptr;
(void) testSIV(Pair[SJ].Src, Pair[SJ].Dst, Level,
Result, NewConstraint, SplitIter);
if (Level == SplitLevel && SplitIter)
(void) testSIV(Pair[SJ].Src, Pair[SJ].Dst, Level,
Result, NewConstraint, SplitIter);
if (Level == SplitLevel && SplitIter)
}
}
llvm_unreachable("somehow reached end of routine");
}
}
llvm_unreachable("somehow reached end of routine");
DominanceFrontier::calculate(const DominatorTree &DT,
const DomTreeNode *Node) {
BasicBlock *BB = Node->getBlock();
DominanceFrontier::calculate(const DominatorTree &DT,
const DomTreeNode *Node) {
BasicBlock *BB = Node->getBlock();
- DomSetType *Result = NULL;
+ DomSetType *Result = nullptr;
std::vector<DFCalculateWorkObject> workList;
SmallPtrSet<BasicBlock *, 32> visited;
std::vector<DFCalculateWorkObject> workList;
SmallPtrSet<BasicBlock *, 32> visited;
- workList.push_back(DFCalculateWorkObject(BB, NULL, Node, NULL));
+ workList.push_back(DFCalculateWorkObject(BB, nullptr, Node, nullptr));
do {
DFCalculateWorkObject *currentW = &workList.back();
assert (currentW && "Missing work object.");
do {
DFCalculateWorkObject *currentW = &workList.back();
assert (currentW && "Missing work object.");
static bool isSimplifiedLoopNest(BasicBlock *BB, const DominatorTree *DT,
const LoopInfo *LI,
SmallPtrSet<Loop*,16> &SimpleLoopNests) {
static bool isSimplifiedLoopNest(BasicBlock *BB, const DominatorTree *DT,
const LoopInfo *LI,
SmallPtrSet<Loop*,16> &SimpleLoopNests) {
+ Loop *NearestLoop = nullptr;
for (DomTreeNode *Rung = DT->getNode(BB);
Rung; Rung = Rung->getIDom()) {
BasicBlock *DomBB = Rung->getBlock();
for (DomTreeNode *Rung = DT->getNode(BB);
Rung; Rung = Rung->getIDom()) {
BasicBlock *DomBB = Rung->getBlock();
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
SE = &getAnalysis<ScalarEvolution>();
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
SE = &getAnalysis<ScalarEvolution>();
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
- DL = DLP ? &DLP->getDataLayout() : 0;
+ DL = DLP ? &DLP->getDataLayout() : nullptr;
// Find all uses of induction variables in this loop, and categorize
// them by stride. Start by finding all of the PHI nodes in the header for
// Find all uses of induction variables in this loop, and categorize
// them by stride. Start by finding all of the PHI nodes in the header for
I != E; ++I)
if (const SCEVAddRecExpr *AR = findAddRecForLoop(*I, L))
return AR;
I != E; ++I)
if (const SCEVAddRecExpr *AR = findAddRecForLoop(*I, L))
return AR;
}
const SCEV *IVUsers::getStride(const IVStrideUse &IU, const Loop *L) const {
if (const SCEVAddRecExpr *AR = findAddRecForLoop(getExpr(IU), L))
return AR->getStepRecurrence(*SE);
}
const SCEV *IVUsers::getStride(const IVStrideUse &IU, const Loop *L) const {
if (const SCEVAddRecExpr *AR = findAddRecForLoop(getExpr(IU), L))
return AR->getStepRecurrence(*SE);
}
void IVStrideUse::transformToPostInc(const Loop *L) {
}
void IVStrideUse::transformToPostInc(const Loop *L) {
void visitInstruction(Instruction &I) {
errs() << "Instruction Count does not know about " << I;
void visitInstruction(Instruction &I) {
errs() << "Instruction Count does not know about " << I;
+ llvm_unreachable(nullptr);
}
public:
static char ID; // Pass identification, replacement for typeid
}
public:
static char ID; // Pass identification, replacement for typeid
Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
// Recursion is always used, so bail out at once if we already hit the limit.
if (!MaxRecurse--)
Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
// Recursion is always used, so bail out at once if we already hit the limit.
if (!MaxRecurse--)
// Check whether the expression has the form "(A op' B) op C".
if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
// Check whether the expression has the form "(A op' B) op C".
if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
}
/// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
}
/// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
// Recursion is always used, so bail out at once if we already hit the limit.
if (!MaxRecurse--)
Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
// Recursion is always used, so bail out at once if we already hit the limit.
if (!MaxRecurse--)
BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
!Op1 || Op1->getOpcode() != OpcodeToExtract)
BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
!Op1 || Op1->getOpcode() != OpcodeToExtract)
// The expression has the form "(A op' B) op (C op' D)".
Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
// The expression has the form "(A op' B) op (C op' D)".
Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
}
/// SimplifyAssociativeBinOp - Generic simplifications for associative binary
}
/// SimplifyAssociativeBinOp - Generic simplifications for associative binary
// Recursion is always used, so bail out at once if we already hit the limit.
if (!MaxRecurse--)
// Recursion is always used, so bail out at once if we already hit the limit.
if (!MaxRecurse--)
BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
// The remaining transforms require commutativity as well as associativity.
if (!Instruction::isCommutative(Opcode))
// The remaining transforms require commutativity as well as associativity.
if (!Instruction::isCommutative(Opcode))
// Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
if (Op0 && Op0->getOpcode() == Opcode) {
// Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
if (Op0 && Op0->getOpcode() == Opcode) {
}
/// ThreadBinOpOverSelect - In the case of a binary operation with a select
}
/// ThreadBinOpOverSelect - In the case of a binary operation with a select
const Query &Q, unsigned MaxRecurse) {
// Recursion is always used, so bail out at once if we already hit the limit.
if (!MaxRecurse--)
const Query &Q, unsigned MaxRecurse) {
// Recursion is always used, so bail out at once if we already hit the limit.
if (!MaxRecurse--)
SelectInst *SI;
if (isa<SelectInst>(LHS)) {
SelectInst *SI;
if (isa<SelectInst>(LHS)) {
}
/// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
}
/// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
unsigned MaxRecurse) {
// Recursion is always used, so bail out at once if we already hit the limit.
if (!MaxRecurse--)
unsigned MaxRecurse) {
// Recursion is always used, so bail out at once if we already hit the limit.
if (!MaxRecurse--)
// Make sure the select is on the LHS.
if (!isa<SelectInst>(LHS)) {
// Make sure the select is on the LHS.
if (!isa<SelectInst>(LHS)) {
// It didn't simplify. However if "cmp TV, RHS" is equal to the select
// condition then we can replace it with 'true'. Otherwise give up.
if (!isSameCompare(Cond, Pred, TV, RHS))
// It didn't simplify. However if "cmp TV, RHS" is equal to the select
// condition then we can replace it with 'true'. Otherwise give up.
if (!isSameCompare(Cond, Pred, TV, RHS))
TCmp = getTrue(Cond->getType());
}
TCmp = getTrue(Cond->getType());
}
// It didn't simplify. However if "cmp FV, RHS" is equal to the select
// condition then we can replace it with 'false'. Otherwise give up.
if (!isSameCompare(Cond, Pred, FV, RHS))
// It didn't simplify. However if "cmp FV, RHS" is equal to the select
// condition then we can replace it with 'false'. Otherwise give up.
if (!isSameCompare(Cond, Pred, FV, RHS))
FCmp = getFalse(Cond->getType());
}
FCmp = getFalse(Cond->getType());
}
// The remaining cases only make sense if the select condition has the same
// type as the result of the comparison, so bail out if this is not so.
if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
// The remaining cases only make sense if the select condition has the same
// type as the result of the comparison, so bail out if this is not so.
if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
// If the false value simplified to false, then the result of the compare
// is equal to "Cond && TCmp". This also catches the case when the false
// value simplified to false and the true value to true, returning "Cond".
// If the false value simplified to false, then the result of the compare
// is equal to "Cond && TCmp". This also catches the case when the false
// value simplified to false and the true value to true, returning "Cond".
Q, MaxRecurse))
return V;
Q, MaxRecurse))
return V;
}
/// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
}
/// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
const Query &Q, unsigned MaxRecurse) {
// Recursion is always used, so bail out at once if we already hit the limit.
if (!MaxRecurse--)
const Query &Q, unsigned MaxRecurse) {
// Recursion is always used, so bail out at once if we already hit the limit.
if (!MaxRecurse--)
PHINode *PI;
if (isa<PHINode>(LHS)) {
PI = cast<PHINode>(LHS);
// Bail out if RHS and the phi may be mutually interdependent due to a loop.
if (!ValueDominatesPHI(RHS, PI, Q.DT))
PHINode *PI;
if (isa<PHINode>(LHS)) {
PI = cast<PHINode>(LHS);
// Bail out if RHS and the phi may be mutually interdependent due to a loop.
if (!ValueDominatesPHI(RHS, PI, Q.DT))
} else {
assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
PI = cast<PHINode>(RHS);
// Bail out if LHS and the phi may be mutually interdependent due to a loop.
if (!ValueDominatesPHI(LHS, PI, Q.DT))
} else {
assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
PI = cast<PHINode>(RHS);
// Bail out if LHS and the phi may be mutually interdependent due to a loop.
if (!ValueDominatesPHI(LHS, PI, Q.DT))
}
// Evaluate the BinOp on the incoming phi values.
}
// Evaluate the BinOp on the incoming phi values.
- Value *CommonValue = 0;
+ Value *CommonValue = nullptr;
for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Value *Incoming = PI->getIncomingValue(i);
// If the incoming value is the phi node itself, it can safely be skipped.
for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Value *Incoming = PI->getIncomingValue(i);
// If the incoming value is the phi node itself, it can safely be skipped.
// If the operation failed to simplify, or simplified to a different value
// to previously, then give up.
if (!V || (CommonValue && V != CommonValue))
// If the operation failed to simplify, or simplified to a different value
// to previously, then give up.
if (!V || (CommonValue && V != CommonValue))
const Query &Q, unsigned MaxRecurse) {
// Recursion is always used, so bail out at once if we already hit the limit.
if (!MaxRecurse--)
const Query &Q, unsigned MaxRecurse) {
// Recursion is always used, so bail out at once if we already hit the limit.
if (!MaxRecurse--)
// Make sure the phi is on the LHS.
if (!isa<PHINode>(LHS)) {
// Make sure the phi is on the LHS.
if (!isa<PHINode>(LHS)) {
// Bail out if RHS and the phi may be mutually interdependent due to a loop.
if (!ValueDominatesPHI(RHS, PI, Q.DT))
// Bail out if RHS and the phi may be mutually interdependent due to a loop.
if (!ValueDominatesPHI(RHS, PI, Q.DT))
// Evaluate the BinOp on the incoming phi values.
// Evaluate the BinOp on the incoming phi values.
- Value *CommonValue = 0;
+ Value *CommonValue = nullptr;
for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Value *Incoming = PI->getIncomingValue(i);
// If the incoming value is the phi node itself, it can safely be skipped.
for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Value *Incoming = PI->getIncomingValue(i);
// If the incoming value is the phi node itself, it can safely be skipped.
// If the operation failed to simplify, or simplified to a different value
// to previously, then give up.
if (!V || (CommonValue && V != CommonValue))
// If the operation failed to simplify, or simplified to a different value
// to previously, then give up.
if (!V || (CommonValue && V != CommonValue))
// X + (Y - X) -> Y
// (Y - X) + X -> Y
// Eg: X + -X -> 0
// X + (Y - X) -> Y
// (Y - X) + X -> Y
// Eg: X + -X -> 0
if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
return Y;
if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
return Y;
// "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
// for threading over phi nodes.
// "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
// for threading over phi nodes.
}
Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
}
Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
// If LHS and RHS are not related via constant offsets to the same base
// value, there is nothing we can do here.
if (LHS != RHS)
// If LHS and RHS are not related via constant offsets to the same base
// value, there is nothing we can do here.
if (LHS != RHS)
// Otherwise, the difference of LHS - RHS can be computed as:
// LHS - RHS
// Otherwise, the difference of LHS - RHS can be computed as:
// LHS - RHS
// (X*2) - X -> X
// (X<<1) - X -> X
// (X*2) - X -> X
// (X<<1) - X -> X
if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
match(Op0, m_Shl(m_Specific(Op1), m_One())))
return Op1;
// (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
// For example, (X + Y) - Y -> X; (Y + X) - Y -> X
if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
match(Op0, m_Shl(m_Specific(Op1), m_One())))
return Op1;
// (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
// For example, (X + Y) - Y -> X; (Y + X) - Y -> X
- Value *Y = 0, *Z = Op1;
+ Value *Y = nullptr, *Z = Op1;
if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
// See if "V === Y - Z" simplifies.
if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
// See if "V === Y - Z" simplifies.
if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
// "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
// for threading over phi nodes.
// "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
// for threading over phi nodes.
}
Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
}
Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
// fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
// where nnan and ninf have to occur at least once somewhere in this
// expression
// fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
// where nnan and ninf have to occur at least once somewhere in this
// expression
+ Value *SubOp = nullptr;
if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
SubOp = Op1;
else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
SubOp = Op1;
else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
return Constant::getNullValue(Op0->getType());
}
return Constant::getNullValue(Op0->getType());
}
}
/// Given operands for an FSub, see if we can fold the result. If not, this
}
/// Given operands for an FSub, see if we can fold the result. If not, this
if (FMF.noNaNs() && FMF.noInfs() && Op0 == Op1)
return Constant::getNullValue(Op0->getType());
if (FMF.noNaNs() && FMF.noInfs() && Op0 == Op1)
return Constant::getNullValue(Op0->getType());
}
/// Given the operands for an FMul, see if we can fold the result
}
/// Given the operands for an FMul, see if we can fold the result
if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
return Op1;
if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
return Op1;
}
/// SimplifyMulInst - Given operands for a Mul, see if we can
}
/// SimplifyMulInst - Given operands for a Mul, see if we can
return Op0;
// (X / Y) * Y -> X if the division is exact.
return Op0;
// (X / Y) * Y -> X if the division is exact.
if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
return X;
if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
return X;
}
Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
}
Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
return ConstantInt::get(Op0->getType(), 1);
// (X * Y) / Y -> X if the multiplication does not overflow.
return ConstantInt::get(Op0->getType(), 1);
// (X * Y) / Y -> X if the multiplication does not overflow.
+ Value *X = nullptr, *Y = nullptr;
if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
return V;
if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
return V;
}
/// SimplifySDivInst - Given operands for an SDiv, see if we can
}
/// SimplifySDivInst - Given operands for an SDiv, see if we can
if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
return V;
if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
return V;
}
Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
}
Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
return V;
if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
return V;
}
Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
}
Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
if (match(Op1, m_Undef()))
return Op1;
if (match(Op1, m_Undef()))
return Op1;
}
Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
}
Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
return V;
if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
return V;
}
/// SimplifySRemInst - Given operands for an SRem, see if we can
}
/// SimplifySRemInst - Given operands for an SRem, see if we can
if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
return V;
if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
return V;
}
Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout *DL,
}
Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout *DL,
if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
return V;
if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
return V;
}
Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout *DL,
}
Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout *DL,
if (match(Op1, m_Undef()))
return Op1;
if (match(Op1, m_Undef()))
return Op1;
}
Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const DataLayout *DL,
}
Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const DataLayout *DL,
if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
return V;
if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
return V;
}
/// SimplifyShlInst - Given operands for an Shl, see if we can
}
/// SimplifyShlInst - Given operands for an Shl, see if we can
Value *X;
if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
return X;
Value *X;
if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
return X;
}
Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
}
Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
return X;
cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
return X;
}
Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
}
Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
return X;
cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
return X;
}
Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
}
Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
return Constant::getNullValue(Op0->getType());
// (A | ?) & A = A
return Constant::getNullValue(Op0->getType());
// (A | ?) & A = A
+ Value *A = nullptr, *B = nullptr;
if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
(A == Op1 || B == Op1))
return Op1;
if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
(A == Op1 || B == Op1))
return Op1;
}
Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout *DL,
}
Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout *DL,
return Constant::getAllOnesValue(Op0->getType());
// (A & ?) | A = A
return Constant::getAllOnesValue(Op0->getType());
// (A & ?) | A = A
+ Value *A = nullptr, *B = nullptr;
if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
(A == Op1 || B == Op1))
return Op1;
if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
(A == Op1 || B == Op1))
return Op1;
if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
return V;
if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
return V;
}
Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout *DL,
}
Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout *DL,
// "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
// for threading over phi nodes.
// "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
// for threading over phi nodes.
}
Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout *DL,
}
Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout *DL,
Value *LHS, Value *RHS) {
SelectInst *SI = dyn_cast<SelectInst>(V);
if (!SI)
Value *LHS, Value *RHS) {
SelectInst *SI = dyn_cast<SelectInst>(V);
if (!SI)
CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
if (!Cmp)
CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
if (!Cmp)
Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
return Cmp;
if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
LHS == CmpRHS && RHS == CmpLHS)
return Cmp;
Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
return Cmp;
if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
LHS == CmpRHS && RHS == CmpLHS)
return Cmp;
}
// A significant optimization not implemented here is assuming that alloca
}
// A significant optimization not implemented here is assuming that alloca
// We can only fold certain predicates on pointer comparisons.
switch (Pred) {
default:
// We can only fold certain predicates on pointer comparisons.
switch (Pred) {
default:
// Equality comaprisons are easy to fold.
case CmpInst::ICMP_EQ:
// Equality comaprisons are easy to fold.
case CmpInst::ICMP_EQ:
}
/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
}
/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
if (MaxRecurse && (LBO || RBO)) {
// Analyze the case when either LHS or RHS is an add instruction.
BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
if (MaxRecurse && (LBO || RBO)) {
// Analyze the case when either LHS or RHS is an add instruction.
- Value *A = 0, *B = 0, *C = 0, *D = 0;
+ Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
// LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
if (LBO && LBO->getOpcode() == Instruction::Add) {
// LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
if (LBO && LBO->getOpcode() == Instruction::Add) {
if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
return V;
if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
return V;
}
Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
}
Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
return V;
if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
return V;
}
Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
}
Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
return TrueVal;
if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
return TrueVal;
}
Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
}
Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
// Check to see if this is constant foldable.
for (unsigned i = 0, e = Ops.size(); i != e; ++i)
if (!isa<Constant>(Ops[i]))
// Check to see if this is constant foldable.
for (unsigned i = 0, e = Ops.size(); i != e; ++i)
if (!isa<Constant>(Ops[i]))
return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
}
return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
}
}
Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
}
Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
// If all of the PHI's incoming values are the same then replace the PHI node
// with the common value.
static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
// If all of the PHI's incoming values are the same then replace the PHI node
// with the common value.
- Value *CommonValue = 0;
+ Value *CommonValue = nullptr;
bool HasUndefInput = false;
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Value *Incoming = PN->getIncomingValue(i);
bool HasUndefInput = false;
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Value *Incoming = PN->getIncomingValue(i);
continue;
}
if (CommonValue && Incoming != CommonValue)
continue;
}
if (CommonValue && Incoming != CommonValue)
- return 0; // Not the same, bail out.
+ return nullptr; // Not the same, bail out.
CommonValue = Incoming;
}
CommonValue = Incoming;
}
// instruction, we cannot return X as the result of the PHI node unless it
// dominates the PHI block.
if (HasUndefInput)
// instruction, we cannot return X as the result of the PHI node unless it
// dominates the PHI block.
if (HasUndefInput)
- return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : 0;
+ return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
if (Constant *C = dyn_cast<Constant>(Op))
return ConstantFoldInstOperands(Instruction::Trunc, Ty, C, Q.DL, Q.TLI);
if (Constant *C = dyn_cast<Constant>(Op))
return ConstantFoldInstOperands(Instruction::Trunc, Ty, C, Q.DL, Q.TLI);
}
Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const DataLayout *DL,
}
Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const DataLayout *DL,
if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
return V;
if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
return V;
const Query &Q, unsigned MaxRecurse) {
// Perform idempotent optimizations
if (!IsIdempotent(IID))
const Query &Q, unsigned MaxRecurse) {
// Perform idempotent optimizations
if (!IsIdempotent(IID))
// Unary Ops
if (std::distance(ArgBegin, ArgEnd) == 1)
// Unary Ops
if (std::distance(ArgBegin, ArgEnd) == 1)
if (II->getIntrinsicID() == IID)
return II;
if (II->getIntrinsicID() == IID)
return II;
}
template <typename IterTy>
}
template <typename IterTy>
Function *F = dyn_cast<Function>(V);
if (!F)
Function *F = dyn_cast<Function>(V);
if (!F)
if (unsigned IID = F->getIntrinsicID())
if (Value *Ret =
if (unsigned IID = F->getIntrinsicID())
if (Value *Ret =
return Ret;
if (!canConstantFoldCallTo(F))
return Ret;
if (!canConstantFoldCallTo(F))
SmallVector<Constant *, 4> ConstantArgs;
ConstantArgs.reserve(ArgEnd - ArgBegin);
for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
Constant *C = dyn_cast<Constant>(*I);
if (!C)
SmallVector<Constant *, 4> ConstantArgs;
ConstantArgs.reserve(ArgEnd - ArgBegin);
for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
Constant *C = dyn_cast<Constant>(*I);
if (!C)
ConstantArgs.push_back(C);
}
ConstantArgs.push_back(C);
}
const DataLayout *DL,
const TargetLibraryInfo *TLI,
const DominatorTree *DT) {
const DataLayout *DL,
const TargetLibraryInfo *TLI,
const DominatorTree *DT) {
- return replaceAndRecursivelySimplifyImpl(I, 0, DL, TLI, DT);
+ return replaceAndRecursivelySimplifyImpl(I, nullptr, DL, TLI, DT);
}
bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
}
bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
delete Intervals[i];
IntervalMap.clear();
Intervals.clear();
delete Intervals[i];
IntervalMap.clear();
Intervals.clear();
+ RootInterval = nullptr;
}
void IntervalPartition::print(raw_ostream &O, const Module*) const {
}
void IntervalPartition::print(raw_ostream &O, const Module*) const {
ConstantRange Range;
public:
ConstantRange Range;
public:
- LVILatticeVal() : Tag(undefined), Val(0), Range(1, true) {}
+ LVILatticeVal() : Tag(undefined), Val(nullptr), Range(1, true) {}
static LVILatticeVal get(Constant *C) {
LVILatticeVal Res;
static LVILatticeVal get(Constant *C) {
LVILatticeVal Res;
BBLV.markOverdefined();
Instruction *BBI = dyn_cast<Instruction>(Val);
BBLV.markOverdefined();
Instruction *BBI = dyn_cast<Instruction>(Val);
- if (BBI == 0 || BBI->getParent() != BB) {
+ if (!BBI || BBI->getParent() != BB) {
return ODCacheUpdater.markResult(solveBlockValueNonLocal(BBLV, Val, BB));
}
return ODCacheUpdater.markResult(solveBlockValueNonLocal(BBLV, Val, BB));
}
Value *UnderlyingVal = GetUnderlyingObject(Val);
// If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
// inside InstructionDereferencesPointer either.
Value *UnderlyingVal = GetUnderlyingObject(Val);
// If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
// inside InstructionDereferencesPointer either.
- if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, NULL, 1)) {
+ if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, nullptr, 1)) {
for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
BI != BE; ++BI) {
if (InstructionDereferencesPointer(BI, UnderlyingVal)) {
for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
BI != BE; ++BI) {
if (InstructionDereferencesPointer(BI, UnderlyingVal)) {
// Recognize the range checking idiom that InstCombine produces.
// (X-C1) u< C2 --> [C1, C1+C2)
// Recognize the range checking idiom that InstCombine produces.
// (X-C1) u< C2 --> [C1, C1+C2)
- ConstantInt *NegOffset = 0;
+ ConstantInt *NegOffset = nullptr;
if (ICI->getPredicate() == ICmpInst::ICMP_ULT)
match(ICI->getOperand(0), m_Add(m_Specific(Val),
m_ConstantInt(NegOffset)));
if (ICI->getPredicate() == ICmpInst::ICMP_ULT)
match(ICI->getOperand(0), m_Add(m_Specific(Val),
m_ConstantInt(NegOffset)));
getCache(PImpl).clear();
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
getCache(PImpl).clear();
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
- DL = DLP ? &DLP->getDataLayout() : 0;
+ DL = DLP ? &DLP->getDataLayout() : nullptr;
TLI = &getAnalysis<TargetLibraryInfo>();
// Fully lazy.
TLI = &getAnalysis<TargetLibraryInfo>();
// Fully lazy.
// If the cache was allocated, free it.
if (PImpl) {
delete &getCache(PImpl);
// If the cache was allocated, free it.
if (PImpl) {
delete &getCache(PImpl);
if (const APInt *SingleVal = CR.getSingleElement())
return ConstantInt::get(V->getContext(), *SingleVal);
}
if (const APInt *SingleVal = CR.getSingleElement())
return ConstantInt::get(V->getContext(), *SingleVal);
}
}
/// getConstantOnEdge - Determine whether the specified value is known to be a
}
/// getConstantOnEdge - Determine whether the specified value is known to be a
if (const APInt *SingleVal = CR.getSingleElement())
return ConstantInt::get(V->getContext(), *SingleVal);
}
if (const APInt *SingleVal = CR.getSingleElement())
return ConstantInt::get(V->getContext(), *SingleVal);
}
}
/// getPredicateOnEdge - Determine whether the specified value comparison
}
/// getPredicateOnEdge - Determine whether the specified value comparison
LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
// If we know the value is a constant, evaluate the conditional.
LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
// If we know the value is a constant, evaluate the conditional.
+ Constant *Res = nullptr;
if (Result.isConstant()) {
Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL,
TLI);
if (Result.isConstant()) {
Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL,
TLI);
// if we have detailed info and if 'P' is any of the locations we know
// about.
const LibCallFunctionInfo::LocationMRInfo *Details = FI->LocationDetails;
// if we have detailed info and if 'P' is any of the locations we know
// about.
const LibCallFunctionInfo::LocationMRInfo *Details = FI->LocationDetails;
+ if (Details == nullptr)
return MRInfo;
// If the details array is of the 'DoesNot' kind, we only know something if
return MRInfo;
// If the details array is of the 'DoesNot' kind, we only know something if
/// If this is the first time we are querying for this info, lazily construct
/// the StringMap to index it.
/// If this is the first time we are querying for this info, lazily construct
/// the StringMap to index it.
Impl = Map = new StringMap<const LibCallFunctionInfo*>();
const LibCallFunctionInfo *Array = getFunctionInfoArray();
Impl = Map = new StringMap<const LibCallFunctionInfo*>();
const LibCallFunctionInfo *Array = getFunctionInfoArray();
- if (Array == 0) return 0;
+ if (!Array) return nullptr;
// We now have the array of entries. Populate the StringMap.
for (unsigned i = 0; Array[i].Name; ++i)
// We now have the array of entries. Populate the StringMap.
for (unsigned i = 0; Array[i].Name; ++i)
// that failed. This provides a nice place to put a breakpoint if you want
// to see why something is not correct.
void CheckFailed(const Twine &Message,
// that failed. This provides a nice place to put a breakpoint if you want
// to see why something is not correct.
void CheckFailed(const Twine &Message,
- const Value *V1 = 0, const Value *V2 = 0,
- const Value *V3 = 0, const Value *V4 = 0) {
+ const Value *V1 = nullptr, const Value *V2 = nullptr,
+ const Value *V3 = nullptr, const Value *V4 = nullptr) {
MessagesStr << Message.str() << "\n";
WriteValue(V1);
WriteValue(V2);
MessagesStr << Message.str() << "\n";
WriteValue(V1);
WriteValue(V2);
AA = &getAnalysis<AliasAnalysis>();
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
AA = &getAnalysis<AliasAnalysis>();
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
- DL = DLP ? &DLP->getDataLayout() : 0;
+ DL = DLP ? &DLP->getDataLayout() : nullptr;
TLI = &getAnalysis<TargetLibraryInfo>();
visit(F);
dbgs() << MessagesStr.str();
TLI = &getAnalysis<TargetLibraryInfo>();
visit(F);
dbgs() << MessagesStr.str();
Value *Callee = CS.getCalledValue();
visitMemoryReference(I, Callee, AliasAnalysis::UnknownSize,
Value *Callee = CS.getCalledValue();
visitMemoryReference(I, Callee, AliasAnalysis::UnknownSize,
+ 0, nullptr, MemRef::Callee);
if (Function *F = dyn_cast<Function>(findValue(Callee, /*OffsetOk=*/false))) {
Assert1(CS.getCallingConv() == F->getCallingConv(),
if (Function *F = dyn_cast<Function>(findValue(Callee, /*OffsetOk=*/false))) {
Assert1(CS.getCallingConv() == F->getCallingConv(),
MemCpyInst *MCI = cast<MemCpyInst>(&I);
// TODO: If the size is known, use it.
visitMemoryReference(I, MCI->getDest(), AliasAnalysis::UnknownSize,
MemCpyInst *MCI = cast<MemCpyInst>(&I);
// TODO: If the size is known, use it.
visitMemoryReference(I, MCI->getDest(), AliasAnalysis::UnknownSize,
- MCI->getAlignment(), 0,
+ MCI->getAlignment(), nullptr,
MemRef::Write);
visitMemoryReference(I, MCI->getSource(), AliasAnalysis::UnknownSize,
MemRef::Write);
visitMemoryReference(I, MCI->getSource(), AliasAnalysis::UnknownSize,
- MCI->getAlignment(), 0,
+ MCI->getAlignment(), nullptr,
MemRef::Read);
// Check that the memcpy arguments don't overlap. The AliasAnalysis API
MemRef::Read);
// Check that the memcpy arguments don't overlap. The AliasAnalysis API
MemMoveInst *MMI = cast<MemMoveInst>(&I);
// TODO: If the size is known, use it.
visitMemoryReference(I, MMI->getDest(), AliasAnalysis::UnknownSize,
MemMoveInst *MMI = cast<MemMoveInst>(&I);
// TODO: If the size is known, use it.
visitMemoryReference(I, MMI->getDest(), AliasAnalysis::UnknownSize,
- MMI->getAlignment(), 0,
+ MMI->getAlignment(), nullptr,
MemRef::Write);
visitMemoryReference(I, MMI->getSource(), AliasAnalysis::UnknownSize,
MemRef::Write);
visitMemoryReference(I, MMI->getSource(), AliasAnalysis::UnknownSize,
- MMI->getAlignment(), 0,
+ MMI->getAlignment(), nullptr,
MemSetInst *MSI = cast<MemSetInst>(&I);
// TODO: If the size is known, use it.
visitMemoryReference(I, MSI->getDest(), AliasAnalysis::UnknownSize,
MemSetInst *MSI = cast<MemSetInst>(&I);
// TODO: If the size is known, use it.
visitMemoryReference(I, MSI->getDest(), AliasAnalysis::UnknownSize,
- MSI->getAlignment(), 0,
+ MSI->getAlignment(), nullptr,
&I);
visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
&I);
visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
- 0, 0, MemRef::Read | MemRef::Write);
+ 0, nullptr, MemRef::Read | MemRef::Write);
break;
case Intrinsic::vacopy:
visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
break;
case Intrinsic::vacopy:
visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
+ 0, nullptr, MemRef::Write);
visitMemoryReference(I, CS.getArgument(1), AliasAnalysis::UnknownSize,
visitMemoryReference(I, CS.getArgument(1), AliasAnalysis::UnknownSize,
+ 0, nullptr, MemRef::Read);
break;
case Intrinsic::vaend:
visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
break;
case Intrinsic::vaend:
visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
- 0, 0, MemRef::Read | MemRef::Write);
+ 0, nullptr, MemRef::Read | MemRef::Write);
break;
case Intrinsic::stackrestore:
break;
case Intrinsic::stackrestore:
// stack pointer, which the compiler may read from or write to
// at any time, so check it for both readability and writeability.
visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
// stack pointer, which the compiler may read from or write to
// at any time, so check it for both readability and writeability.
visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
- 0, 0, MemRef::Read | MemRef::Write);
+ 0, nullptr, MemRef::Read | MemRef::Write);
}
void Lint::visitVAArgInst(VAArgInst &I) {
}
void Lint::visitVAArgInst(VAArgInst &I) {
- visitMemoryReference(I, I.getOperand(0), AliasAnalysis::UnknownSize, 0, 0,
- MemRef::Read | MemRef::Write);
+ visitMemoryReference(I, I.getOperand(0), AliasAnalysis::UnknownSize, 0,
+ nullptr, MemRef::Read | MemRef::Write);
}
void Lint::visitIndirectBrInst(IndirectBrInst &I) {
}
void Lint::visitIndirectBrInst(IndirectBrInst &I) {
- visitMemoryReference(I, I.getAddress(), AliasAnalysis::UnknownSize, 0, 0,
- MemRef::Branchee);
+ visitMemoryReference(I, I.getAddress(), AliasAnalysis::UnknownSize, 0,
+ nullptr, MemRef::Branchee);
Assert1(I.getNumDestinations() != 0,
"Undefined behavior: indirectbr with no destinations", &I);
Assert1(I.getNumDestinations() != 0,
"Undefined behavior: indirectbr with no destinations", &I);
if (ByteOffset < 0) // out of bounds
return false;
if (ByteOffset < 0) // out of bounds
return false;
+ Type *BaseType = nullptr;
unsigned BaseAlign = 0;
if (const AllocaInst *AI = dyn_cast<AllocaInst>(Base)) {
// An alloca is safe to load from as load as it is suitably aligned.
unsigned BaseAlign = 0;
if (const AllocaInst *AI = dyn_cast<AllocaInst>(Base)) {
// An alloca is safe to load from as load as it is suitably aligned.
ScanFrom++;
// Don't scan huge blocks.
ScanFrom++;
// Don't scan huge blocks.
- if (MaxInstsToScan-- == 0) return 0;
+ if (MaxInstsToScan-- == 0) return nullptr;
--ScanFrom;
// If this is a load of Ptr, the loaded value is available.
--ScanFrom;
// If this is a load of Ptr, the loaded value is available.
// Otherwise the store that may or may not alias the pointer, bail out.
++ScanFrom;
// Otherwise the store that may or may not alias the pointer, bail out.
++ScanFrom;
}
// If this is some other instruction that may clobber Ptr, bail out.
}
// If this is some other instruction that may clobber Ptr, bail out.
// May modify the pointer, bail out.
++ScanFrom;
// May modify the pointer, bail out.
++ScanFrom;
}
}
// Got to the start of the block, we didn't find it, but are done for this
// block.
}
}
// Got to the start of the block, we didn't find it, but are done for this
// block.
PHINode *Loop::getCanonicalInductionVariable() const {
BasicBlock *H = getHeader();
PHINode *Loop::getCanonicalInductionVariable() const {
BasicBlock *H = getHeader();
- BasicBlock *Incoming = 0, *Backedge = 0;
+ BasicBlock *Incoming = nullptr, *Backedge = nullptr;
pred_iterator PI = pred_begin(H);
assert(PI != pred_end(H) &&
"Loop must have at least one backedge!");
Backedge = *PI++;
pred_iterator PI = pred_begin(H);
assert(PI != pred_end(H) &&
"Loop must have at least one backedge!");
Backedge = *PI++;
- if (PI == pred_end(H)) return 0; // dead loop
+ if (PI == pred_end(H)) return nullptr; // dead loop
- if (PI != pred_end(H)) return 0; // multiple backedges?
+ if (PI != pred_end(H)) return nullptr; // multiple backedges?
if (contains(Incoming)) {
if (contains(Backedge))
if (contains(Incoming)) {
if (contains(Backedge))
std::swap(Incoming, Backedge);
} else if (!contains(Backedge))
std::swap(Incoming, Backedge);
} else if (!contains(Backedge))
// Loop over all of the PHI nodes, looking for a canonical indvar.
for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
// Loop over all of the PHI nodes, looking for a canonical indvar.
for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
if (CI->equalsInt(1))
return PN;
}
if (CI->equalsInt(1))
return PN;
}
}
/// isLCSSAForm - Return true if the Loop is in LCSSA form
}
/// isLCSSAForm - Return true if the Loop is in LCSSA form
}
MDNode *Loop::getLoopID() const {
}
MDNode *Loop::getLoopID() const {
+ MDNode *LoopID = nullptr;
if (isLoopSimplifyForm()) {
LoopID = getLoopLatch()->getTerminator()->getMetadata(LoopMDName);
} else {
if (isLoopSimplifyForm()) {
LoopID = getLoopLatch()->getTerminator()->getMetadata(LoopMDName);
} else {
BasicBlock *H = getHeader();
for (block_iterator I = block_begin(), IE = block_end(); I != IE; ++I) {
TerminatorInst *TI = (*I)->getTerminator();
BasicBlock *H = getHeader();
for (block_iterator I = block_begin(), IE = block_end(); I != IE; ++I) {
TerminatorInst *TI = (*I)->getTerminator();
// Check if this terminator branches to the loop header.
for (unsigned i = 0, ie = TI->getNumSuccessors(); i != ie; ++i) {
// Check if this terminator branches to the loop header.
for (unsigned i = 0, ie = TI->getNumSuccessors(); i != ie; ++i) {
if (!LoopID)
LoopID = MD;
else if (MD != LoopID)
if (!LoopID)
LoopID = MD;
else if (MD != LoopID)
}
}
if (!LoopID || LoopID->getNumOperands() == 0 ||
LoopID->getOperand(0) != LoopID)
}
}
if (!LoopID || LoopID->getNumOperands() == 0 ||
LoopID->getOperand(0) != LoopID)
getUniqueExitBlocks(UniqueExitBlocks);
if (UniqueExitBlocks.size() == 1)
return UniqueExitBlocks[0];
getUniqueExitBlocks(UniqueExitBlocks);
if (UniqueExitBlocks.size() == 1)
return UniqueExitBlocks[0];
}
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
}
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
// is considered uninitialized.
Loop *NearLoop = BBLoop;
// is considered uninitialized.
Loop *NearLoop = BBLoop;
+ Loop *Subloop = nullptr;
if (NearLoop != Unloop && Unloop->contains(NearLoop)) {
Subloop = NearLoop;
// Find the subloop ancestor that is directly contained within Unloop.
if (NearLoop != Unloop && Unloop->contains(NearLoop)) {
Subloop = NearLoop;
// Find the subloop ancestor that is directly contained within Unloop.
succ_iterator I = succ_begin(BB), E = succ_end(BB);
if (I == E) {
assert(!Subloop && "subloop blocks must have a successor");
succ_iterator I = succ_begin(BB), E = succ_end(BB);
if (I == E) {
assert(!Subloop && "subloop blocks must have a successor");
- NearLoop = 0; // unloop blocks may now exit the function.
+ NearLoop = nullptr; // unloop blocks may now exit the function.
}
for (; I != E; ++I) {
if (*I == BB)
}
for (; I != E; ++I) {
if (*I == BB)
// Blocks no longer have a parent but are still referenced by Unloop until
// the Unloop object is deleted.
// Blocks no longer have a parent but are still referenced by Unloop until
// the Unloop object is deleted.
- LI.changeLoopFor(*I, 0);
+ LI.changeLoopFor(*I, nullptr);
}
// Remove the loop from the top-level LoopInfo object.
}
// Remove the loop from the top-level LoopInfo object.
: FunctionPass(ID), PMDataManager() {
skipThisLoop = false;
redoThisLoop = false;
: FunctionPass(ID), PMDataManager() {
skipThisLoop = false;
redoThisLoop = false;
- LI = NULL;
- CurrentLoop = NULL;
+ LI = nullptr;
+ CurrentLoop = nullptr;
}
/// Delete loop from the loop queue and loop hierarchy (LoopInfo).
}
/// Delete loop from the loop queue and loop hierarchy (LoopInfo).
bool runOnFunction(Function &F) override;
bool runOnFunction(Function &F) override;
- void print(raw_ostream &OS, const Module * = 0) const override;
+ void print(raw_ostream &OS, const Module * = nullptr) const override;
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequiredTransitive<AliasAnalysis>();
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequiredTransitive<AliasAnalysis>();
void releaseMemory() override {
Deps.clear();
void releaseMemory() override {
Deps.clear();
MemDepResult Res = MDA.getDependency(Inst);
if (!Res.isNonLocal()) {
Deps[Inst].insert(std::make_pair(getInstTypePair(Res),
MemDepResult Res = MDA.getDependency(Inst);
if (!Res.isNonLocal()) {
Deps[Inst].insert(std::make_pair(getInstTypePair(Res),
- static_cast<BasicBlock *>(0)));
+ static_cast<BasicBlock *>(nullptr)));
} else if (CallSite CS = cast<Value>(Inst)) {
const MemoryDependenceAnalysis::NonLocalDepInfo &NLDI =
MDA.getNonLocalCallDependency(CS);
} else if (CallSite CS = cast<Value>(Inst)) {
const MemoryDependenceAnalysis::NonLocalDepInfo &NLDI =
MDA.getNonLocalCallDependency(CS);
if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
if (!LI->isUnordered()) {
// FIXME: Handle atomic/volatile loads.
if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
if (!LI->isUnordered()) {
// FIXME: Handle atomic/volatile loads.
- Deps[Inst].insert(std::make_pair(getInstTypePair(0, Unknown),
- static_cast<BasicBlock *>(0)));
+ Deps[Inst].insert(std::make_pair(getInstTypePair(nullptr, Unknown),
+ static_cast<BasicBlock *>(nullptr)));
continue;
}
AliasAnalysis::Location Loc = AA.getLocation(LI);
continue;
}
AliasAnalysis::Location Loc = AA.getLocation(LI);
} else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
if (!SI->isUnordered()) {
// FIXME: Handle atomic/volatile stores.
} else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
if (!SI->isUnordered()) {
// FIXME: Handle atomic/volatile stores.
- Deps[Inst].insert(std::make_pair(getInstTypePair(0, Unknown),
- static_cast<BasicBlock *>(0)));
+ Deps[Inst].insert(std::make_pair(getInstTypePair(nullptr, Unknown),
+ static_cast<BasicBlock *>(nullptr)));
continue;
}
AliasAnalysis::Location Loc = AA.getLocation(SI);
continue;
}
AliasAnalysis::Location Loc = AA.getLocation(SI);
CallSite CS(const_cast<Value*>(V));
if (!CS.getInstruction())
CallSite CS(const_cast<Value*>(V));
if (!CS.getInstruction())
Function *Callee = CS.getCalledFunction();
if (!Callee || !Callee->isDeclaration())
Function *Callee = CS.getCalledFunction();
if (!Callee || !Callee->isDeclaration())
bool LookThroughBitCast = false) {
// Skip intrinsics
if (isa<IntrinsicInst>(V))
bool LookThroughBitCast = false) {
// Skip intrinsics
if (isa<IntrinsicInst>(V))
Function *Callee = getCalledFunction(V, LookThroughBitCast);
if (!Callee)
Function *Callee = getCalledFunction(V, LookThroughBitCast);
if (!Callee)
// Make sure that the function is available.
StringRef FnName = Callee->getName();
LibFunc::Func TLIFn;
if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
// Make sure that the function is available.
StringRef FnName = Callee->getName();
LibFunc::Func TLIFn;
if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
unsigned i = 0;
bool found = false;
unsigned i = 0;
bool found = false;
const AllocFnsTy *FnData = &AllocationFnData[i];
if ((FnData->AllocTy & AllocTy) != FnData->AllocTy)
const AllocFnsTy *FnData = &AllocationFnData[i];
if ((FnData->AllocTy & AllocTy) != FnData->AllocTy)
// Check function prototype.
int FstParam = FnData->FstParam;
// Check function prototype.
int FstParam = FnData->FstParam;
FTy->getParamType(SndParam)->isIntegerTy(32) ||
FTy->getParamType(SndParam)->isIntegerTy(64)))
return FnData;
FTy->getParamType(SndParam)->isIntegerTy(32) ||
FTy->getParamType(SndParam)->isIntegerTy(64)))
return FnData;
}
static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
}
static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) {
/// ignore InvokeInst here.
const CallInst *llvm::extractMallocCall(const Value *I,
const TargetLibraryInfo *TLI) {
/// ignore InvokeInst here.
const CallInst *llvm::extractMallocCall(const Value *I,
const TargetLibraryInfo *TLI) {
- return isMallocLikeFn(I, TLI) ? dyn_cast<CallInst>(I) : 0;
+ return isMallocLikeFn(I, TLI) ? dyn_cast<CallInst>(I) : nullptr;
}
static Value *computeArraySize(const CallInst *CI, const DataLayout *DL,
const TargetLibraryInfo *TLI,
bool LookThroughSExt = false) {
if (!CI)
}
static Value *computeArraySize(const CallInst *CI, const DataLayout *DL,
const TargetLibraryInfo *TLI,
bool LookThroughSExt = false) {
if (!CI)
// The size of the malloc's result type must be known to determine array size.
Type *T = getMallocAllocatedType(CI, TLI);
if (!T || !T->isSized() || !DL)
// The size of the malloc's result type must be known to determine array size.
Type *T = getMallocAllocatedType(CI, TLI);
if (!T || !T->isSized() || !DL)
unsigned ElementSize = DL->getTypeAllocSize(T);
if (StructType *ST = dyn_cast<StructType>(T))
unsigned ElementSize = DL->getTypeAllocSize(T);
if (StructType *ST = dyn_cast<StructType>(T))
// If malloc call's arg can be determined to be a multiple of ElementSize,
// return the multiple. Otherwise, return NULL.
Value *MallocArg = CI->getArgOperand(0);
// If malloc call's arg can be determined to be a multiple of ElementSize,
// return the multiple. Otherwise, return NULL.
Value *MallocArg = CI->getArgOperand(0);
+ Value *Multiple = nullptr;
if (ComputeMultiple(MallocArg, ElementSize, Multiple,
LookThroughSExt))
return Multiple;
if (ComputeMultiple(MallocArg, ElementSize, Multiple,
LookThroughSExt))
return Multiple;
}
/// isArrayMalloc - Returns the corresponding CallInst if the instruction
}
/// isArrayMalloc - Returns the corresponding CallInst if the instruction
return CI;
// CI is a non-array malloc or we can't figure out that it is an array malloc.
return CI;
// CI is a non-array malloc or we can't figure out that it is an array malloc.
}
/// getMallocType - Returns the PointerType resulting from the malloc call.
}
/// getMallocType - Returns the PointerType resulting from the malloc call.
const TargetLibraryInfo *TLI) {
assert(isMallocLikeFn(CI, TLI) && "getMallocType and not malloc call");
const TargetLibraryInfo *TLI) {
assert(isMallocLikeFn(CI, TLI) && "getMallocType and not malloc call");
- PointerType *MallocType = 0;
+ PointerType *MallocType = nullptr;
unsigned NumOfBitCastUses = 0;
// Determine if CallInst has a bitcast use.
unsigned NumOfBitCastUses = 0;
// Determine if CallInst has a bitcast use.
return cast<PointerType>(CI->getType());
// Type could not be determined.
return cast<PointerType>(CI->getType());
// Type could not be determined.
}
/// getMallocAllocatedType - Returns the Type allocated by malloc call.
}
/// getMallocAllocatedType - Returns the Type allocated by malloc call.
Type *llvm::getMallocAllocatedType(const CallInst *CI,
const TargetLibraryInfo *TLI) {
PointerType *PT = getMallocType(CI, TLI);
Type *llvm::getMallocAllocatedType(const CallInst *CI,
const TargetLibraryInfo *TLI) {
PointerType *PT = getMallocType(CI, TLI);
- return PT ? PT->getElementType() : 0;
+ return PT ? PT->getElementType() : nullptr;
}
/// getMallocArraySize - Returns the array size of a malloc call. If the
}
/// getMallocArraySize - Returns the array size of a malloc call. If the
/// is a calloc call.
const CallInst *llvm::extractCallocCall(const Value *I,
const TargetLibraryInfo *TLI) {
/// is a calloc call.
const CallInst *llvm::extractCallocCall(const Value *I,
const TargetLibraryInfo *TLI) {
- return isCallocLikeFn(I, TLI) ? cast<CallInst>(I) : 0;
+ return isCallocLikeFn(I, TLI) ? cast<CallInst>(I) : nullptr;
const CallInst *llvm::isFreeCall(const Value *I, const TargetLibraryInfo *TLI) {
const CallInst *CI = dyn_cast<CallInst>(I);
if (!CI || isa<IntrinsicInst>(CI))
const CallInst *llvm::isFreeCall(const Value *I, const TargetLibraryInfo *TLI) {
const CallInst *CI = dyn_cast<CallInst>(I);
if (!CI || isa<IntrinsicInst>(CI))
Function *Callee = CI->getCalledFunction();
Function *Callee = CI->getCalledFunction();
- if (Callee == 0 || !Callee->isDeclaration())
- return 0;
+ if (Callee == nullptr || !Callee->isDeclaration())
+ return nullptr;
StringRef FnName = Callee->getName();
LibFunc::Func TLIFn;
if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
StringRef FnName = Callee->getName();
LibFunc::Func TLIFn;
if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn))
unsigned ExpectedNumParams;
if (TLIFn == LibFunc::free ||
unsigned ExpectedNumParams;
if (TLIFn == LibFunc::free ||
TLIFn == LibFunc::ZdaPvRKSt9nothrow_t) // delete[](void*, nothrow)
ExpectedNumParams = 2;
else
TLIFn == LibFunc::ZdaPvRKSt9nothrow_t) // delete[](void*, nothrow)
ExpectedNumParams = 2;
else
// Check free prototype.
// FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
// attribute will exist.
FunctionType *FTy = Callee->getFunctionType();
if (!FTy->getReturnType()->isVoidTy())
// Check free prototype.
// FIXME: workaround for PR5130, this will be obsolete when a nobuiltin
// attribute will exist.
FunctionType *FTy = Callee->getFunctionType();
if (!FTy->getReturnType()->isVoidTy())
if (FTy->getNumParams() != ExpectedNumParams)
if (FTy->getNumParams() != ExpectedNumParams)
if (FTy->getParamType(0) != Type::getInt8PtrTy(Callee->getContext()))
if (FTy->getParamType(0) != Type::getInt8PtrTy(Callee->getContext()))
bool MemoryDependenceAnalysis::runOnFunction(Function &) {
AA = &getAnalysis<AliasAnalysis>();
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
bool MemoryDependenceAnalysis::runOnFunction(Function &) {
AA = &getAnalysis<AliasAnalysis>();
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
- DL = DLP ? &DLP->getDataLayout() : 0;
+ DL = DLP ? &DLP->getDataLayout() : nullptr;
DominatorTreeWrapperPass *DTWP =
getAnalysisIfAvailable<DominatorTreeWrapperPass>();
DominatorTreeWrapperPass *DTWP =
getAnalysisIfAvailable<DominatorTreeWrapperPass>();
- DT = DTWP ? &DTWP->getDomTree() : 0;
+ DT = DTWP ? &DTWP->getDomTree() : nullptr;
if (!PredCache)
PredCache.reset(new PredIteratorCache());
return false;
if (!PredCache)
PredCache.reset(new PredIteratorCache());
return false;
const LoadInst *LI,
const DataLayout *DL) {
// If we have no target data, we can't do this.
const LoadInst *LI,
const DataLayout *DL) {
// If we have no target data, we can't do this.
- if (DL == 0) return false;
// If we haven't already computed the base/offset of MemLoc, do so now.
// If we haven't already computed the base/offset of MemLoc, do so now.
MemLocBase = GetPointerBaseWithConstantOffset(MemLoc.Ptr, MemLocOffs, DL);
unsigned Size = MemoryDependenceAnalysis::
MemLocBase = GetPointerBaseWithConstantOffset(MemLoc.Ptr, MemLocOffs, DL);
unsigned Size = MemoryDependenceAnalysis::
BasicBlock::iterator ScanIt, BasicBlock *BB,
Instruction *QueryInst) {
BasicBlock::iterator ScanIt, BasicBlock *BB,
Instruction *QueryInst) {
- const Value *MemLocBase = 0;
+ const Value *MemLocBase = nullptr;
int64_t MemLocOffset = 0;
unsigned Limit = BlockScanLimit;
bool isInvariantLoad = false;
if (isLoad && QueryInst) {
LoadInst *LI = dyn_cast<LoadInst>(QueryInst);
int64_t MemLocOffset = 0;
unsigned Limit = BlockScanLimit;
bool isInvariantLoad = false;
if (isLoad && QueryInst) {
LoadInst *LI = dyn_cast<LoadInst>(QueryInst);
- if (LI && LI->getMetadata(LLVMContext::MD_invariant_load) != 0)
+ if (LI && LI->getMetadata(LLVMContext::MD_invariant_load) != nullptr)
isInvariantLoad = true;
}
isInvariantLoad = true;
}
if (Entry != Cache.begin() && std::prev(Entry)->getBB() == DirtyBB)
--Entry;
if (Entry != Cache.begin() && std::prev(Entry)->getBB() == DirtyBB)
--Entry;
- NonLocalDepEntry *ExistingResult = 0;
+ NonLocalDepEntry *ExistingResult = nullptr;
if (Entry != Cache.begin()+NumSortedEntries &&
Entry->getBB() == DirtyBB) {
// If we already have an entry, and if it isn't already dirty, the block
if (Entry != Cache.begin()+NumSortedEntries &&
Entry->getBB() == DirtyBB) {
// If we already have an entry, and if it isn't already dirty, the block
if (Entry != Cache->begin() && (Entry-1)->getBB() == BB)
--Entry;
if (Entry != Cache->begin() && (Entry-1)->getBB() == BB)
--Entry;
- NonLocalDepEntry *ExistingResult = 0;
+ NonLocalDepEntry *ExistingResult = nullptr;
if (Entry != Cache->begin()+NumSortedEntries && Entry->getBB() == BB)
ExistingResult = &*Entry;
if (Entry != Cache->begin()+NumSortedEntries && Entry->getBB() == BB)
ExistingResult = &*Entry;
if (CacheInfo->TBAATag != Loc.TBAATag) {
if (CacheInfo->TBAATag) {
CacheInfo->Pair = BBSkipFirstBlockPair();
if (CacheInfo->TBAATag != Loc.TBAATag) {
if (CacheInfo->TBAATag) {
CacheInfo->Pair = BBSkipFirstBlockPair();
- CacheInfo->TBAATag = 0;
+ CacheInfo->TBAATag = nullptr;
for (NonLocalDepInfo::iterator DI = CacheInfo->NonLocalDeps.begin(),
DE = CacheInfo->NonLocalDeps.end(); DI != DE; ++DI)
if (Instruction *Inst = DI->getResult().getInst())
for (NonLocalDepInfo::iterator DI = CacheInfo->NonLocalDeps.begin(),
DE = CacheInfo->NonLocalDeps.end(); DI != DE; ++DI)
if (Instruction *Inst = DI->getResult().getInst())
SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
NumSortedEntries = Cache->size();
}
SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
NumSortedEntries = Cache->size();
}
PredList.clear();
for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) {
PredList.clear();
for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) {
// Get the PHI translated pointer in this predecessor. This can fail if
// not translatable, in which case the getAddr() returns null.
PHITransAddr &PredPointer = PredList.back().second;
// Get the PHI translated pointer in this predecessor. This can fail if
// not translatable, in which case the getAddr() returns null.
PHITransAddr &PredPointer = PredList.back().second;
- PredPointer.PHITranslateValue(BB, Pred, 0);
+ PredPointer.PHITranslateValue(BB, Pred, nullptr);
Value *PredPtrVal = PredPointer.getAddr();
Value *PredPtrVal = PredPointer.getAddr();
// predecessor, then we have to assume that the pointer is clobbered in
// that predecessor. We can still do PRE of the load, which would insert
// a computation of the pointer in this predecessor.
// predecessor, then we have to assume that the pointer is clobbered in
// that predecessor. We can still do PRE of the load, which would insert
// a computation of the pointer in this predecessor.
CanTranslate = false;
// FIXME: it is entirely possible that PHI translating will end up with
CanTranslate = false;
// FIXME: it is entirely possible that PHI translating will end up with
// for the given block. It assumes that we haven't modified any of
// our datastructures while processing the current block.
// for the given block. It assumes that we haven't modified any of
// our datastructures while processing the current block.
// Refresh the CacheInfo/Cache pointer if it got invalidated.
CacheInfo = &NonLocalPointerDeps[CacheKey];
Cache = &CacheInfo->NonLocalDeps;
// Refresh the CacheInfo/Cache pointer if it got invalidated.
CacheInfo = &NonLocalPointerDeps[CacheKey];
Cache = &CacheInfo->NonLocalDeps;
for (unsigned i = 0, e = PInfo.size(); i != e; ++i) {
Instruction *Target = PInfo[i].getResult().getInst();
for (unsigned i = 0, e = PInfo.size(); i != e; ++i) {
Instruction *Target = PInfo[i].getResult().getInst();
- if (Target == 0) continue; // Ignore non-local dep results.
+ if (!Target) continue; // Ignore non-local dep results.
assert(Target->getParent() == PInfo[i].getBB());
// Eliminating the dirty entry from 'Cache', so update the reverse info.
assert(Target->getParent() == PInfo[i].getBB());
// Eliminating the dirty entry from 'Cache', so update the reverse info.
// Note: NoAA does not call InitializeAliasAnalysis because it's
// special and does not support chaining.
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
// Note: NoAA does not call InitializeAliasAnalysis because it's
// special and does not support chaining.
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
- DL = DLP ? &DLP->getDataLayout() : 0;
+ DL = DLP ? &DLP->getDataLayout() : nullptr;
}
AliasResult alias(const Location &LocA, const Location &LocB) override {
}
AliasResult alias(const Location &LocA, const Location &LocB) override {
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
void PHITransAddr::dump() const {
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
void PHITransAddr::dump() const {
dbgs() << "PHITransAddr: null\n";
return;
}
dbgs() << "PHITransAddr: null\n";
return;
}
SmallVectorImpl<Instruction*> &InstInputs) {
// If this is a non-instruction value, there is nothing to do.
Instruction *I = dyn_cast<Instruction>(Expr);
SmallVectorImpl<Instruction*> &InstInputs) {
// If this is a non-instruction value, there is nothing to do.
Instruction *I = dyn_cast<Instruction>(Expr);
- if (I == 0) return true;
// If it's an instruction, it is either in Tmp or its operands recursively
// are.
// If it's an instruction, it is either in Tmp or its operands recursively
// are.
/// structure is valid, it returns true. If invalid, it prints errors and
/// returns false.
bool PHITransAddr::Verify() const {
/// structure is valid, it returns true. If invalid, it prints errors and
/// returns false.
bool PHITransAddr::Verify() const {
- if (Addr == 0) return true;
+ if (!Addr) return true;
SmallVector<Instruction*, 8> Tmp(InstInputs.begin(), InstInputs.end());
SmallVector<Instruction*, 8> Tmp(InstInputs.begin(), InstInputs.end());
// If the input value is not an instruction, or if it is not defined in CurBB,
// then we don't need to phi translate it.
Instruction *Inst = dyn_cast<Instruction>(Addr);
// If the input value is not an instruction, or if it is not defined in CurBB,
// then we don't need to phi translate it.
Instruction *Inst = dyn_cast<Instruction>(Addr);
- return Inst == 0 || CanPHITrans(Inst);
+ return !Inst || CanPHITrans(Inst);
}
static void RemoveInstInputs(Value *V,
SmallVectorImpl<Instruction*> &InstInputs) {
Instruction *I = dyn_cast<Instruction>(V);
}
static void RemoveInstInputs(Value *V,
SmallVectorImpl<Instruction*> &InstInputs) {
Instruction *I = dyn_cast<Instruction>(V);
// If the instruction is in the InstInputs list, remove it.
SmallVectorImpl<Instruction*>::iterator Entry =
// If the instruction is in the InstInputs list, remove it.
SmallVectorImpl<Instruction*>::iterator Entry =
const DominatorTree *DT) {
// If this is a non-instruction value, it can't require PHI translation.
Instruction *Inst = dyn_cast<Instruction>(V);
const DominatorTree *DT) {
// If this is a non-instruction value, it can't require PHI translation.
Instruction *Inst = dyn_cast<Instruction>(V);
- if (Inst == 0) return V;
// Determine whether 'Inst' is an input to our PHI translatable expression.
bool isInput = std::count(InstInputs.begin(), InstInputs.end(), Inst);
// Determine whether 'Inst' is an input to our PHI translatable expression.
bool isInput = std::count(InstInputs.begin(), InstInputs.end(), Inst);
// If this is a non-phi value, and it is analyzable, we can incorporate it
// into the expression by making all instruction operands be inputs.
if (!CanPHITrans(Inst))
// If this is a non-phi value, and it is analyzable, we can incorporate it
// into the expression by making all instruction operands be inputs.
if (!CanPHITrans(Inst))
// All instruction operands are now inputs (and of course, they may also be
// defined in this block, so they may need to be phi translated themselves.
// All instruction operands are now inputs (and of course, they may also be
// defined in this block, so they may need to be phi translated themselves.
// operands need to be phi translated, and if so, reconstruct it.
if (CastInst *Cast = dyn_cast<CastInst>(Inst)) {
// operands need to be phi translated, and if so, reconstruct it.
if (CastInst *Cast = dyn_cast<CastInst>(Inst)) {
- if (!isSafeToSpeculativelyExecute(Cast)) return 0;
+ if (!isSafeToSpeculativelyExecute(Cast)) return nullptr;
Value *PHIIn = PHITranslateSubExpr(Cast->getOperand(0), CurBB, PredBB, DT);
Value *PHIIn = PHITranslateSubExpr(Cast->getOperand(0), CurBB, PredBB, DT);
- if (PHIIn == 0) return 0;
+ if (!PHIIn) return nullptr;
if (PHIIn == Cast->getOperand(0))
return Cast;
if (PHIIn == Cast->getOperand(0))
return Cast;
(!DT || DT->dominates(CastI->getParent(), PredBB)))
return CastI;
}
(!DT || DT->dominates(CastI->getParent(), PredBB)))
return CastI;
}
}
// Handle getelementptr with at least one PHI translatable operand.
}
// Handle getelementptr with at least one PHI translatable operand.
bool AnyChanged = false;
for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) {
Value *GEPOp = PHITranslateSubExpr(GEP->getOperand(i), CurBB, PredBB, DT);
bool AnyChanged = false;
for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) {
Value *GEPOp = PHITranslateSubExpr(GEP->getOperand(i), CurBB, PredBB, DT);
- if (GEPOp == 0) return 0;
+ if (!GEPOp) return nullptr;
AnyChanged |= GEPOp != GEP->getOperand(i);
GEPOps.push_back(GEPOp);
AnyChanged |= GEPOp != GEP->getOperand(i);
GEPOps.push_back(GEPOp);
}
// Handle add with a constant RHS.
}
// Handle add with a constant RHS.
bool isNUW = cast<BinaryOperator>(Inst)->hasNoUnsignedWrap();
Value *LHS = PHITranslateSubExpr(Inst->getOperand(0), CurBB, PredBB, DT);
bool isNUW = cast<BinaryOperator>(Inst)->hasNoUnsignedWrap();
Value *LHS = PHITranslateSubExpr(Inst->getOperand(0), CurBB, PredBB, DT);
- if (LHS == 0) return 0;
+ if (!LHS) return nullptr;
// If the PHI translated LHS is an add of a constant, fold the immediates.
if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(LHS))
// If the PHI translated LHS is an add of a constant, fold the immediates.
if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(LHS))
}
// Otherwise, we failed.
}
// Otherwise, we failed.
// Make sure the value is live in the predecessor.
if (Instruction *Inst = dyn_cast_or_null<Instruction>(Addr))
if (!DT->dominates(Inst->getParent(), PredBB))
// Make sure the value is live in the predecessor.
if (Instruction *Inst = dyn_cast_or_null<Instruction>(Addr))
if (!DT->dominates(Inst->getParent(), PredBB))
+ return Addr == nullptr;
}
/// PHITranslateWithInsertion - PHI translate this value into the specified
}
/// PHITranslateWithInsertion - PHI translate this value into the specified
// If not, destroy any intermediate instructions inserted.
while (NewInsts.size() != NISize)
NewInsts.pop_back_val()->eraseFromParent();
// If not, destroy any intermediate instructions inserted.
while (NewInsts.size() != NISize)
NewInsts.pop_back_val()->eraseFromParent();
// Handle cast of PHI translatable value.
if (CastInst *Cast = dyn_cast<CastInst>(Inst)) {
// Handle cast of PHI translatable value.
if (CastInst *Cast = dyn_cast<CastInst>(Inst)) {
- if (!isSafeToSpeculativelyExecute(Cast)) return 0;
+ if (!isSafeToSpeculativelyExecute(Cast)) return nullptr;
Value *OpVal = InsertPHITranslatedSubExpr(Cast->getOperand(0),
CurBB, PredBB, DT, NewInsts);
Value *OpVal = InsertPHITranslatedSubExpr(Cast->getOperand(0),
CurBB, PredBB, DT, NewInsts);
- if (OpVal == 0) return 0;
+ if (!OpVal) return nullptr;
// Otherwise insert a cast at the end of PredBB.
CastInst *New = CastInst::Create(Cast->getOpcode(),
// Otherwise insert a cast at the end of PredBB.
CastInst *New = CastInst::Create(Cast->getOpcode(),
for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) {
Value *OpVal = InsertPHITranslatedSubExpr(GEP->getOperand(i),
CurBB, PredBB, DT, NewInsts);
for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) {
Value *OpVal = InsertPHITranslatedSubExpr(GEP->getOperand(i),
CurBB, PredBB, DT, NewInsts);
- if (OpVal == 0) return 0;
+ if (!OpVal) return nullptr;
GEPOps.push_back(OpVal);
}
GEPOps.push_back(OpVal);
}
// BBs that are not part of any loop are element of the Loop
// described by the NULL pointer. This loop is not part of any region,
// except if the region describes the whole function.
// BBs that are not part of any loop are element of the Loop
// described by the NULL pointer. This loop is not part of any region,
// except if the region describes the whole function.
- if (L == 0)
- return getExit() == 0;
+ if (!L)
+ return getExit() == nullptr;
if (!contains(L->getHeader()))
return false;
if (!contains(L->getHeader()))
return false;
Loop *Region::outermostLoopInRegion(Loop *L) const {
if (!contains(L))
Loop *Region::outermostLoopInRegion(Loop *L) const {
if (!contains(L))
while (L && contains(L->getParentLoop())) {
L = L->getParentLoop();
while (L && contains(L->getParentLoop())) {
L = L->getParentLoop();
BasicBlock *Region::getEnteringBlock() const {
BasicBlock *entry = getEntry();
BasicBlock *Pred;
BasicBlock *Region::getEnteringBlock() const {
BasicBlock *entry = getEntry();
BasicBlock *Pred;
- BasicBlock *enteringBlock = 0;
+ BasicBlock *enteringBlock = nullptr;
for (pred_iterator PI = pred_begin(entry), PE = pred_end(entry); PI != PE;
++PI) {
Pred = *PI;
if (DT->getNode(Pred) && !contains(Pred)) {
if (enteringBlock)
for (pred_iterator PI = pred_begin(entry), PE = pred_end(entry); PI != PE;
++PI) {
Pred = *PI;
if (DT->getNode(Pred) && !contains(Pred)) {
if (enteringBlock)
BasicBlock *Region::getExitingBlock() const {
BasicBlock *exit = getExit();
BasicBlock *Pred;
BasicBlock *Region::getExitingBlock() const {
BasicBlock *exit = getExit();
BasicBlock *Pred;
- BasicBlock *exitingBlock = 0;
+ BasicBlock *exitingBlock = nullptr;
for (pred_iterator PI = pred_begin(exit), PE = pred_end(exit); PI != PE;
++PI) {
Pred = *PI;
if (contains(Pred)) {
if (exitingBlock)
for (pred_iterator PI = pred_begin(exit), PE = pred_end(exit); PI != PE;
++PI) {
Pred = *PI;
if (contains(Pred)) {
if (exitingBlock)
Region *R = RI->getRegionFor(BB);
if (!R || R == this)
Region *R = RI->getRegionFor(BB);
if (!R || R == this)
// If we pass the BB out of this region, that means our code is broken.
assert(contains(R) && "BB not in current region!");
// If we pass the BB out of this region, that means our code is broken.
assert(contains(R) && "BB not in current region!");
R = R->getParent();
if (R->getEntry() != BB)
R = R->getParent();
if (R->getEntry() != BB)
}
void Region::addSubRegion(Region *SubRegion, bool moveChildren) {
}
void Region::addSubRegion(Region *SubRegion, bool moveChildren) {
- assert(SubRegion->parent == 0 && "SubRegion already has a parent!");
+ assert(!SubRegion->parent && "SubRegion already has a parent!");
assert(std::find(begin(), end(), SubRegion) == children.end()
&& "Subregion already exists!");
assert(std::find(begin(), end(), SubRegion) == children.end()
&& "Subregion already exists!");
Region *Region::removeSubRegion(Region *Child) {
assert(Child->parent == this && "Child is not a child of this region!");
Region *Region::removeSubRegion(Region *Child) {
assert(Child->parent == this && "Child is not a child of this region!");
+ Child->parent = nullptr;
RegionSet::iterator I = std::find(children.begin(), children.end(), Child);
assert(I != children.end() && "Region does not exit. Unable to remove.");
children.erase(children.begin()+(I-begin()));
RegionSet::iterator I = std::find(children.begin(), children.end(), Child);
assert(I != children.end() && "Region does not exit. Unable to remove.");
children.erase(children.begin()+(I-begin()));
unsigned Region::getDepth() const {
unsigned Depth = 0;
unsigned Region::getDepth() const {
unsigned Depth = 0;
- for (Region *R = parent; R != 0; R = R->parent)
+ for (Region *R = parent; R != nullptr; R = R->parent)
unsigned NumSuccessors = exit->getTerminator()->getNumSuccessors();
if (NumSuccessors == 0)
unsigned NumSuccessors = exit->getTerminator()->getNumSuccessors();
if (NumSuccessors == 0)
for (pred_iterator PI = pred_begin(getExit()), PE = pred_end(getExit());
PI != PE; ++PI)
if (!DT->dominates(getEntry(), *PI))
for (pred_iterator PI = pred_begin(getExit()), PE = pred_end(getExit());
PI != PE; ++PI)
if (!DT->dominates(getEntry(), *PI))
Region *R = RI->getRegionFor(exit);
Region *R = RI->getRegionFor(exit);
if (exit->getTerminator()->getNumSuccessors() == 1)
return new Region(getEntry(), *succ_begin(exit), RI, DT);
else
if (exit->getTerminator()->getNumSuccessors() == 1)
return new Region(getEntry(), *succ_begin(exit), RI, DT);
else
}
while (R->getParent() && R->getParent()->getEntry() == exit)
}
while (R->getParent() && R->getParent()->getEntry() == exit)
for (pred_iterator PI = pred_begin(getExit()), PE = pred_end(getExit());
PI != PE; ++PI)
if (!DT->dominates(R->getExit(), *PI))
for (pred_iterator PI = pred_begin(getExit()), PE = pred_end(getExit());
PI != PE; ++PI)
if (!DT->dominates(R->getExit(), *PI))
return new Region(getEntry(), R->getExit(), RI, DT);
}
return new Region(getEntry(), R->getExit(), RI, DT);
}
assert(entry && exit && "entry and exit must not be null!");
if (isTrivialRegion(entry, exit))
assert(entry && exit && "entry and exit must not be null!");
if (isTrivialRegion(entry, exit))
Region *region = new Region(entry, exit, this, DT);
BBtoRegion.insert(std::make_pair(entry, region));
Region *region = new Region(entry, exit, this, DT);
BBtoRegion.insert(std::make_pair(entry, region));
+ Region *lastRegion= nullptr;
BasicBlock *lastExit = entry;
// As only a BasicBlock that postdominates entry can finish a region, walk the
BasicBlock *lastExit = entry;
// As only a BasicBlock that postdominates entry can finish a region, walk the
BBtoRegion.clear();
if (TopLevelRegion)
delete TopLevelRegion;
BBtoRegion.clear();
if (TopLevelRegion)
delete TopLevelRegion;
+ TopLevelRegion = nullptr;
}
RegionInfo::RegionInfo() : FunctionPass(ID) {
initializeRegionInfoPass(*PassRegistry::getPassRegistry());
}
RegionInfo::RegionInfo() : FunctionPass(ID) {
initializeRegionInfoPass(*PassRegistry::getPassRegistry());
+ TopLevelRegion = nullptr;
}
RegionInfo::~RegionInfo() {
}
RegionInfo::~RegionInfo() {
PDT = &getAnalysis<PostDominatorTree>();
DF = &getAnalysis<DominanceFrontier>();
PDT = &getAnalysis<PostDominatorTree>();
DF = &getAnalysis<DominanceFrontier>();
- TopLevelRegion = new Region(&F.getEntryBlock(), 0, this, DT, 0);
+ TopLevelRegion = new Region(&F.getEntryBlock(), nullptr, this, DT, nullptr);
updateStatistics(TopLevelRegion);
Calculate(F);
updateStatistics(TopLevelRegion);
Calculate(F);
Region *RegionInfo::getRegionFor(BasicBlock *BB) const {
BBtoRegionMap::const_iterator I=
BBtoRegion.find(BB);
Region *RegionInfo::getRegionFor(BasicBlock *BB) const {
BBtoRegionMap::const_iterator I=
BBtoRegion.find(BB);
- return I != BBtoRegion.end() ? I->second : 0;
+ return I != BBtoRegion.end() ? I->second : nullptr;
}
void RegionInfo::setRegionFor(BasicBlock *BB, Region *R) {
}
void RegionInfo::setRegionFor(BasicBlock *BB, Region *R) {
}
BasicBlock *RegionInfo::getMaxRegionExit(BasicBlock *BB) const {
}
BasicBlock *RegionInfo::getMaxRegionExit(BasicBlock *BB) const {
- BasicBlock *Exit = NULL;
+ BasicBlock *Exit = nullptr;
while (true) {
// Get largest region that starts at BB.
while (true) {
// Get largest region that starts at BB.
: FunctionPass(ID), PMDataManager() {
skipThisRegion = false;
redoThisRegion = false;
: FunctionPass(ID), PMDataManager() {
skipThisRegion = false;
redoThisRegion = false;
- RI = NULL;
- CurrentRegion = NULL;
+ RI = nullptr;
+ CurrentRegion = nullptr;
}
// Recurse through all subregions and all regions into RQ.
}
// Recurse through all subregions and all regions into RQ.
case scUMaxExpr:
case scSMaxExpr: {
const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
case scUMaxExpr:
case scSMaxExpr: {
const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
+ const char *OpStr = nullptr;
switch (NAry->getSCEVType()) {
case scAddExpr: OpStr = " + "; break;
case scMulExpr: OpStr = " * "; break;
switch (NAry->getSCEVType()) {
case scAddExpr: OpStr = " + "; break;
case scMulExpr: OpStr = " * "; break;
FoldingSetNodeID ID;
ID.AddInteger(scConstant);
ID.AddPointer(V);
FoldingSetNodeID ID;
ID.AddInteger(scConstant);
ID.AddPointer(V);
if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
UniqueSCEVs.InsertNode(S, IP);
if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
UniqueSCEVs.InsertNode(S, IP);
SE->UniqueSCEVs.RemoveNode(this);
// Release the value.
SE->UniqueSCEVs.RemoveNode(this);
// Release the value.
}
void SCEVUnknown::allUsesReplacedWith(Value *New) {
}
void SCEVUnknown::allUsesReplacedWith(Value *New) {
ID.AddInteger(scTruncate);
ID.AddPointer(Op);
ID.AddPointer(Ty);
ID.AddInteger(scTruncate);
ID.AddPointer(Op);
ID.AddPointer(Ty);
if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
// Fold if the operand is constant.
if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
// Fold if the operand is constant.
ID.AddInteger(scZeroExtend);
ID.AddPointer(Op);
ID.AddPointer(Ty);
ID.AddInteger(scZeroExtend);
ID.AddPointer(Op);
ID.AddPointer(Ty);
if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
// zext(trunc(x)) --> zext(x) or x or trunc(x)
if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
// zext(trunc(x)) --> zext(x) or x or trunc(x)
return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
SE->getSignedRange(Step).getSignedMin());
}
return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
SE->getSignedRange(Step).getSignedMin());
}
}
// The recurrence AR has been shown to have no signed wrap. Typically, if we can
}
// The recurrence AR has been shown to have no signed wrap. Typically, if we can
// Check for a simple looking step prior to loop entry.
const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
if (!SA)
// Check for a simple looking step prior to loop entry.
const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
if (!SA)
// Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
// subtraction is expensive. For this purpose, perform a quick and dirty
// Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
// subtraction is expensive. For this purpose, perform a quick and dirty
DiffOps.push_back(*I);
}
if (DiffOps.size() == SA->getNumOperands())
DiffOps.push_back(*I);
}
if (DiffOps.size() == SA->getNumOperands())
// This is a postinc AR. Check for overflow on the preinc recurrence using the
// same three conditions that getSignExtendedExpr checks.
// This is a postinc AR. Check for overflow on the preinc recurrence using the
// same three conditions that getSignExtendedExpr checks.
SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) {
return PreStart;
}
SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) {
return PreStart;
}
}
// Get the normalized sign-extended expression for this AddRec's Start.
}
// Get the normalized sign-extended expression for this AddRec's Start.
ID.AddInteger(scSignExtend);
ID.AddPointer(Op);
ID.AddPointer(Ty);
ID.AddInteger(scSignExtend);
ID.AddPointer(Op);
ID.AddPointer(Ty);
if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
// If the input value is provably positive, build a zext instead.
if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
// If the input value is provably positive, build a zext instead.
ID.AddInteger(scAddExpr);
for (unsigned i = 0, e = Ops.size(); i != e; ++i)
ID.AddPointer(Ops[i]);
ID.AddInteger(scAddExpr);
for (unsigned i = 0, e = Ops.size(); i != e; ++i)
ID.AddPointer(Ops[i]);
SCEVAddExpr *S =
static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
if (!S) {
SCEVAddExpr *S =
static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
if (!S) {
ID.AddInteger(scMulExpr);
for (unsigned i = 0, e = Ops.size(); i != e; ++i)
ID.AddPointer(Ops[i]);
ID.AddInteger(scMulExpr);
for (unsigned i = 0, e = Ops.size(); i != e; ++i)
ID.AddPointer(Ops[i]);
SCEVMulExpr *S =
static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
if (!S) {
SCEVMulExpr *S =
static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
if (!S) {
ID.AddInteger(scUDivExpr);
ID.AddPointer(LHS);
ID.AddPointer(RHS);
ID.AddInteger(scUDivExpr);
ID.AddPointer(LHS);
ID.AddPointer(RHS);
if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
LHS, RHS);
if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
LHS, RHS);
for (unsigned i = 0, e = Operands.size(); i != e; ++i)
ID.AddPointer(Operands[i]);
ID.AddPointer(L);
for (unsigned i = 0, e = Operands.size(); i != e; ++i)
ID.AddPointer(Operands[i]);
ID.AddPointer(L);
SCEVAddRecExpr *S =
static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
if (!S) {
SCEVAddRecExpr *S =
static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
if (!S) {
ID.AddInteger(scSMaxExpr);
for (unsigned i = 0, e = Ops.size(); i != e; ++i)
ID.AddPointer(Ops[i]);
ID.AddInteger(scSMaxExpr);
for (unsigned i = 0, e = Ops.size(); i != e; ++i)
ID.AddPointer(Ops[i]);
if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
std::uninitialized_copy(Ops.begin(), Ops.end(), O);
if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
std::uninitialized_copy(Ops.begin(), Ops.end(), O);
ID.AddInteger(scUMaxExpr);
for (unsigned i = 0, e = Ops.size(); i != e; ++i)
ID.AddPointer(Ops[i]);
ID.AddInteger(scUMaxExpr);
for (unsigned i = 0, e = Ops.size(); i != e; ++i)
ID.AddPointer(Ops[i]);
if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
std::uninitialized_copy(Ops.begin(), Ops.end(), O);
if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
std::uninitialized_copy(Ops.begin(), Ops.end(), O);
FoldingSetNodeID ID;
ID.AddInteger(scUnknown);
ID.AddPointer(V);
FoldingSetNodeID ID;
ID.AddInteger(scUnknown);
ID.AddPointer(V);
if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
assert(cast<SCEVUnknown>(S)->getValue() == V &&
"Stale SCEVUnknown in uniquing map!");
if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
assert(cast<SCEVUnknown>(S)->getValue() == V &&
"Stale SCEVUnknown in uniquing map!");
return getPointerBase(Cast->getOperand());
}
else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
return getPointerBase(Cast->getOperand());
}
else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
+ const SCEV *PtrOp = nullptr;
for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
I != E; ++I) {
if ((*I)->getType()->isPointerTy()) {
for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
I != E; ++I) {
if ((*I)->getType()->isPointerTy()) {
// The loop may have multiple entrances or multiple exits; we can analyze
// this phi as an addrec if it has a unique entry value and a unique
// backedge value.
// The loop may have multiple entrances or multiple exits; we can analyze
// this phi as an addrec if it has a unique entry value and a unique
// backedge value.
- Value *BEValueV = 0, *StartValueV = 0;
+ Value *BEValueV = nullptr, *StartValueV = nullptr;
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Value *V = PN->getIncomingValue(i);
if (L->contains(PN->getIncomingBlock(i))) {
if (!BEValueV) {
BEValueV = V;
} else if (BEValueV != V) {
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Value *V = PN->getIncomingValue(i);
if (L->contains(PN->getIncomingBlock(i))) {
if (!BEValueV) {
BEValueV = V;
} else if (BEValueV != V) {
break;
}
} else if (!StartValueV) {
StartValueV = V;
} else if (StartValueV != V) {
break;
}
} else if (!StartValueV) {
StartValueV = V;
} else if (StartValueV != V) {
if (!ExitNotTaken.ExitingBlock) return SE->getCouldNotCompute();
assert(ExitNotTaken.ExactNotTaken && "uninitialized not-taken info");
if (!ExitNotTaken.ExitingBlock) return SE->getCouldNotCompute();
assert(ExitNotTaken.ExactNotTaken && "uninitialized not-taken info");
- const SCEV *BECount = 0;
+ const SCEV *BECount = nullptr;
for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
- ENT != 0; ENT = ENT->getNextExit()) {
+ ENT != nullptr; ENT = ENT->getNextExit()) {
assert(ENT->ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
assert(ENT->ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
ScalarEvolution *SE) const {
for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
ScalarEvolution *SE) const {
for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
- ENT != 0; ENT = ENT->getNextExit()) {
+ ENT != nullptr; ENT = ENT->getNextExit()) {
if (ENT->ExitingBlock == ExitingBlock)
return ENT->ExactNotTaken;
if (ENT->ExitingBlock == ExitingBlock)
return ENT->ExactNotTaken;
return false;
for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
return false;
for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
- ENT != 0; ENT = ENT->getNextExit()) {
+ ENT != nullptr; ENT = ENT->getNextExit()) {
if (ENT->ExactNotTaken != SE->getCouldNotCompute()
&& SE->hasOperand(ENT->ExactNotTaken, S)) {
if (ENT->ExactNotTaken != SE->getCouldNotCompute()
&& SE->hasOperand(ENT->ExactNotTaken, S)) {
/// clear - Invalidate this result and free the ExitNotTakenInfo array.
void ScalarEvolution::BackedgeTakenInfo::clear() {
/// clear - Invalidate this result and free the ExitNotTakenInfo array.
void ScalarEvolution::BackedgeTakenInfo::clear() {
- ExitNotTaken.ExitingBlock = 0;
- ExitNotTaken.ExactNotTaken = 0;
+ ExitNotTaken.ExitingBlock = nullptr;
+ ExitNotTaken.ExactNotTaken = nullptr;
delete[] ExitNotTaken.getNextExit();
}
delete[] ExitNotTaken.getNextExit();
}
const SCEV *MaxBECount = getCouldNotCompute();
bool CouldComputeBECount = true;
BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
const SCEV *MaxBECount = getCouldNotCompute();
bool CouldComputeBECount = true;
BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
- const SCEV *LatchMaxCount = 0;
+ const SCEV *LatchMaxCount = nullptr;
SmallVector<std::pair<BasicBlock *, const SCEV *>, 4> ExitCounts;
for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
ExitLimit EL = ComputeExitLimit(L, ExitingBlocks[i]);
SmallVector<std::pair<BasicBlock *, const SCEV *>, 4> ExitCounts;
for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
ExitLimit EL = ComputeExitLimit(L, ExitingBlocks[i]);
// exit at this block and remember the exit block and whether all other targets
// lead to the loop header.
bool MustExecuteLoopHeader = true;
// exit at this block and remember the exit block and whether all other targets
// lead to the loop header.
bool MustExecuteLoopHeader = true;
+ BasicBlock *Exit = nullptr;
for (succ_iterator SI = succ_begin(ExitingBlock), SE = succ_end(ExitingBlock);
SI != SE; ++SI)
if (!L->contains(*SI)) {
for (succ_iterator SI = succ_begin(ExitingBlock), SE = succ_end(ExitingBlock);
SI != SE; ++SI)
if (!L->contains(*SI)) {
return getCouldNotCompute();
// Okay, we allow one non-constant index into the GEP instruction.
return getCouldNotCompute();
// Okay, we allow one non-constant index into the GEP instruction.
+ Value *VarIdx = nullptr;
std::vector<Constant*> Indexes;
unsigned VarIdxNum = 0;
for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
std::vector<Constant*> Indexes;
unsigned VarIdxNum = 0;
for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
VarIdx = GEP->getOperand(i);
VarIdxNum = i-2;
if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
VarIdx = GEP->getOperand(i);
VarIdxNum = i-2;
+ Indexes.push_back(nullptr);
}
// Loop-invariant loads may be a byproduct of loop optimization. Skip them.
}
// Loop-invariant loads may be a byproduct of loop optimization. Skip them.
Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
Indexes);
Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
Indexes);
- if (Result == 0) break; // Cannot compute!
+ if (!Result) break; // Cannot compute!
// Evaluate the condition for this iteration.
Result = ConstantExpr::getICmp(predicate, Result, RHS);
// Evaluate the condition for this iteration.
Result = ConstantExpr::getICmp(predicate, Result, RHS);
// Otherwise, we can evaluate this instruction if all of its operands are
// constant or derived from a PHI node themselves.
// Otherwise, we can evaluate this instruction if all of its operands are
// constant or derived from a PHI node themselves.
+ PHINode *PHI = nullptr;
for (Instruction::op_iterator OpI = UseInst->op_begin(),
OpE = UseInst->op_end(); OpI != OpE; ++OpI) {
if (isa<Constant>(*OpI)) continue;
Instruction *OpInst = dyn_cast<Instruction>(*OpI);
for (Instruction::op_iterator OpI = UseInst->op_begin(),
OpE = UseInst->op_end(); OpI != OpE; ++OpI) {
if (isa<Constant>(*OpI)) continue;
Instruction *OpInst = dyn_cast<Instruction>(*OpI);
- if (!OpInst || !canConstantEvolve(OpInst, L)) return 0;
+ if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
PHINode *P = dyn_cast<PHINode>(OpInst);
if (!P)
PHINode *P = dyn_cast<PHINode>(OpInst);
if (!P)
P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap);
PHIMap[OpInst] = P;
}
P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap);
PHIMap[OpInst] = P;
}
- if (P == 0) return 0; // Not evolving from PHI
- if (PHI && PHI != P) return 0; // Evolving from multiple different PHIs.
+ if (!P)
+ return nullptr; // Not evolving from PHI
+ if (PHI && PHI != P)
+ return nullptr; // Evolving from multiple different PHIs.
PHI = P;
}
// This is a expression evolving from a constant PHI!
PHI = P;
}
// This is a expression evolving from a constant PHI!
/// constraints, return null.
static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
Instruction *I = dyn_cast<Instruction>(V);
/// constraints, return null.
static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
Instruction *I = dyn_cast<Instruction>(V);
- if (I == 0 || !canConstantEvolve(I, L)) return 0;
+ if (!I || !canConstantEvolve(I, L)) return nullptr;
if (PHINode *PN = dyn_cast<PHINode>(I)) {
return PN;
if (PHINode *PN = dyn_cast<PHINode>(I)) {
return PN;
// Convenient constant check, but redundant for recursive calls.
if (Constant *C = dyn_cast<Constant>(V)) return C;
Instruction *I = dyn_cast<Instruction>(V);
// Convenient constant check, but redundant for recursive calls.
if (Constant *C = dyn_cast<Constant>(V)) return C;
Instruction *I = dyn_cast<Instruction>(V);
+ if (!I) return nullptr;
if (Constant *C = Vals.lookup(I)) return C;
// An instruction inside the loop depends on a value outside the loop that we
// weren't given a mapping for, or a value such as a call inside the loop.
if (Constant *C = Vals.lookup(I)) return C;
// An instruction inside the loop depends on a value outside the loop that we
// weren't given a mapping for, or a value such as a call inside the loop.
- if (!canConstantEvolve(I, L)) return 0;
+ if (!canConstantEvolve(I, L)) return nullptr;
// An unmapped PHI can be due to a branch or another loop inside this loop,
// or due to this not being the initial iteration through a loop where we
// couldn't compute the evolution of this particular PHI last time.
// An unmapped PHI can be due to a branch or another loop inside this loop,
// or due to this not being the initial iteration through a loop where we
// couldn't compute the evolution of this particular PHI last time.
- if (isa<PHINode>(I)) return 0;
+ if (isa<PHINode>(I)) return nullptr;
std::vector<Constant*> Operands(I->getNumOperands());
std::vector<Constant*> Operands(I->getNumOperands());
Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
if (!Operand) {
Operands[i] = dyn_cast<Constant>(I->getOperand(i));
Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
if (!Operand) {
Operands[i] = dyn_cast<Constant>(I->getOperand(i));
- if (!Operands[i]) return 0;
+ if (!Operands[i]) return nullptr;
continue;
}
Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
Vals[Operand] = C;
continue;
}
Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
Vals[Operand] = C;
+ if (!C) return nullptr;
return I->second;
if (BEs.ugt(MaxBruteForceIterations))
return I->second;
if (BEs.ugt(MaxBruteForceIterations))
- return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
+ return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
// entry must be a constant (coming in from outside of the loop), and the
// second must be derived from the same PHI.
bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
// entry must be a constant (coming in from outside of the loop), and the
// second must be derived from the same PHI.
bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
+ PHINode *PHI = nullptr;
for (BasicBlock::iterator I = Header->begin();
(PHI = dyn_cast<PHINode>(I)); ++I) {
Constant *StartCST =
dyn_cast<Constant>(PHI->getIncomingValue(!SecondIsBackedge));
for (BasicBlock::iterator I = Header->begin();
(PHI = dyn_cast<PHINode>(I)); ++I) {
Constant *StartCST =
dyn_cast<Constant>(PHI->getIncomingValue(!SecondIsBackedge));
- if (StartCST == 0) continue;
+ if (!StartCST) continue;
CurrentIterVals[PHI] = StartCST;
}
if (!CurrentIterVals.count(PN))
CurrentIterVals[PHI] = StartCST;
}
if (!CurrentIterVals.count(PN))
+ return RetVal = nullptr;
Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
// Execute the loop symbolically to determine the exit value.
if (BEs.getActiveBits() >= 32)
Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
// Execute the loop symbolically to determine the exit value.
if (BEs.getActiveBits() >= 32)
- return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
+ return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
unsigned NumIterations = BEs.getZExtValue(); // must be in range
unsigned IterationNum = 0;
unsigned NumIterations = BEs.getZExtValue(); // must be in range
unsigned IterationNum = 0;
DenseMap<Instruction *, Constant *> NextIterVals;
Constant *NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL,
TLI);
DenseMap<Instruction *, Constant *> NextIterVals;
Constant *NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL,
TLI);
- if (NextPHI == 0)
- return 0; // Couldn't evaluate!
+ if (!NextPHI)
+ return nullptr; // Couldn't evaluate!
NextIterVals[PN] = NextPHI;
bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
NextIterVals[PN] = NextPHI;
bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
Value *Cond,
bool ExitWhen) {
PHINode *PN = getConstantEvolvingPHI(Cond, L);
Value *Cond,
bool ExitWhen) {
PHINode *PN = getConstantEvolvingPHI(Cond, L);
- if (PN == 0) return getCouldNotCompute();
+ if (!PN) return getCouldNotCompute();
// If the loop is canonicalized, the PHI will have exactly two entries.
// That's the only form we support here.
// If the loop is canonicalized, the PHI will have exactly two entries.
// That's the only form we support here.
// One entry must be a constant (coming in from outside of the loop), and the
// second must be derived from the same PHI.
bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
// One entry must be a constant (coming in from outside of the loop), and the
// second must be derived from the same PHI.
bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
+ PHINode *PHI = nullptr;
for (BasicBlock::iterator I = Header->begin();
(PHI = dyn_cast<PHINode>(I)); ++I) {
Constant *StartCST =
dyn_cast<Constant>(PHI->getIncomingValue(!SecondIsBackedge));
for (BasicBlock::iterator I = Header->begin();
(PHI = dyn_cast<PHINode>(I)); ++I) {
Constant *StartCST =
dyn_cast<Constant>(PHI->getIncomingValue(!SecondIsBackedge));
- if (StartCST == 0) continue;
+ if (!StartCST) continue;
CurrentIterVals[PHI] = StartCST;
}
if (!CurrentIterVals.count(PN))
CurrentIterVals[PHI] = StartCST;
}
if (!CurrentIterVals.count(PN))
if (Values[u].first == L)
return Values[u].second ? Values[u].second : V;
}
if (Values[u].first == L)
return Values[u].second ? Values[u].second : V;
}
- Values.push_back(std::make_pair(L, static_cast<const SCEV *>(0)));
+ Values.push_back(std::make_pair(L, static_cast<const SCEV *>(nullptr)));
// Otherwise compute it.
const SCEV *C = computeSCEVAtScope(V, L);
SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values2 = ValuesAtScopes[V];
// Otherwise compute it.
const SCEV *C = computeSCEVAtScope(V, L);
SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values2 = ValuesAtScopes[V];
}
for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
}
for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
+ if (!C2) return nullptr;
// First pointer!
if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
// First pointer!
if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
// Don't bother trying to sum two pointers. We probably can't
// statically compute a load that results from it anyway.
if (C2->getType()->isPointerTy())
// Don't bother trying to sum two pointers. We probably can't
// statically compute a load that results from it anyway.
if (C2->getType()->isPointerTy())
if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
if (PTy->getElementType()->isStructTy())
if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
if (PTy->getElementType()->isStructTy())
const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
// Don't bother with pointers at all.
const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
// Don't bother with pointers at all.
- if (C->getType()->isPointerTy()) return 0;
+ if (C->getType()->isPointerTy()) return nullptr;
for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
- if (!C2 || C2->getType()->isPointerTy()) return 0;
+ if (!C2 || C2->getType()->isPointerTy()) return nullptr;
C = ConstantExpr::getMul(C, C2);
}
return C;
C = ConstantExpr::getMul(C, C2);
}
return C;
case scUMaxExpr:
break; // TODO: smax, umax.
}
case scUMaxExpr:
break; // TODO: smax, umax.
}
}
const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
}
const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
// Check to see if getSCEVAtScope actually made an improvement.
if (MadeImprovement) {
// Check to see if getSCEVAtScope actually made an improvement.
if (MadeImprovement) {
if (const CmpInst *CI = dyn_cast<CmpInst>(I))
C = ConstantFoldCompareInstOperands(CI->getPredicate(),
Operands[0], Operands[1], DL,
if (const CmpInst *CI = dyn_cast<CmpInst>(I))
C = ConstantFoldCompareInstOperands(CI->getPredicate(),
Operands[0], Operands[1], DL,
// to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
// We have not yet seen any such cases.
const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
// to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
// We have not yet seen any such cases.
const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
- if (StepC == 0 || StepC->getValue()->equalsInt(0))
+ if (!StepC || StepC->getValue()->equalsInt(0))
return getCouldNotCompute();
// For positive steps (counting up until unsigned overflow):
return getCouldNotCompute();
// For positive steps (counting up until unsigned overflow):
//===----------------------------------------------------------------------===//
ScalarEvolution::ScalarEvolution()
//===----------------------------------------------------------------------===//
ScalarEvolution::ScalarEvolution()
- : FunctionPass(ID), ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64), FirstUnknown(0) {
+ : FunctionPass(ID), ValuesAtScopes(64), LoopDispositions(64),
+ BlockDispositions(64), FirstUnknown(nullptr) {
initializeScalarEvolutionPass(*PassRegistry::getPassRegistry());
}
initializeScalarEvolutionPass(*PassRegistry::getPassRegistry());
}
this->F = &F;
LI = &getAnalysis<LoopInfo>();
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
this->F = &F;
LI = &getAnalysis<LoopInfo>();
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
- DL = DLP ? &DLP->getDataLayout() : 0;
+ DL = DLP ? &DLP->getDataLayout() : nullptr;
TLI = &getAnalysis<TargetLibraryInfo>();
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
return false;
TLI = &getAnalysis<TargetLibraryInfo>();
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
return false;
// destructors, so that they release their references to their values.
for (SCEVUnknown *U = FirstUnknown; U; U = U->Next)
U->~SCEVUnknown();
// destructors, so that they release their references to their values.
for (SCEVUnknown *U = FirstUnknown; U; U = U->Next)
U->~SCEVUnknown();
+ FirstUnknown = nullptr;
public:
static char ID; // Class identification, replacement for typeinfo
public:
static char ID; // Class identification, replacement for typeinfo
- ScalarEvolutionAliasAnalysis() : FunctionPass(ID), SE(0) {
+ ScalarEvolutionAliasAnalysis() : FunctionPass(ID), SE(nullptr) {
initializeScalarEvolutionAliasAnalysisPass(
*PassRegistry::getPassRegistry());
}
initializeScalarEvolutionAliasAnalysisPass(
*PassRegistry::getPassRegistry());
}
return U->getValue();
}
// No Identified object found.
return U->getValue();
}
// No Identified object found.
}
AliasAnalysis::AliasResult
}
AliasAnalysis::AliasResult
if ((AO && AO != LocA.Ptr) || (BO && BO != LocB.Ptr))
if (alias(Location(AO ? AO : LocA.Ptr,
AO ? +UnknownSize : LocA.Size,
if ((AO && AO != LocA.Ptr) || (BO && BO != LocB.Ptr))
if (alias(Location(AO ? AO : LocA.Ptr,
AO ? +UnknownSize : LocA.Size,
- AO ? 0 : LocA.TBAATag),
+ AO ? nullptr : LocA.TBAATag),
Location(BO ? BO : LocB.Ptr,
BO ? +UnknownSize : LocB.Size,
Location(BO ? BO : LocB.Ptr,
BO ? +UnknownSize : LocB.Size,
- BO ? 0 : LocB.TBAATag)) == NoAlias)
+ BO ? nullptr : LocB.TBAATag)) == NoAlias)
return NoAlias;
// Forward the query to the next analysis.
return NoAlias;
// Forward the query to the next analysis.
// not allowed to move it.
BasicBlock::iterator BIP = Builder.GetInsertPoint();
// not allowed to move it.
BasicBlock::iterator BIP = Builder.GetInsertPoint();
- Instruction *Ret = NULL;
+ Instruction *Ret = nullptr;
// Check to see if there is already a cast!
for (User *U : V->users())
// Check to see if there is already a cast!
for (User *U : V->users())
const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
// Test whether we've already computed the most relevant loop for this SCEV.
std::pair<DenseMap<const SCEV *, const Loop *>::iterator, bool> Pair =
const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
// Test whether we've already computed the most relevant loop for this SCEV.
std::pair<DenseMap<const SCEV *, const Loop *>::iterator, bool> Pair =
- RelevantLoops.insert(std::make_pair(S, static_cast<const Loop *>(0)));
+ RelevantLoops.insert(std::make_pair(S, nullptr));
if (!Pair.second)
return Pair.first->second;
if (isa<SCEVConstant>(S))
// A constant has no relevant loops.
if (!Pair.second)
return Pair.first->second;
if (isa<SCEVConstant>(S))
// A constant has no relevant loops.
if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
return Pair.first->second = SE.LI->getLoopFor(I->getParent());
// A non-instruction has no relevant loops.
if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
return Pair.first->second = SE.LI->getLoopFor(I->getParent());
// A non-instruction has no relevant loops.
}
if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
}
if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
+ const Loop *L = nullptr;
if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
L = AR->getLoop();
for (SCEVNAryExpr::op_iterator I = N->op_begin(), E = N->op_end();
if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
L = AR->getLoop();
for (SCEVNAryExpr::op_iterator I = N->op_begin(), E = N->op_end();
// Emit instructions to add all the operands. Hoist as much as possible
// out of loops, and form meaningful getelementptrs where possible.
// Emit instructions to add all the operands. Hoist as much as possible
// out of loops, and form meaningful getelementptrs where possible.
for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
const Loop *CurLoop = I->first;
for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
const Loop *CurLoop = I->first;
// Emit instructions to mul all the operands. Hoist as much as possible
// out of loops.
// Emit instructions to mul all the operands. Hoist as much as possible
// out of loops.
for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
const SCEV *Op = I->second;
for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
const SCEV *Op = I->second;
Instruction *InsertPos,
bool allowScale) {
if (IncV == InsertPos)
Instruction *InsertPos,
bool allowScale) {
if (IncV == InsertPos)
switch (IncV->getOpcode()) {
default:
switch (IncV->getOpcode()) {
default:
// Check for a simple Add/Sub or GEP of a loop invariant step.
case Instruction::Add:
case Instruction::Sub: {
Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
if (!OInst || SE.DT->dominates(OInst, InsertPos))
return dyn_cast<Instruction>(IncV->getOperand(0));
// Check for a simple Add/Sub or GEP of a loop invariant step.
case Instruction::Add:
case Instruction::Sub: {
Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
if (!OInst || SE.DT->dominates(OInst, InsertPos))
return dyn_cast<Instruction>(IncV->getOperand(0));
}
case Instruction::BitCast:
return dyn_cast<Instruction>(IncV->getOperand(0));
}
case Instruction::BitCast:
return dyn_cast<Instruction>(IncV->getOperand(0));
continue;
if (Instruction *OInst = dyn_cast<Instruction>(*I)) {
if (!SE.DT->dominates(OInst, InsertPos))
continue;
if (Instruction *OInst = dyn_cast<Instruction>(*I)) {
if (!SE.DT->dominates(OInst, InsertPos))
}
if (allowScale) {
// allow any kind of GEP as long as it can be hoisted.
}
if (allowScale) {
// allow any kind of GEP as long as it can be hoisted.
// have 2 operands. i1* is used by the expander to represent an
// address-size element.
if (IncV->getNumOperands() != 2)
// have 2 operands. i1* is used by the expander to represent an
// address-size element.
if (IncV->getNumOperands() != 2)
unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
&& IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
&& IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
break;
}
return dyn_cast<Instruction>(IncV->getOperand(0));
break;
}
return dyn_cast<Instruction>(IncV->getOperand(0));
// Reuse a previously-inserted PHI, if present.
BasicBlock *LatchBlock = L->getLoopLatch();
if (LatchBlock) {
// Reuse a previously-inserted PHI, if present.
BasicBlock *LatchBlock = L->getLoopLatch();
if (LatchBlock) {
- PHINode *AddRecPhiMatch = 0;
- Instruction *IncV = 0;
- TruncTy = 0;
+ PHINode *AddRecPhiMatch = nullptr;
+ Instruction *IncV = nullptr;
+ TruncTy = nullptr;
InvertStep = false;
// Only try partially matching scevs that need truncation and/or
InvertStep = false;
// Only try partially matching scevs that need truncation and/or
// Stop if we have found an exact match SCEV.
if (IsMatchingSCEV) {
IncV = TempIncV;
// Stop if we have found an exact match SCEV.
if (IsMatchingSCEV) {
IncV = TempIncV;
InvertStep = false;
AddRecPhiMatch = PN;
break;
InvertStep = false;
AddRecPhiMatch = PN;
break;
PostIncLoopSet Loops;
Loops.insert(L);
Normalized =
PostIncLoopSet Loops;
Loops.insert(L);
Normalized =
- cast<SCEVAddRecExpr>(TransformForPostIncUse(Normalize, S, 0, 0,
- Loops, SE, *SE.DT));
+ cast<SCEVAddRecExpr>(TransformForPostIncUse(Normalize, S, nullptr,
+ nullptr, Loops, SE, *SE.DT));
}
// Strip off any non-loop-dominating component from the addrec start.
const SCEV *Start = Normalized->getStart();
}
// Strip off any non-loop-dominating component from the addrec start.
const SCEV *Start = Normalized->getStart();
- const SCEV *PostLoopOffset = 0;
+ const SCEV *PostLoopOffset = nullptr;
if (!SE.properlyDominates(Start, L->getHeader())) {
PostLoopOffset = Start;
Start = SE.getConstant(Normalized->getType(), 0);
if (!SE.properlyDominates(Start, L->getHeader())) {
PostLoopOffset = Start;
Start = SE.getConstant(Normalized->getType(), 0);
// Strip off any non-loop-dominating component from the addrec step.
const SCEV *Step = Normalized->getStepRecurrence(SE);
// Strip off any non-loop-dominating component from the addrec step.
const SCEV *Step = Normalized->getStepRecurrence(SE);
- const SCEV *PostLoopScale = 0;
+ const SCEV *PostLoopScale = nullptr;
if (!SE.dominates(Step, L->getHeader())) {
PostLoopScale = Step;
Step = SE.getConstant(Normalized->getType(), 1);
if (!SE.dominates(Step, L->getHeader())) {
PostLoopScale = Step;
Step = SE.getConstant(Normalized->getType(), 1);
Type *ExpandTy = PostLoopScale ? IntTy : STy;
// In some cases, we decide to reuse an existing phi node but need to truncate
// it and/or invert the step.
Type *ExpandTy = PostLoopScale ? IntTy : STy;
// In some cases, we decide to reuse an existing phi node but need to truncate
// it and/or invert the step.
+ Type *TruncTy = nullptr;
bool InvertStep = false;
PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy,
TruncTy, InvertStep);
bool InvertStep = false;
PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy,
TruncTy, InvertStep);
const Loop *L = S->getLoop();
// First check for an existing canonical IV in a suitable type.
const Loop *L = S->getLoop();
// First check for an existing canonical IV in a suitable type.
- PHINode *CanonicalIV = 0;
+ PHINode *CanonicalIV = nullptr;
if (PHINode *PN = L->getCanonicalInductionVariable())
if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
CanonicalIV = PN;
if (PHINode *PN = L->getCanonicalInductionVariable())
if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
CanonicalIV = PN;
while (isa<PHINode>(NewInsertPt) || isa<DbgInfoIntrinsic>(NewInsertPt) ||
isa<LandingPadInst>(NewInsertPt))
++NewInsertPt;
while (isa<PHINode>(NewInsertPt) || isa<DbgInfoIntrinsic>(NewInsertPt) ||
isa<LandingPadInst>(NewInsertPt))
++NewInsertPt;
- V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0,
+ V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), nullptr,
NewInsertPt);
return V;
}
NewInsertPt);
return V;
}
// Emit code for it.
BuilderType::InsertPointGuard Guard(Builder);
// Emit code for it.
BuilderType::InsertPointGuard Guard(Builder);
- PHINode *V = cast<PHINode>(expandCodeFor(H, 0, L->getHeader()->begin()));
+ PHINode *V = cast<PHINode>(expandCodeFor(H, nullptr,
+ L->getHeader()->begin()));
// Transform each operand.
for (SCEVNAryExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
I != E; ++I) {
// Transform each operand.
for (SCEVNAryExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
I != E; ++I) {
- Operands.push_back(TransformSubExpr(*I, LUser, 0));
+ Operands.push_back(TransformSubExpr(*I, LUser, nullptr));
}
// Conservatively use AnyWrap until/unless we need FlagNW.
const SCEV *Result = SE.getAddRecExpr(Operands, L, SCEV::FlagAnyWrap);
}
// Conservatively use AnyWrap until/unless we need FlagNW.
const SCEV *Result = SE.getAddRecExpr(Operands, L, SCEV::FlagAnyWrap);
return;
Constant *C = LatticeFunc->GetConstant(BCValue, BI->getCondition(), *this);
return;
Constant *C = LatticeFunc->GetConstant(BCValue, BI->getCondition(), *this);
- if (C == 0 || !isa<ConstantInt>(C)) {
+ if (!C || !isa<ConstantInt>(C)) {
// Non-constant values can go either way.
Succs[0] = Succs[1] = true;
return;
// Non-constant values can go either way.
Succs[0] = Succs[1] = true;
return;
return;
Constant *C = LatticeFunc->GetConstant(SCValue, SI.getCondition(), *this);
return;
Constant *C = LatticeFunc->GetConstant(SCValue, SI.getCondition(), *this);
- if (C == 0 || !isa<ConstantInt>(C)) {
+ if (!C || !isa<ConstantInt>(C)) {
// All destinations are executable!
Succs.assign(TI.getNumSuccessors(), true);
return;
// All destinations are executable!
Succs.assign(TI.getNumSuccessors(), true);
return;
struct NoTTI final : ImmutablePass, TargetTransformInfo {
const DataLayout *DL;
struct NoTTI final : ImmutablePass, TargetTransformInfo {
const DataLayout *DL;
- NoTTI() : ImmutablePass(ID), DL(0) {
+ NoTTI() : ImmutablePass(ID), DL(nullptr) {
initializeNoTTIPass(*PassRegistry::getPassRegistry());
}
initializeNoTTIPass(*PassRegistry::getPassRegistry());
}
// Note that this subclass is special, and must *not* call initializeTTI as
// it does not chain.
TopTTI = this;
// Note that this subclass is special, and must *not* call initializeTTI as
// it does not chain.
TopTTI = this;
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
- DL = DLP ? &DLP->getDataLayout() : 0;
+ DL = DLP ? &DLP->getDataLayout() : nullptr;
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const override {
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const override {
// Otherwise delegate to the fully generic implementations.
return getOperationCost(Operator::getOpcode(U), U->getType(),
U->getNumOperands() == 1 ?
// Otherwise delegate to the fully generic implementations.
return getOperationCost(Operator::getOpcode(U), U->getType(),
U->getNumOperands() == 1 ?
- U->getOperand(0)->getType() : 0);
+ U->getOperand(0)->getType() : nullptr);
}
bool hasBranchDivergence() const override { return false; }
}
bool hasBranchDivergence() const override { return false; }
}
unsigned getShuffleCost(ShuffleKind Kind, Type *Ty,
}
unsigned getShuffleCost(ShuffleKind Kind, Type *Ty,
- int Index = 0, Type *SubTp = 0) const override {
+ int Index = 0, Type *SubTp = nullptr) const override {
}
unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
}
unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
- Type *CondTy = 0) const override {
+ Type *CondTy = nullptr) const override {
const MDNode *Node;
public:
const MDNode *Node;
public:
- TBAANode() : Node(0) {}
+ TBAANode() : Node(nullptr) {}
explicit TBAANode(const MDNode *N) : Node(N) {}
/// getNode - Get the MDNode for this TBAANode.
explicit TBAANode(const MDNode *N) : Node(N) {}
/// getNode - Get the MDNode for this TBAANode.
const MDNode *Node;
public:
const MDNode *Node;
public:
- TBAAStructTagNode() : Node(0) {}
+ TBAAStructTagNode() : Node(nullptr) {}
explicit TBAAStructTagNode(const MDNode *N) : Node(N) {}
/// Get the MDNode for this TBAAStructTagNode.
explicit TBAAStructTagNode(const MDNode *N) : Node(N) {}
/// Get the MDNode for this TBAAStructTagNode.
const MDNode *Node;
public:
const MDNode *Node;
public:
- TBAAStructTypeNode() : Node(0) {}
+ TBAAStructTypeNode() : Node(nullptr) {}
explicit TBAAStructTypeNode(const MDNode *N) : Node(N) {}
/// Get the MDNode for this TBAAStructTypeNode.
explicit TBAAStructTypeNode(const MDNode *N) : Node(N) {}
/// Get the MDNode for this TBAAStructTypeNode.
MDNode *MDNode::getMostGenericTBAA(MDNode *A, MDNode *B) {
if (!A || !B)
MDNode *MDNode::getMostGenericTBAA(MDNode *A, MDNode *B) {
if (!A || !B)
bool StructPath = isStructPathTBAA(A);
if (StructPath) {
A = cast_or_null<MDNode>(A->getOperand(1));
bool StructPath = isStructPathTBAA(A);
if (StructPath) {
A = cast_or_null<MDNode>(A->getOperand(1));
+ if (!A) return nullptr;
B = cast_or_null<MDNode>(B->getOperand(1));
B = cast_or_null<MDNode>(B->getOperand(1));
+ if (!B) return nullptr;
}
SmallVector<MDNode *, 4> PathA;
MDNode *T = A;
while (T) {
PathA.push_back(T);
}
SmallVector<MDNode *, 4> PathA;
MDNode *T = A;
while (T) {
PathA.push_back(T);
- T = T->getNumOperands() >= 2 ? cast_or_null<MDNode>(T->getOperand(1)) : 0;
+ T = T->getNumOperands() >= 2 ? cast_or_null<MDNode>(T->getOperand(1))
+ : nullptr;
}
SmallVector<MDNode *, 4> PathB;
T = B;
while (T) {
PathB.push_back(T);
}
SmallVector<MDNode *, 4> PathB;
T = B;
while (T) {
PathB.push_back(T);
- T = T->getNumOperands() >= 2 ? cast_or_null<MDNode>(T->getOperand(1)) : 0;
+ T = T->getNumOperands() >= 2 ? cast_or_null<MDNode>(T->getOperand(1))
+ : nullptr;
}
int IA = PathA.size() - 1;
int IB = PathB.size() - 1;
}
int IA = PathA.size() - 1;
int IB = PathB.size() - 1;
while (IA >= 0 && IB >=0) {
if (PathA[IA] == PathB[IB])
Ret = PathA[IA];
while (IA >= 0 && IB >=0) {
if (PathA[IA] == PathB[IB])
Ret = PathA[IA];
// We need to convert from a type node to a tag node.
Type *Int64 = IntegerType::get(A->getContext(), 64);
Value *Ops[3] = { Ret, Ret, ConstantInt::get(Int64, 0) };
// We need to convert from a type node to a tag node.
Type *Int64 = IntegerType::get(A->getContext(), 64);
Value *Ops[3] = { Ret, Ret, ConstantInt::get(Int64, 0) };
if (Depth++ == MaxDepth)
return false;
if (Depth++ == MaxDepth)
return false;
+ Value *X = nullptr, *Y = nullptr;
// A shift of a power of two is a power of two or zero.
if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
match(V, m_Shr(m_Value(X), m_Value()))))
// A shift of a power of two is a power of two or zero.
if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
match(V, m_Shr(m_Value(X), m_Value()))))
unsigned BitWidth = V->getType()->getScalarSizeInBits();
APInt LHSZeroBits(BitWidth, 0), LHSOneBits(BitWidth, 0);
unsigned BitWidth = V->getType()->getScalarSizeInBits();
APInt LHSZeroBits(BitWidth, 0), LHSOneBits(BitWidth, 0);
- ComputeMaskedBits(X, LHSZeroBits, LHSOneBits, 0, Depth);
+ ComputeMaskedBits(X, LHSZeroBits, LHSOneBits, nullptr, Depth);
APInt RHSZeroBits(BitWidth, 0), RHSOneBits(BitWidth, 0);
APInt RHSZeroBits(BitWidth, 0), RHSOneBits(BitWidth, 0);
- ComputeMaskedBits(Y, RHSZeroBits, RHSOneBits, 0, Depth);
+ ComputeMaskedBits(Y, RHSZeroBits, RHSOneBits, nullptr, Depth);
// If i8 V is a power of two or zero:
// ZeroBits: 1 1 1 0 1 1 1 1
// ~ZeroBits: 0 0 0 1 0 0 0 0
// If i8 V is a power of two or zero:
// ZeroBits: 1 1 1 0 1 1 1 1
// ~ZeroBits: 0 0 0 1 0 0 0 0
unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), TD);
// X | Y != 0 if X != 0 or Y != 0.
unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), TD);
// X | Y != 0 if X != 0 or Y != 0.
+ Value *X = nullptr, *Y = nullptr;
if (match(V, m_Or(m_Value(X), m_Value(Y))))
return isKnownNonZero(X, TD, Depth) || isKnownNonZero(Y, TD, Depth);
if (match(V, m_Or(m_Value(X), m_Value(Y))))
return isKnownNonZero(X, TD, Depth) || isKnownNonZero(Y, TD, Depth);
Op1 = ConstantInt::get(V->getContext(), API);
}
Op1 = ConstantInt::get(V->getContext(), API);
}
if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
if (Constant *Op1C = dyn_cast<Constant>(Op1))
if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
if (Constant *Op1C = dyn_cast<Constant>(Op1))
if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
if (Constant *Op0C = dyn_cast<Constant>(Op0))
if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
if (Constant *Op0C = dyn_cast<Constant>(Op0))
if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
return 1; // Limit search depth.
const Operator *I = dyn_cast<Operator>(V);
return 1; // Limit search depth.
const Operator *I = dyn_cast<Operator>(V);
- if (I == 0) return false;
// Check if the nsz fast-math flag is set
if (const FPMathOperator *FPO = dyn_cast<FPMathOperator>(I))
// Check if the nsz fast-math flag is set
if (const FPMathOperator *FPO = dyn_cast<FPMathOperator>(I))
// If the top/bottom halves aren't the same, reject it.
if (Val != Val2)
// If the top/bottom halves aren't the same, reject it.
if (Val != Val2)
}
return ConstantInt::get(V->getContext(), Val);
}
}
return ConstantInt::get(V->getContext(), Val);
}
Value *Elt = CA->getElementAsConstant(0);
Value *Val = isBytewiseValue(Elt);
if (!Val)
Value *Elt = CA->getElementAsConstant(0);
Value *Val = isBytewiseValue(Elt);
if (!Val)
for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
if (CA->getElementAsConstant(I) != Elt)
for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
if (CA->getElementAsConstant(I) != Elt)
// %c = or i16 %a, %b
// but until there is an example that actually needs this, it doesn't seem
// worth worrying about.
// %c = or i16 %a, %b
// but until there is an example that actually needs this, it doesn't seem
// worth worrying about.
Value *V = FindInsertedValue(From, Idxs);
if (!V)
Value *V = FindInsertedValue(From, Idxs);
if (!V)
// Insert the value in the new (sub) aggregrate
return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
// Insert the value in the new (sub) aggregrate
return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
if (Constant *C = dyn_cast<Constant>(V)) {
C = C->getAggregateElement(idx_range[0]);
if (Constant *C = dyn_cast<Constant>(V)) {
C = C->getAggregateElement(idx_range[0]);
+ if (!C) return nullptr;
return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
}
return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
}
if (req_idx == idx_range.end()) {
// We can't handle this without inserting insertvalues
if (!InsertBefore)
if (req_idx == idx_range.end()) {
// We can't handle this without inserting insertvalues
if (!InsertBefore)
// The requested index identifies a part of a nested aggregate. Handle
// this specially. For example,
// The requested index identifies a part of a nested aggregate. Handle
// this specially. For example,
}
// Otherwise, we don't know (such as, extracting from a function return value
// or load instruction)
}
// Otherwise, we don't know (such as, extracting from a function return value
// or load instruction)
}
/// GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if
}
/// GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if
// Make sure the index-ee is a pointer to array of i8.
PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
// Make sure the index-ee is a pointer to array of i8.
PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
- if (AT == 0 || !AT->getElementType()->isIntegerTy(8))
+ if (!AT || !AT->getElementType()->isIntegerTy(8))
return false;
// Check to make sure that the first operand of the GEP is an integer and
// has value 0 so that we are sure we're indexing into the initializer.
const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
return false;
// Check to make sure that the first operand of the GEP is an integer and
// has value 0 so that we are sure we're indexing into the initializer.
const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
- if (FirstIdx == 0 || !FirstIdx->isZero())
+ if (!FirstIdx || !FirstIdx->isZero())
return false;
// If the second index isn't a ConstantInt, then this is a variable index
return false;
// If the second index isn't a ConstantInt, then this is a variable index
// Must be a Constant Array
const ConstantDataArray *Array =
dyn_cast<ConstantDataArray>(GV->getInitializer());
// Must be a Constant Array
const ConstantDataArray *Array =
dyn_cast<ConstantDataArray>(GV->getInitializer());
- if (Array == 0 || !Array->isString())
+ if (!Array || !Array->isString())
return false;
// Get the number of elements in the array
return false;
// Get the number of elements in the array
// See if InstructionSimplify knows any relevant tricks.
if (Instruction *I = dyn_cast<Instruction>(V))
// TODO: Acquire a DominatorTree and use it.
// See if InstructionSimplify knows any relevant tricks.
if (Instruction *I = dyn_cast<Instruction>(V))
// TODO: Acquire a DominatorTree and use it.
- if (Value *Simplified = SimplifyInstruction(I, TD, 0)) {
+ if (Value *Simplified = SimplifyInstruction(I, TD, nullptr)) {
V = Simplified;
continue;
}
V = Simplified;
continue;
}