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