llvm.org GIT mirror llvm / 2fbfdcf
Change references to the Method class to be references to the Function class. The Method class is obsolete (renamed) and all references to it are being converted over to Function. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@2144 91177308-0d34-0410-b5e6-96231b3b80d8 Chris Lattner 18 years ago
57 changed file(s) with 798 addition(s) and 836 deletion(s). Raw diff Collapse all Expand all
33 // graph of some sort. This iterator is parametric, allowing iterator over the
44 // following types of graphs:
55 //
6 // 1. A Method* object, composed of BasicBlock nodes.
6 // 1. A Function* object, composed of BasicBlock nodes.
77 // 2. An IntervalPartition& object, composed of Interval nodes.
88 //
99 // This iterator is defined to walk the control flow graph, returning intervals
2626 #define LLVM_INTERVAL_ITERATOR_H
2727
2828 #include "llvm/Analysis/IntervalPartition.h"
29 #include "llvm/Method.h"
29 #include "llvm/Function.h"
3030 #include "llvm/BasicBlock.h"
3131 #include "llvm/Support/CFG.h"
3232 #include
4646 // source graph node that corresponds to the BasicBlock. This is the opposite
4747 // of getNodeHeader.
4848 //
49 inline BasicBlock *getSourceGraphNode(Method *, BasicBlock *BB) {
49 inline BasicBlock *getSourceGraphNode(Function *, BasicBlock *BB) {
5050 return BB;
5151 }
5252 inline Interval *getSourceGraphNode(IntervalPartition *IP, BasicBlock *BB) {
9292 typedef std::forward_iterator_tag iterator_category;
9393
9494 IntervalIterator() {} // End iterator, empty stack
95 IntervalIterator(Method *M, bool OwnMemory) : IOwnMem(OwnMemory) {
95 IntervalIterator(Function *M, bool OwnMemory) : IOwnMem(OwnMemory) {
9696 OrigContainer = M;
9797 if (!ProcessInterval(M->front())) {
9898 assert(0 && "ProcessInterval should never fail for first interval!");
226226 }
227227 };
228228
229 typedef IntervalIteratorMethod> method_interval_iterator;
229 typedef IntervalIteratorFunction> function_interval_iterator;
230230 typedef IntervalIterator interval_part_interval_iterator;
231231
232232
233 inline method_interval_iterator intervals_begin(Method *M,
234 bool DeleteInts = true) {
235 return method_interval_iterator(M, DeleteInts);
236 }
237 inline method_interval_iterator intervals_end(Method *M) {
238 return method_interval_iterator();
233 inline function_interval_iterator intervals_begin(Function *F,
234 bool DeleteInts = true) {
235 return function_interval_iterator(F, DeleteInts);
236 }
237 inline function_interval_iterator intervals_end(Function *) {
238 return function_interval_iterator();
239239 }
240240
241241 inline interval_part_interval_iterator
0 //===-- llvm/Support/CFG.h - Process LLVM structures as graphs ---*- C++ -*--=//
11 //
2 // This file defines specializations of GraphTraits that allow Methods and
2 // This file defines specializations of GraphTraits that allow Function and
33 // BasicBlock graphs to be treated as proper graphs for generic algorithms.
44 //
55 //===----------------------------------------------------------------------===//
88 #define LLVM_CFG_H
99
1010 #include "Support/GraphTraits.h"
11 #include "llvm/Method.h"
11 #include "llvm/Function.h"
1212 #include "llvm/BasicBlock.h"
1313 #include "llvm/InstrTypes.h"
1414 #include
136136 // GraphTraits specializations for basic block graphs (CFGs)
137137 //===--------------------------------------------------------------------===//
138138
139 // Provide specializations of GraphTraits to be able to treat a method as a
139 // Provide specializations of GraphTraits to be able to treat a function as a
140140 // graph of basic blocks...
141141
142142 template <> struct GraphTraits {
166166 }
167167 };
168168
169 // Provide specializations of GraphTraits to be able to treat a method as a
169 // Provide specializations of GraphTraits to be able to treat a function as a
170170 // graph of basic blocks... and to walk it in inverse order. Inverse order for
171 // a method is considered to be when traversing the predecessor edges of a BB
171 // a function is considered to be when traversing the predecessor edges of a BB
172172 // instead of the successor edges.
173173 //
174174 template <> struct GraphTraits > {
200200
201201
202202 //===--------------------------------------------------------------------===//
203 // GraphTraits specializations for method basic block graphs (CFGs)
204 //===--------------------------------------------------------------------===//
205
206 // Provide specializations of GraphTraits to be able to treat a method as a
203 // GraphTraits specializations for function basic block graphs (CFGs)
204 //===--------------------------------------------------------------------===//
205
206 // Provide specializations of GraphTraits to be able to treat a function as a
207207 // graph of basic blocks... these are the same as the basic block iterators,
208 // except that the root node is implicitly the first node of the method.
209 //
210 template <> struct GraphTraits : public GraphTraits {
211 static NodeType *getEntryNode(Method *M) { return M->front(); }
212 };
213 template <> struct GraphTraits :
208 // except that the root node is implicitly the first node of the function.
209 //
210 template <> struct GraphTraits : public GraphTraits {
211 static NodeType *getEntryNode(Function *F) { return F->getEntryNode(); }
212 };
213 template <> struct GraphTraits :
214214 public GraphTraits {
215 static NodeType *getEntryNode(const Method *M) { return M->front(); }
216 };
217
218
219 // Provide specializations of GraphTraits to be able to treat a method as a
215 static NodeType *getEntryNode(const Function *F) { return F->getEntryNode(); }
216 };
217
218
219 // Provide specializations of GraphTraits to be able to treat a function as a
220220 // graph of basic blocks... and to walk it in inverse order. Inverse order for
221 // a method is considered to be when traversing the predecessor edges of a BB
221 // a function is considered to be when traversing the predecessor edges of a BB
222222 // instead of the successor edges.
223223 //
224 template <> struct GraphTraitsMethod*> > :
224 template <> struct GraphTraitsFunction*> > :
225225 public GraphTraits > {
226 static NodeType *getEntryNode(Inverse G) { return G.Graph->front();}
227 };
228 template <> struct GraphTraits > :
226 static NodeType *getEntryNode(Inverse G) {
227 return G.Graph->front();
228 }
229 };
230 template <> struct GraphTraits > :
229231 public GraphTraits > {
230 static NodeType *getEntryNode(InverseMethod *> G) {
232 static NodeType *getEntryNode(InverseFunction *> G) {
231233 return G.Graph->front();
232234 }
233235 };
0 //===-- llvm/Support/InstIterator.h - Classes for inst iteration -*- C++ -*--=//
11 //
22 // This file contains definitions of two iterators for iterating over the
3 // instructions in a method. This is effectively a wrapper around a two level
3 // instructions in a function. This is effectively a wrapper around a two level
44 // iterator that can probably be genericized later.
55 //
66 // Note that this iterator gets invalidated any time that basic blocks or
1212 #define LLVM_INST_ITERATOR_H
1313
1414 #include "llvm/BasicBlock.h"
15 #include "llvm/Method.h"
15 #include "llvm/Function.h"
1616
1717 // This class is implements inst_begin() & inst_end() for
1818 // inst_iterator and const_inst_iterator's.
9595 };
9696
9797
98 typedef InstIterator, Method::iterator,
99 BasicBlock::iterator, Instruction*> inst_iterator;
100 typedef InstIterator,
101 Method::const_iterator,
98 typedef InstIterator,
99 Function::iterator, BasicBlock::iterator,
100 Instruction*> inst_iterator;
101 typedef InstIterator,
102 Function::const_iterator,
102103 BasicBlock::const_iterator,
103104 const Instruction*> const_inst_iterator;
104105
105 inline inst_iterator inst_begin(Method *M) { return inst_iterator(*M); }
106 inline inst_iterator inst_end(Method *M) { return inst_iterator(*M, true); }
107 inline const_inst_iterator inst_begin(const Method *M) {
108 return const_inst_iterator(*M);
106 inline inst_iterator inst_begin(Function *F) { return inst_iterator(*F); }
107 inline inst_iterator inst_end(Function *F) { return inst_iterator(*F, true); }
108 inline const_inst_iterator inst_begin(const Function *F) {
109 return const_inst_iterator(*F);
109110 }
110 inline const_inst_iterator inst_end(const Method *M) {
111 return const_inst_iterator(*M, true);
111 inline const_inst_iterator inst_end(const Function *F) {
112 return const_inst_iterator(*F, true);
112113 }
113114
114115 #endif
77 #ifndef LLVM_TRANSFORMS_SCALAR_DCE_H
88 #define LLVM_TRANSFORMS_SCALAR_DCE_H
99
10 #include "llvm/Method.h"
10 #include "llvm/Function.h"
1111 #include "llvm/BasicBlock.h"
1212 class Pass;
1313
5959 //
6060 // WARNING: The entry node of a method may not be simplified.
6161 //
62 bool SimplifyCFG(Method::iterator &BBIt);
62 bool SimplifyCFG(Function::iterator &BBIt);
6363
6464 #endif
None //===- SafePointerAccess.cpp - Check pointer usage safety -------------------=//
0 //===- FindUnsafePointerTypes.cpp - Check pointer usage safety --------------=//
11 //
22 // This file defines a pass that can be used to determine, interprocedurally,
33 // which pointer types are accessed unsafely in a program. If there is an
1919 #include "llvm/Assembly/CachedWriter.h"
2020 #include "llvm/Type.h"
2121 #include "llvm/Instruction.h"
22 #include "llvm/Method.h"
22 #include "llvm/Function.h"
2323 #include "llvm/Module.h"
2424 #include "llvm/Support/InstIterator.h"
2525 #include "Support/CommandLine.h"
5050 }
5151
5252
53 // runOnMethod - Inspect the operations that the specified method does on
54 // values of various types. If they are deemed to be 'unsafe' note that the
55 // type is not safe to transform.
56 //
5753 bool FindUnsafePointerTypes::run(Module *Mod) {
5854 for (Module::iterator MI = Mod->begin(), ME = Mod->end();
5955 MI != ME; ++MI) {
60 const Method *M = *MI; // We don't need/want write access
56 const Function *M = *MI; // We don't need/want write access
6157 for (const_inst_iterator I = inst_begin(M), E = inst_end(M); I != E; ++I) {
6258 const Instruction *Inst = *I;
6359 const Type *ITy = Inst->getType();
None //===- FindUsedTypes.h - Find all Types used by a module --------------------=//
0 //===- FindUsedTypes.cpp - Find all Types used by a module ------------------=//
11 //
22 // This pass is used to seek out all of the types in use by the program.
33 //
99 #include "llvm/GlobalVariable.h"
1010 #include "llvm/DerivedTypes.h"
1111 #include "llvm/Module.h"
12 #include "llvm/Method.h"
12 #include "llvm/Function.h"
1313 #include "llvm/Instruction.h"
1414 #include "llvm/Support/InstIterator.h"
1515
4040 assert(0 && "Unimp");
4141 }
4242
43 // doPerMethodWork - This incorporates all types used by the specified method
43 // run - This incorporates all types used by the specified module
4444 //
4545 bool FindUsedTypes::run(Module *m) {
4646 UsedTypes.clear(); // reset if run multiple times...
5353 IncorporateType((*I)->getType());
5454
5555 for (Module::iterator MI = m->begin(), ME = m->end(); MI != ME; ++MI) {
56 const Method *M = *MI;
56 const Function *M = *MI;
5757 if (IncludeSymbolTables && M->hasSymbolTable())
5858 IncorporateSymbolTable(M->getSymbolTable()); // Add symtab first...
5959
60 // Loop over all of the instructions in the method, adding their return type
61 // as well as the types of their operands.
60 // Loop over all of the instructions in the function, adding their return
61 // type as well as the types of their operands.
6262 //
6363 for (const_inst_iterator II = inst_begin(M), IE = inst_end(M);
6464 II != IE; ++II) {
0 //===- IntervalPartition.cpp - Interval Partition module code ----*- C++ -*--=//
11 //
22 // This file contains the definition of the cfg::IntervalPartition class, which
3 // calculates and represent the interval partition of a method.
3 // calculates and represent the interval partition of a function.
44 //
55 //===----------------------------------------------------------------------===//
66
1616 // IntervalPartition Implementation
1717 //===----------------------------------------------------------------------===//
1818
19 // destroy - Reset state back to before method was analyzed
19 // destroy - Reset state back to before function was analyzed
2020 void IntervalPartition::destroy() {
2121 for_each(begin(), end(), deleter);
2222 IntervalMap.clear();
4949 }
5050
5151 // IntervalPartition ctor - Build the first level interval partition for the
52 // specified method...
52 // specified function...
5353 //
54 bool IntervalPartition::runOnMethod(Method *M) {
54 bool IntervalPartition::runOnMethod(Function *M) {
5555 assert(M->front() && "Cannot operate on prototypes!");
5656
5757 // Pass false to intervals_begin because we take ownership of it's memory
58 method_interval_iterator I = intervals_begin(M, false);
59 assert(I != intervals_end(M) && "No intervals in method!?!?!");
58 function_interval_iterator I = intervals_begin(M, false);
59 assert(I != intervals_end(M) && "No intervals in function!?!?!");
6060
6161 addIntervalToPartition(RootInterval = *I);
6262
7979 // distinguish it from a copy constructor. Always pass in false for now.
8080 //
8181 IntervalPartition::IntervalPartition(IntervalPartition &IP, bool) {
82 Interval *MethodStart = IP.getRootInterval();
83 assert(MethodStart && "Cannot operate on empty IntervalPartitions!");
82 Interval *FunctionStart = IP.getRootInterval();
83 assert(FunctionStart && "Cannot operate on empty IntervalPartitions!");
8484
8585 // Pass false to intervals_begin because we take ownership of it's memory
8686 interval_part_interval_iterator I = intervals_begin(IP, false);
0 //===- DominatorSet.cpp - Dominator Set Calculation --------------*- C++ -*--=//
11 //
2 // This file provides a simple class to calculate the dominator set of a method.
2 // This file provides a simple class to calculate the dominator set of a
3 // function.
34 //
45 //===----------------------------------------------------------------------===//
56
67 #include "llvm/Analysis/Dominators.h"
78 #include "llvm/Transforms/UnifyMethodExitNodes.h"
8 #include "llvm/Method.h"
9 #include "llvm/Function.h"
910 #include "llvm/Support/CFG.h"
1011 #include "Support/DepthFirstIterator.h"
1112 #include "Support/STLExtras.h"
2021 AnalysisID cfg::DominatorSet::ID(AnalysisID::create());
2122 AnalysisID cfg::DominatorSet::PostDomID(AnalysisID::create());
2223
23 bool cfg::DominatorSet::runOnMethod(Method *M) {
24 bool cfg::DominatorSet::runOnMethod(Function *F) {
2425 Doms.clear(); // Reset from the last time we were run...
2526
2627 if (isPostDominator())
27 calcPostDominatorSet(M);
28 calcPostDominatorSet(F);
2829 else
29 calcForwardDominatorSet(M);
30 calcForwardDominatorSet(F);
3031 return false;
3132 }
3233
3334
3435 // calcForwardDominatorSet - This method calculates the forward dominator sets
35 // for the specified method.
36 //
37 void cfg::DominatorSet::calcForwardDominatorSet(Method *M) {
36 // for the specified function.
37 //
38 void cfg::DominatorSet::calcForwardDominatorSet(Function *M) {
3839 Root = M->getEntryNode();
3940 assert(pred_begin(Root) == pred_end(Root) &&
40 "Root node has predecessors in method!");
41 "Root node has predecessors in function!");
4142
4243 bool Changed;
4344 do {
4445 Changed = false;
4546
4647 DomSetType WorkingSet;
47 df_iterator<Method*> It = df_begin(M), End = df_end(M);
48 df_iterator<Function*> It = df_begin(M), End = df_end(M);
4849 for ( ; It != End; ++It) {
4950 const BasicBlock *BB = *It;
5051 pred_const_iterator PI = pred_begin(BB), PEnd = pred_end(BB);
7475 } while (Changed);
7576 }
7677
77 // Postdominator set constructor. This ctor converts the specified method to
78 // Postdominator set constructor. This ctor converts the specified function to
7879 // only have a single exit node (return stmt), then calculates the post
79 // dominance sets for the method.
80 //
81 void cfg::DominatorSet::calcPostDominatorSet(Method *M) {
80 // dominance sets for the function.
81 //
82 void cfg::DominatorSet::calcPostDominatorSet(Function *M) {
8283 // Since we require that the unify all exit nodes pass has been run, we know
83 // that there can be at most one return instruction in the method left.
84 // that there can be at most one return instruction in the function left.
8485 // Get it.
8586 //
8687 Root = getAnalysis().getExitNode();
8788
88 if (Root == 0) { // No exit node for the method? Postdomsets are all empty
89 for (Method::const_iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI)
89 if (Root == 0) { // No exit node for the function? Postdomsets are all empty
90 for (Function::const_iterator MI = M->begin(), ME = M->end(); MI!=ME; ++MI)
9091 Doms[*MI] = DomSetType();
9192 return;
9293 }
206207 // Given immediate dominators, we can also calculate the dominator tree
207208 cfg::DominatorTree::DominatorTree(const ImmediateDominators &IDoms)
208209 : DominatorBase(IDoms.getRoot()) {
209 const Method *M = Root->getParent();
210 const Function *M = Root->getParent();
210211
211212 Nodes[Root] = new Node(Root, 0); // Add a node for the root...
212213
213214 // Iterate over all nodes in depth first order...
214 for (df_iteratorMethod*> I = df_begin(M), E = df_end(M); I != E; ++I) {
215 for (df_iteratorFunction*> I = df_begin(M), E = df_end(M); I!=E; ++I) {
215216 const BasicBlock *BB = *I, *IDom = IDoms[*I];
216217
217218 if (IDom != 0) { // Ignore the root node and other nasty nodes
248249 // current node, and it is our idom! We know that we have already added
249250 // a DominatorTree node for our idom, because the idom must be a
250251 // predecessor in the depth first order that we are iterating through the
251 // method.
252 // function.
252253 //
253254 DominatorSet::DomSetType::const_iterator I = Dominators.begin();
254255 DominatorSet::DomSetType::const_iterator End = Dominators.end();
289290 // chain than the current node, and it is our idom! We know that we have
290291 // already added a DominatorTree node for our idom, because the idom must
291292 // be a predecessor in the depth first order that we are iterating through
292 // the method.
293 // the function.
293294 //
294295 DominatorSet::DomSetType::const_iterator I = Dominators.begin();
295296 DominatorSet::DomSetType::const_iterator End = Dominators.end();
1010
1111 #include "WriterInternals.h"
1212 #include "llvm/Module.h"
13 #include "llvm/Method.h"
13 #include "llvm/Function.h"
1414 #include "llvm/BasicBlock.h"
1515 #include "llvm/Instruction.h"
1616 #include "llvm/DerivedTypes.h"
5151 }
5252
5353
54 // outputInstrVarArgsCall - Output the obsurdly annoying varargs method calls.
54 // outputInstrVarArgsCall - Output the obsurdly annoying varargs function calls.
5555 // This are more annoying than most because the signature of the call does not
5656 // tell us anything about the types of the arguments in the varargs portion.
5757 // Because of this, we encode (as type 0) all of the argument types explicitly
7070
7171 unsigned NumArgs = I->getNumOperands();
7272 output_vbr(NumArgs*2, Out);
73 // TODO: Don't need to emit types for the fixed types of the varargs method
73 // TODO: Don't need to emit types for the fixed types of the varargs function
7474 // prototype...
7575
76 // The type for the method has already been emitted in the type field of the
76 // The type for the function has already been emitted in the type field of the
7777 // instruction. Just emit the slot # now.
7878 int Slot = Table.getValSlot(I->getOperand(0));
7979 assert(Slot >= 0 && "No slot number for value!?!?");
1010
1111 #include "llvm/Analysis/SlotCalculator.h"
1212 #include "llvm/Analysis/ConstantsScanner.h"
13 #include "llvm/Method.h"
13 #include "llvm/Function.h"
1414 #include "llvm/GlobalVariable.h"
1515 #include "llvm/Module.h"
1616 #include "llvm/BasicBlock.h"
4444 processModule();
4545 }
4646
47 SlotCalculator::SlotCalculator(const Method *M, bool IgnoreNamed) {
47 SlotCalculator::SlotCalculator(const Function *M, bool IgnoreNamed) {
4848 IgnoreNamedNodes = IgnoreNamed;
4949 TheModule = M ? M->getParent() : 0;
5050
6363 }
6464
6565
66 // processModule - Process all of the module level method declarations and
66 // processModule - Process all of the module level function declarations and
6767 // types that are available.
6868 //
6969 void SlotCalculator::processModule() {
8282 for_each(TheModule->gbegin(), TheModule->gend(),
8383 bind_obj(this, &SlotCalculator::insertValue));
8484
85 // Scavenge the types out of the methods, then add the methods themselves to
86 // the value table...
87 //
88 for_each(TheModule->begin(), TheModule->end(), // Insert methods...
85 // Scavenge the types out of the functions, then add the functions themselves
86 // to the value table...
87 //
88 for_each(TheModule->begin(), TheModule->end(), // Insert functions...
8989 bind_obj(this, &SlotCalculator::insertValue));
9090
9191 // Insert constants that are named at module level into the slot pool so that
118118 }
119119
120120
121 void SlotCalculator::incorporateMethod(const Method *M) {
121 void SlotCalculator::incorporateMethod(const Function *M) {
122122 assert(ModuleLevel.size() == 0 && "Module already incorporated!");
123123
124 SC_DEBUG("begin processMethod!\n");
125
126 // Save the Table state before we process the method...
124 SC_DEBUG("begin processFunction!\n");
125
126 // Save the Table state before we process the function...
127127 for (unsigned i = 0; i < Table.size(); ++i)
128128 ModuleLevel.push_back(Table[i].size());
129129
130 SC_DEBUG("Inserting method arguments\n");
131
132 // Iterate over method arguments, adding them to the value table...
130 SC_DEBUG("Inserting function arguments\n");
131
132 // Iterate over function arguments, adding them to the value table...
133133 for_each(M->getArgumentList().begin(), M->getArgumentList().end(),
134134 bind_obj(this, &SlotCalculator::insertValue));
135135
136 // Iterate over all of the instructions in the method, looking for constant
136 // Iterate over all of the instructions in the function, looking for constant
137137 // values that are referenced. Add these to the value pools before any
138138 // nonconstant values. This will be turned into the constant pool for the
139139 // bytecode writer.
140140 //
141141 if (!IgnoreNamedNodes) { // Assembly writer does not need this!
142 SC_DEBUG("Inserting method constants:\n";
142 SC_DEBUG("Inserting function constants:\n";
143143 for (constant_iterator I = constant_begin(M), E = constant_end(M);
144144 I != E; ++I) {
145145 cerr << " " << I->getType()->getDescription()
147147 });
148148
149149 // Emit all of the constants that are being used by the instructions in the
150 // method...
150 // function...
151151 for_each(constant_begin(M), constant_end(M),
152152 bind_obj(this, &SlotCalculator::insertValue));
153153
178178 processSymbolTable(M->getSymbolTable());
179179 }
180180
181 SC_DEBUG("end processMethod!\n");
181 SC_DEBUG("end processFunction!\n");
182182 }
183183
184184 void SlotCalculator::purgeMethod() {
185185 assert(ModuleLevel.size() != 0 && "Module not incorporated!");
186186 unsigned NumModuleTypes = ModuleLevel.size();
187187
188 SC_DEBUG("begin purgeMethod!\n");
188 SC_DEBUG("begin purgeFunction!\n");
189189
190190 // First, remove values from existing type planes
191191 for (unsigned i = 0; i < NumModuleTypes; ++i) {
192 unsigned ModuleSize = ModuleLevel[i]; // Size of plane before method came
192 unsigned ModuleSize = ModuleLevel[i]; // Size of plane before function came
193193 TypePlane &CurPlane = Table[i];
194194 //SC_DEBUG("Processing Plane " <
195195
206206 // We don't need this state anymore, free it up.
207207 ModuleLevel.clear();
208208
209 // Next, remove any type planes defined by the method...
209 // Next, remove any type planes defined by the function...
210210 while (NumModuleTypes != Table.size()) {
211211 TypePlane &Plane = Table.back();
212212 SC_DEBUG("Removing Plane " << (Table.size()-1) << " of size "
219219 Table.pop_back(); // Nuke the plane, we don't like it.
220220 }
221221
222 SC_DEBUG("end purgeMethod!\n");
222 SC_DEBUG("end purgeFunction!\n");
223223 }
224224
225225 int SlotCalculator::getValSlot(const Value *D) const {
336336
337337 SC_DEBUG(" Inserting value [" << Ty << "] = " << D << " slot=" <<
338338 DestSlot << " [");
339 // G = Global, C = Constant, T = Type, M = Method, o = other
339 // G = Global, C = Constant, T = Type, F = Function, o = other
340340 SC_DEBUG((isa(D) ? "G" : (isa(D) ? "C" :
341 (isa(D) ? "T" : (isa<Method>(D) ? "M" : "o")))));
341 (isa(D) ? "T" : (isa<Function>(D) ? "F" : "o")))));
342342 SC_DEBUG("]\n");
343343 return (int)DestSlot;
344344 }
1919 #include "llvm/Target/MachineRegInfo.h"
2020 #include "llvm/Target/TargetMachine.h"
2121 #include "llvm/BasicBlock.h"
22 #include "llvm/Method.h"
22 #include "llvm/Function.h"
2323 #include "llvm/iOther.h"
2424 #include "Support/StringExtras.h"
2525 #include "Support/STLExtras.h"
954954 //
955955
956956 /*ctor*/
957 SchedGraphSet::SchedGraphSet(const Method* _method,
957 SchedGraphSet::SchedGraphSet(const Function* _function,
958958 const TargetMachine& target) :
959 method(_method)
959 method(_function)
960960 {
961961 buildGraphsForMethod(method, target);
962962 }
974974 void
975975 SchedGraphSet::dump() const
976976 {
977 cerr << "======== Sched graphs for method `" << method->getName()
977 cerr << "======== Sched graphs for function `" << method->getName()
978978 << "' ========\n\n";
979979
980980 for (const_iterator I=begin(); I != end(); ++I)
981981 (*I)->dump();
982982
983 cerr << "\n====== End graphs for method `" << method->getName()
983 cerr << "\n====== End graphs for function `" << method->getName()
984984 << "' ========\n\n";
985985 }
986986
987987
988988 void
989 SchedGraphSet::buildGraphsForMethod(const Method *method,
989 SchedGraphSet::buildGraphsForMethod(const Function *F,
990990 const TargetMachine& target)
991991 {
992 for (Method::const_iterator BI = method->begin(); BI != method->end(); ++BI)
993 this->addGraph(new SchedGraph(*BI, target));
992 for (Function::const_iterator BI = F->begin(); BI != F->end(); ++BI)
993 addGraph(new SchedGraph(*BI, target));
994994 }
995995
996996
2222 #include "llvm/Target/MachineRegInfo.h"
2323 #include "llvm/Target/TargetMachine.h"
2424 #include "llvm/BasicBlock.h"
25 #include "llvm/Method.h"
25 #include "llvm/Function.h"
2626 #include "llvm/iPHINode.h"
2727 #include "Support/CommandLine.h"
2828 #include
5959 short* nts,
6060 TargetMachine &target);
6161
62 static void InsertCode4AllPhisInMeth(Method *method, TargetMachine &target);
62 static void InsertCode4AllPhisInMeth(Function *F, TargetMachine &target);
6363
6464
6565
7272 //---------------------------------------------------------------------------
7373
7474 bool
75 SelectInstructionsForMethod(Method* method, TargetMachine &target)
75 SelectInstructionsForMethod(Function *F, TargetMachine &target)
7676 {
7777 bool failed = false;
7878
7979 //
8080 // Build the instruction trees to be given as inputs to BURG.
8181 //
82 InstrForest instrForest(method);
82 InstrForest instrForest(F);
8383
8484 if (SelectDebugLevel >= Select_DebugInstTrees)
8585 {
86 cerr << "\n\n*** Input to instruction selection for method "
87 << (method->hasName()? method->getName() : "")
88 << "\n\n";
89 method->dump();
90
91 cerr << "\n\n*** Instruction trees for method "
92 << (method->hasName()? method->getName() : "")
93 << "\n\n";
86 cerr << "\n\n*** Input to instruction selection for function "
87 << F->getName() << "\n\n";
88 F->dump();
89
90 cerr << "\n\n*** Instruction trees for function "
91 << F->getName() << "\n\n";
9492 instrForest.dump();
9593 }
9694
124122 //
125123 // Record instructions in the vector for each basic block
126124 //
127 for (Method::iterator BI = method->begin(); BI != method->end(); ++BI)
125 for (Function::iterator BI = F->begin(), BE = F->end(); BI != BE; ++BI)
128126 {
129127 MachineCodeForBasicBlock& bbMvec = (*BI)->getMachineInstrVec();
130128 for (BasicBlock::iterator II = (*BI)->begin(); II != (*BI)->end(); ++II)
136134 }
137135
138136 // Insert phi elimination code -- added by Ruchira
139 InsertCode4AllPhisInMeth(method, target);
137 InsertCode4AllPhisInMeth(F, target);
140138
141139
142140 if (SelectDebugLevel >= Select_PrintMachineCode)
143141 {
144142 cerr << "\n*** Machine instructions after INSTRUCTION SELECTION\n";
145 MachineCodeForMethod::get(method).dump();
143 MachineCodeForMethod::get(F).dump();
146144 }
147145
148146 return false;
189187 //-------------------------------------------------------------------------
190188
191189 void
192 InsertCode4AllPhisInMeth(Method *method, TargetMachine &target)
190 InsertCode4AllPhisInMeth(Function *F, TargetMachine &target)
193191 {
194 // for all basic blocks in method
192 // for all basic blocks in function
195193 //
196 for (Method::iterator BI = method->begin(); BI != method->end(); ++BI) {
194 for (Function::iterator BI = F->begin(); BI != F->end(); ++BI) {
197195
198196 BasicBlock *BB = *BI;
199197 const BasicBlock::InstListType &InstList = BB->getInstList();
235233 else break; // since PHI nodes can only be at the top
236234
237235 } // for each Phi Instr in BB
238
239 } // for all BBs in method
240
236 } // for all BBs in function
241237 }
242238
243239
1919 #include "llvm/Target/TargetMachine.h"
2020 #include "llvm/Target/MachineRegInfo.h"
2121 #include "llvm/ConstantVals.h"
22 #include "llvm/Method.h"
22 #include "llvm/Function.h"
2323 #include "llvm/BasicBlock.h"
2424 #include "llvm/Type.h"
2525 #include "llvm/iMemory.h"
2929
3030
3131 static TmpInstruction*
32 InsertCodeToLoadConstant(Method* method,
32 InsertCodeToLoadConstant(Function *F,
3333 Value* opValue,
3434 Instruction* vmInstr,
3535 vector& loadConstVec,
4242 MachineCodeForInstruction &MCFI = MachineCodeForInstruction::get(vmInstr);
4343 MCFI.addTemp(tmpReg);
4444
45 target.getInstrInfo().CreateCodeToLoadConst(method, opValue, tmpReg,
45 target.getInstrInfo().CreateCodeToLoadConst(F, opValue, tmpReg,
4646 loadConstVec, tempVec);
4747
4848 // Register the new tmp values created for this m/c instruction sequence
343343 const MachineInstrDescriptor& instrDesc =
344344 target.getInstrInfo().getDescriptor(minstr->getOpCode());
345345
346 Method* method = vmInstr->getParent()->getParent();
346 Function *F = vmInstr->getParent()->getParent();
347347
348348 for (unsigned op=0; op < minstr->getNumOperands(); op++)
349349 {
380380
381381 if (constantThatMustBeLoaded || isa(opValue))
382382 { // opValue is a constant that must be explicitly loaded into a reg.
383 TmpInstruction* tmpReg = InsertCodeToLoadConstant(method, opValue, vmInstr,
384 loadConstVec, target);
383 TmpInstruction* tmpReg = InsertCodeToLoadConstant(F, opValue, vmInstr,
384 loadConstVec,
385 target);
385386 minstr->SetMachineOperandVal(op, MachineOperand::MO_VirtualRegister,
386387 tmpReg);
387388 }
403404 {
404405 Value* oldVal = minstr->getImplicitRef(i);
405406 TmpInstruction* tmpReg =
406 InsertCodeToLoadConstant(method, oldVal, vmInstr, loadConstVec, target);
407 InsertCodeToLoadConstant(F, oldVal, vmInstr, loadConstVec, target);
407408 minstr->setImplicitRef(i, tmpReg);
408409 }
409410
None //===-- MachineCodeForMethod.cpp --------------------------------------------=//
0 //===-- MachineCodeForFunction.cpp ------------------------------------------=//
11 //
22 // Purpose:
3 // Collect native machine code information for a method.
3 // Collect native machine code information for a function.
44 // This allows target-specific information about the generated code
5 // to be stored with each method.
5 // to be stored with each function.
66 //===----------------------------------------------------------------------===//
77
88 #include "llvm/CodeGen/MachineCodeForMethod.h"
1010 #include "llvm/Target/TargetMachine.h"
1111 #include "llvm/Target/MachineFrameInfo.h"
1212 #include "llvm/Target/MachineCacheInfo.h"
13 #include "llvm/Method.h"
13 #include "llvm/Function.h"
1414 #include "llvm/BasicBlock.h"
1515 #include "llvm/iOther.h"
1616 #include
1919 const int INVALID_FRAME_OFFSET = INT_MAX; // std::numeric_limits::max();
2020
2121 static AnnotationID MCFM_AID(
22 AnnotationManager::getID("CodeGen::MachineCodeForMethod"));
22 AnnotationManager::getID("CodeGen::MachineCodeForFunction"));
2323
2424 // The next two methods are used to construct and to retrieve
25 // the MachineCodeForMethod object for the given method.
26 // construct() -- Allocates and initializes for a given method and target
25 // the MachineCodeForFunction object for the given function.
26 // construct() -- Allocates and initializes for a given function and target
2727 // get() -- Returns a handle to the object.
2828 // This should not be called before "construct()"
29 // for a given Method.
29 // for a given Function.
3030 //
3131 MachineCodeForMethod&
32 MachineCodeForMethod::construct(const Method *M, const TargetMachine &Tar)
32 MachineCodeForMethod::construct(const Function *M, const TargetMachine &Tar)
3333 {
3434 assert(M->getAnnotation(MCFM_AID) == 0 &&
35 "Object already exists for this method!");
35 "Object already exists for this function!");
3636 MachineCodeForMethod* mcInfo = new MachineCodeForMethod(M, Tar);
3737 M->addAnnotation(mcInfo);
3838 return *mcInfo;
3939 }
4040
4141 void
42 MachineCodeForMethod::destruct(const Method *M)
42 MachineCodeForMethod::destruct(const Function *M)
4343 {
4444 bool Deleted = M->deleteAnnotation(MCFM_AID);
45 assert(Deleted && "Machine code did not exist for method!");
45 assert(Deleted && "Machine code did not exist for function!");
4646 }
4747
4848 MachineCodeForMethod&
49 MachineCodeForMethod::get(const Method* method)
50 {
51 MachineCodeForMethod* mc = (MachineCodeForMethod*)
52 method->getAnnotation(MCFM_AID);
49 MachineCodeForMethod::get(const Function *F)
50 {
51 MachineCodeForMethod *mc = (MachineCodeForMethod*)F->getAnnotation(MCFM_AID);
5352 assert(mc && "Call construct() method first to allocate the object");
5453 return *mc;
5554 }
5655
5756 static unsigned
58 ComputeMaxOptionalArgsSize(const TargetMachine& target, const Method* method)
57 ComputeMaxOptionalArgsSize(const TargetMachine& target, const Function *F)
5958 {
6059 const MachineFrameInfo& frameInfo = target.getFrameInfo();
6160
6261 unsigned int maxSize = 0;
6362
64 for (Method::const_iterator MI=method->begin(), ME=method->end();
65 MI != ME; ++MI)
63 for (Function::const_iterator MI = F->begin(), ME = F->end(); MI != ME; ++MI)
6664 {
6765 const BasicBlock *BB = *MI;
68 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
66 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
6967 if (CallInst *callInst = dyn_cast(*I))
7068 {
7169 unsigned int numOperands = callInst->getNumOperands() - 1;
72 int numExtra = (int) numOperands - frameInfo.getNumFixedOutgoingArgs();
70 int numExtra = (int)numOperands-frameInfo.getNumFixedOutgoingArgs();
7371 if (numExtra <= 0)
7472 continue;
7573
8179 }
8280 else
8381 {
84 assert(0 && "UNTESTED CODE: Size per stack argument is not fixed on this architecture: use actual arg sizes to compute MaxOptionalArgsSize");
82 assert(0 && "UNTESTED CODE: Size per stack argument is not "
83 "fixed on this architecture: use actual arg sizes to "
84 "compute MaxOptionalArgsSize");
8585 sizeForThisCall = 0;
8686 for (unsigned i=0; i < numOperands; ++i)
8787 sizeForThisCall += target.findOptimalStorageSize(callInst->
117117
118118
119119 /*ctor*/
120 MachineCodeForMethod::MachineCodeForMethod(const Method* _M,
120 MachineCodeForMethod::MachineCodeForMethod(const Function *F,
121121 const TargetMachine& target)
122122 : Annotation(MCFM_AID),
123 method(_M), compiledAsLeaf(false), staticStackSize(0),
123 method(F), compiledAsLeaf(false), staticStackSize(0),
124124 automaticVarsSize(0), regSpillsSize(0),
125125 currentOptionalArgsSize(0), maxOptionalArgsSize(0),
126126 currentTmpValuesSize(0), maxTmpValuesSize(0)
306306 std::cerr << "\n" << method->getReturnType()
307307 << " \"" << method->getName() << "\"\n";
308308
309 for (Method::const_iterator BI = method->begin(); BI != method->end(); ++BI)
309 for (Function::const_iterator BI = method->begin(); BI != method->end(); ++BI)
310310 {
311311 BasicBlock* bb = *BI;
312312 std::cerr << "\n" << bb->getName() << " (" << bb << ")" << ":\n";
315315 for (unsigned i=0; i < mvec.size(); i++)
316316 std::cerr << "\t" << *mvec[i];
317317 }
318 std::cerr << "\nEnd method \"" << method->getName() << "\"\n\n";
319 }
318 std::cerr << "\nEnd function \"" << method->getName() << "\"\n\n";
319 }
11 #include "llvm/CodeGen/RegClass.h"
22 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/Target/TargetMachine.h"
4 #include "llvm/Method.h"
4 #include "llvm/Function.h"
55 #include "llvm/BasicBlock.h"
66 #include "Support/SetOperations.h"
77 #include
88 using std::cerr;
99
10 LiveRangeInfo::LiveRangeInfo(const Method *M, const TargetMachine &tm,
10 LiveRangeInfo::LiveRangeInfo(const Function *F, const TargetMachine &tm,
1111 std::vector &RCL)
12 : Meth(M), TM(tm), RegClassList(RCL), MRI(tm.getRegInfo()) { }
12 : Meth(F), TM(tm), RegClassList(RCL), MRI(tm.getRegInfo()) { }
1313
1414
1515 LiveRangeInfo::~LiveRangeInfo() {
4747 //assert(( L1->getTypeID() == L2->getTypeID()) && "Merge:Different types");
4848
4949 L1->insert(*L2It); // add the var in L2 to L1
50 LiveRangeMap[*L2It] = L1; // now the elements in L2 should map
50 LiveRangeMap[*L2It] = L1; // now the elements in L2 should map
5151 //to L1
5252 }
5353
7272
7373
7474 //---------------------------------------------------------------------------
75 // Method for constructing all live ranges in a method. It creates live
75 // Method for constructing all live ranges in a function. It creates live
7676 // ranges for all values defined in the instruction stream. Also, it
77 // creates live ranges for all incoming arguments of the method.
77 // creates live ranges for all incoming arguments of the function.
7878 //---------------------------------------------------------------------------
7979 void LiveRangeInfo::constructLiveRanges() {
8080
8181 if (DEBUG_RA)
8282 cerr << "Consturcting Live Ranges ...\n";
8383
84 // first find the live ranges for all incoming args of the method since
85 // those LRs start from the start of the method
84 // first find the live ranges for all incoming args of the function since
85 // those LRs start from the start of the function
8686
87 // get the argument list
88 const Method::ArgumentListType& ArgList = Meth->getArgumentList();
89 // get an iterator to arg list
90 Method::ArgumentListType::const_iterator ArgIt = ArgList.begin();
91
92
87 // get the argument list
88 const Function::ArgumentListType& ArgList = Meth->getArgumentList();
89
90 Function::ArgumentListType::const_iterator ArgIt = ArgList.begin();
9391 for( ; ArgIt != ArgList.end() ; ++ArgIt) { // for each argument
9492 LiveRange * ArgRange = new LiveRange(); // creates a new LR and
9593 const Value *Val = (const Value *) *ArgIt;
110108 }
111109 }
112110
113 // Now suggest hardware registers for these method args
111 // Now suggest hardware registers for these function args
114112 MRI.suggestRegs4MethodArgs(Meth, *this);
115
116113
117114
118115 // Now find speical LLVM instructions (CALL, RET) and LRs in machine
119116 // instructions.
120117 //
121 for (Method::const_iterator BBI = Meth->begin(); BBI != Meth->end(); ++BBI) {
118 for (Function::const_iterator BBI = Meth->begin(); BBI != Meth->end(); ++BBI){
122119 // Now find all LRs for machine the instructions. A new LR will be created
123120 // only for defs in the machine instr since, we assume that all Values are
124121 // defined before they are used. However, there can be multiple defs for
206203
207204 } // for all machine instructions in the BB
208205
209 } // for all BBs in method
206 } // for all BBs in function
210207
211208
212209 // Now we have to suggest clors for call and return arg live ranges.
224221 //---------------------------------------------------------------------------
225222 // If some live ranges must be colored with specific hardware registers
226223 // (e.g., for outgoing call args), suggesting of colors for such live
227 // ranges is done using target specific method. Those methods are called
224 // ranges is done using target specific function. Those functions are called
228225 // from this function. The target specific methods must:
229226 // 1) suggest colors for call and return args.
230227 // 2) create new LRs for implicit defs in machine instructions
231228 //---------------------------------------------------------------------------
232229 void LiveRangeInfo::suggestRegs4CallRets()
233230 {
234
235231 CallRetInstrListType::const_iterator It = CallRetInstrList.begin();
236
237232 for( ; It != CallRetInstrList.end(); ++It ) {
238233
239234 const MachineInstr *MInst = *It;
258253
259254
260255 /* Algorithm:
261 for each BB in method
256 for each BB in function
262257 for each machine instruction (inst)
263258 for each definition (def) in inst
264259 for each operand (op) of inst that is a use
272267 //---------------------------------------------------------------------------
273268 void LiveRangeInfo::coalesceLRs()
274269 {
275 if( DEBUG_RA)
270 if(DEBUG_RA)
276271 cerr << "\nCoalscing LRs ...\n";
277272
278 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
279
280 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
273 for(Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
274 BBI != BBE; ++BBI) {
281275
282276 // get the iterator for machine instructions
283277 const MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
1818 #include "llvm/Target/TargetMachine.h"
1919 #include "llvm/Target/MachineFrameInfo.h"
2020 #include "llvm/BasicBlock.h"
21 #include "llvm/Method.h"
21 #include "llvm/Function.h"
2222 #include "llvm/Type.h"
2323 #include
2424 #include
4444 public:
4545 inline RegisterAllocator(TargetMachine &T) : Target(T) {}
4646
47 bool runOnMethod(Method *M) {
47 bool runOnMethod(Function *F) {
4848 if (DEBUG_RA)
49 cerr << "\n******************** Method "<< M->getName()
49 cerr << "\n******************** Method "<< F->getName()
5050 << " ********************\n";
5151
52 PhyRegAlloc PRA(M, Target, &getAnalysis(),
52 PhyRegAlloc PRA(F, Target, &getAnalysis(),
5353 &getAnalysis());
5454 PRA.allocateRegisters();
5555
7474 //----------------------------------------------------------------------------
7575 // Constructor: Init local composite objects and create register classes.
7676 //----------------------------------------------------------------------------
77 PhyRegAlloc::PhyRegAlloc(Method *M,
77 PhyRegAlloc::PhyRegAlloc(Function *F,
7878 const TargetMachine& tm,
7979 MethodLiveVarInfo *Lvi,
8080 cfg::LoopInfo *LDC)
81 : TM(tm), Meth(M),
82 mcInfo(MachineCodeForMethod::get(M)),
83 LVI(Lvi), LRI(M, tm, RegClassList),
84 MRI( tm.getRegInfo() ),
81 : TM(tm), Meth(F),
82 mcInfo(MachineCodeForMethod::get(F)),
83 LVI(Lvi), LRI(F, tm, RegClassList),
84 MRI(tm.getRegInfo()),
8585 NumOfRegClasses(MRI.getNumOfRegClasses()),
8686 LoopDepthCalc(LDC) {
8787
8888 // create each RegisterClass and put in RegClassList
8989 //
9090 for(unsigned int rc=0; rc < NumOfRegClasses; rc++)
91 RegClassList.push_back( new RegClass(M, MRI.getMachineRegClass(rc),
92 &ResColList) );
91 RegClassList.push_back(new RegClass(F, MRI.getMachineRegClass(rc),
92 &ResColList));
9393 }
9494
9595
277277 if(DEBUG_RA) cerr << "Creating interference graphs ...\n";
278278
279279 unsigned BBLoopDepthCost;
280 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
281
282 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
280 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
281 BBI != BBE; ++BBI) {
283282
284283 // find the 10^(loop_depth) of this BB
285284 //
286 BBLoopDepthCost = (unsigned) pow( 10.0, LoopDepthCalc->getLoopDepth(*BBI));
285 BBLoopDepthCost = (unsigned) pow(10.0, LoopDepthCalc->getLoopDepth(*BBI));
287286
288287 // get the iterator for machine instructions
289288 //
345344
346345
347346 } // for all machine instructions in BB
348
349 } // for all BBs in method
350
351
352 // add interferences for method arguments. Since there are no explict
353 // defs in method for args, we have to add them manually
347 } // for all BBs in function
348
349
350 // add interferences for function arguments. Since there are no explict
351 // defs in the function for args, we have to add them manually
354352 //
355353 addInterferencesForArgs();
356354
404402
405403
406404 //----------------------------------------------------------------------------
407 // This method will add interferences for incoming arguments to a method.
405 // This method will add interferences for incoming arguments to a function.
408406 //----------------------------------------------------------------------------
409407 void PhyRegAlloc::addInterferencesForArgs() {
410408 // get the InSet of root BB
411409 const ValueSet &InSet = LVI->getInSetOfBB(Meth->front());
412410
413411 // get the argument list
414 const Method::ArgumentListType& ArgList = Meth->getArgumentList();
412 const Function::ArgumentListType &ArgList = Meth->getArgumentList();
415413
416414 // get an iterator to arg list
417 Method::ArgumentListType::const_iterator ArgIt = ArgList.begin();
415 Function::ArgumentListType::const_iterator ArgIt = ArgList.begin();
418416
419417
420418 for( ; ArgIt != ArgList.end() ; ++ArgIt) { // for each argument
440438 void PhyRegAlloc::updateMachineCode()
441439 {
442440
443 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
444
445 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
446
441 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
442 BBI != BBE; ++BBI) {
447443 // get the iterator for machine instructions
448444 //
449445 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
954950 void PhyRegAlloc::printMachineCode()
955951 {
956952
957 cerr << "\n;************** Method " << Meth->getName()
953 cerr << "\n;************** Function " << Meth->getName()
958954 << " *****************\n";
959955
960 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
961
962 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
963
964 cerr << "\n"; printLabel( *BBI); cerr << ": ";
956 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
957 BBI != BBE; ++BBI) {
958 cerr << "\n"; printLabel(*BBI); cerr << ": ";
965959
966960 // get the iterator for machine instructions
967961 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
969963
970964 // iterate over all the machine instructions in BB
971965 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
972
973966 MachineInstr *const MInst = *MInstIterator;
974
975967
976968 cerr << "\n\t";
977969 cerr << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
978
979
980 //for(MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
981970
982971 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
983
984972 MachineOperand& Op = MInst->getOperand(OpNum);
985973
986974 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
10721060 // Tmp stack poistions are needed by some calls that have spilled args
10731061 // So reset it before we call each such method
10741062 //mcInfo.popAllTempValues(TM);
1075
10761063
10771064
10781065 if (TM.getInstrInfo().isCall(OpCode))
232232 // This annotation will only be created on GlobalValue objects...
233233 GlobalValue *GVal = cast((Value*)O);
234234
235 if (isa(GVal)) {
236 // The GlobalAddress object for a method is just a pointer to method itself.
237 // Don't delete it when the annotation is gone though!
235 if (isa(GVal)) {
236 // The GlobalAddress object for a function is just a pointer to function
237 // itself. Don't delete it when the annotation is gone though!
238238 return new GlobalAddress(GVal, false);
239239 }
240240
241241 // Handle the case of a global variable...
242242 assert(isa(GVal) &&
243 "Global value found that isn't a method or global variable!");
243 "Global value found that isn't a function or global variable!");
244244 GlobalVariable *GV = cast(GVal);
245245
246246 // First off, we must allocate space for the global variable to point at...
666666 }
667667
668668 // Save previously executing meth
669 const Method *M = ECStack.back().CurMethod;
669 const Function *M = ECStack.back().CurMethod;
670670
671671 // Pop the current stack frame... this invalidates SF
672672 ECStack.pop_back();
674674 if (ECStack.empty()) { // Finished main. Put result into exit code...
675675 if (RetTy) { // Nonvoid return type?
676676 if (!QuietMode) {
677 CW << "Method " << M->getType() << " \"" << M->getName()
677 CW << "Function " << M->getType() << " \"" << M->getName()
678678 << "\" returned ";
679679 print(RetTy, Result);
680680 cout << "\n";
702702 } else if (!QuietMode) {
703703 // This must be a function that is executing because of a user 'call'
704704 // instruction.
705 CW << "Method " << M->getType() << " \"" << M->getName()
705 CW << "Function " << M->getType() << " \"" << M->getName()
706706 << "\" returned ";
707707 print(RetTy, Result);
708708 cout << "\n";
893893 ArgVals.push_back(getOperandValue(I->getOperand(i), SF));
894894
895895 // To handle indirect calls, we must get the pointer value from the argument
896 // and treat it as a method pointer.
896 // and treat it as a function pointer.
897897 GenericValue SRC = getOperandValue(I->getCalledValue(), SF);
898898
899 callMethod((Method*)SRC.PointerVal, ArgVals);
899 callMethod((Function*)SRC.PointerVal, ArgVals);
900900 }
901901
902902 static void executePHINode(PHINode *I, ExecutionContext &SF) {
10231023 // Dispatch and Execution Code
10241024 //===----------------------------------------------------------------------===//
10251025
1026 MethodInfo::MethodInfo(Method *M) : Annotation(MethodInfoAID) {
1027 // Assign slot numbers to the method arguments...
1028 const Method::ArgumentListType &ArgList = M->getArgumentList();
1029 for (Method::ArgumentListType::const_iterator AI = ArgList.begin(),
1026 MethodInfo::MethodInfo(Function *M) : Annotation(MethodInfoAID) {
1027 // Assign slot numbers to the function arguments...
1028 const Function::ArgumentListType &ArgList = M->getArgumentList();
1029 for (Function::ArgumentListType::const_iterator AI = ArgList.begin(),
10301030 AE = ArgList.end(); AI != AE; ++AI)
10311031 (*AI)->addAnnotation(new SlotNumber(getValueSlot(*AI)));
10321032
10331033 // Iterate over all of the instructions...
10341034 unsigned InstNum = 0;
1035 for (Method::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI) {
1035 for (Function::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI) {
10361036 BasicBlock *BB = *MI;
10371037 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE; ++II){
10381038 Instruction *I = *II; // For each instruction... Add Annote
10501050
10511051
10521052 //===----------------------------------------------------------------------===//
1053 // callMethod - Execute the specified method...
1053 // callMethod - Execute the specified function...
10541054 //
1055 void Interpreter::callMethod(Method *M, const vector &ArgVals) {
1055 void Interpreter::callMethod(Function *M, const vector &ArgVals) {
10561056 assert((ECStack.empty() || ECStack.back().Caller == 0 ||
10571057 ECStack.back().Caller->getNumOperands()-1 == ArgVals.size()) &&
10581058 "Incorrect number of arguments passed into function call!");
10701070 SF.Caller = 0; // We returned from the call...
10711071 } else if (!QuietMode) {
10721072 // print it.
1073 CW << "Method " << M->getType() << " \"" << M->getName()
1073 CW << "Function " << M->getType() << " \"" << M->getName()
10741074 << "\" returned ";
10751075 print(RetTy, Result);
10761076 cout << "\n";
10831083 return;
10841084 }
10851085
1086 // Process the method, assigning instruction numbers to the instructions in
1087 // the method. Also calculate the number of values for each type slot active.
1086 // Process the function, assigning instruction numbers to the instructions in
1087 // the function. Also calculate the number of values for each type slot
1088 // active.
10881089 //
10891090 MethodInfo *MethInfo = (MethodInfo*)M->getOrCreateAnnotation(MethodInfoAID);
10901091 ECStack.push_back(ExecutionContext()); // Make a new stack frame...
11081109 StackFrame.PrevBB = 0; // No previous BB for PHI nodes...
11091110
11101111
1111 // Run through the method arguments and initialize their values...
1112 // Run through the function arguments and initialize their values...
11121113 assert(ArgVals.size() == M->getArgumentList().size() &&
1113 "Invalid number of values passed to method invocation!");
1114 "Invalid number of values passed to function invocation!");
11141115 unsigned i = 0;
1115 for (Method::ArgumentListType::iterator MI = M->getArgumentList().begin(),
1116 for (Function::ArgumentListType::iterator MI = M->getArgumentList().begin(),
11161117 ME = M->getArgumentList().end(); MI != ME; ++MI, ++i) {
11171118 SetValue(*MI, ArgVals[i], StackFrame);
11181119 }
13181319 Value *PickedVal = ChooseOneOption(Name, LookupMatchingNames(Name));
13191320 if (!PickedVal) return;
13201321
1321 if (const Method *M = dyn_cast(PickedVal)) {
1322 CW << M; // Print the method
1322 if (const Function *F = dyn_cast(PickedVal)) {
1323 CW << F; // Print the function
13231324 } else if (const Type *Ty = dyn_cast(PickedVal)) {
13241325 CW << "type %" << Name << " = " << Ty->getDescription() << "\n";
13251326 } else if (const BasicBlock *BB = dyn_cast(PickedVal)) {
13471348 //
13481349 void Interpreter::printStackFrame(int FrameNo = -1) {
13491350 if (FrameNo == -1) FrameNo = CurFrame;
1350 Method *Meth = ECStack[FrameNo].CurMethod;
1351 const Type *RetTy = Meth->getReturnType();
1351 Function *Func = ECStack[FrameNo].CurMethod;
1352 const Type *RetTy = Func->getReturnType();
13521353
13531354 CW << ((FrameNo == CurFrame) ? '>' : '-') << "#" << FrameNo << ". "
1354 << (Value*)RetTy << " \"" << Meth->getName() << "\"(";
1355 << (Value*)RetTy << " \"" << Func->getName() << "\"(";
13551356
1356 Method::ArgumentListType &Args = Meth->getArgumentList();
1357 Function::ArgumentListType &Args = Func->getArgumentList();
13571358 for (unsigned i = 0; i < Args.size(); ++i) {
13581359 if (i != 0) cout << ", ";
13591360 CW << (Value*)Args[i] << "=";
1010 // Support for MethodInfo annotations
1111 //===----------------------------------------------------------------------===//
1212
13 // This annotation (attached only to Method objects) is used to cache useful
14 // information about the method, including the number of types present in the
15 // method, and the number of values for each type.
13 // This annotation (attached only to Function objects) is used to cache useful
14 // information about the function, including the number of types present in the
15 // function, and the number of values for each type.
1616 //
1717 // This annotation object is created on demand, and attaches other annotation
18 // objects to the instructions in the method when it's created.
18 // objects to the instructions in the function when it's created.
1919 //
2020 static AnnotationID MethodInfoAID(
21 AnnotationManager::getID("Interpreter::MethodInfo"));
21 AnnotationManager::getID("Interpreter::FunctionInfo"));
2222
2323 struct MethodInfo : public Annotation {
24 MethodInfo(Method *M);
24 MethodInfo(Function *F);
2525 std::vector NumPlaneElements;
2626
2727
3030 //
3131 static Annotation *Create(AnnotationID AID, const Annotable *O, void *) {
3232 assert(AID == MethodInfoAID);
33 return new MethodInfo(cast<Method>((Value*)O)); // Simply invoke the ctor
33 return new MethodInfo(cast<Function>((Value*)O)); // Simply invoke the ctor
3434 }
3535
3636 private:
4646 // used to hold the the slot number for the value in its type plane.
4747 //
4848 // Entities have this annotation attached to them when the containing
49 // method has it's MethodInfo created (by the MethodInfo ctor).
49 // function has it's MethodInfo created (by the MethodInfo ctor).
5050 //
5151 static AnnotationID SlotNumberAID(
5252 AnnotationManager::getID("Interpreter::SlotNumber"));
7070 // its type plane. InstNumber's are used for user interaction, and for
7171 // calculating which value slot to store the result of the instruction in.
7272 //
73 // Instructions have this annotation attached to them when the containing method
74 // has it's MethodInfo created (by the MethodInfo ctor).
73 // Instructions have this annotation attached to them when the containing
74 // function has it's MethodInfo created (by the MethodInfo ctor).
7575 //
7676 struct InstNumber : public SlotNumber {
7777 unsigned InstNum; // Ranges from 1->
9494 //===----------------------------------------------------------------------===//
9595
9696 // This annotation (attached only to GlobalValue objects) is used to hold the
97 // address of the chunk of memory that represents a global value. For Method's,
98 // this pointer is the Method object pointer that represents it. For global
99 // variables, this is the dynamically allocated (and potentially initialized)
100 // chunk of memory for the global. This annotation is created on demand.
97 // address of the chunk of memory that represents a global value. For
98 // Functions, this pointer is the Function object pointer that represents it.
99 // For global variables, this is the dynamically allocated (and potentially
100 // initialized) chunk of memory for the global. This annotation is created on
101 // demand.
101102 //
102103 static AnnotationID GlobalAddressAID(
103104 AnnotationManager::getID("Interpreter::GlobalAddress"));
None //===-- ExternalMethods.cpp - Implement External Functions ----------------===//
0 //===-- ExternalFunctions.cpp - Implement External Functions --------------===//
11 //
2 // This file contains both code to deal with invoking "external" methods, but
3 // also contains code that implements "exported" external methods.
2 // This file contains both code to deal with invoking "external" functions, but
3 // also contains code that implements "exported" external functions.
44 //
5 // External methods in LLI are implemented by dlopen'ing the lli executable and
6 // using dlsym to look op the methods that we want to invoke. If a method is
7 // found, then the arguments are mangled and passed in to the function call.
5 // External functions in LLI are implemented by dlopen'ing the lli executable
6 // and using dlsym to look op the functions that we want to invoke. If a
7 // function is found, then the arguments are mangled and passed in to the
8 // function call.
89 //
910 //===----------------------------------------------------------------------===//
1011
9091 const vector &ArgVals) {
9192 TheInterpreter = this;
9293
93 // Do a lookup to see if the method is in our cache... this should just be a
94 // Do a lookup to see if the function is in our cache... this should just be a
9495 // defered annotation!
9596 std::map::iterator FI = Functions.find(M);
9697 ExFunc Fn = (FI == Functions.end()) ? lookupFunction(M) : FI->second;
9798 if (Fn == 0) {
98 cout << "Tried to execute an unknown external method: "
99 cout << "Tried to execute an unknown external function: "
99100 << M->getType()->getDescription() << " " << M->getName() << "\n";
100101 return GenericValue();
101102 }
102103
103104 // TODO: FIXME when types are not const!
104 GenericValue Result = Fn(const_cast(M->getFunctionType()),ArgVals);
105 GenericValue Result = Fn(const_cast(M->getFunctionType()),
106 ArgVals);
105107 return Result;
106108 }
107109
1111
1212
1313 #include "llvm/Module.h"
14 #include "llvm/Method.h"
14 #include "llvm/Function.h"
1515 #include "llvm/BasicBlock.h"
1616 #include "Support/DataTypes.h"
1717 #include "llvm/Assembly/CachedWriter.h"
7777 // executing.
7878 //
7979 struct ExecutionContext {
80 Method *CurMethod; // The currently executing method
80 Function *CurMethod; // The currently executing function
8181 BasicBlock *CurBB; // The currently executing BB
8282 BasicBlock::iterator CurInst; // The next instruction to execute
83 MethodInfo *MethInfo; // The MethInfo annotation for the method
83 MethodInfo *MethInfo; // The MethInfo annotation for the function
8484 std::vector Values;// ValuePlanes for each type
8585
8686 BasicBlock *PrevBB; // The previous BB or null if in first BB
9999 int CurFrame; // The current stack frame being inspected
100100
101101 // The runtime stack of executing code. The top of the stack is the current
102 // method record.
102 // function record.
103103 std::vector ECStack;
104104
105105 public:
134134 void printStackTrace(); // Do the 'backtrace' command
135135
136136 // Code execution methods...
137 void callMethod(Method *Meth, const std::vector &ArgVals);
137 void callMethod(Function *F, const std::vector &ArgVals);
138138 bool executeInstruction(); // Execute one instruction...
139139
140140 void stepInstruction(); // Do the 'step' command
147147 void executeRetInst(ReturnInst *I, ExecutionContext &SF);
148148 void executeBrInst(BranchInst *I, ExecutionContext &SF);
149149 void executeAllocInst(AllocationInst *I, ExecutionContext &SF);
150 GenericValue callExternalMethod(Method *Meth,
150 GenericValue callExternalMethod(Function *F,
151151 const std::vector &ArgVals);
152152 void exitCalled(GenericValue GV);
153153
154154 // getCurrentMethod - Return the currently executing method
155 inline Method *getCurrentMethod() const {
155 inline Function *getCurrentMethod() const {
156156 return CurFrame < 0 ? 0 : ECStack[CurFrame].CurMethod;
157157 }
158158
177177 //
178178 void printStackFrame(int FrameNo = -1);
179179
180 // LookupMatchingNames - Search the current method namespace, then the global
181 // namespace looking for values that match the specified name. Return ALL
182 // matches to that name. This is obviously slow, and should only be used for
183 // user interaction.
180 // LookupMatchingNames - Search the current function namespace, then the
181 // global namespace looking for values that match the specified name. Return
182 // ALL matches to that name. This is obviously slow, and should only be used
183 // for user interaction.
184184 //
185185 std::vector LookupMatchingNames(const std::string &Name);
186186
3030 }
3131 }
3232
33 // LookupMatchingNames - Search the current method namespace, then the global
33 // LookupMatchingNames - Search the current function namespace, then the global
3434 // namespace looking for values that match the specified name. Return ALL
3535 // matches to that name. This is obviously slow, and should only be used for
3636 // user interaction.
3737 //
3838 std::vector Interpreter::LookupMatchingNames(const std::string &Name) {
3939 std::vector Results;
40 Method *CurMeth = getCurrentMethod();
40 Function *CurMeth = getCurrentMethod();
4141
4242 if (CurMeth) ::LookupMatchingNames(Name, *CurMeth, Results);
4343 if (CurMod ) ::LookupMatchingNames(Name, *CurMod , Results);
123123 case Finish: finish(); break;
124124 case Call:
125125 cin >> Command;
126 callMethod(Command); // Enter the specified method
126 callMethod(Command); // Enter the specified function
127127 finish(); // Run until it's complete
128128 break;
129129
214214 bool Interpreter::callMethod(const string &Name) {
215215 std::vector Options = LookupMatchingNames(Name);
216216
217 for (unsigned i = 0; i < Options.size(); ++i) { // Remove nonmethod matches...
217 for (unsigned i = 0; i < Options.size(); ++i) { // Remove non-fn matches...
218218 if (!isa(Options[i])) {
219219 Options.erase(Options.begin()+i);
220220 --i;
262262 const std::vector &InputArgv) {
263263 std::vector Options = LookupMatchingNames(Name);
264264
265 for (unsigned i = 0; i < Options.size(); ++i) { // Remove nonmethod matches...
265 for (unsigned i = 0; i < Options.size(); ++i) { // Remove non-fn matches...
266266 if (!isa(Options[i])) {
267267 Options.erase(Options.begin()+i);
268268 --i;
320320 if (ECStack.empty())
321321 cout << "Error: No program executing!\n";
322322 else
323 CW << ECStack[CurFrame].CurMethod; // Just print the method out...
323 CW << ECStack[CurFrame].CurMethod; // Just print the function out...
324324 }
325325
326326 void Interpreter::printStackTrace() {
1919 #include "llvm/Target/MachineRegInfo.h"
2020 #include "llvm/Target/TargetMachine.h"
2121 #include "llvm/BasicBlock.h"
22 #include "llvm/Method.h"
22 #include "llvm/Function.h"
2323 #include "llvm/iOther.h"
2424 #include "Support/StringExtras.h"
2525 #include "Support/STLExtras.h"
954954 //
955955
956956 /*ctor*/
957 SchedGraphSet::SchedGraphSet(const Method* _method,
957 SchedGraphSet::SchedGraphSet(const Function* _function,
958958 const TargetMachine& target) :
959 method(_method)
959 method(_function)
960960 {
961961 buildGraphsForMethod(method, target);
962962 }
974974 void
975975 SchedGraphSet::dump() const
976976 {
977 cerr << "======== Sched graphs for method `" << method->getName()
977 cerr << "======== Sched graphs for function `" << method->getName()
978978 << "' ========\n\n";
979979
980980 for (const_iterator I=begin(); I != end(); ++I)
981981 (*I)->dump();
982982
983 cerr << "\n====== End graphs for method `" << method->getName()
983 cerr << "\n====== End graphs for function `" << method->getName()
984984 << "' ========\n\n";
985985 }
986986
987987
988988 void
989 SchedGraphSet::buildGraphsForMethod(const Method *method,
989 SchedGraphSet::buildGraphsForMethod(const Function *F,
990990 const TargetMachine& target)
991991 {
992 for (Method::const_iterator BI = method->begin(); BI != method->end(); ++BI)
993 this->addGraph(new SchedGraph(*BI, target));
992 for (Function::const_iterator BI = F->begin(); BI != F->end(); ++BI)
993 addGraph(new SchedGraph(*BI, target));
994994 }
995995
996996
2222 #include "llvm/Target/MachineRegInfo.h"
2323 #include "llvm/Target/TargetMachine.h"
2424 #include "llvm/BasicBlock.h"
25 #include "llvm/Method.h"
25 #include "llvm/Function.h"
2626 #include "llvm/iPHINode.h"
2727 #include "Support/CommandLine.h"
2828 #include
5959 short* nts,
6060 TargetMachine &target);
6161
62 static void InsertCode4AllPhisInMeth(Method *method, TargetMachine &target);
62 static void InsertCode4AllPhisInMeth(Function *F, TargetMachine &target);
6363
6464
6565
7272 //---------------------------------------------------------------------------
7373
7474 bool
75 SelectInstructionsForMethod(Method* method, TargetMachine &target)
75 SelectInstructionsForMethod(Function *F, TargetMachine &target)
7676 {
7777 bool failed = false;
7878
7979 //
8080 // Build the instruction trees to be given as inputs to BURG.
8181 //
82 InstrForest instrForest(method);
82 InstrForest instrForest(F);
8383
8484 if (SelectDebugLevel >= Select_DebugInstTrees)
8585 {
86 cerr << "\n\n*** Input to instruction selection for method "
87 << (method->hasName()? method->getName() : "")
88 << "\n\n";
89 method->dump();
90
91 cerr << "\n\n*** Instruction trees for method "
92 << (method->hasName()? method->getName() : "")
93 << "\n\n";
86 cerr << "\n\n*** Input to instruction selection for function "
87 << F->getName() << "\n\n";
88 F->dump();
89
90 cerr << "\n\n*** Instruction trees for function "
91 << F->getName() << "\n\n";
9492 instrForest.dump();
9593 }
9694
124122 //
125123 // Record instructions in the vector for each basic block
126124 //
127 for (Method::iterator BI = method->begin(); BI != method->end(); ++BI)
125 for (Function::iterator BI = F->begin(), BE = F->end(); BI != BE; ++BI)
128126 {
129127 MachineCodeForBasicBlock& bbMvec = (*BI)->getMachineInstrVec();
130128 for (BasicBlock::iterator II = (*BI)->begin(); II != (*BI)->end(); ++II)
136134 }
137135
138136 // Insert phi elimination code -- added by Ruchira
139 InsertCode4AllPhisInMeth(method, target);
137 InsertCode4AllPhisInMeth(F, target);
140138
141139
142140 if (SelectDebugLevel >= Select_PrintMachineCode)
143141 {
144142 cerr << "\n*** Machine instructions after INSTRUCTION SELECTION\n";
145 MachineCodeForMethod::get(method).dump();
143 MachineCodeForMethod::get(F).dump();
146144 }
147145
148146 return false;
189187 //-------------------------------------------------------------------------
190188
191189 void
192 InsertCode4AllPhisInMeth(Method *method, TargetMachine &target)
190 InsertCode4AllPhisInMeth(Function *F, TargetMachine &target)
193191 {
194 // for all basic blocks in method
192 // for all basic blocks in function
195193 //
196 for (Method::iterator BI = method->begin(); BI != method->end(); ++BI) {
194 for (Function::iterator BI = F->begin(); BI != F->end(); ++BI) {
197195
198196 BasicBlock *BB = *BI;
199197 const BasicBlock::InstListType &InstList = BB->getInstList();
235233 else break; // since PHI nodes can only be at the top
236234
237235 } // for each Phi Instr in BB
238
239 } // for all BBs in method
240
236 } // for all BBs in function
241237 }
242238
243239
1919 #include "llvm/Target/TargetMachine.h"
2020 #include "llvm/Target/MachineRegInfo.h"
2121 #include "llvm/ConstantVals.h"
22 #include "llvm/Method.h"
22 #include "llvm/Function.h"
2323 #include "llvm/BasicBlock.h"
2424 #include "llvm/Type.h"
2525 #include "llvm/iMemory.h"
2929
3030
3131 static TmpInstruction*
32 InsertCodeToLoadConstant(Method* method,
32 InsertCodeToLoadConstant(Function *F,
3333 Value* opValue,
3434 Instruction* vmInstr,
3535 vector& loadConstVec,
4242 MachineCodeForInstruction &MCFI = MachineCodeForInstruction::get(vmInstr);
4343 MCFI.addTemp(tmpReg);
4444
45 target.getInstrInfo().CreateCodeToLoadConst(method, opValue, tmpReg,
45 target.getInstrInfo().CreateCodeToLoadConst(F, opValue, tmpReg,
4646 loadConstVec, tempVec);
4747
4848 // Register the new tmp values created for this m/c instruction sequence
343343 const MachineInstrDescriptor& instrDesc =
344344 target.getInstrInfo().getDescriptor(minstr->getOpCode());
345345
346 Method* method = vmInstr->getParent()->getParent();
346 Function *F = vmInstr->getParent()->getParent();
347347
348348 for (unsigned op=0; op < minstr->getNumOperands(); op++)
349349 {
380380
381381 if (constantThatMustBeLoaded || isa(opValue))
382382 { // opValue is a constant that must be explicitly loaded into a reg.
383 TmpInstruction* tmpReg = InsertCodeToLoadConstant(method, opValue, vmInstr,
384 loadConstVec, target);
383 TmpInstruction* tmpReg = InsertCodeToLoadConstant(F, opValue, vmInstr,
384 loadConstVec,
385 target);
385386 minstr->SetMachineOperandVal(op, MachineOperand::MO_VirtualRegister,
386387 tmpReg);
387388 }
403404 {
404405 Value* oldVal = minstr->getImplicitRef(i);
405406 TmpInstruction* tmpReg =
406 InsertCodeToLoadConstant(method, oldVal, vmInstr, loadConstVec, target);
407 InsertCodeToLoadConstant(F, oldVal, vmInstr, loadConstVec, target);
407408 minstr->setImplicitRef(i, tmpReg);
408409 }
409410
11 #include "llvm/CodeGen/RegClass.h"
22 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/Target/TargetMachine.h"
4 #include "llvm/Method.h"
4 #include "llvm/Function.h"
55 #include "llvm/BasicBlock.h"
66 #include "Support/SetOperations.h"
77 #include
88 using std::cerr;
99
10 LiveRangeInfo::LiveRangeInfo(const Method *M, const TargetMachine &tm,
10 LiveRangeInfo::LiveRangeInfo(const Function *F, const TargetMachine &tm,
1111 std::vector &RCL)
12 : Meth(M), TM(tm), RegClassList(RCL), MRI(tm.getRegInfo()) { }
12 : Meth(F), TM(tm), RegClassList(RCL), MRI(tm.getRegInfo()) { }
1313
1414
1515 LiveRangeInfo::~LiveRangeInfo() {
4747 //assert(( L1->getTypeID() == L2->getTypeID()) && "Merge:Different types");
4848
4949 L1->insert(*L2It); // add the var in L2 to L1
50 LiveRangeMap[*L2It] = L1; // now the elements in L2 should map
50 LiveRangeMap[*L2It] = L1; // now the elements in L2 should map
5151 //to L1
5252 }
5353
7272
7373
7474 //---------------------------------------------------------------------------
75 // Method for constructing all live ranges in a method. It creates live
75 // Method for constructing all live ranges in a function. It creates live
7676 // ranges for all values defined in the instruction stream. Also, it
77 // creates live ranges for all incoming arguments of the method.
77 // creates live ranges for all incoming arguments of the function.
7878 //---------------------------------------------------------------------------
7979 void LiveRangeInfo::constructLiveRanges() {
8080
8181 if (DEBUG_RA)
8282 cerr << "Consturcting Live Ranges ...\n";
8383
84 // first find the live ranges for all incoming args of the method since
85 // those LRs start from the start of the method
84 // first find the live ranges for all incoming args of the function since
85 // those LRs start from the start of the function
8686
87 // get the argument list
88 const Method::ArgumentListType& ArgList = Meth->getArgumentList();
89 // get an iterator to arg list
90 Method::ArgumentListType::const_iterator ArgIt = ArgList.begin();
91
92
87 // get the argument list
88 const Function::ArgumentListType& ArgList = Meth->getArgumentList();
89
90 Function::ArgumentListType::const_iterator ArgIt = ArgList.begin();
9391 for( ; ArgIt != ArgList.end() ; ++ArgIt) { // for each argument
9492 LiveRange * ArgRange = new LiveRange(); // creates a new LR and
9593 const Value *Val = (const Value *) *ArgIt;
110108 }
111109 }
112110
113 // Now suggest hardware registers for these method args
111 // Now suggest hardware registers for these function args
114112 MRI.suggestRegs4MethodArgs(Meth, *this);
115
116113
117114
118115 // Now find speical LLVM instructions (CALL, RET) and LRs in machine
119116 // instructions.
120117 //
121 for (Method::const_iterator BBI = Meth->begin(); BBI != Meth->end(); ++BBI) {
118 for (Function::const_iterator BBI = Meth->begin(); BBI != Meth->end(); ++BBI){
122119 // Now find all LRs for machine the instructions. A new LR will be created
123120 // only for defs in the machine instr since, we assume that all Values are
124121 // defined before they are used. However, there can be multiple defs for
206203
207204 } // for all machine instructions in the BB
208205
209 } // for all BBs in method
206 } // for all BBs in function
210207
211208
212209 // Now we have to suggest clors for call and return arg live ranges.
224221 //---------------------------------------------------------------------------
225222 // If some live ranges must be colored with specific hardware registers
226223 // (e.g., for outgoing call args), suggesting of colors for such live
227 // ranges is done using target specific method. Those methods are called
224 // ranges is done using target specific function. Those functions are called
228225 // from this function. The target specific methods must:
229226 // 1) suggest colors for call and return args.
230227 // 2) create new LRs for implicit defs in machine instructions
231228 //---------------------------------------------------------------------------
232229 void LiveRangeInfo::suggestRegs4CallRets()
233230 {
234
235231 CallRetInstrListType::const_iterator It = CallRetInstrList.begin();
236
237232 for( ; It != CallRetInstrList.end(); ++It ) {
238233
239234 const MachineInstr *MInst = *It;
258253
259254
260255 /* Algorithm:
261 for each BB in method
256 for each BB in function
262257 for each machine instruction (inst)
263258 for each definition (def) in inst
264259 for each operand (op) of inst that is a use
272267 //---------------------------------------------------------------------------
273268 void LiveRangeInfo::coalesceLRs()
274269 {
275 if( DEBUG_RA)
270 if(DEBUG_RA)
276271 cerr << "\nCoalscing LRs ...\n";
277272
278 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
279
280 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
273 for(Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
274 BBI != BBE; ++BBI) {
281275
282276 // get the iterator for machine instructions
283277 const MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
1818 #include "llvm/Target/TargetMachine.h"
1919 #include "llvm/Target/MachineFrameInfo.h"
2020 #include "llvm/BasicBlock.h"
21 #include "llvm/Method.h"
21 #include "llvm/Function.h"
2222 #include "llvm/Type.h"
2323 #include
2424 #include
4444 public:
4545 inline RegisterAllocator(TargetMachine &T) : Target(T) {}
4646
47 bool runOnMethod(Method *M) {
47 bool runOnMethod(Function *F) {
4848 if (DEBUG_RA)
49 cerr << "\n******************** Method "<< M->getName()
49 cerr << "\n******************** Method "<< F->getName()
5050 << " ********************\n";
5151
52 PhyRegAlloc PRA(M, Target, &getAnalysis(),
52 PhyRegAlloc PRA(F, Target, &getAnalysis(),
5353 &getAnalysis());
5454 PRA.allocateRegisters();
5555
7474 //----------------------------------------------------------------------------
7575 // Constructor: Init local composite objects and create register classes.
7676 //----------------------------------------------------------------------------
77 PhyRegAlloc::PhyRegAlloc(Method *M,
77 PhyRegAlloc::PhyRegAlloc(Function *F,
7878 const TargetMachine& tm,
7979 MethodLiveVarInfo *Lvi,
8080 cfg::LoopInfo *LDC)
81 : TM(tm), Meth(M),
82 mcInfo(MachineCodeForMethod::get(M)),
83 LVI(Lvi), LRI(M, tm, RegClassList),
84 MRI( tm.getRegInfo() ),
81 : TM(tm), Meth(F),
82 mcInfo(MachineCodeForMethod::get(F)),
83 LVI(Lvi), LRI(F, tm, RegClassList),
84 MRI(tm.getRegInfo()),
8585 NumOfRegClasses(MRI.getNumOfRegClasses()),
8686 LoopDepthCalc(LDC) {
8787
8888 // create each RegisterClass and put in RegClassList
8989 //
9090 for(unsigned int rc=0; rc < NumOfRegClasses; rc++)
91 RegClassList.push_back( new RegClass(M, MRI.getMachineRegClass(rc),
92 &ResColList) );
91 RegClassList.push_back(new RegClass(F, MRI.getMachineRegClass(rc),
92 &ResColList));
9393 }
9494
9595
277277 if(DEBUG_RA) cerr << "Creating interference graphs ...\n";
278278
279279 unsigned BBLoopDepthCost;
280 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
281
282 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
280 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
281 BBI != BBE; ++BBI) {
283282
284283 // find the 10^(loop_depth) of this BB
285284 //
286 BBLoopDepthCost = (unsigned) pow( 10.0, LoopDepthCalc->getLoopDepth(*BBI));
285 BBLoopDepthCost = (unsigned) pow(10.0, LoopDepthCalc->getLoopDepth(*BBI));
287286
288287 // get the iterator for machine instructions
289288 //
345344
346345
347346 } // for all machine instructions in BB
348
349 } // for all BBs in method
350
351
352 // add interferences for method arguments. Since there are no explict
353 // defs in method for args, we have to add them manually
347 } // for all BBs in function
348
349
350 // add interferences for function arguments. Since there are no explict
351 // defs in the function for args, we have to add them manually
354352 //
355353 addInterferencesForArgs();
356354
404402
405403
406404 //----------------------------------------------------------------------------
407 // This method will add interferences for incoming arguments to a method.
405 // This method will add interferences for incoming arguments to a function.
408406 //----------------------------------------------------------------------------
409407 void PhyRegAlloc::addInterferencesForArgs() {
410408 // get the InSet of root BB
411409 const ValueSet &InSet = LVI->getInSetOfBB(Meth->front());
412410
413411 // get the argument list
414 const Method::ArgumentListType& ArgList = Meth->getArgumentList();
412 const Function::ArgumentListType &ArgList = Meth->getArgumentList();
415413
416414 // get an iterator to arg list
417 Method::ArgumentListType::const_iterator ArgIt = ArgList.begin();
415 Function::ArgumentListType::const_iterator ArgIt = ArgList.begin();
418416
419417
420418 for( ; ArgIt != ArgList.end() ; ++ArgIt) { // for each argument
440438 void PhyRegAlloc::updateMachineCode()
441439 {
442440
443 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
444
445 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
446
441 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
442 BBI != BBE; ++BBI) {
447443 // get the iterator for machine instructions
448444 //
449445 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
954950 void PhyRegAlloc::printMachineCode()
955951 {
956952
957 cerr << "\n;************** Method " << Meth->getName()
953 cerr << "\n;************** Function " << Meth->getName()
958954 << " *****************\n";
959955
960 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
961
962 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
963
964 cerr << "\n"; printLabel( *BBI); cerr << ": ";
956 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
957 BBI != BBE; ++BBI) {
958 cerr << "\n"; printLabel(*BBI); cerr << ": ";
965959
966960 // get the iterator for machine instructions
967961 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
969963
970964 // iterate over all the machine instructions in BB
971965 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
972
973966 MachineInstr *const MInst = *MInstIterator;
974
975967
976968 cerr << "\n\t";
977969 cerr << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
978
979
980 //for(MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
981970
982971 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
983
984972 MachineOperand& Op = MInst->getOperand(OpNum);
985973
986974 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
10721060 // Tmp stack poistions are needed by some calls that have spilled args
10731061 // So reset it before we call each such method
10741062 //mcInfo.popAllTempValues(TM);
1075
10761063
10771064
10781065 if (TM.getInstrInfo().isCall(OpCode))
1919 #include "llvm/DerivedTypes.h"
2020 #include "llvm/Annotation.h"
2121 #include "llvm/BasicBlock.h"
22 #include "llvm/Method.h"
22 #include "llvm/Function.h"
2323 #include "llvm/Module.h"
2424 #include "Support/StringExtras.h"
2525 #include "Support/HashExtras.h"
7373 AsmPrinter(std::ostream &os, const TargetMachine &T)
7474 : idTable(0), toAsm(os), Target(T), CurSection(Unknown) {}
7575
76 // (start|end)(Module|Method) - Callback methods to be invoked by subclasses
76 // (start|end)(Module|Function) - Callback methods to be invoked by subclasses
7777 void startModule(Module *M) {
7878 // Create the global id table if it does not already exist
7979 idTable = (GlobalIdTable*) M->getAnnotation(GlobalIdTable::AnnotId);
8282 M->addAnnotation(idTable);
8383 }
8484 }
85 void startMethod(Method *M) {
85 void startFunction(Function *F) {
8686 // Make sure the slot table has information about this method...
87 idTable->Table->incorporateMethod(M);
88 }
89 void endMethod(Method *M) {
90 idTable->Table->purgeMethod(); // Forget all about M.
87 idTable->Table->incorporateMethod(F);
88 }
89 void endFunction(Function *F) {
90 idTable->Table->purgeMethod(); // Forget all about F
9191 }
9292 void endModule() {
9393 }
9696 // Only functions can currently be external. "main" is the only name
9797 // that is visible externally.
9898 bool isExternal(const Value* V) {
99 const Method* meth = dyn_cast(V);
100 return bool(meth != NULL
101 && (meth->isExternal() || meth->getName() == "main"));
99 const Function *F = dyn_cast(V);
100 return F && (F->isExternal() || F->getName() == "main");
102101 }
103102
104103 // enterSection - Use this method to enter a different section of the output
176175 string getID(const Module *M) {
177176 return getID(M, "LLVMModule_");
178177 }
179 string getID(const Method *M) {
180 return getID(M, "LLVMMethod_");
178 string getID(const Function *F) {
179 return getID(F, "LLVMFunction_");
181180 }
182181 string getID(const BasicBlock *BB) {
183182 return getID(BB, "LL", (".L_"+getID(BB->getParent())+"_").c_str());
193192
194193
195194 //===----------------------------------------------------------------------===//
196 // SparcMethodAsmPrinter Code
195 // SparcFunctionAsmPrinter Code
197196 //===----------------------------------------------------------------------===//
198197
199 struct SparcMethodAsmPrinter : public MethodPass, public AsmPrinter {
200 inline SparcMethodAsmPrinter(std::ostream &os, const TargetMachine &t)
198 struct SparcFunctionAsmPrinter : public MethodPass, public AsmPrinter {
199 inline SparcFunctionAsmPrinter(std::ostream &os, const TargetMachine &t)
201200 : AsmPrinter(os, t) {}
202201
203202 virtual bool doInitialization(Module *M) {
205204 return false;
206205 }
207206
208 virtual bool runOnMethod(Method *M) {
209 startMethod(M);
210 emitMethod(M);
211 endMethod(M);
207 virtual bool runOnMethod(Function *F) {
208 startFunction(F);
209 emitFunction(F);
210 endFunction(F);
212211 return false;
213212 }
214213
217216 return false;
218217 }
219218
220 void emitMethod(const Method *M);
219 void emitFunction(const Function *F);
221220 private :
222221 void emitBasicBlock(const BasicBlock *BB);
223222 void emitMachineInst(const MachineInstr *MI);
238237 };
239238
240239 inline bool
241 SparcMethodAsmPrinter::OpIsBranchTargetLabel(const MachineInstr *MI,
242 unsigned int opNum) {
240 SparcFunctionAsmPrinter::OpIsBranchTargetLabel(const MachineInstr *MI,
241 unsigned int opNum) {
243242 switch (MI->getOpCode()) {
244243 case JMPLCALL:
245244 case JMPLRET: return (opNum == 0);
249248
250249
251250 inline bool
252 SparcMethodAsmPrinter::OpIsMemoryAddressBase(const MachineInstr *MI,
253 unsigned int opNum) {
251 SparcFunctionAsmPrinter::OpIsMemoryAddressBase(const MachineInstr *MI,
252 unsigned int opNum) {
254253 if (Target.getInstrInfo().isLoad(MI->getOpCode()))
255254 return (opNum == 0);
256255 else if (Target.getInstrInfo().isStore(MI->getOpCode()))
266265 printOneOperand(Op2);
267266
268267 unsigned int
269 SparcMethodAsmPrinter::printOperands(const MachineInstr *MI,
268 SparcFunctionAsmPrinter::printOperands(const MachineInstr *MI,
270269 unsigned int opNum)
271270 {
272271 const MachineOperand& Op = MI->getOperand(opNum);
292291
293292
294293 void
295 SparcMethodAsmPrinter::printOneOperand(const MachineOperand &op)
294 SparcFunctionAsmPrinter::printOneOperand(const MachineOperand &op)
296295 {
297296 switch (op.getOperandType())
298297 {
318317 toAsm << "\t<*NULL Value*>";
319318 else if (const BasicBlock *BB = dyn_cast(Val))
320319 toAsm << getID(BB);
321 else if (const Method *M = dyn_cast>(Val))
320 else if (const Function *M = dyn_cast>(Val))
322321 toAsm << getID(M);
323322 else if (const GlobalVariable *GV=dyn_cast(Val))
324323 toAsm << getID(GV);
342341
343342
344343 void
345 SparcMethodAsmPrinter::emitMachineInst(const MachineInstr *MI)
344 SparcFunctionAsmPrinter::emitMachineInst(const MachineInstr *MI)
346345 {
347346 unsigned Opcode = MI->getOpCode();
348347
368367 }
369368
370369 void
371 SparcMethodAsmPrinter::emitBasicBlock(const BasicBlock *BB)
370 SparcFunctionAsmPrinter::emitBasicBlock(const BasicBlock *BB)
372371 {
373372 // Emit a label for the basic block
374373 toAsm << getID(BB) << ":\n";
384383 }
385384
386385 void
387 SparcMethodAsmPrinter::emitMethod(const Method *M)
386 SparcFunctionAsmPrinter::emitFunction(const Function *M)
388387 {
389388 string methName = getID(M);
390 toAsm << "!****** Outputing Method: " << methName << " ******\n";
389 toAsm << "!****** Outputing Function: " << methName << " ******\n";
391390 enterSection(AsmPrinter::Text);
392391 toAsm << "\t.align\t4\n\t.global\t" << methName << "\n";
393392 //toAsm << "\t.type\t" << methName << ",#function\n";
394393 toAsm << "\t.type\t" << methName << ", 2\n";
395394 toAsm << methName << ":\n";
396395
397 // Output code for all of the basic blocks in the method...
398 for (Method::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
396 // Output code for all of the basic blocks in the function...
397 for (Function::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
399398 emitBasicBlock(*I);
400399
401400 // Output a .size directive so the debugger knows the extents of the function
403402 << methName << ", .EndOf_"
404403 << methName << "-" << methName << "\n";
405404
406 // Put some spaces between the methods
405 // Put some spaces between the functions
407406 toAsm << "\n\n";
408407 }
409408
410409 } // End anonymous namespace
411410
412411 Pass *UltraSparc::getMethodAsmPrinterPass(PassManager &PM, std::ostream &Out) {
413 return new SparcMethodAsmPrinter(Out, *this);
412 return new SparcFunctionAsmPrinter(Out, *this);
414413 }
415414
416415
418417
419418
420419 //===----------------------------------------------------------------------===//
421 // SparcMethodAsmPrinter Code
420 // SparcFunctionAsmPrinter Code
422421 //===----------------------------------------------------------------------===//
423422
424423 namespace {
1616 #include "llvm/CodeGen/InstrSelectionSupport.h"
1717 #include "llvm/CodeGen/MachineInstr.h"
1818 #include "llvm/CodeGen/MachineCodeForMethod.h"
19 #include "llvm/Method.h"
19 #include "llvm/Function.h"
2020 #include "llvm/ConstantVals.h"
2121 #include "llvm/DerivedTypes.h"
2222
135135 // Any temp. registers (TmpInstruction) created are returned in `tempVec'.
136136 //
137137 void
138 UltraSparcInstrInfo::CreateCodeToLoadConst(Method* method,
139 Value* val,
138 UltraSparcInstrInfo::CreateCodeToLoadConst(Function *F, Value* val,
140139 Instruction* dest,
141 std::vector& minstrVec,
142 std::vector<TmpInstruction*>& tempVec) const
140 std::vector<MachineInstr*>&minstrVec,
141 std::vector& tempVec) const
143142 {
144143 MachineInstr* minstr;
145144
196195
197196 minstr = new MachineInstr(SETX);
198197 minstr->SetMachineOperandVal(0, MachineOperand::MO_PCRelativeDisp, val);
199 minstr->SetMachineOperandVal(1, MachineOperand::MO_VirtualRegister, tmpReg,
198 minstr->SetMachineOperandVal(1, MachineOperand::MO_VirtualRegister,tmpReg,
200199 /*isdef*/ true);
201 minstr->SetMachineOperandVal(2, MachineOperand::MO_VirtualRegister,addrVal);
200 minstr->SetMachineOperandVal(2, MachineOperand::MO_VirtualRegister,
201 addrVal);
202202 minstrVec.push_back(minstr);
203203
204204 if (isa(val))
205205 {
206206 // Make sure constant is emitted to constant pool in assembly code.
207 MachineCodeForMethod& mcinfo = MachineCodeForMethod::get(method);
207 MachineCodeForMethod& mcinfo = MachineCodeForMethod::get(F);
208208 mcinfo.addToConstantPool(cast(val));
209209
210210 // Generate the load instruction
211211 minstr = new MachineInstr(ChooseLoadInstruction(val->getType()));
212212 minstr->SetMachineOperandVal(0, MachineOperand::MO_VirtualRegister,
213213 addrVal);
214 minstr->SetMachineOperandConst(1, MachineOperand::MO_SignExtendedImmed,
214 minstr->SetMachineOperandConst(1,MachineOperand::MO_SignExtendedImmed,
215215 zeroOffset);
216216 minstr->SetMachineOperandVal(2, MachineOperand::MO_VirtualRegister,
217217 dest);
228228 // Any temp. registers (TmpInstruction) created are returned in `tempVec'.
229229 //
230230 void
231 UltraSparcInstrInfo::CreateCodeToCopyIntToFloat(Method* method,
231 UltraSparcInstrInfo::CreateCodeToCopyIntToFloat(Function *F,
232232 Value* val,
233233 Instruction* dest,
234234 std::vector& minstrVec,
237237 {
238238 assert((val->getType()->isIntegral() || val->getType()->isPointerType())
239239 && "Source type must be integral");
240 assert((dest->getType() ==Type::FloatTy || dest->getType() ==Type::DoubleTy)
240 assert((dest->getType() == Type::FloatTy || dest->getType() == Type::DoubleTy)
241241 && "Dest type must be float/double");
242242
243 MachineCodeForMethod& mcinfo = MachineCodeForMethod::get(method);
243 MachineCodeForMethod& mcinfo = MachineCodeForMethod::get(F);
244244 int offset = mcinfo.allocateLocalVar(target, val);
245245
246246 // Store instruction stores `val' to [%fp+offset].
254254 MachineInstr* store = new MachineInstr(ChooseStoreInstruction(tmpType));
255255 store->SetMachineOperandVal(0, MachineOperand::MO_VirtualRegister, val);
256256 store->SetMachineOperandReg(1, target.getRegInfo().getFramePointer());
257 store->SetMachineOperandConst(2, MachineOperand::MO_SignExtendedImmed, offset);
257 store->SetMachineOperandConst(2,MachineOperand::MO_SignExtendedImmed, offset);
258258 minstrVec.push_back(store);
259259
260260 // Load instruction loads [%fp+offset] to `dest'.
272272 // See the previous function for information about return values.
273273 //
274274 void
275 UltraSparcInstrInfo::CreateCodeToCopyFloatToInt(Method* method,
275 UltraSparcInstrInfo::CreateCodeToCopyFloatToInt(Function *F,
276276 Value* val,
277277 Instruction* dest,
278278 std::vector& minstrVec,
284284 assert((dest->getType()->isIntegral() || dest->getType()->isPointerType())
285285 && "Dest type must be integral");
286286
287 MachineCodeForMethod& mcinfo = MachineCodeForMethod::get(method);
287 MachineCodeForMethod& mcinfo = MachineCodeForMethod::get(F);
288288 int offset = mcinfo.allocateLocalVar(target, val);
289289
290290 // Store instruction stores `val' to [%fp+offset].
2323 #include "llvm/iMemory.h"
2424 #include "llvm/iOther.h"
2525 #include "llvm/BasicBlock.h"
26 #include "llvm/Method.h"
26 #include "llvm/Function.h"
2727 #include "llvm/ConstantVals.h"
2828 #include "Support/MathExtras.h"
2929 #include
140140 // Eventually the entire BURG instruction selection should be put
141141 // into a separate class that can hold such information.
142142 // The static cache is not too bad because the memory for these
143 // TmpInstructions will be freed along with the rest of the Method anyway.
143 // TmpInstructions will be freed along with the rest of the Function anyway.
144144 //
145145 static TmpInstruction*
146 GetTmpForCC(Value* boolVal, const Method* method, const Type* ccType)
146 GetTmpForCC(Value* boolVal, const Function *F, const Type* ccType)
147147 {
148148 typedef std::hash_map BoolTmpCache;
149149 static BoolTmpCache boolToTmpCache; // Map boolVal -> TmpInstruction*
150 static const Method* lastMethod = NULL; // Use to flush cache between methods
150 static const Function *lastFunction = 0;// Use to flush cache between funcs
151151
152152 assert(boolVal->getType() == Type::BoolTy && "Weird but ok! Delete assert");
153153
154 if (lastMethod != method)
155 {
156 lastMethod = method;
154 if (lastFunction != F)
155 {
156 lastFunction = F;
157157 boolToTmpCache.clear();
158158 }
159159
808808
809809 // Get the constant offset from SP for dynamically allocated storage
810810 // and create a temporary Value to hold it.
811 assert(result && result->getParent() && "Result value is not part of a method?");
812 Method* method = result->getParent()->getParent();
813 MachineCodeForMethod& mcInfo = MachineCodeForMethod::get(method);
811 assert(result && result->getParent() && "Result value is not part of a fn?");
812 Function *F = result->getParent()->getParent();
813 MachineCodeForMethod& mcInfo = MachineCodeForMethod::get(F);
814814 bool growUp;
815815 ConstantSInt* dynamicAreaOffset =
816816 ConstantSInt::get(Type::IntTy,
852852 vector& getMvec)
853853 {
854854 assert(result && result->getParent() &&
855 "Result value is not part of a method?");
856 Method* method = result->getParent()->getParent();
857 MachineCodeForMethod& mcInfo = MachineCodeForMethod::get(method);
858
859 // Check if the offset would small enough to use as an immediate in load/stores
860 // (check LDX because all load/stores have the same-size immediate field).
861 // If not, put the variable in the dynamically sized area of the frame.
855 "Result value is not part of a function?");
856 Function *F = result->getParent()->getParent();
857 MachineCodeForMethod &mcInfo = MachineCodeForMethod::get(F);
858
859 // Check if the offset would small enough to use as an immediate in
860 // load/stores (check LDX because all load/stores have the same-size immediate
861 // field). If not, put the variable in the dynamically sized area of the
862 // frame.
862863 unsigned int paddedSizeIgnored;
863864 int offsetFromFP = mcInfo.computeOffsetforLocalVar(target, result,
864865 paddedSizeIgnored,
11471148
11481149 void UltraSparcInstrInfo::
11491150 CreateCopyInstructionsByType(const TargetMachine& target,
1150 Method* method,
1151 Function *F,
11511152 Value* src,
11521153 Instruction* dest,
11531154 vector& minstrVec) const
11851186 { // `src' is constant and cannot fit in immed field for the ADD
11861187 // Insert instructions to "load" the constant into a register
11871188 vector tempVec;
1188 target.getInstrInfo().CreateCodeToLoadConst(method, src, dest,
1189 minstrVec,tempVec);
1189 target.getInstrInfo().CreateCodeToLoadConst(F, src, dest,
1190 minstrVec, tempVec);
11901191 for (unsigned i=0; i < tempVec.size(); i++)
11911192 MachineCodeForInstruction::get(dest).addTemp(tempVec[i]);
11921193 }
12341235 // We will assume that local register `l0' is unused since the SAVE
12351236 // instruction must be the first instruction in each procedure.
12361237 //
1237 Method* method = entryBB->getParent();
1238 MachineCodeForMethod& mcInfo = MachineCodeForMethod::get(method);
1238 Function *F = entryBB->getParent();
1239 MachineCodeForMethod& mcInfo = MachineCodeForMethod::get(F);
12391240 unsigned int staticStackSize = mcInfo.getStaticStackSize();
12401241
12411242 if (staticStackSize < (unsigned) frameInfo.getMinStackFrameSize())
1717 #include "llvm/CodeGen/MachineCodeForMethod.h"
1818 #include "llvm/CodeGen/RegisterAllocation.h"
1919 #include "llvm/CodeGen/MachineInstr.h"
20 #include "llvm/Method.h"
20 #include "llvm/Function.h"
2121 #include "llvm/BasicBlock.h"
2222 #include "llvm/PassManager.h"
2323 #include
4444 //---------------------------------------------------------------------------
4545 // class InsertPrologEpilogCode
4646 //
47 // Insert SAVE/RESTORE instructions for the method
48 //
49 // Insert prolog code at the unique method entry point.
50 // Insert epilog code at each method exit point.
51 // InsertPrologEpilog invokes these only if the method is not compiled
52 // with the leaf method optimization.
47 // Insert SAVE/RESTORE instructions for the function
48 //
49 // Insert prolog code at the unique function entry point.
50 // Insert epilog code at each function exit point.
51 // InsertPrologEpilog invokes these only if the function is not compiled
52 // with the leaf function optimization.
5353 //
5454 //---------------------------------------------------------------------------
5555 static MachineInstr* minstrVec[MAX_INSTR_PER_VMINSTR];
5858 TargetMachine &Target;
5959 public:
6060 inline InsertPrologEpilogCode(TargetMachine &T) : Target(T) {}
61 bool runOnMethod(Method *M) {
62 MachineCodeForMethod &mcodeInfo = MachineCodeForMethod::get(M);
61 bool runOnMethod(Function *F) {
62 MachineCodeForMethod &mcodeInfo = MachineCodeForMethod::get(F);
6363 if (!mcodeInfo.isCompiledAsLeafMethod()) {
64 InsertPrologCode(M);
65 InsertEpilogCode(M);
64 InsertPrologCode(F);
65 InsertEpilogCode(F);
6666 }
6767 return false;
6868 }
6969
70 void InsertPrologCode(Method *M);
71 void InsertEpilogCode(Method *M);
72 };
73
74 void InsertPrologEpilogCode::InsertPrologCode(Method* method)
75 {
76 BasicBlock* entryBB = method->getEntryNode();
70 void InsertPrologCode(Function *F);
71 void InsertEpilogCode(Function *F);
72 };
73
74 void InsertPrologEpilogCode::InsertPrologCode(Function *F)
75 {
76 BasicBlock *entryBB = F->getEntryNode();
7777 unsigned N = GetInstructionsForProlog(entryBB, Target, minstrVec);
7878 assert(N <= MAX_INSTR_PER_VMINSTR);
7979 MachineCodeForBasicBlock& bbMvec = entryBB->getMachineInstrVec();
8181 }
8282
8383
84 void InsertPrologEpilogCode::InsertEpilogCode(Method* method)
85 {
86 for (Method::iterator I=method->begin(), E=method->end(); I != E; ++I) {
84 void InsertPrologEpilogCode::InsertEpilogCode(Function *F)
85 {
86 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
8787 Instruction *TermInst = (Instruction*)(*I)->getTerminator();
8888 if (TermInst->getOpcode() == Instruction::Ret)
8989 {
208208 // Native code generation for a specified target.
209209 //===---------------------------------------------------------------------===//
210210
211 class ConstructMachineCodeForMethod : public MethodPass {
211 class ConstructMachineCodeForFunction : public MethodPass {
212212 TargetMachine &Target;
213213 public:
214 inline ConstructMachineCodeForMethod(TargetMachine &T) : Target(T) {}
215 bool runOnMethod(Method *M) {
216 MachineCodeForMethod::construct(M, Target);
214 inline ConstructMachineCodeForFunction(TargetMachine &T) : Target(T) {}
215 bool runOnMethod(Function *F) {
216 MachineCodeForMethod::construct(F, Target);
217217 return false;
218218 }
219219 };
222222 TargetMachine &Target;
223223 public:
224224 inline InstructionSelection(TargetMachine &T) : Target(T) {}
225 bool runOnMethod(Method *M) {
226 if (SelectInstructionsForMethod(M, Target))
227 cerr << "Instr selection failed for method " << M->getName() << "\n";
228 return false;
229 }
230 };
231
232 struct FreeMachineCodeForMethod : public MethodPass {
225 bool runOnMethod(Function *F) {
226 if (SelectInstructionsForMethod(F, Target)) {
227 cerr << "Instr selection failed for function " << F->getName() << "\n";
228 abort();
229 }
230 return false;
231 }
232 };
233
234 struct FreeMachineCodeForFunction : public MethodPass {
233235 static void freeMachineCode(Instruction *I) {
234236 MachineCodeForInstruction::destroy(I);
235237 }
236238
237 bool runOnMethod(Method *M) {
238 for (Method::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI)
239 for (BasicBlock::iterator I = (*MI)->begin(), E = (*MI)->end();
239 bool runOnMethod(Function *F) {
240 for (Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
241 for (BasicBlock::iterator I = (*FI)->begin(), E = (*FI)->end();
240242 I != E; ++I)
241243 MachineCodeForInstruction::get(*I).dropAllReferences();
242244
243 for (Method::iterator MI = M->begin(), ME = M->end(); MI != ME; ++MI)
244 for (BasicBlock::iterator I = (*MI)->begin(), E = (*MI)->end();
245 for (Method::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
246 for (BasicBlock::iterator I = (*FI)->begin(), E = (*FI)->end();
245247 I != E; ++I)
246248 freeMachineCode(*I);
247249
255257 // process for the ultra sparc.
256258 //
257259 void UltraSparc::addPassesToEmitAssembly(PassManager &PM, std::ostream &Out) {
258 // Construct and initialize the MachineCodeForMethod object for this method.
259 PM.add(new ConstructMachineCodeForMethod(*this));
260 // Construct and initialize the MachineCodeForMethod object for this fn.
261 PM.add(new ConstructMachineCodeForFunction(*this));
260262
261263 PM.add(new InstructionSelection(*this));
262264
272274 PM.add(new InsertPrologEpilogCode(*this));
273275
274276 // Output assembly language to the .s file. Assembly emission is split into
275 // two parts: Method output and Global value output. This is because method
276 // output is pipelined with all of the rest of code generation stuff,
277 // allowing machine code representations for methods to be free'd after the
278 // method has been emitted.
277 // two parts: Function output and Global value output. This is because
278 // function output is pipelined with all of the rest of code generation stuff,
279 // allowing machine code representations for functions to be free'd after the
280 // function has been emitted.
279281 //
280282 PM.add(getMethodAsmPrinterPass(PM, Out));
281 PM.add(new FreeMachineCodeForMethod()); // Free stuff no longer needed
282
283 // Emit Module level assembly after all of the methods have been processed.
283 PM.add(new FreeMachineCodeForFunction()); // Free stuff no longer needed
284
285 // Emit Module level assembly after all of the functions have been processed.
284286 PM.add(getModuleAsmPrinterPass(PM, Out));
285287
286288 // Emit bytecode to the sparc assembly file into its special section next
66 //===----------------------------------------------------------------------===//
77
88 #include "TransformInternals.h"
9 #include "llvm/Method.h"
9 #include "llvm/Function.h"
1010 #include "llvm/iOther.h"
1111 #include "llvm/iPHINode.h"
1212 #include "llvm/iMemory.h"
827827 assert (OI != I->op_end() && "Not using value!");
828828 unsigned OpNum = OI - I->op_begin();
829829
830 // Are we trying to change the method pointer value to a new type?
830 // Are we trying to change the function pointer value to a new type?
831831 if (OpNum == 0) {
832832 PointerType *PTy = dyn_cast(Ty);
833833 if (PTy == 0) return false; // Can't convert to a non-pointer type...
834834 FunctionType *MTy = dyn_cast(PTy->getElementType());
835 if (MTy == 0) return false; // Can't convert to a non ptr to method...
836
837 // Perform sanity checks to make sure that new method type has the
835 if (MTy == 0) return false; // Can't convert to a non ptr to function...
836
837 // Perform sanity checks to make sure that new function type has the
838838 // correct number of arguments...
839839 //
840 unsigned NumArgs = I->getNumOperands()-1; // Don't include method ptr
840 unsigned NumArgs = I->getNumOperands()-1; // Don't include function ptr
841841
842842 // Cannot convert to a type that requires more fixed arguments than
843843 // the call provides...
844844 //
845845 if (NumArgs < MTy->getParamTypes().size()) return false;
846846
847 // Unless this is a vararg method type, we cannot provide more arguments
847 // Unless this is a vararg function type, we cannot provide more arguments
848848 // than are desired...
849849 //
850850 if (!MTy->isVarArg() && NumArgs > MTy->getParamTypes().size())
851851 return false;
852852
853 // Okay, at this point, we know that the call and the method type match
853 // Okay, at this point, we know that the call and the function type match
854854 // number of arguments. Now we see if we can convert the arguments
855855 // themselves. Note that we do not require operands to be convertable,
856856 // we can insert casts if they are convertible but not compatible. The
857 // reason for this is that we prefer to have resolved methods but casted
857 // reason for this is that we prefer to have resolved functions but casted
858858 // arguments if possible.
859859 //
860860 const FunctionType::ParamTypes &PTs = MTy->getParamTypes();
877877 return false; // It's not in the varargs section...
878878
879879 // If we get this far, we know the value is in the varargs section of the
880 // method! We can convert if we don't reinterpret the value...
880 // function! We can convert if we don't reinterpret the value...
881881 //
882882 return Ty->isLosslesslyConvertableTo(V->getType());
883883 }
10971097 Value *Meth = I->getOperand(0);
10981098 std::vector Params(I->op_begin()+1, I->op_end());
10991099
1100 if (Meth == OldVal) { // Changing the method pointer?
1100 if (Meth == OldVal) { // Changing the function pointer?
11011101 PointerType *NewPTy = cast(NewVal->getType());
11021102 FunctionType *NewTy = cast(NewPTy->getElementType());
11031103 const FunctionType::ParamTypes &PTs = NewTy->getParamTypes();
11061106 // operands if needbe. Note that we do not require operands to be
11071107 // convertable, we can insert casts if they are convertible but not
11081108 // compatible. The reason for this is that we prefer to have resolved
1109 // methods but casted arguments if possible.
1109 // functions but casted arguments if possible.
11101110 //
11111111 BasicBlock::iterator It = find(BIL.begin(), BIL.end(), I);
11121112
99 #include "llvm/iPHINode.h"
1010 #include "llvm/iOther.h"
1111 #include "llvm/BasicBlock.h"
12 #include "llvm/Method.h"
12 #include "llvm/Function.h"
1313 #include "llvm/Pass.h"
1414 #include
1515 #include
4141 // Entry point for normalizing constant args in PHIs
4242 //---------------------------------------------------------------------------
4343
44 static bool doHoistPHIConstants(Method *M) {
44 static bool doHoistPHIConstants(Function *M) {
4545 CachedCopyMap Cache;
4646 bool Changed = false;
4747
48 for (Method::iterator BI = M->begin(), BE = M->end(); BI != BE; ++BI) {
48 for (Function::iterator BI = M->begin(), BE = M->end(); BI != BE; ++BI) {
4949 std::vector phis; // normalizing invalidates BB iterator
5050
5151 for (BasicBlock::iterator II = (*BI)->begin(); II != (*BI)->end(); ++II) {
7474
7575 namespace {
7676 struct HoistPHIConstants : public MethodPass {
77 virtual bool runOnMethod(Method *M) { return doHoistPHIConstants(M); }
77 virtual bool runOnMethod(Function *F) { return doHoistPHIConstants(F); }
7878 };
7979 }
8080
88 // and elminate duplicates when it is initialized.
99 //
1010 // The DynamicConstantMerge method is a superset of the ConstantMerge algorithm
11 // that checks for each method to see if constants have been added to the
11 // that checks for each function to see if constants have been added to the
1212 // constant pool since it was last run... if so, it processes them.
1313 //
1414 //===----------------------------------------------------------------------===//
1616 #include "llvm/Transforms/ConstantMerge.h"
1717 #include "llvm/GlobalVariable.h"
1818 #include "llvm/Module.h"
19 #include "llvm/Method.h"
19 #include "llvm/Function.h"
2020 #include "llvm/Pass.h"
2121
2222 // mergeDuplicateConstants - Workhorse for the pass. This eliminates duplicate
7272 return ::mergeDuplicateConstants(M, LastConstantSeen, Constants);
7373 }
7474
75 bool runOnMethod(Method*) { return false; }
75 bool runOnMethod(Function *) { return false; }
7676
7777 // doFinalization - Clean up internal state for this module
7878 //
8484 };
8585
8686 struct DynamicConstantMerge : public ConstantMerge {
87 // doPerMethodWork - Check to see if any globals have been added to the
87 // runOnMethod - Check to see if any globals have been added to the
8888 // global list for the module. If so, eliminate them.
8989 //
90 bool runOnMethod(Method *M) {
91 return ::mergeDuplicateConstants(M->getParent(), LastConstantSeen,
90 bool runOnMethod(Function *F) {
91 return ::mergeDuplicateConstants(F->getParent(), LastConstantSeen,
9292 Constants);
9393 }
9494 };
None //===-- GlobalDCE.cpp - DCE unreachable internal methods ---------*- C++ -*--=//
0 //===-- GlobalDCE.cpp - DCE unreachable internal functions ----------------===//
11 //
22 // This transform is designed to eliminate unreachable internal globals
33 //
66 #include "llvm/Transforms/IPO/GlobalDCE.h"
77 #include "llvm/Analysis/CallGraph.h"
88 #include "llvm/Module.h"
9 #include "llvm/Method.h"
9 #include "llvm/Function.h"
1010 #include "llvm/Pass.h"
1111 #include "Support/DepthFirstIterator.h"
1212 #include
1313
14 static bool RemoveUnreachableMethods(Module *M, CallGraph &CallGraph) {
15 // Calculate which methods are reachable from the external methods in the call
16 // graph.
14 static bool RemoveUnreachableFunctions(Module *M, CallGraph &CallGraph) {
15 // Calculate which functions are reachable from the external functions in the
16 // call graph.
1717 //
1818 std::set ReachableNodes(df_begin(&CallGraph),
1919 df_end(&CallGraph));
2020
21 // Loop over the methods in the module twice. The first time is used to drop
22 // references that methods have to each other before they are deleted. The
23 // second pass removes the methods that need to be removed.
21 // Loop over the functions in the module twice. The first time is used to
22 // drop references that functions have to each other before they are deleted.
23 // The second pass removes the functions that need to be removed.
2424 //
25 std::vector MethodsToDelete; // Track unused methods
25 std::vector FunctionsToDelete; // Track unused functions
2626 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
2727 CallGraphNode *N = CallGraph[*I];
2828 if (!ReachableNodes.count(N)) { // Not reachable??
2929 (*I)->dropAllReferences();
3030 N->removeAllCalledMethods();
31 MethodsToDelete.push_back(N);
31 FunctionsToDelete.push_back(N);
3232 }
3333 }
3434
35 // Nothing to do if no unreachable methods have been found...
36 if (MethodsToDelete.empty()) return false;
35 // Nothing to do if no unreachable functions have been found...
36 if (FunctionsToDelete.empty()) return false;
3737
38 // Unreachables methods have been found and should have no references to them,
39 // delete them now.
38 // Unreachables functions have been found and should have no references to
39 // them, delete them now.
4040 //
41 for (std::vector::iterator I = MethodsToDelete.begin(),
42 E = MethodsToDelete.end(); I != E; ++I)
41 for (std::vector::iterator I = FunctionsToDelete.begin(),
42 E = FunctionsToDelete.end(); I != E; ++I)
4343 delete CallGraph.removeMethodFromModule(*I);
4444
4545 return true;
5151 // the specified callgraph to reflect the changes.
5252 //
5353 bool run(Module *M) {
54 return RemoveUnreachableMethods(M, getAnalysis());
54 return RemoveUnreachableFunctions(M, getAnalysis());
5555 }
5656
5757 // getAnalysisUsageInfo - This function works on the call graph of a module.
None //===- MethodInlining.cpp - Code to perform method inlining ---------------===//
1 //
2 // This file implements inlining of methods.
0 //===- FunctionInlining.cpp - Code to perform function inlining -----------===//
1 //
2 // This file implements inlining of functions.
33 //
44 // Specifically, this:
5 // * Exports functionality to inline any method call
6 // * Inlines methods that consist of a single basic block
7 // * Is able to inline ANY method call
8 // . Has a smart heuristic for when to inline a method
5 // * Exports functionality to inline any function call
6 // * Inlines functions that consist of a single basic block
7 // * Is able to inline ANY function call
8 // . Has a smart heuristic for when to inline a function
99 //
1010 // Notice that:
1111 // * This pass opens up a lot of opportunities for constant propogation. It
1212 // is a good idea to to run a constant propogation pass, then a DCE pass
1313 // sometime after running this pass.
1414 //
15 // TODO: Currently this throws away all of the symbol names in the method being
16 // inlined. This shouldn't happen.
17 //
1815 //===----------------------------------------------------------------------===//
1916
2017 #include "llvm/Transforms/MethodInlining.h"
2118 #include "llvm/Module.h"
22 #include "llvm/Method.h"
19 #include "llvm/Function.h"
2320 #include "llvm/Pass.h"
2421 #include "llvm/iTerminators.h"
2522 #include "llvm/iPHINode.h"
5249 }
5350 }
5451
55 // InlineMethod - This function forcibly inlines the called method into the
52 // InlineMethod - This function forcibly inlines the called function into the
5653 // basic block of the caller. This returns false if it is not possible to
5754 // inline this call. The program is still in a well defined state if this
5855 // occurs though.
6057 // Note that this only does one level of inlining. For example, if the
6158 // instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
6259 // exists in the instruction stream. Similiarly this will inline a recursive
63 // method by one level.
60 // function by one level.
6461 //
6562 bool InlineMethod(BasicBlock::iterator CIIt) {
6663 assert(isa(*CIIt) && "InlineMethod only works on CallInst nodes!");
6764 assert((*CIIt)->getParent() && "Instruction not embedded in basic block!");
68 assert((*CIIt)->getParent()->getParent() && "Instruction not in method!");
65 assert((*CIIt)->getParent()->getParent() && "Instruction not in function!");
6966
7067 CallInst *CI = cast(*CIIt);
7168 const Function *CalledMeth = CI->getCalledFunction();
72 if (CalledMeth == 0 || // Can't inline external method or indirect call!
69 if (CalledMeth == 0 || // Can't inline external function or indirect call!
7370 CalledMeth->isExternal()) return false;
7471
7572 //cerr << "Inlining " << CalledMeth->getName() << " into "
8986
9087 // If we have a return value generated by this call, convert it into a PHI
9188 // node that gets values from each of the old RET instructions in the original
92 // method.
89 // function.
9390 //
9491 PHINode *PHI = 0;
9592 if (CalledMeth->getReturnType() != Type::VoidTy) {
106103 CI->replaceAllUsesWith(PHI);
107104 }
108105
109 // Keep a mapping between the original method's values and the new duplicated
110 // code's values. This includes all of: Method arguments, instruction values,
111 // constant pool entries, and basic blocks.
106 // Keep a mapping between the original function's values and the new
107 // duplicated code's values. This includes all of: Function arguments,
108 // instruction values, constant pool entries, and basic blocks.
112109 //
113110 std::map ValueMap;
114111
115 // Add the method arguments to the mapping: (start counting at 1 to skip the
116 // method reference itself)
117 //
118 Method::ArgumentListType::const_iterator PTI =
112 // Add the function arguments to the mapping: (start counting at 1 to skip the
113 // function reference itself)
114 //
115 Function::ArgumentListType::const_iterator PTI =
119116 CalledMeth->getArgumentList().begin();
120117 for (unsigned a = 1, E = CI->getNumOperands(); a != E; ++a, ++PTI)
121118 ValueMap[*PTI] = CI->getOperand(a);
122119
123120 ValueMap[NewBB] = NewBB; // Returns get converted to reference NewBB
124121
125 // Loop over all of the basic blocks in the method, inlining them as
126 // appropriate. Keep track of the first basic block of the method...
127 //
128 for (Method::const_iterator BI = CalledMeth->begin();
122 // Loop over all of the basic blocks in the function, inlining them as
123 // appropriate. Keep track of the first basic block of the function...
124 //
125 for (Function::const_iterator BI = CalledMeth->begin();
129126 BI != CalledMeth->end(); ++BI) {
130127 const BasicBlock *BB = *BI;
131128 assert(BB->getTerminator() && "BasicBlock doesn't have terminator!?!?");
160157 if (PHI) { // The PHI node should include this value!
161158 assert(RI->getReturnValue() && "Ret should have value!");
162159 assert(RI->getReturnValue()->getType() == PHI->getType() &&
163 "Ret value not consistent in method!");
160 "Ret value not consistent in function!");
164161 PHI->addIncoming((Value*)RI->getReturnValue(), cast(BB));
165162 }
166163
173170 break;
174171
175172 default:
176 cerr << "MethodInlining: Don't know how to handle terminator: " << TI;
173 cerr << "FunctionInlining: Don't know how to handle terminator: " << TI;
177174 abort();
178175 }
179176 }
180177
181178
182 // Loop over all of the instructions in the method, fixing up operand
179 // Loop over all of the instructions in the function, fixing up operand
183180 // references as we go. This uses ValueMap to do all the hard work.
184181 //
185 for (Method::const_iterator BI = CalledMeth->begin();
182 for (Function::const_iterator BI = CalledMeth->begin();
186183 BI != CalledMeth->end(); ++BI) {
187184 const BasicBlock *BB = *BI;
188185 BasicBlock *NBB = (BasicBlock*)ValueMap[BB];
196193 if (PHI) RemapInstruction(PHI, ValueMap); // Fix the PHI node also...
197194
198195 // Change the branch that used to go to NewBB to branch to the first basic
199 // block of the inlined method.
196 // block of the inlined function.
200197 //
201198 TerminatorInst *Br = OrigBB->getTerminator();
202199 assert(Br && Br->getOpcode() == Instruction::Br &&
219216 return InlineMethod(CallIt);
220217 }
221218
222 static inline bool ShouldInlineMethod(const CallInst *CI, const Method *M) {
219 static inline bool ShouldInlineFunction(const CallInst *CI, const Function *F) {
223220 assert(CI->getParent() && CI->getParent()->getParent() &&
224221 "Call not embedded into a method!");
225222
226223 // Don't inline a recursive call.
227 if (CI->getParent()->getParent() == M) return false;
224 if (CI->getParent()->getParent() == F) return false;
228225
229226 // Don't inline something too big. This is a really crappy heuristic
230 if (M->size() > 3) return false;
227 if (F->size() > 3) return false;
231228
232229 // Don't inline into something too big. This is a **really** crappy heuristic
233230 if (CI->getParent()->getParent()->size() > 10) return false;
237234 }
238235
239236
240 static inline bool DoMethodInlining(BasicBlock *BB) {
237 static inline bool DoFunctionInlining(BasicBlock *BB) {
241238 for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
242239 if (CallInst *CI = dyn_cast(*I)) {
243 // Check to see if we should inline this method
244 Method *F = CI->getCalledFunction();
245 if (F && ShouldInlineMethod(CI, F))
240 // Check to see if we should inline this function
241 Function *F = CI->getCalledFunction();
242 if (F && ShouldInlineFunction(CI, F))
246243 return InlineMethod(I);
247244 }
248245 }
249246 return false;
250247 }
251248
252 // doMethodInlining - Use a heuristic based approach to inline methods that
249 // doFunctionInlining - Use a heuristic based approach to inline functions that
253250 // seem to look good.
254251 //
255 static bool doMethodInlining(Method *M) {
252 static bool doFunctionInlining(Function *F) {
256253 bool Changed = false;
257254
258255 // Loop through now and inline instructions a basic block at a time...
259 for (Method::iterator I = M->begin(); I != M->end(); )
260 if (DoMethodInlining(*I)) {
256 for (Function::iterator I = F->begin(); I != F->end(); )
257 if (DoFunctionInlining(*I)) {
261258 Changed = true;
262259 // Iterator is now invalidated by new basic blocks inserted
263 I = M->begin();
260 I = F->begin();
264261 } else {
265262 ++I;
266263 }
269266 }
270267
271268 namespace {
272 struct MethodInlining : public MethodPass {
273 virtual bool runOnMethod(Method *M) {
274 return doMethodInlining(M);
269 struct FunctionInlining : public MethodPass {
270 virtual bool runOnMethod(Function *F) {
271 return doFunctionInlining(F);
275272 }
276273 };
277274 }
278275
279 Pass *createMethodInliningPass() { return new MethodInlining(); }
276 Pass *createMethodInliningPass() { return new FunctionInlining(); }
0 //===-- ProfilePaths.cpp - interface to insert instrumentation ---*- C++ -*--=//
11 //
22 // This inserts intrumentation for counting
3 // execution of paths though a given method
4 // Its implemented as a "Method" Pass, and called using opt
3 // execution of paths though a given function
4 // Its implemented as a "Function" Pass, and called using opt
55 //
66 // This pass is implemented by using algorithms similar to <