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