Mark barrier instructions. Execution does not fall through uncond branches
[oota-llvm.git] / lib / Target / SparcV9 / SparcV9InstrInfo.cpp
1 //===-- SparcV9InstrInfo.cpp - SparcV9 Instr. Selection Support Methods ---===//
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 // This file contains various methods of the class SparcV9InstrInfo, many of
11 // which appear to build canned sequences of MachineInstrs, and are
12 // used in instruction selection.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/CodeGen/InstrSelection.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineFunctionInfo.h"
24 #include "llvm/CodeGen/MachineCodeForInstruction.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "SparcV9Internals.h"
27 #include "SparcV9InstrSelectionSupport.h"
28 #include "SparcV9InstrInfo.h"
29
30 namespace llvm {
31
32 static const uint32_t MAXLO   = (1 << 10) - 1; // set bits set by %lo(*)
33 static const uint32_t MAXSIMM = (1 << 12) - 1; // set bits in simm13 field of OR
34
35 //---------------------------------------------------------------------------
36 // Function ConvertConstantToIntType
37 // 
38 // Function to get the value of an integral constant in the form
39 // that must be put into the machine register.  The specified constant is
40 // interpreted as (i.e., converted if necessary to) the specified destination
41 // type.  The result is always returned as an uint64_t, since the representation
42 // of int64_t and uint64_t are identical.  The argument can be any known const.
43 // 
44 // isValidConstant is set to true if a valid constant was found.
45 //---------------------------------------------------------------------------
46
47 uint64_t
48 ConvertConstantToIntType(const TargetMachine &target,
49                                               const Value *V,
50                                               const Type *destType,
51                                               bool  &isValidConstant)
52 {
53   isValidConstant = false;
54   uint64_t C = 0;
55
56   if (! destType->isIntegral() && ! isa<PointerType>(destType))
57     return C;
58
59   if (! isa<Constant>(V) || isa<GlobalValue>(V))
60     return C;
61
62   // GlobalValue: no conversions needed: get value and return it
63   if (const GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
64     isValidConstant = true;             // may be overwritten by recursive call
65     return ConvertConstantToIntType(target, GV, destType, isValidConstant);
66   }
67
68   // ConstantBool: no conversions needed: get value and return it
69   if (const ConstantBool *CB = dyn_cast<ConstantBool>(V)) {
70     isValidConstant = true;
71     return (uint64_t) CB->getValue();
72   }
73
74   // ConstantPointerNull: it's really just a big, shiny version of zero.
75   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(V)) {
76     isValidConstant = true;
77     return 0;
78   }
79
80   // For other types of constants, some conversion may be needed.
81   // First, extract the constant operand according to its own type
82   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
83     switch(CE->getOpcode()) {
84     case Instruction::Cast:             // recursively get the value as cast
85       C = ConvertConstantToIntType(target, CE->getOperand(0), CE->getType(),
86                                    isValidConstant);
87       break;
88     default:                            // not simplifying other ConstantExprs
89       break;
90     }
91   else if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
92     isValidConstant = true;
93     C = CI->getRawValue();
94   }
95   else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
96     isValidConstant = true;
97     double fC = CFP->getValue();
98     C = (destType->isSigned()? (uint64_t) (int64_t) fC
99                              : (uint64_t)           fC);
100   }
101
102   // Now if a valid value was found, convert it to destType.
103   if (isValidConstant) {
104     unsigned opSize   = target.getTargetData().getTypeSize(V->getType());
105     unsigned destSize = target.getTargetData().getTypeSize(destType);
106     uint64_t maskHi   = (destSize < 8)? (1U << 8*destSize) - 1 : ~0;
107     assert(opSize <= 8 && destSize <= 8 && ">8-byte int type unexpected");
108     
109     if (destType->isSigned()) {
110       if (opSize > destSize)            // operand is larger than dest:
111         C = C & maskHi;                 // mask high bits
112
113       if (opSize > destSize ||
114           (opSize == destSize && ! V->getType()->isSigned()))
115         if (C & (1U << (8*destSize - 1)))
116           C =  C | ~maskHi;             // sign-extend from destSize to 64 bits
117     }
118     else {
119       if (opSize > destSize || (V->getType()->isSigned() && destSize < 8)) {
120         // operand is larger than dest,
121         //    OR both are equal but smaller than the full register size
122         //       AND operand is signed, so it may have extra sign bits:
123         // mask high bits
124         C = C & maskHi;
125       }
126     }
127   }
128
129   return C;
130 }
131
132
133 //----------------------------------------------------------------------------
134 // Function: CreateSETUWConst
135 // 
136 // Set a 32-bit unsigned constant in the register `dest', using
137 // SETHI, OR in the worst case.  This function correctly emulates
138 // the SETUW pseudo-op for SPARC v9 (if argument isSigned == false).
139 //
140 // The isSigned=true case is used to implement SETSW without duplicating code.
141 // 
142 // Optimize some common cases:
143 // (1) Small value that fits in simm13 field of OR: don't need SETHI.
144 // (2) isSigned = true and C is a small negative signed value, i.e.,
145 //     high bits are 1, and the remaining bits fit in simm13(OR).
146 //----------------------------------------------------------------------------
147
148 static inline void
149 CreateSETUWConst(const TargetMachine& target, uint32_t C,
150                  Instruction* dest, std::vector<MachineInstr*>& mvec,
151                  bool isSigned = false)
152 {
153   MachineInstr *miSETHI = NULL, *miOR = NULL;
154
155   // In order to get efficient code, we should not generate the SETHI if
156   // all high bits are 1 (i.e., this is a small signed value that fits in
157   // the simm13 field of OR).  So we check for and handle that case specially.
158   // NOTE: The value C = 0x80000000 is bad: sC < 0 *and* -sC < 0.
159   //       In fact, sC == -sC, so we have to check for this explicitly.
160   int32_t sC = (int32_t) C;
161   bool smallNegValue =isSigned && sC < 0 && sC != -sC && -sC < (int32_t)MAXSIMM;
162
163   // Set the high 22 bits in dest if non-zero and simm13 field of OR not enough
164   if (!smallNegValue && (C & ~MAXLO) && C > MAXSIMM) {
165     miSETHI = BuildMI(V9::SETHI, 2).addZImm(C).addRegDef(dest);
166     miSETHI->getOperand(0).markHi32();
167     mvec.push_back(miSETHI);
168   }
169   
170   // Set the low 10 or 12 bits in dest.  This is necessary if no SETHI
171   // was generated, or if the low 10 bits are non-zero.
172   if (miSETHI==NULL || C & MAXLO) {
173     if (miSETHI) {
174       // unsigned value with high-order bits set using SETHI
175       miOR = BuildMI(V9::ORi,3).addReg(dest).addZImm(C).addRegDef(dest);
176       miOR->getOperand(1).markLo32();
177     } else {
178       // unsigned or small signed value that fits in simm13 field of OR
179       assert(smallNegValue || (C & ~MAXSIMM) == 0);
180       miOR = BuildMI(V9::ORi, 3).addMReg(target.getRegInfo()->getZeroRegNum())
181         .addSImm(sC).addRegDef(dest);
182     }
183     mvec.push_back(miOR);
184   }
185   
186   assert((miSETHI || miOR) && "Oops, no code was generated!");
187 }
188
189
190 //----------------------------------------------------------------------------
191 // Function: CreateSETSWConst
192 // 
193 // Set a 32-bit signed constant in the register `dest', with sign-extension
194 // to 64 bits.  This uses SETHI, OR, SRA in the worst case.
195 // This function correctly emulates the SETSW pseudo-op for SPARC v9.
196 //
197 // Optimize the same cases as SETUWConst, plus:
198 // (1) SRA is not needed for positive or small negative values.
199 //----------------------------------------------------------------------------
200
201 static inline void
202 CreateSETSWConst(const TargetMachine& target, int32_t C,
203                  Instruction* dest, std::vector<MachineInstr*>& mvec)
204 {
205   // Set the low 32 bits of dest
206   CreateSETUWConst(target, (uint32_t) C,  dest, mvec, /*isSigned*/true);
207
208   // Sign-extend to the high 32 bits if needed.
209   // NOTE: The value C = 0x80000000 is bad: -C == C and so -C is < MAXSIMM
210   if (C < 0 && (C == -C || -C > (int32_t) MAXSIMM))
211     mvec.push_back(BuildMI(V9::SRAi5,3).addReg(dest).addZImm(0).addRegDef(dest));
212 }
213
214
215 //----------------------------------------------------------------------------
216 // Function: CreateSETXConst
217 // 
218 // Set a 64-bit signed or unsigned constant in the register `dest'.
219 // Use SETUWConst for each 32 bit word, plus a left-shift-by-32 in between.
220 // This function correctly emulates the SETX pseudo-op for SPARC v9.
221 //
222 // Optimize the same cases as SETUWConst for each 32 bit word.
223 //----------------------------------------------------------------------------
224
225 static inline void
226 CreateSETXConst(const TargetMachine& target, uint64_t C,
227                 Instruction* tmpReg, Instruction* dest,
228                 std::vector<MachineInstr*>& mvec)
229 {
230   assert(C > (unsigned int) ~0 && "Use SETUW/SETSW for 32-bit values!");
231   
232   MachineInstr* MI;
233   
234   // Code to set the upper 32 bits of the value in register `tmpReg'
235   CreateSETUWConst(target, (C >> 32), tmpReg, mvec);
236   
237   // Shift tmpReg left by 32 bits
238   mvec.push_back(BuildMI(V9::SLLXi6, 3).addReg(tmpReg).addZImm(32)
239                  .addRegDef(tmpReg));
240   
241   // Code to set the low 32 bits of the value in register `dest'
242   CreateSETUWConst(target, C, dest, mvec);
243   
244   // dest = OR(tmpReg, dest)
245   mvec.push_back(BuildMI(V9::ORr,3).addReg(dest).addReg(tmpReg).addRegDef(dest));
246 }
247
248
249 //----------------------------------------------------------------------------
250 // Function: CreateSETUWLabel
251 // 
252 // Set a 32-bit constant (given by a symbolic label) in the register `dest'.
253 //----------------------------------------------------------------------------
254
255 static inline void
256 CreateSETUWLabel(const TargetMachine& target, Value* val,
257                  Instruction* dest, std::vector<MachineInstr*>& mvec)
258 {
259   MachineInstr* MI;
260   
261   // Set the high 22 bits in dest
262   MI = BuildMI(V9::SETHI, 2).addReg(val).addRegDef(dest);
263   MI->getOperand(0).markHi32();
264   mvec.push_back(MI);
265   
266   // Set the low 10 bits in dest
267   MI = BuildMI(V9::ORr, 3).addReg(dest).addReg(val).addRegDef(dest);
268   MI->getOperand(1).markLo32();
269   mvec.push_back(MI);
270 }
271
272
273 //----------------------------------------------------------------------------
274 // Function: CreateSETXLabel
275 // 
276 // Set a 64-bit constant (given by a symbolic label) in the register `dest'.
277 //----------------------------------------------------------------------------
278
279 static inline void
280 CreateSETXLabel(const TargetMachine& target,
281                 Value* val, Instruction* tmpReg, Instruction* dest,
282                 std::vector<MachineInstr*>& mvec)
283 {
284   assert(isa<Constant>(val) && 
285          "I only know about constant values and global addresses");
286   
287   MachineInstr* MI;
288   
289   MI = BuildMI(V9::SETHI, 2).addPCDisp(val).addRegDef(tmpReg);
290   MI->getOperand(0).markHi64();
291   mvec.push_back(MI);
292   
293   MI = BuildMI(V9::ORi, 3).addReg(tmpReg).addPCDisp(val).addRegDef(tmpReg);
294   MI->getOperand(1).markLo64();
295   mvec.push_back(MI);
296   
297   mvec.push_back(BuildMI(V9::SLLXi6, 3).addReg(tmpReg).addZImm(32)
298                  .addRegDef(tmpReg));
299   MI = BuildMI(V9::SETHI, 2).addPCDisp(val).addRegDef(dest);
300   MI->getOperand(0).markHi32();
301   mvec.push_back(MI);
302   
303   MI = BuildMI(V9::ORr, 3).addReg(dest).addReg(tmpReg).addRegDef(dest);
304   mvec.push_back(MI);
305   
306   MI = BuildMI(V9::ORi, 3).addReg(dest).addPCDisp(val).addRegDef(dest);
307   MI->getOperand(1).markLo32();
308   mvec.push_back(MI);
309 }
310
311
312 //----------------------------------------------------------------------------
313 // Function: CreateUIntSetInstruction
314 // 
315 // Create code to Set an unsigned constant in the register `dest'.
316 // Uses CreateSETUWConst, CreateSETSWConst or CreateSETXConst as needed.
317 // CreateSETSWConst is an optimization for the case that the unsigned value
318 // has all ones in the 33 high bits (so that sign-extension sets them all).
319 //----------------------------------------------------------------------------
320
321 static inline void
322 CreateUIntSetInstruction(const TargetMachine& target,
323                          uint64_t C, Instruction* dest,
324                          std::vector<MachineInstr*>& mvec,
325                          MachineCodeForInstruction& mcfi)
326 {
327   static const uint64_t lo32 = (uint32_t) ~0;
328   if (C <= lo32)                        // High 32 bits are 0.  Set low 32 bits.
329     CreateSETUWConst(target, (uint32_t) C, dest, mvec);
330   else if ((C & ~lo32) == ~lo32 && (C & (1U << 31))) {
331     // All high 33 (not 32) bits are 1s: sign-extension will take care
332     // of high 32 bits, so use the sequence for signed int
333     CreateSETSWConst(target, (int32_t) C, dest, mvec);
334   } else if (C > lo32) {
335     // C does not fit in 32 bits
336     TmpInstruction* tmpReg = new TmpInstruction(mcfi, Type::IntTy);
337     CreateSETXConst(target, C, tmpReg, dest, mvec);
338   }
339 }
340
341
342 //----------------------------------------------------------------------------
343 // Function: CreateIntSetInstruction
344 // 
345 // Create code to Set a signed constant in the register `dest'.
346 // Really the same as CreateUIntSetInstruction.
347 //----------------------------------------------------------------------------
348
349 static inline void
350 CreateIntSetInstruction(const TargetMachine& target,
351                         int64_t C, Instruction* dest,
352                         std::vector<MachineInstr*>& mvec,
353                         MachineCodeForInstruction& mcfi)
354 {
355   CreateUIntSetInstruction(target, (uint64_t) C, dest, mvec, mcfi);
356 }
357
358
359 //---------------------------------------------------------------------------
360 // Create a table of LLVM opcode -> max. immediate constant likely to
361 // be usable for that operation.
362 //---------------------------------------------------------------------------
363
364 // Entry == 0 ==> no immediate constant field exists at all.
365 // Entry >  0 ==> abs(immediate constant) <= Entry
366 // 
367 std::vector<int> MaxConstantsTable(Instruction::OtherOpsEnd);
368
369 static int
370 MaxConstantForInstr(unsigned llvmOpCode)
371 {
372   int modelOpCode = -1;
373
374   if (llvmOpCode >= Instruction::BinaryOpsBegin &&
375       llvmOpCode <  Instruction::BinaryOpsEnd)
376     modelOpCode = V9::ADDi;
377   else
378     switch(llvmOpCode) {
379     case Instruction::Ret:   modelOpCode = V9::JMPLCALLi; break;
380
381     case Instruction::Malloc:         
382     case Instruction::Alloca:         
383     case Instruction::GetElementPtr:  
384     case Instruction::PHI:       
385     case Instruction::Cast:
386     case Instruction::Call:  modelOpCode = V9::ADDi; break;
387
388     case Instruction::Shl:
389     case Instruction::Shr:   modelOpCode = V9::SLLXi6; break;
390
391     default: break;
392     };
393
394   return (modelOpCode < 0)? 0: SparcV9MachineInstrDesc[modelOpCode].maxImmedConst;
395 }
396
397 static void
398 InitializeMaxConstantsTable()
399 {
400   unsigned op;
401   assert(MaxConstantsTable.size() == Instruction::OtherOpsEnd &&
402          "assignments below will be illegal!");
403   for (op = Instruction::TermOpsBegin; op < Instruction::TermOpsEnd; ++op)
404     MaxConstantsTable[op] = MaxConstantForInstr(op);
405   for (op = Instruction::BinaryOpsBegin; op < Instruction::BinaryOpsEnd; ++op)
406     MaxConstantsTable[op] = MaxConstantForInstr(op);
407   for (op = Instruction::MemoryOpsBegin; op < Instruction::MemoryOpsEnd; ++op)
408     MaxConstantsTable[op] = MaxConstantForInstr(op);
409   for (op = Instruction::OtherOpsBegin; op < Instruction::OtherOpsEnd; ++op)
410     MaxConstantsTable[op] = MaxConstantForInstr(op);
411 }
412
413
414 //---------------------------------------------------------------------------
415 // class SparcV9InstrInfo 
416 // 
417 // Purpose:
418 //   Information about individual instructions.
419 //   Most information is stored in the SparcV9MachineInstrDesc array above.
420 //   Other information is computed on demand, and most such functions
421 //   default to member functions in base class TargetInstrInfo. 
422 //---------------------------------------------------------------------------
423
424 SparcV9InstrInfo::SparcV9InstrInfo()
425   : TargetInstrInfo(SparcV9MachineInstrDesc, V9::NUM_TOTAL_OPCODES) {
426   InitializeMaxConstantsTable();
427 }
428
429 bool ConstantMayNotFitInImmedField(const Constant* CV, const Instruction* I) {
430   if (I->getOpcode() >= MaxConstantsTable.size()) // user-defined op (or bug!)
431     return true;
432
433   if (isa<ConstantPointerNull>(CV))               // can always use %g0
434     return false;
435
436   if (isa<SwitchInst>(I)) // Switch instructions will be lowered!
437     return false;
438
439   if (const ConstantInt* CI = dyn_cast<ConstantInt>(CV))
440     return labs((int64_t)CI->getRawValue()) > MaxConstantsTable[I->getOpcode()];
441
442   if (isa<ConstantBool>(CV))
443     return 1 > MaxConstantsTable[I->getOpcode()];
444
445   return true;
446 }
447
448 // 
449 // Create an instruction sequence to put the constant `val' into
450 // the virtual register `dest'.  `val' may be a Constant or a
451 // GlobalValue, viz., the constant address of a global variable or function.
452 // The generated instructions are returned in `mvec'.
453 // Any temp. registers (TmpInstruction) created are recorded in mcfi.
454 // Any stack space required is allocated via MachineFunction.
455 // 
456 void
457 CreateCodeToLoadConst(const TargetMachine& target,
458                                       Function* F,
459                                       Value* val,
460                                       Instruction* dest,
461                                       std::vector<MachineInstr*>& mvec,
462                                       MachineCodeForInstruction& mcfi)
463 {
464   assert(isa<Constant>(val) &&
465          "I only know about constant values and global addresses");
466   
467   // Use a "set" instruction for known constants or symbolic constants (labels)
468   // that can go in an integer reg.
469   // We have to use a "load" instruction for all other constants,
470   // in particular, floating point constants.
471   // 
472   const Type* valType = val->getType();
473   
474   if (isa<GlobalValue>(val)) {
475       TmpInstruction* tmpReg =
476         new TmpInstruction(mcfi, PointerType::get(val->getType()), val);
477       CreateSETXLabel(target, val, tmpReg, dest, mvec);
478       return;
479   }
480
481   bool isValid;
482   uint64_t C = ConvertConstantToIntType(target, val, dest->getType(), isValid);
483   if (isValid) {
484     if (dest->getType()->isSigned())
485       CreateUIntSetInstruction(target, C, dest, mvec, mcfi);
486     else
487       CreateIntSetInstruction(target, (int64_t) C, dest, mvec, mcfi);
488
489   } else {
490     // Make an instruction sequence to load the constant, viz:
491     //            SETX <addr-of-constant>, tmpReg, addrReg
492     //            LOAD  /*addr*/ addrReg, /*offset*/ 0, dest
493       
494     // First, create a tmp register to be used by the SETX sequence.
495     TmpInstruction* tmpReg =
496       new TmpInstruction(mcfi, PointerType::get(val->getType()));
497       
498     // Create another TmpInstruction for the address register
499     TmpInstruction* addrReg =
500       new TmpInstruction(mcfi, PointerType::get(val->getType()));
501     
502     // Get the constant pool index for this constant
503     MachineConstantPool *CP = MachineFunction::get(F).getConstantPool();
504     Constant *C = cast<Constant>(val);
505     unsigned CPI = CP->getConstantPoolIndex(C);
506
507     // Put the address of the constant into a register
508     MachineInstr* MI;
509   
510     MI = BuildMI(V9::SETHI, 2).addConstantPoolIndex(CPI).addRegDef(tmpReg);
511     MI->getOperand(0).markHi64();
512     mvec.push_back(MI);
513   
514     MI = BuildMI(V9::ORi, 3).addReg(tmpReg).addConstantPoolIndex(CPI)
515       .addRegDef(tmpReg);
516     MI->getOperand(1).markLo64();
517     mvec.push_back(MI);
518   
519     mvec.push_back(BuildMI(V9::SLLXi6, 3).addReg(tmpReg).addZImm(32)
520                    .addRegDef(tmpReg));
521     MI = BuildMI(V9::SETHI, 2).addConstantPoolIndex(CPI).addRegDef(addrReg);
522     MI->getOperand(0).markHi32();
523     mvec.push_back(MI);
524   
525     MI = BuildMI(V9::ORr, 3).addReg(addrReg).addReg(tmpReg).addRegDef(addrReg);
526     mvec.push_back(MI);
527   
528     MI = BuildMI(V9::ORi, 3).addReg(addrReg).addConstantPoolIndex(CPI)
529       .addRegDef(addrReg);
530     MI->getOperand(1).markLo32();
531     mvec.push_back(MI);
532
533     // Now load the constant from out ConstantPool label
534     unsigned Opcode = ChooseLoadInstruction(val->getType());
535     Opcode = convertOpcodeFromRegToImm(Opcode);
536     mvec.push_back(BuildMI(Opcode, 3)
537                    .addReg(addrReg).addSImm((int64_t)0).addRegDef(dest));
538   }
539 }
540
541 // Create an instruction sequence to copy an integer register `val'
542 // to a floating point register `dest' by copying to memory and back.
543 // val must be an integral type.  dest must be a Float or Double.
544 // The generated instructions are returned in `mvec'.
545 // Any temp. registers (TmpInstruction) created are recorded in mcfi.
546 // Any stack space required is allocated via MachineFunction.
547 // 
548 void
549 CreateCodeToCopyIntToFloat(const TargetMachine& target,
550                                         Function* F,
551                                         Value* val,
552                                         Instruction* dest,
553                                         std::vector<MachineInstr*>& mvec,
554                                         MachineCodeForInstruction& mcfi)
555 {
556   assert((val->getType()->isIntegral() || isa<PointerType>(val->getType()))
557          && "Source type must be integral (integer or bool) or pointer");
558   assert(dest->getType()->isFloatingPoint()
559          && "Dest type must be float/double");
560
561   // Get a stack slot to use for the copy
562   int offset = MachineFunction::get(F).getInfo()->allocateLocalVar(val);
563
564   // Get the size of the source value being copied. 
565   size_t srcSize = target.getTargetData().getTypeSize(val->getType());
566
567   // Store instruction stores `val' to [%fp+offset].
568   // The store and load opCodes are based on the size of the source value.
569   // If the value is smaller than 32 bits, we must sign- or zero-extend it
570   // to 32 bits since the load-float will load 32 bits.
571   // Note that the store instruction is the same for signed and unsigned ints.
572   const Type* storeType = (srcSize <= 4)? Type::IntTy : Type::LongTy;
573   Value* storeVal = val;
574   if (srcSize < target.getTargetData().getTypeSize(Type::FloatTy)) {
575     // sign- or zero-extend respectively
576     storeVal = new TmpInstruction(mcfi, storeType, val);
577     if (val->getType()->isSigned())
578       CreateSignExtensionInstructions(target, F, val, storeVal, 8*srcSize,
579                                       mvec, mcfi);
580     else
581       CreateZeroExtensionInstructions(target, F, val, storeVal, 8*srcSize,
582                                       mvec, mcfi);
583   }
584
585   unsigned FPReg = target.getRegInfo()->getFramePointer();
586   unsigned StoreOpcode = ChooseStoreInstruction(storeType);
587   StoreOpcode = convertOpcodeFromRegToImm(StoreOpcode);
588   mvec.push_back(BuildMI(StoreOpcode, 3)
589                  .addReg(storeVal).addMReg(FPReg).addSImm(offset));
590
591   // Load instruction loads [%fp+offset] to `dest'.
592   // The type of the load opCode is the floating point type that matches the
593   // stored type in size:
594   // On SparcV9: float for int or smaller, double for long.
595   // 
596   const Type* loadType = (srcSize <= 4)? Type::FloatTy : Type::DoubleTy;
597   unsigned LoadOpcode = ChooseLoadInstruction(loadType);
598   LoadOpcode = convertOpcodeFromRegToImm(LoadOpcode);
599   mvec.push_back(BuildMI(LoadOpcode, 3)
600                  .addMReg(FPReg).addSImm(offset).addRegDef(dest));
601 }
602
603 // Similarly, create an instruction sequence to copy an FP register
604 // `val' to an integer register `dest' by copying to memory and back.
605 // The generated instructions are returned in `mvec'.
606 // Any temp. virtual registers (TmpInstruction) created are recorded in mcfi.
607 // Temporary stack space required is allocated via MachineFunction.
608 // 
609 void
610 CreateCodeToCopyFloatToInt(const TargetMachine& target,
611                                         Function* F,
612                                         Value* val,
613                                         Instruction* dest,
614                                         std::vector<MachineInstr*>& mvec,
615                                         MachineCodeForInstruction& mcfi)
616 {
617   const Type* opTy   = val->getType();
618   const Type* destTy = dest->getType();
619
620   assert(opTy->isFloatingPoint() && "Source type must be float/double");
621   assert((destTy->isIntegral() || isa<PointerType>(destTy))
622          && "Dest type must be integer, bool or pointer");
623
624   // FIXME: For now, we allocate permanent space because the stack frame
625   // manager does not allow locals to be allocated (e.g., for alloca) after
626   // a temp is allocated!
627   // 
628   int offset = MachineFunction::get(F).getInfo()->allocateLocalVar(val); 
629
630   unsigned FPReg = target.getRegInfo()->getFramePointer();
631
632   // Store instruction stores `val' to [%fp+offset].
633   // The store opCode is based only the source value being copied.
634   // 
635   unsigned StoreOpcode = ChooseStoreInstruction(opTy);
636   StoreOpcode = convertOpcodeFromRegToImm(StoreOpcode);  
637   mvec.push_back(BuildMI(StoreOpcode, 3)
638                  .addReg(val).addMReg(FPReg).addSImm(offset));
639
640   // Load instruction loads [%fp+offset] to `dest'.
641   // The type of the load opCode is the integer type that matches the
642   // source type in size:
643   // On SparcV9: int for float, long for double.
644   // Note that we *must* use signed loads even for unsigned dest types, to
645   // ensure correct sign-extension for UByte, UShort or UInt:
646   // 
647   const Type* loadTy = (opTy == Type::FloatTy)? Type::IntTy : Type::LongTy;
648   unsigned LoadOpcode = ChooseLoadInstruction(loadTy);
649   LoadOpcode = convertOpcodeFromRegToImm(LoadOpcode);
650   mvec.push_back(BuildMI(LoadOpcode, 3).addMReg(FPReg)
651                  .addSImm(offset).addRegDef(dest));
652 }
653
654
655 // Create instruction(s) to copy src to dest, for arbitrary types
656 // The generated instructions are returned in `mvec'.
657 // Any temp. registers (TmpInstruction) created are recorded in mcfi.
658 // Any stack space required is allocated via MachineFunction.
659 // 
660 void
661 CreateCopyInstructionsByType(const TargetMachine& target,
662                                              Function *F,
663                                              Value* src,
664                                              Instruction* dest,
665                                              std::vector<MachineInstr*>& mvec,
666                                           MachineCodeForInstruction& mcfi)
667 {
668   bool loadConstantToReg = false;
669   
670   const Type* resultType = dest->getType();
671   
672   MachineOpCode opCode = ChooseAddInstructionByType(resultType);
673   assert (opCode != V9::INVALID_OPCODE
674           && "Unsupported result type in CreateCopyInstructionsByType()");
675   
676   // if `src' is a constant that doesn't fit in the immed field or if it is
677   // a global variable (i.e., a constant address), generate a load
678   // instruction instead of an add
679   // 
680   if (isa<GlobalValue>(src))
681     loadConstantToReg = true;
682   else if (isa<Constant>(src)) {
683     unsigned int machineRegNum;
684     int64_t immedValue;
685     MachineOperand::MachineOperandType opType =
686       ChooseRegOrImmed(src, opCode, target, /*canUseImmed*/ true,
687                        machineRegNum, immedValue);
688       
689     if (opType == MachineOperand::MO_VirtualRegister)
690       loadConstantToReg = true;
691   }
692   
693   if (loadConstantToReg) { 
694     // `src' is constant and cannot fit in immed field for the ADD
695     // Insert instructions to "load" the constant into a register
696     CreateCodeToLoadConst(target, F, src, dest, mvec, mcfi);
697   } else { 
698     // Create a reg-to-reg copy instruction for the given type:
699     // -- For FP values, create a FMOVS or FMOVD instruction
700     // -- For non-FP values, create an add-with-0 instruction (opCode as above)
701     // Make `src' the second operand, in case it is a small constant!
702     // 
703     MachineInstr* MI;
704     if (resultType->isFloatingPoint())
705       MI = (BuildMI(resultType == Type::FloatTy? V9::FMOVS : V9::FMOVD, 2)
706             .addReg(src).addRegDef(dest));
707     else {
708         const Type* Ty =isa<PointerType>(resultType)? Type::ULongTy :resultType;
709         MI = (BuildMI(opCode, 3)
710               .addSImm((int64_t) 0).addReg(src).addRegDef(dest));
711     }
712     mvec.push_back(MI);
713   }
714 }
715
716
717 // Helper function for sign-extension and zero-extension.
718 // For SPARC v9, we sign-extend the given operand using SLL; SRA/SRL.
719 inline void
720 CreateBitExtensionInstructions(bool signExtend,
721                                const TargetMachine& target,
722                                Function* F,
723                                Value* srcVal,
724                                Value* destVal,
725                                unsigned int numLowBits,
726                                std::vector<MachineInstr*>& mvec,
727                                MachineCodeForInstruction& mcfi)
728 {
729   MachineInstr* M;
730
731   assert(numLowBits <= 32 && "Otherwise, nothing should be done here!");
732
733   if (numLowBits < 32) {
734     // SLL is needed since operand size is < 32 bits.
735     TmpInstruction *tmpI = new TmpInstruction(mcfi, destVal->getType(),
736                                               srcVal, destVal, "make32");
737     mvec.push_back(BuildMI(V9::SLLXi6, 3).addReg(srcVal)
738                    .addZImm(32-numLowBits).addRegDef(tmpI));
739     srcVal = tmpI;
740   }
741
742   mvec.push_back(BuildMI(signExtend? V9::SRAi5 : V9::SRLi5, 3)
743                  .addReg(srcVal).addZImm(32-numLowBits).addRegDef(destVal));
744 }
745
746
747 // Create instruction sequence to produce a sign-extended register value
748 // from an arbitrary-sized integer value (sized in bits, not bytes).
749 // The generated instructions are returned in `mvec'.
750 // Any temp. registers (TmpInstruction) created are recorded in mcfi.
751 // Any stack space required is allocated via MachineFunction.
752 // 
753 void
754 CreateSignExtensionInstructions(
755                                         const TargetMachine& target,
756                                         Function* F,
757                                         Value* srcVal,
758                                         Value* destVal,
759                                         unsigned int numLowBits,
760                                         std::vector<MachineInstr*>& mvec,
761                                         MachineCodeForInstruction& mcfi)
762 {
763   CreateBitExtensionInstructions(/*signExtend*/ true, target, F, srcVal,
764                                  destVal, numLowBits, mvec, mcfi);
765 }
766
767
768 // Create instruction sequence to produce a zero-extended register value
769 // from an arbitrary-sized integer value (sized in bits, not bytes).
770 // For SPARC v9, we sign-extend the given operand using SLL; SRL.
771 // The generated instructions are returned in `mvec'.
772 // Any temp. registers (TmpInstruction) created are recorded in mcfi.
773 // Any stack space required is allocated via MachineFunction.
774 // 
775 void
776 CreateZeroExtensionInstructions(
777                                         const TargetMachine& target,
778                                         Function* F,
779                                         Value* srcVal,
780                                         Value* destVal,
781                                         unsigned int numLowBits,
782                                         std::vector<MachineInstr*>& mvec,
783                                         MachineCodeForInstruction& mcfi)
784 {
785   CreateBitExtensionInstructions(/*signExtend*/ false, target, F, srcVal,
786                                  destVal, numLowBits, mvec, mcfi);
787 }
788
789 } // End llvm namespace