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