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