Get rid of the abort in PhyRegAlloc::finishSavingState().
[oota-llvm.git] / lib / Target / SparcV9 / RegAlloc / PhyRegAlloc.cpp
1 //===-- PhyRegAlloc.cpp ---------------------------------------------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 // 
10 // Traditional graph-coloring global register allocator currently used
11 // by the SPARC back-end.
12 //
13 // NOTE: This register allocator has some special support
14 // for the Reoptimizer, such as not saving some registers on calls to
15 // the first-level instrumentation function.
16 //
17 // NOTE 2: This register allocator can save its state in a global
18 // variable in the module it's working on. This feature is not
19 // thread-safe; if you have doubts, leave it turned off.
20 // 
21 //===----------------------------------------------------------------------===//
22
23 #include "AllocInfo.h"
24 #include "IGNode.h"
25 #include "PhyRegAlloc.h"
26 #include "RegAllocCommon.h"
27 #include "RegClass.h"
28 #include "../LiveVar/FunctionLiveVarInfo.h"
29 #include "llvm/Constants.h"
30 #include "llvm/DerivedTypes.h"
31 #include "llvm/iOther.h"
32 #include "llvm/Module.h"
33 #include "llvm/Type.h"
34 #include "llvm/Analysis/LoopInfo.h"
35 #include "llvm/CodeGen/InstrSelection.h"
36 #include "llvm/CodeGen/MachineCodeForInstruction.h"
37 #include "llvm/CodeGen/MachineFunction.h"
38 #include "llvm/CodeGen/MachineFunctionInfo.h"
39 #include "llvm/CodeGen/MachineInstr.h"
40 #include "llvm/CodeGen/MachineInstrBuilder.h"
41 #include "../MachineInstrAnnot.h"
42 #include "llvm/CodeGen/Passes.h"
43 #include "llvm/Support/InstIterator.h"
44 #include "llvm/Target/TargetInstrInfo.h"
45 #include "Support/CommandLine.h"
46 #include "Support/SetOperations.h"
47 #include "Support/STLExtras.h"
48 #include <cmath>
49
50 namespace llvm {
51
52 RegAllocDebugLevel_t DEBUG_RA;
53
54 static cl::opt<RegAllocDebugLevel_t, true>
55 DRA_opt("dregalloc", cl::Hidden, cl::location(DEBUG_RA),
56         cl::desc("enable register allocation debugging information"),
57         cl::values(
58   clEnumValN(RA_DEBUG_None   ,     "n", "disable debug output"),
59   clEnumValN(RA_DEBUG_Results,     "y", "debug output for allocation results"),
60   clEnumValN(RA_DEBUG_Coloring,    "c", "debug output for graph coloring step"),
61   clEnumValN(RA_DEBUG_Interference,"ig","debug output for interference graphs"),
62   clEnumValN(RA_DEBUG_LiveRanges , "lr","debug output for live ranges"),
63   clEnumValN(RA_DEBUG_Verbose,     "v", "extra debug output"),
64                    0));
65
66 /// The reoptimizer wants to be able to grovel through the register
67 /// allocator's state after it has done its job. This is a hack.
68 ///
69 PhyRegAlloc::SavedStateMapTy ExportedFnAllocState;
70 bool SaveRegAllocState = false;
71 bool SaveStateToModule = true;
72 static cl::opt<bool, true>
73 SaveRegAllocStateOpt("save-ra-state", cl::Hidden,
74                   cl::location (SaveRegAllocState),
75                   cl::init(false),
76                   cl::desc("write reg. allocator state into module"));
77
78 FunctionPass *getRegisterAllocator(TargetMachine &T) {
79   return new PhyRegAlloc (T);
80 }
81
82 void PhyRegAlloc::getAnalysisUsage(AnalysisUsage &AU) const {
83   AU.addRequired<LoopInfo> ();
84   AU.addRequired<FunctionLiveVarInfo> ();
85 }
86
87
88 /// Initialize interference graphs (one in each reg class) and IGNodeLists
89 /// (one in each IG). The actual nodes will be pushed later.
90 ///
91 void PhyRegAlloc::createIGNodeListsAndIGs() {
92   if (DEBUG_RA >= RA_DEBUG_LiveRanges) std::cerr << "Creating LR lists ...\n";
93
94   LiveRangeMapType::const_iterator HMI = LRI->getLiveRangeMap()->begin();   
95   LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap()->end();   
96
97   for (; HMI != HMIEnd ; ++HMI ) {
98     if (HMI->first) { 
99       LiveRange *L = HMI->second;   // get the LiveRange
100       if (!L) { 
101         if (DEBUG_RA)
102           std::cerr << "\n**** ?!?WARNING: NULL LIVE RANGE FOUND FOR: "
103                << RAV(HMI->first) << "****\n";
104         continue;
105       }
106
107       // if the Value * is not null, and LR is not yet written to the IGNodeList
108       if (!(L->getUserIGNode())  ) {  
109         RegClass *const RC =           // RegClass of first value in the LR
110           RegClassList[ L->getRegClassID() ];
111         RC->addLRToIG(L);              // add this LR to an IG
112       }
113     }
114   }
115     
116   // init RegClassList
117   for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)  
118     RegClassList[rc]->createInterferenceGraph();
119
120   if (DEBUG_RA >= RA_DEBUG_LiveRanges) std::cerr << "LRLists Created!\n";
121 }
122
123
124 /// Add all interferences for a given instruction.  Interference occurs only
125 /// if the LR of Def (Inst or Arg) is of the same reg class as that of live
126 /// var. The live var passed to this function is the LVset AFTER the
127 /// instruction.
128 ///
129 void PhyRegAlloc::addInterference(const Value *Def, const ValueSet *LVSet,
130                                   bool isCallInst) {
131   ValueSet::const_iterator LIt = LVSet->begin();
132
133   // get the live range of instruction
134   const LiveRange *const LROfDef = LRI->getLiveRangeForValue( Def );   
135
136   IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
137   assert( IGNodeOfDef );
138
139   RegClass *const RCOfDef = LROfDef->getRegClass(); 
140
141   // for each live var in live variable set
142   for ( ; LIt != LVSet->end(); ++LIt) {
143
144     if (DEBUG_RA >= RA_DEBUG_Verbose)
145       std::cerr << "< Def=" << RAV(Def) << ", Lvar=" << RAV(*LIt) << "> ";
146
147     //  get the live range corresponding to live var
148     LiveRange *LROfVar = LRI->getLiveRangeForValue(*LIt);
149
150     // LROfVar can be null if it is a const since a const 
151     // doesn't have a dominating def - see Assumptions above
152     if (LROfVar)
153       if (LROfDef != LROfVar)                  // do not set interf for same LR
154         if (RCOfDef == LROfVar->getRegClass()) // 2 reg classes are the same
155           RCOfDef->setInterference( LROfDef, LROfVar);  
156   }
157 }
158
159
160 /// For a call instruction, this method sets the CallInterference flag in 
161 /// the LR of each variable live in the Live Variable Set live after the
162 /// call instruction (except the return value of the call instruction - since
163 /// the return value does not interfere with that call itself).
164 ///
165 void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst, 
166                                        const ValueSet *LVSetAft) {
167   if (DEBUG_RA >= RA_DEBUG_Interference)
168     std::cerr << "\n For call inst: " << *MInst;
169
170   // for each live var in live variable set after machine inst
171   for (ValueSet::const_iterator LIt = LVSetAft->begin(), LEnd = LVSetAft->end();
172        LIt != LEnd; ++LIt) {
173
174     //  get the live range corresponding to live var
175     LiveRange *const LR = LRI->getLiveRangeForValue(*LIt ); 
176
177     // LR can be null if it is a const since a const 
178     // doesn't have a dominating def - see Assumptions above
179     if (LR ) {  
180       if (DEBUG_RA >= RA_DEBUG_Interference) {
181         std::cerr << "\n\tLR after Call: ";
182         printSet(*LR);
183       }
184       LR->setCallInterference();
185       if (DEBUG_RA >= RA_DEBUG_Interference) {
186         std::cerr << "\n  ++After adding call interference for LR: " ;
187         printSet(*LR);
188       }
189     }
190
191   }
192
193   // Now find the LR of the return value of the call
194   // We do this because, we look at the LV set *after* the instruction
195   // to determine, which LRs must be saved across calls. The return value
196   // of the call is live in this set - but it does not interfere with call
197   // (i.e., we can allocate a volatile register to the return value)
198   CallArgsDescriptor* argDesc = CallArgsDescriptor::get(MInst);
199   
200   if (const Value *RetVal = argDesc->getReturnValue()) {
201     LiveRange *RetValLR = LRI->getLiveRangeForValue( RetVal );
202     assert( RetValLR && "No LR for RetValue of call");
203     RetValLR->clearCallInterference();
204   }
205
206   // If the CALL is an indirect call, find the LR of the function pointer.
207   // That has a call interference because it conflicts with outgoing args.
208   if (const Value *AddrVal = argDesc->getIndirectFuncPtr()) {
209     LiveRange *AddrValLR = LRI->getLiveRangeForValue( AddrVal );
210     assert( AddrValLR && "No LR for indirect addr val of call");
211     AddrValLR->setCallInterference();
212   }
213 }
214
215
216 /// Create interferences in the IG of each RegClass, and calculate the spill
217 /// cost of each Live Range (it is done in this method to save another pass
218 /// over the code).
219 ///
220 void PhyRegAlloc::buildInterferenceGraphs() {
221   if (DEBUG_RA >= RA_DEBUG_Interference)
222     std::cerr << "Creating interference graphs ...\n";
223
224   unsigned BBLoopDepthCost;
225   for (MachineFunction::iterator BBI = MF->begin(), BBE = MF->end();
226        BBI != BBE; ++BBI) {
227     const MachineBasicBlock &MBB = *BBI;
228     const BasicBlock *BB = MBB.getBasicBlock();
229
230     // find the 10^(loop_depth) of this BB 
231     BBLoopDepthCost = (unsigned)pow(10.0, LoopDepthCalc->getLoopDepth(BB));
232
233     // get the iterator for machine instructions
234     MachineBasicBlock::const_iterator MII = MBB.begin();
235
236     // iterate over all the machine instructions in BB
237     for ( ; MII != MBB.end(); ++MII) {
238       const MachineInstr *MInst = MII;
239
240       // get the LV set after the instruction
241       const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, BB);
242       bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpcode());
243
244       if (isCallInst) {
245         // set the isCallInterference flag of each live range which extends
246         // across this call instruction. This information is used by graph
247         // coloring algorithm to avoid allocating volatile colors to live ranges
248         // that span across calls (since they have to be saved/restored)
249         setCallInterferences(MInst, &LVSetAI);
250       }
251
252       // iterate over all MI operands to find defs
253       for (MachineInstr::const_val_op_iterator OpI = MInst->begin(),
254              OpE = MInst->end(); OpI != OpE; ++OpI) {
255         if (OpI.isDef()) // create a new LR since def
256           addInterference(*OpI, &LVSetAI, isCallInst);
257
258         // Calculate the spill cost of each live range
259         LiveRange *LR = LRI->getLiveRangeForValue(*OpI);
260         if (LR) LR->addSpillCost(BBLoopDepthCost);
261       } 
262
263       // Mark all operands of pseudo-instructions as interfering with one
264       // another.  This must be done because pseudo-instructions may be
265       // expanded to multiple instructions by the assembler, so all the
266       // operands must get distinct registers.
267       if (TM.getInstrInfo().isPseudoInstr(MInst->getOpcode()))
268         addInterf4PseudoInstr(MInst);
269
270       // Also add interference for any implicit definitions in a machine
271       // instr (currently, only calls have this).
272       unsigned NumOfImpRefs =  MInst->getNumImplicitRefs();
273       for (unsigned z=0; z < NumOfImpRefs; z++) 
274         if (MInst->getImplicitOp(z).isDef())
275           addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
276
277     } // for all machine instructions in BB
278   } // for all BBs in function
279
280   // add interferences for function arguments. Since there are no explicit 
281   // defs in the function for args, we have to add them manually
282   addInterferencesForArgs();          
283
284   if (DEBUG_RA >= RA_DEBUG_Interference)
285     std::cerr << "Interference graphs calculated!\n";
286 }
287
288
289 /// Mark all operands of the given MachineInstr as interfering with one
290 /// another.
291 ///
292 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
293   bool setInterf = false;
294
295   // iterate over MI operands to find defs
296   for (MachineInstr::const_val_op_iterator It1 = MInst->begin(),
297          ItE = MInst->end(); It1 != ItE; ++It1) {
298     const LiveRange *LROfOp1 = LRI->getLiveRangeForValue(*It1); 
299     assert((LROfOp1 || It1.isDef()) && "No LR for Def in PSEUDO insruction");
300
301     MachineInstr::const_val_op_iterator It2 = It1;
302     for (++It2; It2 != ItE; ++It2) {
303       const LiveRange *LROfOp2 = LRI->getLiveRangeForValue(*It2); 
304
305       if (LROfOp2) {
306         RegClass *RCOfOp1 = LROfOp1->getRegClass(); 
307         RegClass *RCOfOp2 = LROfOp2->getRegClass(); 
308  
309         if (RCOfOp1 == RCOfOp2 ){ 
310           RCOfOp1->setInterference( LROfOp1, LROfOp2 );  
311           setInterf = true;
312         }
313       } // if Op2 has a LR
314     } // for all other defs in machine instr
315   } // for all operands in an instruction
316
317   if (!setInterf && MInst->getNumOperands() > 2) {
318     std::cerr << "\nInterf not set for any operand in pseudo instr:\n";
319     std::cerr << *MInst;
320     assert(0 && "Interf not set for pseudo instr with > 2 operands" );
321   }
322
323
324
325 /// Add interferences for incoming arguments to a function.
326 ///
327 void PhyRegAlloc::addInterferencesForArgs() {
328   // get the InSet of root BB
329   const ValueSet &InSet = LVI->getInSetOfBB(&Fn->front());  
330
331   for (Function::const_aiterator AI = Fn->abegin(); AI != Fn->aend(); ++AI) {
332     // add interferences between args and LVars at start 
333     addInterference(AI, &InSet, false);
334     
335     if (DEBUG_RA >= RA_DEBUG_Interference)
336       std::cerr << " - %% adding interference for argument " << RAV(AI) << "\n";
337   }
338 }
339
340
341 /// The following are utility functions used solely by updateMachineCode and
342 /// the functions that it calls. They should probably be folded back into
343 /// updateMachineCode at some point.
344 ///
345
346 // used by: updateMachineCode (1 time), PrependInstructions (1 time)
347 inline void InsertBefore(MachineInstr* newMI, MachineBasicBlock& MBB,
348                          MachineBasicBlock::iterator& MII) {
349   MII = MBB.insert(MII, newMI);
350   ++MII;
351 }
352
353 // used by: AppendInstructions (1 time)
354 inline void InsertAfter(MachineInstr* newMI, MachineBasicBlock& MBB,
355                         MachineBasicBlock::iterator& MII) {
356   ++MII;    // insert before the next instruction
357   MII = MBB.insert(MII, newMI);
358 }
359
360 // used by: updateMachineCode (2 times)
361 inline void PrependInstructions(std::vector<MachineInstr *> &IBef,
362                                 MachineBasicBlock& MBB,
363                                 MachineBasicBlock::iterator& MII,
364                                 const std::string& msg) {
365   if (!IBef.empty()) {
366       MachineInstr* OrigMI = MII;
367       std::vector<MachineInstr *>::iterator AdIt; 
368       for (AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt) {
369           if (DEBUG_RA) {
370             if (OrigMI) std::cerr << "For MInst:\n  " << *OrigMI;
371             std::cerr << msg << "PREPENDed instr:\n  " << **AdIt << "\n";
372           }
373           InsertBefore(*AdIt, MBB, MII);
374         }
375     }
376 }
377
378 // used by: updateMachineCode (1 time)
379 inline void AppendInstructions(std::vector<MachineInstr *> &IAft,
380                                MachineBasicBlock& MBB,
381                                MachineBasicBlock::iterator& MII,
382                                const std::string& msg) {
383   if (!IAft.empty()) {
384       MachineInstr* OrigMI = MII;
385       std::vector<MachineInstr *>::iterator AdIt; 
386       for ( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt ) {
387           if (DEBUG_RA) {
388             if (OrigMI) std::cerr << "For MInst:\n  " << *OrigMI;
389             std::cerr << msg << "APPENDed instr:\n  "  << **AdIt << "\n";
390           }
391           InsertAfter(*AdIt, MBB, MII);
392         }
393     }
394 }
395
396 /// Set the registers for operands in the given MachineInstr, if a register was
397 /// successfully allocated.  Return true if any of its operands has been marked
398 /// for spill.
399 ///
400 bool PhyRegAlloc::markAllocatedRegs(MachineInstr* MInst)
401 {
402   bool instrNeedsSpills = false;
403
404   // First, set the registers for operands in the machine instruction
405   // if a register was successfully allocated.  Do this first because we
406   // will need to know which registers are already used by this instr'n.
407   for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
408       MachineOperand& Op = MInst->getOperand(OpNum);
409       if (Op.getType() ==  MachineOperand::MO_VirtualRegister || 
410           Op.getType() ==  MachineOperand::MO_CCRegister) {
411           const Value *const Val =  Op.getVRegValue();
412           if (const LiveRange* LR = LRI->getLiveRangeForValue(Val)) {
413             // Remember if any operand needs spilling
414             instrNeedsSpills |= LR->isMarkedForSpill();
415
416             // An operand may have a color whether or not it needs spilling
417             if (LR->hasColor())
418               MInst->SetRegForOperand(OpNum,
419                           MRI.getUnifiedRegNum(LR->getRegClassID(),
420                                                LR->getColor()));
421           }
422         }
423     } // for each operand
424
425   return instrNeedsSpills;
426 }
427
428 /// Mark allocated registers (using markAllocatedRegs()) on the instruction
429 /// that MII points to. Then, if it's a call instruction, insert caller-saving
430 /// code before and after it. Finally, insert spill code before and after it,
431 /// using insertCode4SpilledLR().
432 ///
433 void PhyRegAlloc::updateInstruction(MachineBasicBlock::iterator& MII,
434                                     MachineBasicBlock &MBB) {
435   MachineInstr* MInst = MII;
436   unsigned Opcode = MInst->getOpcode();
437
438   // Reset tmp stack positions so they can be reused for each machine instr.
439   MF->getInfo()->popAllTempValues();  
440
441   // Mark the operands for which regs have been allocated.
442   bool instrNeedsSpills = markAllocatedRegs(MII);
443
444 #ifndef NDEBUG
445   // Mark that the operands have been updated.  Later,
446   // setRelRegsUsedByThisInst() is called to find registers used by each
447   // MachineInst, and it should not be used for an instruction until
448   // this is done.  This flag just serves as a sanity check.
449   OperandsColoredMap[MInst] = true;
450 #endif
451
452   // Now insert caller-saving code before/after the call.
453   // Do this before inserting spill code since some registers must be
454   // used by save/restore and spill code should not use those registers.
455   if (TM.getInstrInfo().isCall(Opcode)) {
456     AddedInstrns &AI = AddedInstrMap[MInst];
457     insertCallerSavingCode(AI.InstrnsBefore, AI.InstrnsAfter, MInst,
458                            MBB.getBasicBlock());
459   }
460
461   // Now insert spill code for remaining operands not allocated to
462   // registers.  This must be done even for call return instructions
463   // since those are not handled by the special code above.
464   if (instrNeedsSpills)
465     for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
466         MachineOperand& Op = MInst->getOperand(OpNum);
467         if (Op.getType() ==  MachineOperand::MO_VirtualRegister || 
468             Op.getType() ==  MachineOperand::MO_CCRegister) {
469             const Value* Val = Op.getVRegValue();
470             if (const LiveRange *LR = LRI->getLiveRangeForValue(Val))
471               if (LR->isMarkedForSpill())
472                 insertCode4SpilledLR(LR, MII, MBB, OpNum);
473           }
474       } // for each operand
475 }
476
477 /// Iterate over all the MachineBasicBlocks in the current function and set
478 /// the allocated registers for each instruction (using updateInstruction()),
479 /// after register allocation is complete. Then move code out of delay slots.
480 ///
481 void PhyRegAlloc::updateMachineCode()
482 {
483   // Insert any instructions needed at method entry
484   MachineBasicBlock::iterator MII = MF->front().begin();
485   PrependInstructions(AddedInstrAtEntry.InstrnsBefore, MF->front(), MII,
486                       "At function entry: \n");
487   assert(AddedInstrAtEntry.InstrnsAfter.empty() &&
488          "InstrsAfter should be unnecessary since we are just inserting at "
489          "the function entry point here.");
490   
491   for (MachineFunction::iterator BBI = MF->begin(), BBE = MF->end();
492        BBI != BBE; ++BBI) {
493     MachineBasicBlock &MBB = *BBI;
494
495     // Iterate over all machine instructions in BB and mark operands with
496     // their assigned registers or insert spill code, as appropriate. 
497     // Also, fix operands of call/return instructions.
498     for (MachineBasicBlock::iterator MII = MBB.begin(); MII != MBB.end(); ++MII)
499       if (! TM.getInstrInfo().isDummyPhiInstr(MII->getOpcode()))
500         updateInstruction(MII, MBB);
501
502     // Now, move code out of delay slots of branches and returns if needed.
503     // (Also, move "after" code from calls to the last delay slot instruction.)
504     // Moving code out of delay slots is needed in 2 situations:
505     // (1) If this is a branch and it needs instructions inserted after it,
506     //     move any existing instructions out of the delay slot so that the
507     //     instructions can go into the delay slot.  This only supports the
508     //     case that #instrsAfter <= #delay slots.
509     // 
510     // (2) If any instruction in the delay slot needs
511     //     instructions inserted, move it out of the delay slot and before the
512     //     branch because putting code before or after it would be VERY BAD!
513     // 
514     // If the annul bit of the branch is set, neither of these is legal!
515     // If so, we need to handle spill differently but annulling is not yet used.
516     for (MachineBasicBlock::iterator MII = MBB.begin(); MII != MBB.end(); ++MII)
517       if (unsigned delaySlots =
518           TM.getInstrInfo().getNumDelaySlots(MII->getOpcode())) { 
519           MachineBasicBlock::iterator DelaySlotMI = next(MII);
520           assert(DelaySlotMI != MBB.end() && "no instruction for delay slot");
521           
522           // Check the 2 conditions above:
523           // (1) Does a branch need instructions added after it?
524           // (2) O/w does delay slot instr. need instrns before or after?
525           bool isBranch = (TM.getInstrInfo().isBranch(MII->getOpcode()) ||
526                            TM.getInstrInfo().isReturn(MII->getOpcode()));
527           bool cond1 = (isBranch &&
528                         AddedInstrMap.count(MII) &&
529                         AddedInstrMap[MII].InstrnsAfter.size() > 0);
530           bool cond2 = (AddedInstrMap.count(DelaySlotMI) &&
531                         (AddedInstrMap[DelaySlotMI].InstrnsBefore.size() > 0 ||
532                          AddedInstrMap[DelaySlotMI].InstrnsAfter.size()  > 0));
533
534           if (cond1 || cond2) {
535               assert(delaySlots==1 &&
536                      "InsertBefore does not yet handle >1 delay slots!");
537
538               if (DEBUG_RA) {
539                 std::cerr << "\nRegAlloc: Moved instr. with added code: "
540                      << *DelaySlotMI
541                      << "           out of delay slots of instr: " << *MII;
542               }
543
544               // move instruction before branch
545               MBB.insert(MII, MBB.remove(DelaySlotMI));
546
547               // On cond1 we are done (we already moved the
548               // instruction out of the delay slot). On cond2 we need
549               // to insert a nop in place of the moved instruction
550               if (cond2) {
551                 MBB.insert(MII, BuildMI(TM.getInstrInfo().getNOPOpCode(),1));
552               }
553             }
554           else {
555             // For non-branch instr with delay slots (probably a call), move
556             // InstrAfter to the instr. in the last delay slot.
557             MachineBasicBlock::iterator tmp = next(MII, delaySlots);
558             move2DelayedInstr(MII, tmp);
559           }
560       }
561
562     // Finally iterate over all instructions in BB and insert before/after
563     for (MachineBasicBlock::iterator MII=MBB.begin(); MII != MBB.end(); ++MII) {
564       MachineInstr *MInst = MII; 
565
566       // do not process Phis
567       if (TM.getInstrInfo().isDummyPhiInstr(MInst->getOpcode()))
568         continue;
569
570       // if there are any added instructions...
571       if (AddedInstrMap.count(MInst)) {
572         AddedInstrns &CallAI = AddedInstrMap[MInst];
573
574 #ifndef NDEBUG
575         bool isBranch = (TM.getInstrInfo().isBranch(MInst->getOpcode()) ||
576                          TM.getInstrInfo().isReturn(MInst->getOpcode()));
577         assert((!isBranch ||
578                 AddedInstrMap[MInst].InstrnsAfter.size() <=
579                 TM.getInstrInfo().getNumDelaySlots(MInst->getOpcode())) &&
580                "Cannot put more than #delaySlots instrns after "
581                "branch or return! Need to handle temps differently.");
582 #endif
583
584 #ifndef NDEBUG
585         // Temporary sanity checking code to detect whether the same machine
586         // instruction is ever inserted twice before/after a call.
587         // I suspect this is happening but am not sure. --Vikram, 7/1/03.
588         std::set<const MachineInstr*> instrsSeen;
589         for (int i = 0, N = CallAI.InstrnsBefore.size(); i < N; ++i) {
590           assert(instrsSeen.count(CallAI.InstrnsBefore[i]) == 0 &&
591                  "Duplicate machine instruction in InstrnsBefore!");
592           instrsSeen.insert(CallAI.InstrnsBefore[i]);
593         } 
594         for (int i = 0, N = CallAI.InstrnsAfter.size(); i < N; ++i) {
595           assert(instrsSeen.count(CallAI.InstrnsAfter[i]) == 0 &&
596                  "Duplicate machine instruction in InstrnsBefore/After!");
597           instrsSeen.insert(CallAI.InstrnsAfter[i]);
598         } 
599 #endif
600
601         // Now add the instructions before/after this MI.
602         // We do this here to ensure that spill for an instruction is inserted
603         // as close as possible to an instruction (see above insertCode4Spill)
604         if (! CallAI.InstrnsBefore.empty())
605           PrependInstructions(CallAI.InstrnsBefore, MBB, MII,"");
606         
607         if (! CallAI.InstrnsAfter.empty())
608           AppendInstructions(CallAI.InstrnsAfter, MBB, MII,"");
609
610       } // if there are any added instructions
611     } // for each machine instruction
612   }
613 }
614
615
616 /// Insert spill code for AN operand whose LR was spilled.  May be called
617 /// repeatedly for a single MachineInstr if it has many spilled operands. On
618 /// each call, it finds a register which is not live at that instruction and
619 /// also which is not used by other spilled operands of the same
620 /// instruction. Then it uses this register temporarily to accommodate the
621 /// spilled value.
622 ///
623 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR, 
624                                        MachineBasicBlock::iterator& MII,
625                                        MachineBasicBlock &MBB,
626                                        const unsigned OpNum) {
627   MachineInstr *MInst = MII;
628   const BasicBlock *BB = MBB.getBasicBlock();
629
630   assert((! TM.getInstrInfo().isCall(MInst->getOpcode()) || OpNum == 0) &&
631          "Outgoing arg of a call must be handled elsewhere (func arg ok)");
632   assert(! TM.getInstrInfo().isReturn(MInst->getOpcode()) &&
633          "Return value of a ret must be handled elsewhere");
634
635   MachineOperand& Op = MInst->getOperand(OpNum);
636   bool isDef =  Op.isDef();
637   bool isUse = Op.isUse();
638   unsigned RegType = MRI.getRegTypeForLR(LR);
639   int SpillOff = LR->getSpillOffFromFP();
640   RegClass *RC = LR->getRegClass();
641
642   // Get the live-variable set to find registers free before this instr.
643   const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
644
645 #ifndef NDEBUG
646   // If this instr. is in the delay slot of a branch or return, we need to
647   // include all live variables before that branch or return -- we don't want to
648   // trample those!  Verify that the set is included in the LV set before MInst.
649   if (MII != MBB.begin()) {
650     MachineBasicBlock::iterator PredMI = prior(MII);
651     if (unsigned DS = TM.getInstrInfo().getNumDelaySlots(PredMI->getOpcode()))
652       assert(set_difference(LVI->getLiveVarSetBeforeMInst(PredMI), LVSetBef)
653              .empty() && "Live-var set before branch should be included in "
654              "live-var set of each delay slot instruction!");
655   }
656 #endif
657
658   MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
659   
660   std::vector<MachineInstr*> MIBef, MIAft;
661   std::vector<MachineInstr*> AdIMid;
662   
663   // Choose a register to hold the spilled value, if one was not preallocated.
664   // This may insert code before and after MInst to free up the value.  If so,
665   // this code should be first/last in the spill sequence before/after MInst.
666   int TmpRegU=(LR->hasColor()
667                ? MRI.getUnifiedRegNum(LR->getRegClassID(),LR->getColor())
668                : getUsableUniRegAtMI(RegType, &LVSetBef, MInst, MIBef,MIAft));
669   
670   // Set the operand first so that it this register does not get used
671   // as a scratch register for later calls to getUsableUniRegAtMI below
672   MInst->SetRegForOperand(OpNum, TmpRegU);
673   
674   // get the added instructions for this instruction
675   AddedInstrns &AI = AddedInstrMap[MInst];
676
677   // We may need a scratch register to copy the spilled value to/from memory.
678   // This may itself have to insert code to free up a scratch register.  
679   // Any such code should go before (after) the spill code for a load (store).
680   // The scratch reg is not marked as used because it is only used
681   // for the copy and not used across MInst.
682   int scratchRegType = -1;
683   int scratchReg = -1;
684   if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType)) {
685       scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
686                                        MInst, MIBef, MIAft);
687       assert(scratchReg != MRI.getInvalidRegNum());
688     }
689   
690   if (isUse) {
691     // for a USE, we have to load the value of LR from stack to a TmpReg
692     // and use the TmpReg as one operand of instruction
693     
694     // actual loading instruction(s)
695     MRI.cpMem2RegMI(AdIMid, MRI.getFramePointer(), SpillOff, TmpRegU,
696                     RegType, scratchReg);
697     
698     // the actual load should be after the instructions to free up TmpRegU
699     MIBef.insert(MIBef.end(), AdIMid.begin(), AdIMid.end());
700     AdIMid.clear();
701   }
702   
703   if (isDef) {   // if this is a Def
704     // for a DEF, we have to store the value produced by this instruction
705     // on the stack position allocated for this LR
706     
707     // actual storing instruction(s)
708     MRI.cpReg2MemMI(AdIMid, TmpRegU, MRI.getFramePointer(), SpillOff,
709                     RegType, scratchReg);
710     
711     MIAft.insert(MIAft.begin(), AdIMid.begin(), AdIMid.end());
712   }  // if !DEF
713   
714   // Finally, insert the entire spill code sequences before/after MInst
715   AI.InstrnsBefore.insert(AI.InstrnsBefore.end(), MIBef.begin(), MIBef.end());
716   AI.InstrnsAfter.insert(AI.InstrnsAfter.begin(), MIAft.begin(), MIAft.end());
717   
718   if (DEBUG_RA) {
719     std::cerr << "\nFor Inst:\n  " << *MInst;
720     std::cerr << "SPILLED LR# " << LR->getUserIGNode()->getIndex();
721     std::cerr << "; added Instructions:";
722     for_each(MIBef.begin(), MIBef.end(), std::mem_fun(&MachineInstr::dump));
723     for_each(MIAft.begin(), MIAft.end(), std::mem_fun(&MachineInstr::dump));
724   }
725 }
726
727
728 /// Insert caller saving/restoring instructions before/after a call machine
729 /// instruction (before or after any other instructions that were inserted for
730 /// the call).
731 ///
732 void
733 PhyRegAlloc::insertCallerSavingCode(std::vector<MachineInstr*> &instrnsBefore,
734                                     std::vector<MachineInstr*> &instrnsAfter,
735                                     MachineInstr *CallMI, 
736                                     const BasicBlock *BB) {
737   assert(TM.getInstrInfo().isCall(CallMI->getOpcode()));
738   
739   // hash set to record which registers were saved/restored
740   hash_set<unsigned> PushedRegSet;
741
742   CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
743   
744   // if the call is to a instrumentation function, do not insert save and
745   // restore instructions the instrumentation function takes care of save
746   // restore for volatile regs.
747   //
748   // FIXME: this should be made general, not specific to the reoptimizer!
749   const Function *Callee = argDesc->getCallInst()->getCalledFunction();
750   bool isLLVMFirstTrigger = Callee && Callee->getName() == "llvm_first_trigger";
751
752   // Now check if the call has a return value (using argDesc) and if so,
753   // find the LR of the TmpInstruction representing the return value register.
754   // (using the last or second-last *implicit operand* of the call MI).
755   // Insert it to to the PushedRegSet since we must not save that register
756   // and restore it after the call.
757   // We do this because, we look at the LV set *after* the instruction
758   // to determine, which LRs must be saved across calls. The return value
759   // of the call is live in this set - but we must not save/restore it.
760   if (const Value *origRetVal = argDesc->getReturnValue()) {
761     unsigned retValRefNum = (CallMI->getNumImplicitRefs() -
762                              (argDesc->getIndirectFuncPtr()? 1 : 2));
763     const TmpInstruction* tmpRetVal =
764       cast<TmpInstruction>(CallMI->getImplicitRef(retValRefNum));
765     assert(tmpRetVal->getOperand(0) == origRetVal &&
766            tmpRetVal->getType() == origRetVal->getType() &&
767            "Wrong implicit ref?");
768     LiveRange *RetValLR = LRI->getLiveRangeForValue(tmpRetVal);
769     assert(RetValLR && "No LR for RetValue of call");
770
771     if (! RetValLR->isMarkedForSpill())
772       PushedRegSet.insert(MRI.getUnifiedRegNum(RetValLR->getRegClassID(),
773                                                RetValLR->getColor()));
774   }
775
776   const ValueSet &LVSetAft =  LVI->getLiveVarSetAfterMInst(CallMI, BB);
777   ValueSet::const_iterator LIt = LVSetAft.begin();
778
779   // for each live var in live variable set after machine inst
780   for( ; LIt != LVSetAft.end(); ++LIt) {
781     // get the live range corresponding to live var
782     LiveRange *const LR = LRI->getLiveRangeForValue(*LIt);
783
784     // LR can be null if it is a const since a const 
785     // doesn't have a dominating def - see Assumptions above
786     if (LR) {  
787       if (! LR->isMarkedForSpill()) {
788         assert(LR->hasColor() && "LR is neither spilled nor colored?");
789         unsigned RCID = LR->getRegClassID();
790         unsigned Color = LR->getColor();
791
792         if (MRI.isRegVolatile(RCID, Color) ) {
793           // if this is a call to the first-level reoptimizer
794           // instrumentation entry point, and the register is not
795           // modified by call, don't save and restore it.
796           if (isLLVMFirstTrigger && !MRI.modifiedByCall(RCID, Color))
797             continue;
798
799           // if the value is in both LV sets (i.e., live before and after 
800           // the call machine instruction)
801           unsigned Reg = MRI.getUnifiedRegNum(RCID, Color);
802           
803           // if we haven't already pushed this register...
804           if( PushedRegSet.find(Reg) == PushedRegSet.end() ) {
805             unsigned RegType = MRI.getRegTypeForLR(LR);
806
807             // Now get two instructions - to push on stack and pop from stack
808             // and add them to InstrnsBefore and InstrnsAfter of the
809             // call instruction
810             int StackOff =
811               MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
812             
813             //---- Insert code for pushing the reg on stack ----------
814             
815             std::vector<MachineInstr*> AdIBef, AdIAft;
816             
817             // We may need a scratch register to copy the saved value
818             // to/from memory.  This may itself have to insert code to
819             // free up a scratch register.  Any such code should go before
820             // the save code.  The scratch register, if any, is by default
821             // temporary and not "used" by the instruction unless the
822             // copy code itself decides to keep the value in the scratch reg.
823             int scratchRegType = -1;
824             int scratchReg = -1;
825             if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
826               { // Find a register not live in the LVSet before CallMI
827                 const ValueSet &LVSetBef =
828                   LVI->getLiveVarSetBeforeMInst(CallMI, BB);
829                 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
830                                                  CallMI, AdIBef, AdIAft);
831                 assert(scratchReg != MRI.getInvalidRegNum());
832               }
833             
834             if (AdIBef.size() > 0)
835               instrnsBefore.insert(instrnsBefore.end(),
836                                    AdIBef.begin(), AdIBef.end());
837             
838             MRI.cpReg2MemMI(instrnsBefore, Reg, MRI.getFramePointer(),
839                             StackOff, RegType, scratchReg);
840             
841             if (AdIAft.size() > 0)
842               instrnsBefore.insert(instrnsBefore.end(),
843                                    AdIAft.begin(), AdIAft.end());
844             
845             //---- Insert code for popping the reg from the stack ----------
846             AdIBef.clear();
847             AdIAft.clear();
848             
849             // We may need a scratch register to copy the saved value
850             // from memory.  This may itself have to insert code to
851             // free up a scratch register.  Any such code should go
852             // after the save code.  As above, scratch is not marked "used".
853             scratchRegType = -1;
854             scratchReg = -1;
855             if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
856               { // Find a register not live in the LVSet after CallMI
857                 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetAft,
858                                                  CallMI, AdIBef, AdIAft);
859                 assert(scratchReg != MRI.getInvalidRegNum());
860               }
861             
862             if (AdIBef.size() > 0)
863               instrnsAfter.insert(instrnsAfter.end(),
864                                   AdIBef.begin(), AdIBef.end());
865             
866             MRI.cpMem2RegMI(instrnsAfter, MRI.getFramePointer(), StackOff,
867                             Reg, RegType, scratchReg);
868             
869             if (AdIAft.size() > 0)
870               instrnsAfter.insert(instrnsAfter.end(),
871                                   AdIAft.begin(), AdIAft.end());
872             
873             PushedRegSet.insert(Reg);
874             
875             if(DEBUG_RA) {
876               std::cerr << "\nFor call inst:" << *CallMI;
877               std::cerr << " -inserted caller saving instrs: Before:\n\t ";
878               for_each(instrnsBefore.begin(), instrnsBefore.end(),
879                        std::mem_fun(&MachineInstr::dump));
880               std::cerr << " -and After:\n\t ";
881               for_each(instrnsAfter.begin(), instrnsAfter.end(),
882                        std::mem_fun(&MachineInstr::dump));
883             }       
884           } // if not already pushed
885         } // if LR has a volatile color
886       } // if LR has color
887     } // if there is a LR for Var
888   } // for each value in the LV set after instruction
889 }
890
891
892 /// Returns the unified register number of a temporary register to be used
893 /// BEFORE MInst. If no register is available, it will pick one and modify
894 /// MIBef and MIAft to contain instructions used to free up this returned
895 /// register.
896 ///
897 int PhyRegAlloc::getUsableUniRegAtMI(const int RegType,
898                                      const ValueSet *LVSetBef,
899                                      MachineInstr *MInst, 
900                                      std::vector<MachineInstr*>& MIBef,
901                                      std::vector<MachineInstr*>& MIAft) {
902   RegClass* RC = getRegClassByID(MRI.getRegClassIDOfRegType(RegType));
903   
904   int RegU = getUnusedUniRegAtMI(RC, RegType, MInst, LVSetBef);
905   
906   if (RegU == -1) {
907     // we couldn't find an unused register. Generate code to free up a reg by
908     // saving it on stack and restoring after the instruction
909     
910     int TmpOff = MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
911     
912     RegU = getUniRegNotUsedByThisInst(RC, RegType, MInst);
913     
914     // Check if we need a scratch register to copy this register to memory.
915     int scratchRegType = -1;
916     if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType)) {
917         int scratchReg = getUsableUniRegAtMI(scratchRegType, LVSetBef,
918                                              MInst, MIBef, MIAft);
919         assert(scratchReg != MRI.getInvalidRegNum());
920         
921         // We may as well hold the value in the scratch register instead
922         // of copying it to memory and back.  But we have to mark the
923         // register as used by this instruction, so it does not get used
924         // as a scratch reg. by another operand or anyone else.
925         ScratchRegsUsed.insert(std::make_pair(MInst, scratchReg));
926         MRI.cpReg2RegMI(MIBef, RegU, scratchReg, RegType);
927         MRI.cpReg2RegMI(MIAft, scratchReg, RegU, RegType);
928     } else { // the register can be copied directly to/from memory so do it.
929         MRI.cpReg2MemMI(MIBef, RegU, MRI.getFramePointer(), TmpOff, RegType);
930         MRI.cpMem2RegMI(MIAft, MRI.getFramePointer(), TmpOff, RegU, RegType);
931     }
932   }
933   
934   return RegU;
935 }
936
937
938 /// Returns the register-class register number of a new unused register that
939 /// can be used to accommodate a temporary value.  May be called repeatedly
940 /// for a single MachineInstr.  On each call, it finds a register which is not
941 /// live at that instruction and which is not used by any spilled operands of
942 /// that instruction.
943 ///
944 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC, const int RegType,
945                                      const MachineInstr *MInst,
946                                      const ValueSet* LVSetBef) {
947   RC->clearColorsUsed();     // Reset array
948
949   if (LVSetBef == NULL) {
950       LVSetBef = &LVI->getLiveVarSetBeforeMInst(MInst);
951       assert(LVSetBef != NULL && "Unable to get live-var set before MInst?");
952   }
953
954   ValueSet::const_iterator LIt = LVSetBef->begin();
955
956   // for each live var in live variable set after machine inst
957   for ( ; LIt != LVSetBef->end(); ++LIt) {
958     // Get the live range corresponding to live var, and its RegClass
959     LiveRange *const LRofLV = LRI->getLiveRangeForValue(*LIt );    
960
961     // LR can be null if it is a const since a const 
962     // doesn't have a dominating def - see Assumptions above
963     if (LRofLV && LRofLV->getRegClass() == RC && LRofLV->hasColor())
964       RC->markColorsUsed(LRofLV->getColor(),
965                          MRI.getRegTypeForLR(LRofLV), RegType);
966   }
967
968   // It is possible that one operand of this MInst was already spilled
969   // and it received some register temporarily. If that's the case,
970   // it is recorded in machine operand. We must skip such registers.
971   setRelRegsUsedByThisInst(RC, RegType, MInst);
972
973   int unusedReg = RC->getUnusedColor(RegType);   // find first unused color
974   if (unusedReg >= 0)
975     return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
976
977   return -1;
978 }
979
980
981 /// Return the unified register number of a register in class RC which is not
982 /// used by any operands of MInst.
983 ///
984 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC, 
985                                             const int RegType,
986                                             const MachineInstr *MInst) {
987   RC->clearColorsUsed();
988
989   setRelRegsUsedByThisInst(RC, RegType, MInst);
990
991   // find the first unused color
992   int unusedReg = RC->getUnusedColor(RegType);
993   assert(unusedReg >= 0 &&
994          "FATAL: No free register could be found in reg class!!");
995
996   return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
997 }
998
999
1000 /// Modify the IsColorUsedArr of register class RC, by setting the bits
1001 /// corresponding to register RegNo. This is a helper method of
1002 /// setRelRegsUsedByThisInst().
1003 ///
1004 static void markRegisterUsed(int RegNo, RegClass *RC, int RegType,
1005                              const TargetRegInfo &TRI) {
1006   unsigned classId = 0;
1007   int classRegNum = TRI.getClassRegNum(RegNo, classId);
1008   if (RC->getID() == classId)
1009     RC->markColorsUsed(classRegNum, RegType, RegType);
1010 }
1011
1012 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC, int RegType,
1013                                            const MachineInstr *MI) {
1014   assert(OperandsColoredMap[MI] == true &&
1015          "Illegal to call setRelRegsUsedByThisInst() until colored operands "
1016          "are marked for an instruction.");
1017
1018   // Add the registers already marked as used by the instruction. Both
1019   // explicit and implicit operands are set.
1020   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
1021     if (MI->getOperand(i).hasAllocatedReg())
1022       markRegisterUsed(MI->getOperand(i).getReg(), RC, RegType,MRI);
1023
1024   for (unsigned i = 0, e = MI->getNumImplicitRefs(); i != e; ++i)
1025     if (MI->getImplicitOp(i).hasAllocatedReg())
1026       markRegisterUsed(MI->getImplicitOp(i).getReg(), RC, RegType,MRI);
1027
1028   // Add all of the scratch registers that are used to save values across the
1029   // instruction (e.g., for saving state register values).
1030   std::pair<ScratchRegsUsedTy::iterator, ScratchRegsUsedTy::iterator>
1031     IR = ScratchRegsUsed.equal_range(MI);
1032   for (ScratchRegsUsedTy::iterator I = IR.first; I != IR.second; ++I)
1033     markRegisterUsed(I->second, RC, RegType, MRI);
1034
1035   // If there are implicit references, mark their allocated regs as well
1036   for (unsigned z=0; z < MI->getNumImplicitRefs(); z++)
1037     if (const LiveRange*
1038         LRofImpRef = LRI->getLiveRangeForValue(MI->getImplicitRef(z)))    
1039       if (LRofImpRef->hasColor())
1040         // this implicit reference is in a LR that received a color
1041         RC->markColorsUsed(LRofImpRef->getColor(),
1042                            MRI.getRegTypeForLR(LRofImpRef), RegType);
1043 }
1044
1045
1046 /// If there are delay slots for an instruction, the instructions added after
1047 /// it must really go after the delayed instruction(s).  So, we Move the
1048 /// InstrAfter of that instruction to the corresponding delayed instruction
1049 /// using the following method.
1050 ///
1051 void PhyRegAlloc::move2DelayedInstr(const MachineInstr *OrigMI,
1052                                     const MachineInstr *DelayedMI)
1053 {
1054   // "added after" instructions of the original instr
1055   std::vector<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI].InstrnsAfter;
1056
1057   if (DEBUG_RA && OrigAft.size() > 0) {
1058     std::cerr << "\nRegAlloc: Moved InstrnsAfter for: " << *OrigMI;
1059     std::cerr << "         to last delay slot instrn: " << *DelayedMI;
1060   }
1061
1062   // "added after" instructions of the delayed instr
1063   std::vector<MachineInstr *> &DelayedAft=AddedInstrMap[DelayedMI].InstrnsAfter;
1064
1065   // go thru all the "added after instructions" of the original instruction
1066   // and append them to the "added after instructions" of the delayed
1067   // instructions
1068   DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
1069
1070   // empty the "added after instructions" of the original instruction
1071   OrigAft.clear();
1072 }
1073
1074
1075 void PhyRegAlloc::colorIncomingArgs()
1076 {
1077   MRI.colorMethodArgs(Fn, *LRI, AddedInstrAtEntry.InstrnsBefore,
1078                       AddedInstrAtEntry.InstrnsAfter);
1079 }
1080
1081
1082 /// Determine whether the suggested color of each live range is really usable,
1083 /// and then call its setSuggestedColorUsable() method to record the answer. A
1084 /// suggested color is NOT usable when the suggested color is volatile AND
1085 /// when there are call interferences.
1086 ///
1087 void PhyRegAlloc::markUnusableSugColors()
1088 {
1089   LiveRangeMapType::const_iterator HMI = (LRI->getLiveRangeMap())->begin();   
1090   LiveRangeMapType::const_iterator HMIEnd = (LRI->getLiveRangeMap())->end();   
1091
1092   for (; HMI != HMIEnd ; ++HMI ) {
1093     if (HMI->first) { 
1094       LiveRange *L = HMI->second;      // get the LiveRange
1095       if (L && L->hasSuggestedColor ())
1096         L->setSuggestedColorUsable
1097           (!(MRI.isRegVolatile (L->getRegClassID (), L->getSuggestedColor ())
1098              && L->isCallInterference ()));
1099     }
1100   } // for all LR's in hash map
1101 }
1102
1103
1104 /// For each live range that is spilled, allocates a new spill position on the
1105 /// stack, and set the stack offsets of the live range that will be spilled to
1106 /// that position. This must be called just after coloring the LRs.
1107 ///
1108 void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
1109   if (DEBUG_RA) std::cerr << "\nSetting LR stack offsets for spills...\n";
1110
1111   LiveRangeMapType::const_iterator HMI    = LRI->getLiveRangeMap()->begin();   
1112   LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap()->end();   
1113
1114   for ( ; HMI != HMIEnd ; ++HMI) {
1115     if (HMI->first && HMI->second) {
1116       LiveRange *L = HMI->second;       // get the LiveRange
1117       if (L->isMarkedForSpill()) {      // NOTE: allocating size of long Type **
1118         int stackOffset = MF->getInfo()->allocateSpilledValue(Type::LongTy);
1119         L->setSpillOffFromFP(stackOffset);
1120         if (DEBUG_RA)
1121           std::cerr << "  LR# " << L->getUserIGNode()->getIndex()
1122                << ": stack-offset = " << stackOffset << "\n";
1123       }
1124     }
1125   } // for all LR's in hash map
1126 }
1127
1128
1129 void PhyRegAlloc::saveStateForValue (std::vector<AllocInfo> &state,
1130                                      const Value *V, int Insn, int Opnd) {
1131   LiveRangeMapType::const_iterator HMI = LRI->getLiveRangeMap ()->find (V); 
1132   LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap ()->end ();   
1133   AllocInfo::AllocStateTy AllocState = AllocInfo::NotAllocated; 
1134   int Placement = -1; 
1135   if ((HMI != HMIEnd) && HMI->second) { 
1136     LiveRange *L = HMI->second; 
1137     assert ((L->hasColor () || L->isMarkedForSpill ()) 
1138             && "Live range exists but not colored or spilled"); 
1139     if (L->hasColor ()) { 
1140       AllocState = AllocInfo::Allocated; 
1141       Placement = MRI.getUnifiedRegNum (L->getRegClassID (), 
1142                                         L->getColor ()); 
1143     } else if (L->isMarkedForSpill ()) { 
1144       AllocState = AllocInfo::Spilled; 
1145       assert (L->hasSpillOffset () 
1146               && "Live range marked for spill but has no spill offset"); 
1147       Placement = L->getSpillOffFromFP (); 
1148     } 
1149   } 
1150   state.push_back (AllocInfo (Insn, Opnd, AllocState, Placement)); 
1151 }
1152
1153
1154 /// Save the global register allocation decisions made by the register
1155 /// allocator so that they can be accessed later (sort of like "poor man's
1156 /// debug info").
1157 ///
1158 void PhyRegAlloc::saveState () {
1159   std::vector<AllocInfo> &state = FnAllocState[Fn];
1160   unsigned ArgNum = 0;
1161   // Arguments encoded as instruction # -1
1162   for (Function::const_aiterator i=Fn->abegin (), e=Fn->aend (); i != e; ++i) {
1163     const Argument *Arg = &*i;
1164     saveStateForValue (state, Arg, -1, ArgNum);
1165     ++ArgNum;
1166   }
1167   unsigned Insn = 0;
1168   // Instructions themselves encoded as operand # -1
1169   for (const_inst_iterator II=inst_begin (Fn), IE=inst_end (Fn); II!=IE; ++II){
1170     saveStateForValue (state, (*II), Insn, -1);
1171     for (unsigned i = 0; i < (*II)->getNumOperands (); ++i) {
1172       const Value *V = (*II)->getOperand (i);
1173       // Don't worry about it unless it's something whose reg. we'll need. 
1174       if (!isa<Argument> (V) && !isa<Instruction> (V)) 
1175         continue; 
1176       saveStateForValue (state, V, Insn, i);
1177     }
1178     ++Insn;
1179   }
1180 }
1181
1182
1183 /// Check the saved state filled in by saveState(), and abort if it looks
1184 /// wrong. Only used when debugging. FIXME: Currently it just prints out
1185 /// the state, which isn't quite as useful.
1186 ///
1187 void PhyRegAlloc::verifySavedState () {
1188   std::vector<AllocInfo> &state = FnAllocState[Fn];
1189   int ArgNum = 0;
1190   for (Function::const_aiterator i=Fn->abegin (), e=Fn->aend (); i != e; ++i) {
1191     const Argument *Arg = &*i;
1192     std::cerr << "Argument:  " << *Arg << "\n"
1193               << "FnAllocState:\n";
1194     for (unsigned i = 0; i < state.size (); ++i) {
1195       AllocInfo &S = state[i];
1196       if (S.Instruction == -1 && S.Operand == ArgNum)
1197         std::cerr << "  " << S << "\n";
1198     }
1199     std::cerr << "----------\n";
1200     ++ArgNum;
1201   }
1202   int Insn = 0;
1203   for (const_inst_iterator II=inst_begin (Fn), IE=inst_end (Fn); II!=IE; ++II) {
1204     const Instruction *I = *II;
1205     MachineCodeForInstruction &Instrs = MachineCodeForInstruction::get (I);
1206     std::cerr << "Instruction: " << *I
1207               << "MachineCodeForInstruction:\n";
1208     for (unsigned i = 0, n = Instrs.size (); i != n; ++i)
1209       std::cerr << "  " << *Instrs[i];
1210     std::cerr << "FnAllocState:\n";
1211     for (unsigned i = 0; i < state.size (); ++i) {
1212       AllocInfo &S = state[i];
1213       if (Insn == S.Instruction)
1214         std::cerr << "  " << S << "\n";
1215     }
1216     std::cerr << "----------\n";
1217     ++Insn;
1218   }
1219 }
1220
1221
1222 bool PhyRegAlloc::doFinalization (Module &M) { 
1223   if (SaveRegAllocState) finishSavingState (M);
1224   return false;
1225 }
1226
1227
1228 /// Finish the job of saveState(), by collapsing FnAllocState into an LLVM
1229 /// Constant and stuffing it inside the Module.
1230 ///
1231 /// FIXME: There should be other, better ways of storing the saved
1232 /// state; this one is cumbersome and does not work well with the JIT.
1233 ///
1234 void PhyRegAlloc::finishSavingState (Module &M) {
1235   if (DEBUG_RA)
1236     std::cerr << "---- Saving reg. alloc state; SaveStateToModule = "
1237               << SaveStateToModule << " ----\n";
1238
1239   // If saving state into the module, just copy new elements to the
1240   // correct global.
1241   if (!SaveStateToModule) {
1242     ExportedFnAllocState = FnAllocState;
1243     // FIXME: should ONLY copy new elements in FnAllocState
1244     return;
1245   }
1246
1247   // Convert FnAllocState to a single Constant array and add it
1248   // to the Module.
1249   ArrayType *AT = ArrayType::get (AllocInfo::getConstantType (), 0);
1250   std::vector<const Type *> TV;
1251   TV.push_back (Type::UIntTy);
1252   TV.push_back (AT);
1253   PointerType *PT = PointerType::get (StructType::get (TV));
1254
1255   std::vector<Constant *> allstate;
1256   for (Module::iterator I = M.begin (), E = M.end (); I != E; ++I) {
1257     Function *F = I;
1258     if (F->isExternal ()) continue;
1259     if (FnAllocState.find (F) == FnAllocState.end ()) {
1260       allstate.push_back (ConstantPointerNull::get (PT));
1261     } else {
1262       std::vector<AllocInfo> &state = FnAllocState[F];
1263
1264       // Convert state into an LLVM ConstantArray, and put it in a
1265       // ConstantStruct (named S) along with its size.
1266       std::vector<Constant *> stateConstants;
1267       for (unsigned i = 0, s = state.size (); i != s; ++i)
1268         stateConstants.push_back (state[i].toConstant ());
1269       unsigned Size = stateConstants.size ();
1270       ArrayType *AT = ArrayType::get (AllocInfo::getConstantType (), Size);
1271       std::vector<const Type *> TV;
1272       TV.push_back (Type::UIntTy);
1273       TV.push_back (AT);
1274       StructType *ST = StructType::get (TV);
1275       std::vector<Constant *> CV;
1276       CV.push_back (ConstantUInt::get (Type::UIntTy, Size));
1277       CV.push_back (ConstantArray::get (AT, stateConstants));
1278       Constant *S = ConstantStruct::get (ST, CV);
1279
1280       GlobalVariable *GV =
1281         new GlobalVariable (ST, true,
1282                             GlobalValue::InternalLinkage, S,
1283                             F->getName () + ".regAllocState", &M);
1284
1285       // Have: { uint, [Size x { uint, int, uint, int }] } *
1286       // Cast it to: { uint, [0 x { uint, int, uint, int }] } *
1287       Constant *CE = ConstantExpr::getCast (ConstantPointerRef::get (GV), PT);
1288       allstate.push_back (CE);
1289     }
1290   }
1291
1292   unsigned Size = allstate.size ();
1293   // Final structure type is:
1294   // { uint, [Size x { uint, [0 x { uint, int, uint, int }] } *] }
1295   std::vector<const Type *> TV2;
1296   TV2.push_back (Type::UIntTy);
1297   ArrayType *AT2 = ArrayType::get (PT, Size);
1298   TV2.push_back (AT2);
1299   StructType *ST2 = StructType::get (TV2);
1300   std::vector<Constant *> CV2;
1301   CV2.push_back (ConstantUInt::get (Type::UIntTy, Size));
1302   CV2.push_back (ConstantArray::get (AT2, allstate));
1303   new GlobalVariable (ST2, true, GlobalValue::ExternalLinkage,
1304                       ConstantStruct::get (ST2, CV2), "_llvm_regAllocState",
1305                       &M);
1306 }
1307
1308
1309 /// Allocate registers for the machine code previously generated for F using
1310 /// the graph-coloring algorithm.
1311 ///
1312 bool PhyRegAlloc::runOnFunction (Function &F) { 
1313   if (DEBUG_RA) 
1314     std::cerr << "\n********* Function "<< F.getName () << " ***********\n"; 
1315  
1316   Fn = &F; 
1317   MF = &MachineFunction::get (Fn); 
1318   LVI = &getAnalysis<FunctionLiveVarInfo> (); 
1319   LRI = new LiveRangeInfo (Fn, TM, RegClassList); 
1320   LoopDepthCalc = &getAnalysis<LoopInfo> (); 
1321  
1322   // Create each RegClass for the target machine and add it to the 
1323   // RegClassList.  This must be done before calling constructLiveRanges().
1324   for (unsigned rc = 0; rc != NumOfRegClasses; ++rc)   
1325     RegClassList.push_back (new RegClass (Fn, &TM.getRegInfo (), 
1326                                           MRI.getMachineRegClass (rc))); 
1327      
1328   LRI->constructLiveRanges();            // create LR info
1329   if (DEBUG_RA >= RA_DEBUG_LiveRanges)
1330     LRI->printLiveRanges();
1331   
1332   createIGNodeListsAndIGs();            // create IGNode list and IGs
1333
1334   buildInterferenceGraphs();            // build IGs in all reg classes
1335   
1336   if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
1337     // print all LRs in all reg classes
1338     for ( unsigned rc=0; rc < NumOfRegClasses  ; rc++)  
1339       RegClassList[rc]->printIGNodeList(); 
1340     
1341     // print IGs in all register classes
1342     for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)  
1343       RegClassList[rc]->printIG();       
1344   }
1345
1346   LRI->coalesceLRs();                    // coalesce all live ranges
1347
1348   if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
1349     // print all LRs in all reg classes
1350     for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1351       RegClassList[rc]->printIGNodeList();
1352     
1353     // print IGs in all register classes
1354     for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1355       RegClassList[rc]->printIG();
1356   }
1357
1358   // mark un-usable suggested color before graph coloring algorithm.
1359   // When this is done, the graph coloring algo will not reserve
1360   // suggested color unnecessarily - they can be used by another LR
1361   markUnusableSugColors(); 
1362
1363   // color all register classes using the graph coloring algo
1364   for (unsigned rc=0; rc < NumOfRegClasses ; rc++)  
1365     RegClassList[rc]->colorAllRegs();    
1366
1367   // After graph coloring, if some LRs did not receive a color (i.e, spilled)
1368   // a position for such spilled LRs
1369   allocateStackSpace4SpilledLRs();
1370
1371   // Reset the temp. area on the stack before use by the first instruction.
1372   // This will also happen after updating each instruction.
1373   MF->getInfo()->popAllTempValues();
1374
1375   // color incoming args - if the correct color was not received
1376   // insert code to copy to the correct register
1377   colorIncomingArgs();
1378
1379   // Save register allocation state for this function in a Constant.
1380   if (SaveRegAllocState) {
1381     saveState();
1382     if (DEBUG_RA) // Check our work.
1383       verifySavedState ();
1384     if (!SaveStateToModule)
1385       finishSavingState (const_cast<Module&> (*Fn->getParent ()));
1386   }
1387
1388   // Now update the machine code with register names and add any additional
1389   // code inserted by the register allocator to the instruction stream.
1390   updateMachineCode(); 
1391
1392   if (DEBUG_RA) {
1393     std::cerr << "\n**** Machine Code After Register Allocation:\n\n";
1394     MF->dump();
1395   }
1396  
1397   // Tear down temporary data structures 
1398   for (unsigned rc = 0; rc < NumOfRegClasses; ++rc) 
1399     delete RegClassList[rc]; 
1400   RegClassList.clear (); 
1401   AddedInstrMap.clear (); 
1402   OperandsColoredMap.clear (); 
1403   ScratchRegsUsed.clear (); 
1404   AddedInstrAtEntry.clear (); 
1405   delete LRI;
1406
1407   if (DEBUG_RA) std::cerr << "\nRegister allocation complete!\n"; 
1408   return false;     // Function was not modified
1409
1410
1411 } // End llvm namespace