30#define DEBUG_TYPE "normalize"
38 const uint64_t kMul = 0x9ddfea08eb382d69ULL;
53 IRNormalizer(IRNormalizerOptions Options) : Options(Options) {}
56 const IRNormalizerOptions Options;
59 const uint64_t MagicHashConstant = 0x6acaa36bef8325c5ULL;
60 DenseSet<const Instruction *> NamedInstructions;
62 SmallVector<Instruction *, 16> Outputs;
66 void nameFunctionArguments(
Function &
F)
const;
68 void nameInstruction(Instruction *
I);
69 void nameAsInitialInstruction(Instruction *
I)
const;
70 void nameAsRegularInstruction(Instruction *
I);
71 void foldInstructionName(Instruction *
I)
const;
76 void reorderInstructions(
Function &
F)
const;
77 void reorderDefinition(Instruction *Definition,
78 std::stack<Instruction *> &TopologicalSort,
79 SmallPtrSet<const Instruction *, 32> &Visited)
const;
80 void reorderInstructionOperandsByNames(Instruction *
I)
const;
81 void reorderPHIIncomingValues(PHINode *Phi)
const;
87 void sortCommutativeOperands(Instruction *
I,
T &
Operands)
const;
88 SmallVector<Instruction *, 16> collectOutputInstructions(
Function &
F)
const;
89 bool isOutput(
const Instruction *
I)
const;
90 bool isInitialInstruction(
const Instruction *
I)
const;
91 bool hasOnlyImmediateOperands(
const Instruction *
I)
const;
93 getOutputFootprint(Instruction *
I,
94 SmallPtrSet<const Instruction *, 32> &Visited)
const;
102bool IRNormalizer::runOnFunction(
Function &
F) {
103 nameFunctionArguments(
F);
106 Outputs = collectOutputInstructions(
F);
109 reorderInstructions(
F);
113 for (
auto &
I : Outputs)
119 reorderInstructionOperandsByNames(&
I);
122 reorderPHIIncomingValues(Phi);
124 foldInstructionName(&
I);
133void IRNormalizer::nameFunctionArguments(
Function &
F)
const {
134 int ArgumentCounter = 0;
135 for (
auto &
A :
F.args()) {
136 if (
Options.RenameAll ||
A.getName().empty()) {
137 A.setName(
"a" + Twine(ArgumentCounter));
138 ArgumentCounter += 1;
147void IRNormalizer::nameBasicBlocks(
Function &
F)
const {
157 if (
Options.RenameAll ||
B.getName().empty()) {
159 B.setName(
"bb" + std::to_string(Hash).
substr(0, 5));
169void IRNormalizer::nameInstruction(Instruction *
I) {
173 if (NamedInstructions.contains(
I))
175 NamedInstructions.insert(
I);
176 if (isInitialInstruction(
I)) {
177 nameAsInitialInstruction(
I);
180 nameAsRegularInstruction(
I);
185void IRNormalizer::sortCommutativeOperands(Instruction *
I,
T &
Operands)
const {
186 if (!(
I->isCommutative() &&
Operands.size() >= 2))
188 auto CommutativeEnd =
Operands.begin();
189 std::advance(CommutativeEnd, 2);
206void IRNormalizer::nameAsInitialInstruction(Instruction *
I)
const {
207 if (
I->getType()->isVoidTy())
209 if (!(
I->getName().empty() ||
Options.RenameAll))
217 for (
auto &
Op :
I->operands()) {
219 std::string TextRepresentation;
220 raw_string_ostream Stream(TextRepresentation);
221 Op->printAsOperand(Stream,
false);
222 Operands.push_back(StringRef(Stream.str()));
234 SmallPtrSet<const Instruction *, 32> Visited;
236 SetVector<int> OutputFootprint = getOutputFootprint(
I, Visited);
239 for (
const int &Output : OutputFootprint)
243 SmallString<256>
Name;
244 Name.append(
"vl" + std::to_string(Hash).
substr(0, 5));
251 Name.append(
F->getName());
255 for (
size_t i = 0; i <
Operands.size(); ++i) {
283void IRNormalizer::nameAsRegularInstruction(Instruction *
I) {
295 for (
auto &
Op :
I->operands()) {
302 std::string TextRepresentation;
303 raw_string_ostream Stream(TextRepresentation);
304 Op->printAsOperand(Stream,
false);
305 Operands.push_back(StringRef(Stream.str()));
318 SmallVector<int, 4> OperandsOpcodes;
321 for (
auto &
Op :
I->operands())
325 sortCommutativeOperands(
I, OperandsOpcodes);
328 for (
const int Code : OperandsOpcodes)
332 SmallString<512>
Name;
333 Name.append(
"op" + std::to_string(Hash).
substr(0, 5));
337 if (
const Function *
F = CI->getCalledFunction())
338 Name.append(
F->getName());
341 for (
size_t i = 0; i <
Operands.size(); ++i) {
349 if ((
I->getName().empty() ||
Options.RenameAll) && !
I->getType()->isVoidTy())
366void IRNormalizer::foldInstructionName(Instruction *
I)
const {
371 for (Instruction *IU :
I->users())
377 if (isOutput(
I) || !
I->getName().starts_with(
"op"))
383 for (
auto &
Op :
I->operands()) {
386 I->getName().starts_with(
"op") ||
I->getName().starts_with(
"vl");
388 Operands.push_back(HasNormalName ?
I->getName().substr(0, 7)
395 SmallString<256>
Name;
396 Name.append(
I->getName().substr(0, 7));
399 for (
size_t i = 0; i <
Operands.size(); ++i) {
417void IRNormalizer::reorderInstructions(
Function &
F)
const {
420 << BB.getName() <<
"\n");
432 std::stack<Instruction *> TopologicalSort;
433 SmallPtrSet<const Instruction *, 32> Visited;
437 if (!(isOutput(&
I) ||
I.mayReadOrWriteMemory() ||
I.isTerminator() ||
440 LLVM_DEBUG(
dbgs() <<
"\tReordering from source effecting instruction: ";
442 reorderDefinition(&
I, TopologicalSort, Visited);
454 LLVM_DEBUG(
dbgs() <<
"\tReordering from source instruction: ";
I.dump());
455 reorderDefinition(&
I, TopologicalSort, Visited);
458 LLVM_DEBUG(
dbgs() <<
"Inserting instructions into: " << BB.getName()
461 while (!TopologicalSort.empty()) {
463 auto FirstNonPHIOrAlloca = BB.getFirstNonPHIOrAlloca();
466 Intrinsic::experimental_convergence_entry ||
468 FirstNonPHIOrAlloca++;
471 TopologicalSort.pop();
476void IRNormalizer::reorderDefinition(
477 Instruction *Definition, std::stack<Instruction *> &TopologicalSort,
478 SmallPtrSet<const Instruction *, 32> &Visited)
const {
481 Visited.
insert(Definition);
484 const auto *
BasicBlock = Definition->getParent();
485 const auto FirstNonPHIOrAlloca =
BasicBlock->getFirstNonPHIOrAlloca();
488 if (Definition->comesBefore(&*FirstNonPHIOrAlloca))
492 for (
auto &Operand : Definition->operands()) {
494 if (
Op->getParent() != Definition->getParent())
496 reorderDefinition(
Op, TopologicalSort, Visited);
500 LLVM_DEBUG(
dbgs() <<
"\t\tNext in topological sort: "; Definition->dump());
501 if (Definition->isTerminator())
520 TopologicalSort.emplace(Definition);
528void IRNormalizer::reorderInstructionOperandsByNames(Instruction *
I)
const {
537 for (
auto &
Op :
I->operands()) {
541 Operands.push_back(std::pair<std::string, Value *>(
V->getName(),
V));
543 std::string TextRepresentation;
544 raw_string_ostream Stream(TextRepresentation);
545 Op->printAsOperand(Stream,
false);
546 Operands.push_back(std::pair<std::string, Value *>(Stream.str(),
V));
555 unsigned Position = 0;
556 for (
auto &
Op :
I->operands()) {
566void IRNormalizer::reorderPHIIncomingValues(PHINode *Phi)
const {
571 for (
auto &BB :
Phi->blocks()) {
572 Value *
V =
Phi->getIncomingValueForBlock(BB);
573 Values.push_back(std::pair<Value *, BasicBlock *>(
V, BB));
578 const std::pair<Value *, BasicBlock *> &
RHS) {
583 for (
unsigned i = 0; i <
Values.size(); ++i) {
584 Phi->setIncomingBlock(i,
Values[i].second);
585 Phi->setIncomingValue(i,
Values[i].first);
594SmallVector<Instruction *, 16>
595IRNormalizer::collectOutputInstructions(
Function &
F)
const {
598 SmallVector<Instruction *, 16> Outputs;
609bool IRNormalizer::isOutput(
const Instruction *
I)
const {
618bool IRNormalizer::isInitialInstruction(
const Instruction *
I)
const {
621 return !
I->user_empty() && hasOnlyImmediateOperands(
I);
627bool IRNormalizer::hasOnlyImmediateOperands(
const Instruction *
I)
const {
628 for (
const auto &
Op :
I->operands())
640SetVector<int> IRNormalizer::getOutputFootprint(
641 Instruction *
I, SmallPtrSet<const Instruction *, 32> &Visited)
const {
645 SetVector<int> Outputs;
656 for (
const auto &
B : *Func) {
657 for (
const auto &
E :
B) {
668 for (Instruction *UI :
I->users()) {
670 SetVector<int> OutputsUsingUI = getOutputFootprint(UI, Visited);
682 static_cast<PassInfoMixin<IRNormalizerPass> *
>(
this)->
printPipeline(
683 OS, MapClassName2PassName);
691 ParamsOS << LS << (
Value ?
"" :
"no-") << Name;
693 PrintParam(
"preserve-order", Options.PreserveOrder, Defaults.
PreserveOrder);
694 PrintParam(
"rename-all", Options.RenameAll, Defaults.
RenameAll);
695 PrintParam(
"fold-all", Options.FoldPreOutputs, Defaults.
FoldPreOutputs);
696 PrintParam(
"reorder-operands", Options.ReorderOperands,
699 OS <<
'<' << Params <<
'>';
704 IRNormalizer(Options).runOnFunction(
F);
Expand Atomic instructions
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static bool runOnFunction(Function &F, bool PostInlining)
static constexpr uint64_t hash_16_bytes(uint64_t low, uint64_t high)
static constexpr uint64_t hash_16_bytes(uint64_t low, uint64_t high)
This file implements a set that has insertion order iteration characteristics.
static StringRef substr(StringRef Str, uint64_t Len)
This file defines the SmallPtrSet class.
This file defines the SmallString class.
This file defines the SmallVector class.
Represents analyses that only rely on functions' control flow.
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
bool isMustTailCall() const
A helper class to return the specified delimiter string after the first invocation of operator String...
A set of analyses that are preserved following a run of a transformation pass.
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
void insert_range(Range &&R)
bool insert(const value_type &X)
Insert a new element into the SetVector.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
void push_back(const T &Elt)
Represent a constant reference to a string, i.e.
LLVM Value Representation.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
A raw_ostream that writes to an SmallVector or SmallString.
@ BasicBlock
Various leaf nodes.
NodeAddr< PhiNode * > Phi
NodeAddr< FuncNode * > Func
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
RelativeUniformCounterPtr Values
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
DWARFExpression::Operation Op
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
bool RenameAll
Renames all instructions (including user-named)
bool ReorderOperands
Sorts and reorders operands in commutative instructions.
bool PreserveOrder
Preserves original instruction order.
bool FoldPreOutputs
Folds all regular instructions (including pre-outputs)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM) const
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)