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