1 //===-- PPC32ISelSimple.cpp - A simple instruction selector PowerPC32 -----===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 #define DEBUG_TYPE "isel"
12 #include "PowerPCInstrBuilder.h"
13 #include "PowerPCInstrInfo.h"
14 #include "PPC32TargetMachine.h"
15 #include "llvm/Constants.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Function.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Pass.h"
20 #include "llvm/CodeGen/IntrinsicLowering.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/SSARegMap.h"
25 #include "llvm/Target/MRegisterInfo.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Support/GetElementPtrTypeIterator.h"
28 #include "llvm/Support/InstVisitor.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/ADT/Statistic.h"
35 /// TypeClass - Used by the PowerPC backend to group LLVM types by their basic
36 /// PPC Representation.
39 cByte, cShort, cInt, cFP32, cFP64, cLong
43 /// getClass - Turn a primitive type into a "class" number which is based on the
44 /// size of the type, and whether or not it is floating point.
46 static inline TypeClass getClass(const Type *Ty) {
47 switch (Ty->getTypeID()) {
49 case Type::UByteTyID: return cByte; // Byte operands are class #0
51 case Type::UShortTyID: return cShort; // Short operands are class #1
54 case Type::PointerTyID: return cInt; // Ints and pointers are class #2
56 case Type::FloatTyID: return cFP32; // Single float is #3
57 case Type::DoubleTyID: return cFP64; // Double Point is #4
60 case Type::ULongTyID: return cLong; // Longs are class #5
62 assert(0 && "Invalid type to getClass!");
63 return cByte; // not reached
67 // getClassB - Just like getClass, but treat boolean values as ints.
68 static inline TypeClass getClassB(const Type *Ty) {
69 if (Ty == Type::BoolTy) return cByte;
74 struct ISel : public FunctionPass, InstVisitor<ISel> {
75 PPC32TargetMachine &TM;
76 MachineFunction *F; // The function we are compiling into
77 MachineBasicBlock *BB; // The current MBB we are compiling
78 int VarArgsFrameIndex; // FrameIndex for start of varargs area
80 std::map<Value*, unsigned> RegMap; // Mapping between Values and SSA Regs
82 // External functions used in the Module
83 Function *fmodfFn, *fmodFn, *__cmpdi2Fn, *__moddi3Fn, *__divdi3Fn,
84 *__umoddi3Fn, *__udivdi3Fn, *__fixsfdiFn, *__fixdfdiFn, *__fixunssfdiFn,
85 *__fixunsdfdiFn, *__floatdisfFn, *__floatdidfFn, *mallocFn, *freeFn;
87 // MBBMap - Mapping between LLVM BB -> Machine BB
88 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
90 // AllocaMap - Mapping from fixed sized alloca instructions to the
91 // FrameIndex for the alloca.
92 std::map<AllocaInst*, unsigned> AllocaMap;
94 // A Reg to hold the base address used for global loads and stores, and a
95 // flag to set whether or not we need to emit it for this function.
96 unsigned GlobalBaseReg;
97 bool GlobalBaseInitialized;
99 ISel(TargetMachine &tm) : TM(reinterpret_cast<PPC32TargetMachine&>(tm)),
102 bool doInitialization(Module &M) {
103 // Add external functions that we may call
104 Type *i = Type::IntTy;
105 Type *d = Type::DoubleTy;
106 Type *f = Type::FloatTy;
107 Type *l = Type::LongTy;
108 Type *ul = Type::ULongTy;
109 Type *voidPtr = PointerType::get(Type::SByteTy);
110 // float fmodf(float, float);
111 fmodfFn = M.getOrInsertFunction("fmodf", f, f, f, 0);
112 // double fmod(double, double);
113 fmodFn = M.getOrInsertFunction("fmod", d, d, d, 0);
114 // int __cmpdi2(long, long);
115 __cmpdi2Fn = M.getOrInsertFunction("__cmpdi2", i, l, l, 0);
116 // long __moddi3(long, long);
117 __moddi3Fn = M.getOrInsertFunction("__moddi3", l, l, l, 0);
118 // long __divdi3(long, long);
119 __divdi3Fn = M.getOrInsertFunction("__divdi3", l, l, l, 0);
120 // unsigned long __umoddi3(unsigned long, unsigned long);
121 __umoddi3Fn = M.getOrInsertFunction("__umoddi3", ul, ul, ul, 0);
122 // unsigned long __udivdi3(unsigned long, unsigned long);
123 __udivdi3Fn = M.getOrInsertFunction("__udivdi3", ul, ul, ul, 0);
124 // long __fixsfdi(float)
125 __fixsfdiFn = M.getOrInsertFunction("__fixsfdi", l, f, 0);
126 // long __fixdfdi(double)
127 __fixdfdiFn = M.getOrInsertFunction("__fixdfdi", l, d, 0);
128 // unsigned long __fixunssfdi(float)
129 __fixunssfdiFn = M.getOrInsertFunction("__fixunssfdi", ul, f, 0);
130 // unsigned long __fixunsdfdi(double)
131 __fixunsdfdiFn = M.getOrInsertFunction("__fixunsdfdi", ul, d, 0);
132 // float __floatdisf(long)
133 __floatdisfFn = M.getOrInsertFunction("__floatdisf", f, l, 0);
134 // double __floatdidf(long)
135 __floatdidfFn = M.getOrInsertFunction("__floatdidf", d, l, 0);
136 // void* malloc(size_t)
137 mallocFn = M.getOrInsertFunction("malloc", voidPtr, Type::UIntTy, 0);
139 freeFn = M.getOrInsertFunction("free", Type::VoidTy, voidPtr, 0);
143 /// runOnFunction - Top level implementation of instruction selection for
144 /// the entire function.
146 bool runOnFunction(Function &Fn) {
147 // First pass over the function, lower any unknown intrinsic functions
148 // with the IntrinsicLowering class.
149 LowerUnknownIntrinsicFunctionCalls(Fn);
151 F = &MachineFunction::construct(&Fn, TM);
153 // Create all of the machine basic blocks for the function...
154 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
155 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
159 // Make sure we re-emit a set of the global base reg if necessary
160 GlobalBaseInitialized = false;
162 // Copy incoming arguments off of the stack...
163 LoadArgumentsToVirtualRegs(Fn);
165 // Instruction select everything except PHI nodes
168 // Select the PHI nodes
175 // We always build a machine code representation for the function
179 virtual const char *getPassName() const {
180 return "PowerPC Simple Instruction Selection";
183 /// visitBasicBlock - This method is called when we are visiting a new basic
184 /// block. This simply creates a new MachineBasicBlock to emit code into
185 /// and adds it to the current MachineFunction. Subsequent visit* for
186 /// instructions will be invoked for all instructions in the basic block.
188 void visitBasicBlock(BasicBlock &LLVM_BB) {
189 BB = MBBMap[&LLVM_BB];
192 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
193 /// function, lowering any calls to unknown intrinsic functions into the
194 /// equivalent LLVM code.
196 void LowerUnknownIntrinsicFunctionCalls(Function &F);
198 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
199 /// from the stack into virtual registers.
201 void LoadArgumentsToVirtualRegs(Function &F);
203 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
204 /// because we have to generate our sources into the source basic blocks,
205 /// not the current one.
207 void SelectPHINodes();
209 // Visitation methods for various instructions. These methods simply emit
210 // fixed PowerPC code for each instruction.
212 // Control flow operators
213 void visitReturnInst(ReturnInst &RI);
214 void visitBranchInst(BranchInst &BI);
220 ValueRecord(unsigned R, const Type *T) : Val(0), Reg(R), Ty(T) {}
221 ValueRecord(Value *V) : Val(V), Reg(0), Ty(V->getType()) {}
224 // This struct is for recording the necessary operations to emit the GEP
225 struct CollapsedGepOp {
229 CollapsedGepOp(bool mul, Value *i, ConstantSInt *s) :
230 isMul(mul), index(i), size(s) {}
233 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
234 const std::vector<ValueRecord> &Args, bool isVarArg);
235 void visitCallInst(CallInst &I);
236 void visitIntrinsicCall(Intrinsic::ID ID, CallInst &I);
238 // Arithmetic operators
239 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
240 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
241 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
242 void visitMul(BinaryOperator &B);
244 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
245 void visitRem(BinaryOperator &B) { visitDivRem(B); }
246 void visitDivRem(BinaryOperator &B);
249 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
250 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
251 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
253 // Comparison operators...
254 void visitSetCondInst(SetCondInst &I);
255 unsigned EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
256 MachineBasicBlock *MBB,
257 MachineBasicBlock::iterator MBBI);
258 void visitSelectInst(SelectInst &SI);
261 // Memory Instructions
262 void visitLoadInst(LoadInst &I);
263 void visitStoreInst(StoreInst &I);
264 void visitGetElementPtrInst(GetElementPtrInst &I);
265 void visitAllocaInst(AllocaInst &I);
266 void visitMallocInst(MallocInst &I);
267 void visitFreeInst(FreeInst &I);
270 void visitShiftInst(ShiftInst &I);
271 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
272 void visitCastInst(CastInst &I);
273 void visitVANextInst(VANextInst &I);
274 void visitVAArgInst(VAArgInst &I);
276 void visitInstruction(Instruction &I) {
277 std::cerr << "Cannot instruction select: " << I;
281 unsigned ExtendOrClear(MachineBasicBlock *MBB,
282 MachineBasicBlock::iterator IP,
283 Value *Op0, Value *Op1);
285 /// promote32 - Make a value 32-bits wide, and put it somewhere.
287 void promote32(unsigned targetReg, const ValueRecord &VR);
289 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
290 /// constant expression GEP support.
292 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
293 Value *Src, User::op_iterator IdxBegin,
294 User::op_iterator IdxEnd, unsigned TargetReg,
295 bool CollapseRemainder, ConstantSInt **Remainder,
296 unsigned *PendingAddReg);
298 /// emitCastOperation - Common code shared between visitCastInst and
299 /// constant expression cast support.
301 void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
302 Value *Src, const Type *DestTy, unsigned TargetReg);
304 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
305 /// and constant expression support.
307 void emitSimpleBinaryOperation(MachineBasicBlock *BB,
308 MachineBasicBlock::iterator IP,
309 Value *Op0, Value *Op1,
310 unsigned OperatorClass, unsigned TargetReg);
312 /// emitBinaryFPOperation - This method handles emission of floating point
313 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
314 void emitBinaryFPOperation(MachineBasicBlock *BB,
315 MachineBasicBlock::iterator IP,
316 Value *Op0, Value *Op1,
317 unsigned OperatorClass, unsigned TargetReg);
319 void emitMultiply(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
320 Value *Op0, Value *Op1, unsigned TargetReg);
322 void doMultiply(MachineBasicBlock *MBB,
323 MachineBasicBlock::iterator IP,
324 unsigned DestReg, Value *Op0, Value *Op1);
326 /// doMultiplyConst - This method will multiply the value in Op0Reg by the
327 /// value of the ContantInt *CI
328 void doMultiplyConst(MachineBasicBlock *MBB,
329 MachineBasicBlock::iterator IP,
330 unsigned DestReg, Value *Op0, ConstantInt *CI);
332 void emitDivRemOperation(MachineBasicBlock *BB,
333 MachineBasicBlock::iterator IP,
334 Value *Op0, Value *Op1, bool isDiv,
337 /// emitSetCCOperation - Common code shared between visitSetCondInst and
338 /// constant expression support.
340 void emitSetCCOperation(MachineBasicBlock *BB,
341 MachineBasicBlock::iterator IP,
342 Value *Op0, Value *Op1, unsigned Opcode,
345 /// emitShiftOperation - Common code shared between visitShiftInst and
346 /// constant expression support.
348 void emitShiftOperation(MachineBasicBlock *MBB,
349 MachineBasicBlock::iterator IP,
350 Value *Op, Value *ShiftAmount, bool isLeftShift,
351 const Type *ResultTy, unsigned DestReg);
353 /// emitSelectOperation - Common code shared between visitSelectInst and the
354 /// constant expression support.
356 void emitSelectOperation(MachineBasicBlock *MBB,
357 MachineBasicBlock::iterator IP,
358 Value *Cond, Value *TrueVal, Value *FalseVal,
361 /// copyGlobalBaseToRegister - Output the instructions required to put the
362 /// base address to use for accessing globals into a register.
364 void ISel::copyGlobalBaseToRegister(MachineBasicBlock *MBB,
365 MachineBasicBlock::iterator IP,
368 /// copyConstantToRegister - Output the instructions required to put the
369 /// specified constant into the specified register.
371 void copyConstantToRegister(MachineBasicBlock *MBB,
372 MachineBasicBlock::iterator MBBI,
373 Constant *C, unsigned Reg);
375 void emitUCOM(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
376 unsigned LHS, unsigned RHS);
378 /// makeAnotherReg - This method returns the next register number we haven't
381 /// Long values are handled somewhat specially. They are always allocated
382 /// as pairs of 32 bit integer values. The register number returned is the
383 /// high 32 bits of the long value, and the regNum+1 is the low 32 bits.
385 unsigned makeAnotherReg(const Type *Ty) {
386 assert(dynamic_cast<const PPC32RegisterInfo*>(TM.getRegisterInfo()) &&
387 "Current target doesn't have PPC reg info??");
388 const PPC32RegisterInfo *PPCRI =
389 static_cast<const PPC32RegisterInfo*>(TM.getRegisterInfo());
390 if (Ty == Type::LongTy || Ty == Type::ULongTy) {
391 const TargetRegisterClass *RC = PPCRI->getRegClassForType(Type::IntTy);
392 // Create the upper part
393 F->getSSARegMap()->createVirtualRegister(RC);
394 // Create the lower part.
395 return F->getSSARegMap()->createVirtualRegister(RC)-1;
398 // Add the mapping of regnumber => reg class to MachineFunction
399 const TargetRegisterClass *RC = PPCRI->getRegClassForType(Ty);
400 return F->getSSARegMap()->createVirtualRegister(RC);
403 /// getReg - This method turns an LLVM value into a register number.
405 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
406 unsigned getReg(Value *V) {
407 // Just append to the end of the current bb.
408 MachineBasicBlock::iterator It = BB->end();
409 return getReg(V, BB, It);
411 unsigned getReg(Value *V, MachineBasicBlock *MBB,
412 MachineBasicBlock::iterator IPt);
414 /// canUseAsImmediateForOpcode - This method returns whether a ConstantInt
415 /// is okay to use as an immediate argument to a certain binary operation
416 bool canUseAsImmediateForOpcode(ConstantInt *CI, unsigned Opcode);
418 /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
419 /// that is to be statically allocated with the initial stack frame
421 unsigned getFixedSizedAllocaFI(AllocaInst *AI);
425 /// dyn_castFixedAlloca - If the specified value is a fixed size alloca
426 /// instruction in the entry block, return it. Otherwise, return a null
428 static AllocaInst *dyn_castFixedAlloca(Value *V) {
429 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
430 BasicBlock *BB = AI->getParent();
431 if (isa<ConstantUInt>(AI->getArraySize()) && BB ==&BB->getParent()->front())
437 /// getReg - This method turns an LLVM value into a register number.
439 unsigned ISel::getReg(Value *V, MachineBasicBlock *MBB,
440 MachineBasicBlock::iterator IPt) {
441 if (Constant *C = dyn_cast<Constant>(V)) {
442 unsigned Reg = makeAnotherReg(V->getType());
443 copyConstantToRegister(MBB, IPt, C, Reg);
445 } else if (AllocaInst *AI = dyn_castFixedAlloca(V)) {
446 unsigned Reg = makeAnotherReg(V->getType());
447 unsigned FI = getFixedSizedAllocaFI(AI);
448 addFrameReference(BuildMI(*MBB, IPt, PPC::ADDI, 2, Reg), FI, 0, false);
452 unsigned &Reg = RegMap[V];
454 Reg = makeAnotherReg(V->getType());
461 /// canUseAsImmediateForOpcode - This method returns whether a ConstantInt
462 /// is okay to use as an immediate argument to a certain binary operator.
464 /// Operator is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for Xor.
465 bool ISel::canUseAsImmediateForOpcode(ConstantInt *CI, unsigned Operator) {
469 // ADDI, Compare, and non-indexed Load take SIMM
470 bool cond1 = (Operator == 0)
471 && (Op1Cs = dyn_cast<ConstantSInt>(CI))
472 && (Op1Cs->getValue() <= 32767)
473 && (Op1Cs->getValue() >= -32768);
475 // SUBI takes -SIMM since it is a mnemonic for ADDI
476 bool cond2 = (Operator == 1)
477 && (Op1Cs = dyn_cast<ConstantSInt>(CI))
478 && (Op1Cs->getValue() <= 32768)
479 && (Op1Cs->getValue() >= -32767);
481 // ANDIo, ORI, and XORI take unsigned values
482 bool cond3 = (Operator >= 2)
483 && (Op1Cs = dyn_cast<ConstantSInt>(CI))
484 && (Op1Cs->getValue() >= 0)
485 && (Op1Cs->getValue() <= 32767);
487 // ADDI and SUBI take SIMMs, so we have to make sure the UInt would fit
488 bool cond4 = (Operator < 2)
489 && (Op1Cu = dyn_cast<ConstantUInt>(CI))
490 && (Op1Cu->getValue() <= 32767);
492 // ANDIo, ORI, and XORI take UIMMs, so they can be larger
493 bool cond5 = (Operator >= 2)
494 && (Op1Cu = dyn_cast<ConstantUInt>(CI))
495 && (Op1Cu->getValue() <= 65535);
497 if (cond1 || cond2 || cond3 || cond4 || cond5)
503 /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
504 /// that is to be statically allocated with the initial stack frame
506 unsigned ISel::getFixedSizedAllocaFI(AllocaInst *AI) {
507 // Already computed this?
508 std::map<AllocaInst*, unsigned>::iterator I = AllocaMap.lower_bound(AI);
509 if (I != AllocaMap.end() && I->first == AI) return I->second;
511 const Type *Ty = AI->getAllocatedType();
512 ConstantUInt *CUI = cast<ConstantUInt>(AI->getArraySize());
513 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
514 TySize *= CUI->getValue(); // Get total allocated size...
515 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
517 // Create a new stack object using the frame manager...
518 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
519 AllocaMap.insert(I, std::make_pair(AI, FrameIdx));
524 /// copyGlobalBaseToRegister - Output the instructions required to put the
525 /// base address to use for accessing globals into a register.
527 void ISel::copyGlobalBaseToRegister(MachineBasicBlock *MBB,
528 MachineBasicBlock::iterator IP,
530 if (!GlobalBaseInitialized) {
531 // Insert the set of GlobalBaseReg into the first MBB of the function
532 MachineBasicBlock &FirstMBB = F->front();
533 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
534 GlobalBaseReg = makeAnotherReg(Type::IntTy);
535 BuildMI(FirstMBB, MBBI, PPC::MovePCtoLR, 0, PPC::LR);
536 BuildMI(FirstMBB, MBBI, PPC::MFLR, 0, GlobalBaseReg).addReg(PPC::LR);
537 GlobalBaseInitialized = true;
539 // Emit our copy of GlobalBaseReg to the destination register in the
541 BuildMI(*MBB, IP, PPC::OR, 2, R).addReg(GlobalBaseReg)
542 .addReg(GlobalBaseReg);
545 /// copyConstantToRegister - Output the instructions required to put the
546 /// specified constant into the specified register.
548 void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
549 MachineBasicBlock::iterator IP,
550 Constant *C, unsigned R) {
551 if (C->getType()->isIntegral()) {
552 unsigned Class = getClassB(C->getType());
554 if (Class == cLong) {
555 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(C)) {
556 uint64_t uval = CUI->getValue();
557 unsigned hiUVal = uval >> 32;
558 unsigned loUVal = uval;
559 ConstantUInt *CUHi = ConstantUInt::get(Type::UIntTy, hiUVal);
560 ConstantUInt *CULo = ConstantUInt::get(Type::UIntTy, loUVal);
561 copyConstantToRegister(MBB, IP, CUHi, R);
562 copyConstantToRegister(MBB, IP, CULo, R+1);
564 } else if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(C)) {
565 int64_t sval = CSI->getValue();
566 int hiSVal = sval >> 32;
568 ConstantSInt *CSHi = ConstantSInt::get(Type::IntTy, hiSVal);
569 ConstantSInt *CSLo = ConstantSInt::get(Type::IntTy, loSVal);
570 copyConstantToRegister(MBB, IP, CSHi, R);
571 copyConstantToRegister(MBB, IP, CSLo, R+1);
574 std::cerr << "Unhandled long constant type!\n";
579 assert(Class <= cInt && "Type not handled yet!");
582 if (C->getType() == Type::BoolTy) {
583 BuildMI(*MBB, IP, PPC::LI, 1, R).addSImm(C == ConstantBool::True);
588 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(C)) {
589 unsigned uval = CUI->getValue();
591 BuildMI(*MBB, IP, PPC::LI, 1, R).addSImm(uval);
593 unsigned Temp = makeAnotherReg(Type::IntTy);
594 BuildMI(*MBB, IP, PPC::LIS, 1, Temp).addSImm(uval >> 16);
595 BuildMI(*MBB, IP, PPC::ORI, 2, R).addReg(Temp).addImm(uval);
598 } else if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(C)) {
599 int sval = CSI->getValue();
600 if (sval < 32768 && sval >= -32768) {
601 BuildMI(*MBB, IP, PPC::LI, 1, R).addSImm(sval);
603 unsigned Temp = makeAnotherReg(Type::IntTy);
604 BuildMI(*MBB, IP, PPC::LIS, 1, Temp).addSImm(sval >> 16);
605 BuildMI(*MBB, IP, PPC::ORI, 2, R).addReg(Temp).addImm(sval);
609 std::cerr << "Unhandled integer constant!\n";
611 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
612 // We need to spill the constant to memory...
613 MachineConstantPool *CP = F->getConstantPool();
614 unsigned CPI = CP->getConstantPoolIndex(CFP);
615 const Type *Ty = CFP->getType();
617 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
619 // Load addr of constant to reg; constant is located at base + distance
620 unsigned GlobalBase = makeAnotherReg(Type::IntTy);
621 unsigned Reg1 = makeAnotherReg(Type::IntTy);
622 unsigned Opcode = (Ty == Type::FloatTy) ? PPC::LFS : PPC::LFD;
623 // Move value at base + distance into return reg
624 copyGlobalBaseToRegister(MBB, IP, GlobalBase);
625 BuildMI(*MBB, IP, PPC::LOADHiAddr, 2, Reg1).addReg(GlobalBase)
626 .addConstantPoolIndex(CPI);
627 BuildMI(*MBB, IP, Opcode, 2, R).addConstantPoolIndex(CPI).addReg(Reg1);
628 } else if (isa<ConstantPointerNull>(C)) {
629 // Copy zero (null pointer) to the register.
630 BuildMI(*MBB, IP, PPC::LI, 1, R).addSImm(0);
631 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
632 // GV is located at base + distance
634 unsigned GlobalBase = makeAnotherReg(Type::IntTy);
635 unsigned TmpReg = makeAnotherReg(GV->getType());
636 unsigned Opcode = (GV->hasWeakLinkage()
638 || dyn_cast<Function>(GV)) ? PPC::LWZ : PPC::LA;
640 // Move value at base + distance into return reg
641 copyGlobalBaseToRegister(MBB, IP, GlobalBase);
642 BuildMI(*MBB, IP, PPC::LOADHiAddr, 2, TmpReg).addReg(GlobalBase)
643 .addGlobalAddress(GV);
644 BuildMI(*MBB, IP, Opcode, 2, R).addGlobalAddress(GV).addReg(TmpReg);
646 // Add the GV to the list of things whose addresses have been taken.
647 TM.AddressTaken.insert(GV);
649 std::cerr << "Offending constant: " << *C << "\n";
650 assert(0 && "Type not handled yet!");
654 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
655 /// the stack into virtual registers.
656 void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
657 unsigned ArgOffset = 24;
658 unsigned GPR_remaining = 8;
659 unsigned FPR_remaining = 13;
660 unsigned GPR_idx = 0, FPR_idx = 0;
661 static const unsigned GPR[] = {
662 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
663 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
665 static const unsigned FPR[] = {
666 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
667 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
670 MachineFrameInfo *MFI = F->getFrameInfo();
672 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
673 bool ArgLive = !I->use_empty();
674 unsigned Reg = ArgLive ? getReg(*I) : 0;
675 int FI; // Frame object index
677 switch (getClassB(I->getType())) {
680 FI = MFI->CreateFixedObject(4, ArgOffset);
681 if (GPR_remaining > 0) {
682 BuildMI(BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx]);
683 BuildMI(BB, PPC::OR, 2, Reg).addReg(GPR[GPR_idx])
684 .addReg(GPR[GPR_idx]);
686 addFrameReference(BuildMI(BB, PPC::LBZ, 2, Reg), FI);
692 FI = MFI->CreateFixedObject(4, ArgOffset);
693 if (GPR_remaining > 0) {
694 BuildMI(BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx]);
695 BuildMI(BB, PPC::OR, 2, Reg).addReg(GPR[GPR_idx])
696 .addReg(GPR[GPR_idx]);
698 addFrameReference(BuildMI(BB, PPC::LHZ, 2, Reg), FI);
704 FI = MFI->CreateFixedObject(4, ArgOffset);
705 if (GPR_remaining > 0) {
706 BuildMI(BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx]);
707 BuildMI(BB, PPC::OR, 2, Reg).addReg(GPR[GPR_idx])
708 .addReg(GPR[GPR_idx]);
710 addFrameReference(BuildMI(BB, PPC::LWZ, 2, Reg), FI);
716 FI = MFI->CreateFixedObject(8, ArgOffset);
717 if (GPR_remaining > 1) {
718 BuildMI(BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx]);
719 BuildMI(BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx+1]);
720 BuildMI(BB, PPC::OR, 2, Reg).addReg(GPR[GPR_idx])
721 .addReg(GPR[GPR_idx]);
722 BuildMI(BB, PPC::OR, 2, Reg+1).addReg(GPR[GPR_idx+1])
723 .addReg(GPR[GPR_idx+1]);
725 addFrameReference(BuildMI(BB, PPC::LWZ, 2, Reg), FI);
726 addFrameReference(BuildMI(BB, PPC::LWZ, 2, Reg+1), FI, 4);
729 // longs require 4 additional bytes and use 2 GPRs
731 if (GPR_remaining > 1) {
738 FI = MFI->CreateFixedObject(4, ArgOffset);
740 if (FPR_remaining > 0) {
741 BuildMI(BB, PPC::IMPLICIT_DEF, 0, FPR[FPR_idx]);
742 BuildMI(BB, PPC::FMR, 1, Reg).addReg(FPR[FPR_idx]);
746 addFrameReference(BuildMI(BB, PPC::LFS, 2, Reg), FI);
752 FI = MFI->CreateFixedObject(8, ArgOffset);
754 if (FPR_remaining > 0) {
755 BuildMI(BB, PPC::IMPLICIT_DEF, 0, FPR[FPR_idx]);
756 BuildMI(BB, PPC::FMR, 1, Reg).addReg(FPR[FPR_idx]);
760 addFrameReference(BuildMI(BB, PPC::LFD, 2, Reg), FI);
764 // doubles require 4 additional bytes and use 2 GPRs of param space
766 if (GPR_remaining > 0) {
772 assert(0 && "Unhandled argument type!");
774 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
775 if (GPR_remaining > 0) {
776 GPR_remaining--; // uses up 2 GPRs
781 // If the function takes variable number of arguments, add a frame offset for
782 // the start of the first vararg value... this is used to expand
784 if (Fn.getFunctionType()->isVarArg())
785 VarArgsFrameIndex = MFI->CreateFixedObject(4, ArgOffset);
789 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
790 /// because we have to generate our sources into the source basic blocks, not
793 void ISel::SelectPHINodes() {
794 const TargetInstrInfo &TII = *TM.getInstrInfo();
795 const Function &LF = *F->getFunction(); // The LLVM function...
796 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
797 const BasicBlock *BB = I;
798 MachineBasicBlock &MBB = *MBBMap[I];
800 // Loop over all of the PHI nodes in the LLVM basic block...
801 MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
802 for (BasicBlock::const_iterator I = BB->begin();
803 PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
805 // Create a new machine instr PHI node, and insert it.
806 unsigned PHIReg = getReg(*PN);
807 MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
808 PPC::PHI, PN->getNumOperands(), PHIReg);
810 MachineInstr *LongPhiMI = 0;
811 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
812 LongPhiMI = BuildMI(MBB, PHIInsertPoint,
813 PPC::PHI, PN->getNumOperands(), PHIReg+1);
815 // PHIValues - Map of blocks to incoming virtual registers. We use this
816 // so that we only initialize one incoming value for a particular block,
817 // even if the block has multiple entries in the PHI node.
819 std::map<MachineBasicBlock*, unsigned> PHIValues;
821 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
822 MachineBasicBlock *PredMBB = 0;
823 for (MachineBasicBlock::pred_iterator PI = MBB.pred_begin (),
824 PE = MBB.pred_end (); PI != PE; ++PI)
825 if (PN->getIncomingBlock(i) == (*PI)->getBasicBlock()) {
829 assert (PredMBB && "Couldn't find incoming machine-cfg edge for phi");
832 std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
833 PHIValues.lower_bound(PredMBB);
835 if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
836 // We already inserted an initialization of the register for this
837 // predecessor. Recycle it.
838 ValReg = EntryIt->second;
840 // Get the incoming value into a virtual register.
842 Value *Val = PN->getIncomingValue(i);
844 // If this is a constant or GlobalValue, we may have to insert code
845 // into the basic block to compute it into a virtual register.
846 if ((isa<Constant>(Val) && !isa<ConstantExpr>(Val)) ||
847 isa<GlobalValue>(Val)) {
848 // Simple constants get emitted at the end of the basic block,
849 // before any terminator instructions. We "know" that the code to
850 // move a constant into a register will never clobber any flags.
851 ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
853 // Because we don't want to clobber any values which might be in
854 // physical registers with the computation of this constant (which
855 // might be arbitrarily complex if it is a constant expression),
856 // just insert the computation at the top of the basic block.
857 MachineBasicBlock::iterator PI = PredMBB->begin();
859 // Skip over any PHI nodes though!
860 while (PI != PredMBB->end() && PI->getOpcode() == PPC::PHI)
863 ValReg = getReg(Val, PredMBB, PI);
866 // Remember that we inserted a value for this PHI for this predecessor
867 PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
870 PhiMI->addRegOperand(ValReg);
871 PhiMI->addMachineBasicBlockOperand(PredMBB);
873 LongPhiMI->addRegOperand(ValReg+1);
874 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
878 // Now that we emitted all of the incoming values for the PHI node, make
879 // sure to reposition the InsertPoint after the PHI that we just added.
880 // This is needed because we might have inserted a constant into this
881 // block, right after the PHI's which is before the old insert point!
882 PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
889 // canFoldSetCCIntoBranchOrSelect - Return the setcc instruction if we can fold
890 // it into the conditional branch or select instruction which is the only user
891 // of the cc instruction. This is the case if the conditional branch is the
892 // only user of the setcc, and if the setcc is in the same basic block as the
893 // conditional branch.
895 static SetCondInst *canFoldSetCCIntoBranchOrSelect(Value *V) {
896 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
897 if (SCI->hasOneUse()) {
898 Instruction *User = cast<Instruction>(SCI->use_back());
899 if ((isa<BranchInst>(User) || isa<SelectInst>(User)) &&
900 SCI->getParent() == User->getParent())
907 // canFoldGEPIntoLoadOrStore - Return the GEP instruction if we can fold it into
908 // the load or store instruction that is the only user of the GEP.
910 static GetElementPtrInst *canFoldGEPIntoLoadOrStore(Value *V) {
911 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V))
912 if (GEPI->hasOneUse()) {
913 Instruction *User = cast<Instruction>(GEPI->use_back());
914 if (isa<StoreInst>(User) &&
915 GEPI->getParent() == User->getParent() &&
916 User->getOperand(0) != GEPI &&
917 User->getOperand(1) == GEPI) {
920 if (isa<LoadInst>(User) &&
921 GEPI->getParent() == User->getParent() &&
922 User->getOperand(0) == GEPI) {
930 // Return a fixed numbering for setcc instructions which does not depend on the
931 // order of the opcodes.
933 static unsigned getSetCCNumber(unsigned Opcode) {
935 default: assert(0 && "Unknown setcc instruction!");
936 case Instruction::SetEQ: return 0;
937 case Instruction::SetNE: return 1;
938 case Instruction::SetLT: return 2;
939 case Instruction::SetGE: return 3;
940 case Instruction::SetGT: return 4;
941 case Instruction::SetLE: return 5;
945 static unsigned getPPCOpcodeForSetCCNumber(unsigned Opcode) {
947 default: assert(0 && "Unknown setcc instruction!");
948 case Instruction::SetEQ: return PPC::BEQ;
949 case Instruction::SetNE: return PPC::BNE;
950 case Instruction::SetLT: return PPC::BLT;
951 case Instruction::SetGE: return PPC::BGE;
952 case Instruction::SetGT: return PPC::BGT;
953 case Instruction::SetLE: return PPC::BLE;
957 /// emitUCOM - emits an unordered FP compare.
958 void ISel::emitUCOM(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
959 unsigned LHS, unsigned RHS) {
960 BuildMI(*MBB, IP, PPC::FCMPU, 2, PPC::CR0).addReg(LHS).addReg(RHS);
963 unsigned ISel::ExtendOrClear(MachineBasicBlock *MBB,
964 MachineBasicBlock::iterator IP,
965 Value *Op0, Value *Op1) {
966 const Type *CompTy = Op0->getType();
967 unsigned Reg = getReg(Op0, MBB, IP);
968 unsigned Class = getClassB(CompTy);
970 // Before we do a comparison or SetCC, we have to make sure that we truncate
971 // the source registers appropriately.
972 if (Class == cByte) {
973 unsigned TmpReg = makeAnotherReg(CompTy);
974 if (CompTy->isSigned())
975 BuildMI(*MBB, IP, PPC::EXTSB, 1, TmpReg).addReg(Reg);
977 BuildMI(*MBB, IP, PPC::RLWINM, 4, TmpReg).addReg(Reg).addImm(0)
978 .addImm(24).addImm(31);
980 } else if (Class == cShort) {
981 unsigned TmpReg = makeAnotherReg(CompTy);
982 if (CompTy->isSigned())
983 BuildMI(*MBB, IP, PPC::EXTSH, 1, TmpReg).addReg(Reg);
985 BuildMI(*MBB, IP, PPC::RLWINM, 4, TmpReg).addReg(Reg).addImm(0)
986 .addImm(16).addImm(31);
992 /// EmitComparison - emits a comparison of the two operands, returning the
993 /// extended setcc code to use. The result is in CR0.
995 unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
996 MachineBasicBlock *MBB,
997 MachineBasicBlock::iterator IP) {
998 // The arguments are already supposed to be of the same type.
999 const Type *CompTy = Op0->getType();
1000 unsigned Class = getClassB(CompTy);
1001 unsigned Op0r = ExtendOrClear(MBB, IP, Op0, Op1);
1003 // Use crand for lt, gt and crandc for le, ge
1004 unsigned CROpcode = (OpNum == 2 || OpNum == 4) ? PPC::CRAND : PPC::CRANDC;
1005 // ? cr1[lt] : cr1[gt]
1006 unsigned CR1field = (OpNum == 2 || OpNum == 3) ? 4 : 5;
1007 // ? cr0[lt] : cr0[gt]
1008 unsigned CR0field = (OpNum == 2 || OpNum == 5) ? 0 : 1;
1009 unsigned Opcode = CompTy->isSigned() ? PPC::CMPW : PPC::CMPLW;
1010 unsigned OpcodeImm = CompTy->isSigned() ? PPC::CMPWI : PPC::CMPLWI;
1012 // Special case handling of: cmp R, i
1013 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1014 if (Class == cByte || Class == cShort || Class == cInt) {
1015 unsigned Op1v = CI->getRawValue() & 0xFFFF;
1016 unsigned OpClass = (CompTy->isSigned()) ? 0 : 2;
1018 // Treat compare like ADDI for the purposes of immediate suitability
1019 if (canUseAsImmediateForOpcode(CI, OpClass)) {
1020 BuildMI(*MBB, IP, OpcodeImm, 2, PPC::CR0).addReg(Op0r).addSImm(Op1v);
1022 unsigned Op1r = getReg(Op1, MBB, IP);
1023 BuildMI(*MBB, IP, Opcode, 2, PPC::CR0).addReg(Op0r).addReg(Op1r);
1027 assert(Class == cLong && "Unknown integer class!");
1028 unsigned LowCst = CI->getRawValue();
1029 unsigned HiCst = CI->getRawValue() >> 32;
1030 if (OpNum < 2) { // seteq, setne
1031 unsigned LoLow = makeAnotherReg(Type::IntTy);
1032 unsigned LoTmp = makeAnotherReg(Type::IntTy);
1033 unsigned HiLow = makeAnotherReg(Type::IntTy);
1034 unsigned HiTmp = makeAnotherReg(Type::IntTy);
1035 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
1037 BuildMI(*MBB, IP, PPC::XORI, 2, LoLow).addReg(Op0r+1)
1038 .addImm(LowCst & 0xFFFF);
1039 BuildMI(*MBB, IP, PPC::XORIS, 2, LoTmp).addReg(LoLow)
1040 .addImm(LowCst >> 16);
1041 BuildMI(*MBB, IP, PPC::XORI, 2, HiLow).addReg(Op0r)
1042 .addImm(HiCst & 0xFFFF);
1043 BuildMI(*MBB, IP, PPC::XORIS, 2, HiTmp).addReg(HiLow)
1044 .addImm(HiCst >> 16);
1045 BuildMI(*MBB, IP, PPC::ORo, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
1048 unsigned ConstReg = makeAnotherReg(CompTy);
1049 copyConstantToRegister(MBB, IP, CI, ConstReg);
1051 // cr0 = r3 ccOpcode r5 or (r3 == r5 AND r4 ccOpcode r6)
1052 BuildMI(*MBB, IP, Opcode, 2, PPC::CR0).addReg(Op0r)
1054 BuildMI(*MBB, IP, Opcode, 2, PPC::CR1).addReg(Op0r+1)
1055 .addReg(ConstReg+1);
1056 BuildMI(*MBB, IP, PPC::CRAND, 3).addImm(2).addImm(2).addImm(CR1field);
1057 BuildMI(*MBB, IP, PPC::CROR, 3).addImm(CR0field).addImm(CR0field)
1064 unsigned Op1r = getReg(Op1, MBB, IP);
1067 default: assert(0 && "Unknown type class!");
1071 BuildMI(*MBB, IP, Opcode, 2, PPC::CR0).addReg(Op0r).addReg(Op1r);
1076 emitUCOM(MBB, IP, Op0r, Op1r);
1080 if (OpNum < 2) { // seteq, setne
1081 unsigned LoTmp = makeAnotherReg(Type::IntTy);
1082 unsigned HiTmp = makeAnotherReg(Type::IntTy);
1083 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
1084 BuildMI(*MBB, IP, PPC::XOR, 2, HiTmp).addReg(Op0r).addReg(Op1r);
1085 BuildMI(*MBB, IP, PPC::XOR, 2, LoTmp).addReg(Op0r+1).addReg(Op1r+1);
1086 BuildMI(*MBB, IP, PPC::ORo, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
1087 break; // Allow the sete or setne to be generated from flags set by OR
1089 unsigned TmpReg1 = makeAnotherReg(Type::IntTy);
1090 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
1092 // cr0 = r3 ccOpcode r5 or (r3 == r5 AND r4 ccOpcode r6)
1093 BuildMI(*MBB, IP, Opcode, 2, PPC::CR0).addReg(Op0r).addReg(Op1r);
1094 BuildMI(*MBB, IP, Opcode, 2, PPC::CR1).addReg(Op0r+1).addReg(Op1r+1);
1095 BuildMI(*MBB, IP, PPC::CRAND, 3).addImm(2).addImm(2).addImm(CR1field);
1096 BuildMI(*MBB, IP, PPC::CROR, 3).addImm(CR0field).addImm(CR0field)
1104 /// visitSetCondInst - emit code to calculate the condition via
1105 /// EmitComparison(), and possibly store a 0 or 1 to a register as a result
1107 void ISel::visitSetCondInst(SetCondInst &I) {
1108 if (canFoldSetCCIntoBranchOrSelect(&I))
1111 unsigned DestReg = getReg(I);
1112 unsigned Opcode = I.getOpcode();
1113 unsigned PPCOpcode = getPPCOpcodeForSetCCNumber(Opcode);
1115 // Create an iterator with which to insert the MBB for copying the false value
1116 // and the MBB to hold the PHI instruction for this SetCC.
1117 MachineBasicBlock *thisMBB = BB;
1118 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1119 ilist<MachineBasicBlock>::iterator It = BB;
1124 // cmpTY cr0, r1, r2
1125 // %TrueValue = li 1
1127 EmitComparison(Opcode, I.getOperand(0), I.getOperand(1), BB, BB->end());
1128 unsigned TrueValue = makeAnotherReg(I.getType());
1129 BuildMI(BB, PPC::LI, 1, TrueValue).addSImm(1);
1130 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
1131 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
1132 BuildMI(BB, PPCOpcode, 2).addReg(PPC::CR0).addMBB(sinkMBB);
1133 F->getBasicBlockList().insert(It, copy0MBB);
1134 F->getBasicBlockList().insert(It, sinkMBB);
1135 // Update machine-CFG edges
1136 BB->addSuccessor(copy0MBB);
1137 BB->addSuccessor(sinkMBB);
1140 // %FalseValue = li 0
1143 unsigned FalseValue = makeAnotherReg(I.getType());
1144 BuildMI(BB, PPC::LI, 1, FalseValue).addSImm(0);
1145 // Update machine-CFG edges
1146 BB->addSuccessor(sinkMBB);
1149 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1152 BuildMI(BB, PPC::PHI, 4, DestReg).addReg(FalseValue)
1153 .addMBB(copy0MBB).addReg(TrueValue).addMBB(thisMBB);
1156 void ISel::visitSelectInst(SelectInst &SI) {
1157 unsigned DestReg = getReg(SI);
1158 MachineBasicBlock::iterator MII = BB->end();
1159 emitSelectOperation(BB, MII, SI.getCondition(), SI.getTrueValue(),
1160 SI.getFalseValue(), DestReg);
1163 /// emitSelect - Common code shared between visitSelectInst and the constant
1164 /// expression support.
1165 /// FIXME: this is most likely broken in one or more ways. Namely, PowerPC has
1166 /// no select instruction. FSEL only works for comparisons against zero.
1167 void ISel::emitSelectOperation(MachineBasicBlock *MBB,
1168 MachineBasicBlock::iterator IP,
1169 Value *Cond, Value *TrueVal, Value *FalseVal,
1171 unsigned SelectClass = getClassB(TrueVal->getType());
1174 // See if we can fold the setcc into the select instruction, or if we have
1175 // to get the register of the Cond value
1176 if (SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(Cond)) {
1177 // We successfully folded the setcc into the select instruction.
1178 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1179 OpNum = EmitComparison(OpNum, SCI->getOperand(0),SCI->getOperand(1),MBB,IP);
1180 Opcode = getPPCOpcodeForSetCCNumber(SCI->getOpcode());
1182 unsigned CondReg = getReg(Cond, MBB, IP);
1183 BuildMI(*MBB, IP, PPC::CMPWI, 2, PPC::CR0).addReg(CondReg).addSImm(0);
1184 Opcode = getPPCOpcodeForSetCCNumber(Instruction::SetNE);
1186 unsigned TrueValue = getReg(TrueVal, BB, BB->end());
1188 MachineBasicBlock *thisMBB = BB;
1189 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1190 ilist<MachineBasicBlock>::iterator It = BB;
1195 // cmpTY cr0, r1, r2
1198 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
1199 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
1200 BuildMI(BB, Opcode, 2).addReg(PPC::CR0).addMBB(sinkMBB);
1201 F->getBasicBlockList().insert(It, copy0MBB);
1202 F->getBasicBlockList().insert(It, sinkMBB);
1203 // Update machine-CFG edges
1204 BB->addSuccessor(copy0MBB);
1205 BB->addSuccessor(sinkMBB);
1208 // %FalseValue = ...
1211 unsigned FalseValue = getReg(FalseVal, BB, BB->begin());
1212 // Update machine-CFG edges
1213 BB->addSuccessor(sinkMBB);
1216 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1219 BuildMI(BB, PPC::PHI, 4, DestReg).addReg(FalseValue)
1220 .addMBB(copy0MBB).addReg(TrueValue).addMBB(thisMBB);
1222 // For a register pair representing a long value, define the second reg
1223 // FIXME: Can this really be correct for selecting longs?
1224 if (getClassB(TrueVal->getType()) == cLong)
1225 BuildMI(BB, PPC::LI, 1, DestReg+1).addImm(0);
1231 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
1232 /// operand, in the specified target register.
1234 void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
1235 bool isUnsigned = VR.Ty->isUnsigned() || VR.Ty == Type::BoolTy;
1237 Value *Val = VR.Val;
1238 const Type *Ty = VR.Ty;
1240 if (Constant *C = dyn_cast<Constant>(Val)) {
1241 Val = ConstantExpr::getCast(C, Type::IntTy);
1242 if (isa<ConstantExpr>(Val)) // Could not fold
1245 Ty = Type::IntTy; // Folded!
1248 // If this is a simple constant, just emit a load directly to avoid the copy
1249 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
1250 int TheVal = CI->getRawValue() & 0xFFFFFFFF;
1252 if (TheVal < 32768 && TheVal >= -32768) {
1253 BuildMI(BB, PPC::LI, 1, targetReg).addSImm(TheVal);
1255 unsigned TmpReg = makeAnotherReg(Type::IntTy);
1256 BuildMI(BB, PPC::LIS, 1, TmpReg).addSImm(TheVal >> 16);
1257 BuildMI(BB, PPC::ORI, 2, targetReg).addReg(TmpReg)
1258 .addImm(TheVal & 0xFFFF);
1264 // Make sure we have the register number for this value...
1265 unsigned Reg = Val ? getReg(Val) : VR.Reg;
1266 switch (getClassB(Ty)) {
1268 // Extend value into target register (8->32)
1270 BuildMI(BB, PPC::RLWINM, 4, targetReg).addReg(Reg).addZImm(0)
1271 .addZImm(24).addZImm(31);
1273 BuildMI(BB, PPC::EXTSB, 1, targetReg).addReg(Reg);
1276 // Extend value into target register (16->32)
1278 BuildMI(BB, PPC::RLWINM, 4, targetReg).addReg(Reg).addZImm(0)
1279 .addZImm(16).addZImm(31);
1281 BuildMI(BB, PPC::EXTSH, 1, targetReg).addReg(Reg);
1284 // Move value into target register (32->32)
1285 BuildMI(BB, PPC::OR, 2, targetReg).addReg(Reg).addReg(Reg);
1288 assert(0 && "Unpromotable operand class in promote32");
1292 /// visitReturnInst - implemented with BLR
1294 void ISel::visitReturnInst(ReturnInst &I) {
1295 // Only do the processing if this is a non-void return
1296 if (I.getNumOperands() > 0) {
1297 Value *RetVal = I.getOperand(0);
1298 switch (getClassB(RetVal->getType())) {
1299 case cByte: // integral return values: extend or move into r3 and return
1302 promote32(PPC::R3, ValueRecord(RetVal));
1305 case cFP64: { // Floats & Doubles: Return in f1
1306 unsigned RetReg = getReg(RetVal);
1307 BuildMI(BB, PPC::FMR, 1, PPC::F1).addReg(RetReg);
1311 unsigned RetReg = getReg(RetVal);
1312 BuildMI(BB, PPC::OR, 2, PPC::R3).addReg(RetReg).addReg(RetReg);
1313 BuildMI(BB, PPC::OR, 2, PPC::R4).addReg(RetReg+1).addReg(RetReg+1);
1317 visitInstruction(I);
1320 BuildMI(BB, PPC::BLR, 1).addImm(0);
1323 // getBlockAfter - Return the basic block which occurs lexically after the
1325 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1326 Function::iterator I = BB; ++I; // Get iterator to next block
1327 return I != BB->getParent()->end() ? &*I : 0;
1330 /// visitBranchInst - Handle conditional and unconditional branches here. Note
1331 /// that since code layout is frozen at this point, that if we are trying to
1332 /// jump to a block that is the immediate successor of the current block, we can
1333 /// just make a fall-through (but we don't currently).
1335 void ISel::visitBranchInst(BranchInst &BI) {
1336 // Update machine-CFG edges
1337 BB->addSuccessor(MBBMap[BI.getSuccessor(0)]);
1338 if (BI.isConditional())
1339 BB->addSuccessor(MBBMap[BI.getSuccessor(1)]);
1341 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
1343 if (!BI.isConditional()) { // Unconditional branch?
1344 if (BI.getSuccessor(0) != NextBB)
1345 BuildMI(BB, PPC::B, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1349 // See if we can fold the setcc into the branch itself...
1350 SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(BI.getCondition());
1352 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
1353 // computed some other way...
1354 unsigned condReg = getReg(BI.getCondition());
1355 BuildMI(BB, PPC::CMPLI, 3, PPC::CR0).addImm(0).addReg(condReg)
1357 if (BI.getSuccessor(1) == NextBB) {
1358 if (BI.getSuccessor(0) != NextBB)
1359 BuildMI(BB, PPC::COND_BRANCH, 3).addReg(PPC::CR0).addImm(PPC::BNE)
1360 .addMBB(MBBMap[BI.getSuccessor(0)])
1361 .addMBB(MBBMap[BI.getSuccessor(1)]);
1363 BuildMI(BB, PPC::COND_BRANCH, 3).addReg(PPC::CR0).addImm(PPC::BEQ)
1364 .addMBB(MBBMap[BI.getSuccessor(1)])
1365 .addMBB(MBBMap[BI.getSuccessor(0)]);
1366 if (BI.getSuccessor(0) != NextBB)
1367 BuildMI(BB, PPC::B, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1372 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1373 unsigned Opcode = getPPCOpcodeForSetCCNumber(SCI->getOpcode());
1374 MachineBasicBlock::iterator MII = BB->end();
1375 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
1377 if (BI.getSuccessor(0) != NextBB) {
1378 BuildMI(BB, PPC::COND_BRANCH, 3).addReg(PPC::CR0).addImm(Opcode)
1379 .addMBB(MBBMap[BI.getSuccessor(0)])
1380 .addMBB(MBBMap[BI.getSuccessor(1)]);
1381 if (BI.getSuccessor(1) != NextBB)
1382 BuildMI(BB, PPC::B, 1).addMBB(MBBMap[BI.getSuccessor(1)]);
1384 // Change to the inverse condition...
1385 if (BI.getSuccessor(1) != NextBB) {
1386 Opcode = PPC32InstrInfo::invertPPCBranchOpcode(Opcode);
1387 BuildMI(BB, PPC::COND_BRANCH, 3).addReg(PPC::CR0).addImm(Opcode)
1388 .addMBB(MBBMap[BI.getSuccessor(1)])
1389 .addMBB(MBBMap[BI.getSuccessor(0)]);
1394 /// doCall - This emits an abstract call instruction, setting up the arguments
1395 /// and the return value as appropriate. For the actual function call itself,
1396 /// it inserts the specified CallMI instruction into the stream.
1398 /// FIXME: See Documentation at the following URL for "correct" behavior
1399 /// <http://developer.apple.com/documentation/DeveloperTools/Conceptual/MachORuntime/2rt_powerpc_abi/chapter_9_section_5.html>
1400 void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
1401 const std::vector<ValueRecord> &Args, bool isVarArg) {
1402 // Count how many bytes are to be pushed on the stack, including the linkage
1403 // area, and parameter passing area.
1404 unsigned NumBytes = 24;
1405 unsigned ArgOffset = 24;
1407 if (!Args.empty()) {
1408 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1409 switch (getClassB(Args[i].Ty)) {
1410 case cByte: case cShort: case cInt:
1411 NumBytes += 4; break;
1413 NumBytes += 8; break;
1415 NumBytes += 4; break;
1417 NumBytes += 8; break;
1419 default: assert(0 && "Unknown class!");
1422 // Just to be safe, we'll always reserve the full 24 bytes of linkage area
1423 // plus 32 bytes of argument space in case any called code gets funky on us.
1424 if (NumBytes < 56) NumBytes = 56;
1426 // Adjust the stack pointer for the new arguments...
1427 // These functions are automatically eliminated by the prolog/epilog pass
1428 BuildMI(BB, PPC::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
1430 // Arguments go on the stack in reverse order, as specified by the ABI.
1431 // Offset to the paramater area on the stack is 24.
1432 int GPR_remaining = 8, FPR_remaining = 13;
1433 unsigned GPR_idx = 0, FPR_idx = 0;
1434 static const unsigned GPR[] = {
1435 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1436 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1438 static const unsigned FPR[] = {
1439 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6,
1440 PPC::F7, PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12,
1444 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1446 switch (getClassB(Args[i].Ty)) {
1449 // Promote arg to 32 bits wide into a temporary register...
1450 ArgReg = makeAnotherReg(Type::UIntTy);
1451 promote32(ArgReg, Args[i]);
1454 if (GPR_remaining > 0) {
1455 BuildMI(BB, PPC::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1457 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1459 if (GPR_remaining <= 0 || isVarArg) {
1460 BuildMI(BB, PPC::STW, 3).addReg(ArgReg).addSImm(ArgOffset)
1465 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1468 if (GPR_remaining > 0) {
1469 BuildMI(BB, PPC::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1471 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1473 if (GPR_remaining <= 0 || isVarArg) {
1474 BuildMI(BB, PPC::STW, 3).addReg(ArgReg).addSImm(ArgOffset)
1479 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1481 // Reg or stack? Note that PPC calling conventions state that long args
1482 // are passed rN = hi, rN+1 = lo, opposite of LLVM.
1483 if (GPR_remaining > 1) {
1484 BuildMI(BB, PPC::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1486 BuildMI(BB, PPC::OR, 2, GPR[GPR_idx+1]).addReg(ArgReg+1)
1488 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1489 CallMI->addRegOperand(GPR[GPR_idx+1], MachineOperand::Use);
1491 if (GPR_remaining <= 1 || isVarArg) {
1492 BuildMI(BB, PPC::STW, 3).addReg(ArgReg).addSImm(ArgOffset)
1494 BuildMI(BB, PPC::STW, 3).addReg(ArgReg+1).addSImm(ArgOffset+4)
1498 ArgOffset += 4; // 8 byte entry, not 4.
1499 GPR_remaining -= 1; // uses up 2 GPRs
1503 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1505 if (FPR_remaining > 0) {
1506 BuildMI(BB, PPC::FMR, 1, FPR[FPR_idx]).addReg(ArgReg);
1507 CallMI->addRegOperand(FPR[FPR_idx], MachineOperand::Use);
1511 // If this is a vararg function, and there are GPRs left, also
1512 // pass the float in an int. Otherwise, put it on the stack.
1514 BuildMI(BB, PPC::STFS, 3).addReg(ArgReg).addSImm(ArgOffset)
1516 if (GPR_remaining > 0) {
1517 BuildMI(BB, PPC::LWZ, 2, GPR[GPR_idx])
1518 .addSImm(ArgOffset).addReg(PPC::R1);
1519 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1523 BuildMI(BB, PPC::STFS, 3).addReg(ArgReg).addSImm(ArgOffset)
1528 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1530 if (FPR_remaining > 0) {
1531 BuildMI(BB, PPC::FMR, 1, FPR[FPR_idx]).addReg(ArgReg);
1532 CallMI->addRegOperand(FPR[FPR_idx], MachineOperand::Use);
1535 // For vararg functions, must pass doubles via int regs as well
1537 BuildMI(BB, PPC::STFD, 3).addReg(ArgReg).addSImm(ArgOffset)
1540 // Doubles can be split across reg + stack for varargs
1541 if (GPR_remaining > 0) {
1542 BuildMI(BB, PPC::LWZ, 2, GPR[GPR_idx]).addSImm(ArgOffset)
1544 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1546 if (GPR_remaining > 1) {
1547 BuildMI(BB, PPC::LWZ, 2, GPR[GPR_idx+1])
1548 .addSImm(ArgOffset+4).addReg(PPC::R1);
1549 CallMI->addRegOperand(GPR[GPR_idx+1], MachineOperand::Use);
1553 BuildMI(BB, PPC::STFD, 3).addReg(ArgReg).addSImm(ArgOffset)
1556 // Doubles use 8 bytes, and 2 GPRs worth of param space
1562 default: assert(0 && "Unknown class!");
1569 BuildMI(BB, PPC::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
1572 BuildMI(BB, PPC::IMPLICIT_DEF, 0, PPC::LR);
1573 BB->push_back(CallMI);
1575 // These functions are automatically eliminated by the prolog/epilog pass
1576 BuildMI(BB, PPC::ADJCALLSTACKUP, 1).addImm(NumBytes);
1578 // If there is a return value, scavenge the result from the location the call
1581 if (Ret.Ty != Type::VoidTy) {
1582 unsigned DestClass = getClassB(Ret.Ty);
1583 switch (DestClass) {
1587 // Integral results are in r3
1588 BuildMI(BB, PPC::OR, 2, Ret.Reg).addReg(PPC::R3).addReg(PPC::R3);
1590 case cFP32: // Floating-point return values live in f1
1592 BuildMI(BB, PPC::FMR, 1, Ret.Reg).addReg(PPC::F1);
1594 case cLong: // Long values are in r3:r4
1595 BuildMI(BB, PPC::OR, 2, Ret.Reg).addReg(PPC::R3).addReg(PPC::R3);
1596 BuildMI(BB, PPC::OR, 2, Ret.Reg+1).addReg(PPC::R4).addReg(PPC::R4);
1598 default: assert(0 && "Unknown class!");
1604 /// visitCallInst - Push args on stack and do a procedure call instruction.
1605 void ISel::visitCallInst(CallInst &CI) {
1606 MachineInstr *TheCall;
1607 Function *F = CI.getCalledFunction();
1609 // Is it an intrinsic function call?
1610 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1611 visitIntrinsicCall(ID, CI); // Special intrinsics are not handled here
1614 // Emit a CALL instruction with PC-relative displacement.
1615 TheCall = BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(F, true);
1616 // Add it to the set of functions called to be used by the Printer
1617 TM.CalledFunctions.insert(F);
1618 } else { // Emit an indirect call through the CTR
1619 unsigned Reg = getReg(CI.getCalledValue());
1620 BuildMI(BB, PPC::OR, 2, PPC::R12).addReg(Reg).addReg(Reg);
1621 BuildMI(BB, PPC::MTCTR, 1).addReg(PPC::R12);
1622 TheCall = BuildMI(PPC::CALLindirect, 2).addZImm(20).addZImm(0)
1626 std::vector<ValueRecord> Args;
1627 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
1628 Args.push_back(ValueRecord(CI.getOperand(i)));
1630 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1631 bool isVarArg = F ? F->getFunctionType()->isVarArg() : true;
1632 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args, isVarArg);
1636 /// dyncastIsNan - Return the operand of an isnan operation if this is an isnan.
1638 static Value *dyncastIsNan(Value *V) {
1639 if (CallInst *CI = dyn_cast<CallInst>(V))
1640 if (Function *F = CI->getCalledFunction())
1641 if (F->getIntrinsicID() == Intrinsic::isunordered)
1642 return CI->getOperand(1);
1646 /// isOnlyUsedByUnorderedComparisons - Return true if this value is only used by
1647 /// or's whos operands are all calls to the isnan predicate.
1648 static bool isOnlyUsedByUnorderedComparisons(Value *V) {
1649 assert(dyncastIsNan(V) && "The value isn't an isnan call!");
1651 // Check all uses, which will be or's of isnans if this predicate is true.
1652 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1653 Instruction *I = cast<Instruction>(*UI);
1654 if (I->getOpcode() != Instruction::Or) return false;
1655 if (I->getOperand(0) != V && !dyncastIsNan(I->getOperand(0))) return false;
1656 if (I->getOperand(1) != V && !dyncastIsNan(I->getOperand(1))) return false;
1662 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1663 /// function, lowering any calls to unknown intrinsic functions into the
1664 /// equivalent LLVM code.
1666 void ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1667 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1668 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1669 if (CallInst *CI = dyn_cast<CallInst>(I++))
1670 if (Function *F = CI->getCalledFunction())
1671 switch (F->getIntrinsicID()) {
1672 case Intrinsic::not_intrinsic:
1673 case Intrinsic::vastart:
1674 case Intrinsic::vacopy:
1675 case Intrinsic::vaend:
1676 case Intrinsic::returnaddress:
1677 case Intrinsic::frameaddress:
1678 // FIXME: should lower these ourselves
1679 // case Intrinsic::isunordered:
1680 // case Intrinsic::memcpy: -> doCall(). system memcpy almost
1681 // guaranteed to be faster than anything we generate ourselves
1682 // We directly implement these intrinsics
1684 case Intrinsic::readio: {
1685 // On PPC, memory operations are in-order. Lower this intrinsic
1686 // into a volatile load.
1687 Instruction *Before = CI->getPrev();
1688 LoadInst * LI = new LoadInst(CI->getOperand(1), "", true, CI);
1689 CI->replaceAllUsesWith(LI);
1690 BB->getInstList().erase(CI);
1693 case Intrinsic::writeio: {
1694 // On PPC, memory operations are in-order. Lower this intrinsic
1695 // into a volatile store.
1696 Instruction *Before = CI->getPrev();
1697 StoreInst *SI = new StoreInst(CI->getOperand(1),
1698 CI->getOperand(2), true, CI);
1699 CI->replaceAllUsesWith(SI);
1700 BB->getInstList().erase(CI);
1704 // All other intrinsic calls we must lower.
1705 Instruction *Before = CI->getPrev();
1706 TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
1707 if (Before) { // Move iterator to instruction after call
1715 void ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
1716 unsigned TmpReg1, TmpReg2, TmpReg3;
1718 case Intrinsic::vastart:
1719 // Get the address of the first vararg value...
1720 TmpReg1 = getReg(CI);
1721 addFrameReference(BuildMI(BB, PPC::ADDI, 2, TmpReg1), VarArgsFrameIndex,
1725 case Intrinsic::vacopy:
1726 TmpReg1 = getReg(CI);
1727 TmpReg2 = getReg(CI.getOperand(1));
1728 BuildMI(BB, PPC::OR, 2, TmpReg1).addReg(TmpReg2).addReg(TmpReg2);
1730 case Intrinsic::vaend: return;
1732 case Intrinsic::returnaddress:
1733 TmpReg1 = getReg(CI);
1734 if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1735 MachineFrameInfo *MFI = F->getFrameInfo();
1736 unsigned NumBytes = MFI->getStackSize();
1738 BuildMI(BB, PPC::LWZ, 2, TmpReg1).addSImm(NumBytes+8)
1741 // Values other than zero are not implemented yet.
1742 BuildMI(BB, PPC::LI, 1, TmpReg1).addSImm(0);
1746 case Intrinsic::frameaddress:
1747 TmpReg1 = getReg(CI);
1748 if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1749 BuildMI(BB, PPC::OR, 2, TmpReg1).addReg(PPC::R1).addReg(PPC::R1);
1751 // Values other than zero are not implemented yet.
1752 BuildMI(BB, PPC::LI, 1, TmpReg1).addSImm(0);
1757 // This may be useful for supporting isunordered
1758 case Intrinsic::isnan:
1759 // If this is only used by 'isunordered' style comparisons, don't emit it.
1760 if (isOnlyUsedByUnorderedComparisons(&CI)) return;
1761 TmpReg1 = getReg(CI.getOperand(1));
1762 emitUCOM(BB, BB->end(), TmpReg1, TmpReg1);
1763 TmpReg2 = makeAnotherReg(Type::IntTy);
1764 BuildMI(BB, PPC::MFCR, TmpReg2);
1765 TmpReg3 = getReg(CI);
1766 BuildMI(BB, PPC::RLWINM, 4, TmpReg3).addReg(TmpReg2).addImm(4).addImm(31).addImm(31);
1770 default: assert(0 && "Error: unknown intrinsics should have been lowered!");
1774 /// visitSimpleBinary - Implement simple binary operators for integral types...
1775 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
1778 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
1779 unsigned DestReg = getReg(B);
1780 MachineBasicBlock::iterator MI = BB->end();
1781 Value *Op0 = B.getOperand(0), *Op1 = B.getOperand(1);
1782 unsigned Class = getClassB(B.getType());
1784 emitSimpleBinaryOperation(BB, MI, Op0, Op1, OperatorClass, DestReg);
1787 /// emitBinaryFPOperation - This method handles emission of floating point
1788 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
1789 void ISel::emitBinaryFPOperation(MachineBasicBlock *BB,
1790 MachineBasicBlock::iterator IP,
1791 Value *Op0, Value *Op1,
1792 unsigned OperatorClass, unsigned DestReg) {
1794 static const unsigned OpcodeTab[][4] = {
1795 { PPC::FADDS, PPC::FSUBS, PPC::FMULS, PPC::FDIVS }, // Float
1796 { PPC::FADD, PPC::FSUB, PPC::FMUL, PPC::FDIV }, // Double
1799 // Special case: R1 = op <const fp>, R2
1800 if (ConstantFP *Op0C = dyn_cast<ConstantFP>(Op0))
1801 if (Op0C->isExactlyValue(-0.0) && OperatorClass == 1) {
1803 unsigned op1Reg = getReg(Op1, BB, IP);
1804 BuildMI(*BB, IP, PPC::FNEG, 1, DestReg).addReg(op1Reg);
1808 unsigned Opcode = OpcodeTab[Op0->getType() == Type::DoubleTy][OperatorClass];
1809 unsigned Op0r = getReg(Op0, BB, IP);
1810 unsigned Op1r = getReg(Op1, BB, IP);
1811 BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1814 /// emitSimpleBinaryOperation - Implement simple binary operators for integral
1815 /// types... OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
1818 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
1819 /// and constant expression support.
1821 void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
1822 MachineBasicBlock::iterator IP,
1823 Value *Op0, Value *Op1,
1824 unsigned OperatorClass, unsigned DestReg) {
1825 unsigned Class = getClassB(Op0->getType());
1827 // Arithmetic and Bitwise operators
1828 static const unsigned OpcodeTab[] = {
1829 PPC::ADD, PPC::SUB, PPC::AND, PPC::OR, PPC::XOR
1831 static const unsigned ImmOpcodeTab[] = {
1832 PPC::ADDI, PPC::SUBI, PPC::ANDIo, PPC::ORI, PPC::XORI
1834 static const unsigned RImmOpcodeTab[] = {
1835 PPC::ADDI, PPC::SUBFIC, PPC::ANDIo, PPC::ORI, PPC::XORI
1838 // Otherwise, code generate the full operation with a constant.
1839 static const unsigned BottomTab[] = {
1840 PPC::ADDC, PPC::SUBC, PPC::AND, PPC::OR, PPC::XOR
1842 static const unsigned TopTab[] = {
1843 PPC::ADDE, PPC::SUBFE, PPC::AND, PPC::OR, PPC::XOR
1846 if (Class == cFP32 || Class == cFP64) {
1847 assert(OperatorClass < 2 && "No logical ops for FP!");
1848 emitBinaryFPOperation(MBB, IP, Op0, Op1, OperatorClass, DestReg);
1852 if (Op0->getType() == Type::BoolTy) {
1853 if (OperatorClass == 3)
1854 // If this is an or of two isnan's, emit an FP comparison directly instead
1855 // of or'ing two isnan's together.
1856 if (Value *LHS = dyncastIsNan(Op0))
1857 if (Value *RHS = dyncastIsNan(Op1)) {
1858 unsigned Op0Reg = getReg(RHS, MBB, IP), Op1Reg = getReg(LHS, MBB, IP);
1859 unsigned TmpReg = makeAnotherReg(Type::IntTy);
1860 emitUCOM(MBB, IP, Op0Reg, Op1Reg);
1861 BuildMI(*MBB, IP, PPC::MFCR, TmpReg);
1862 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(TmpReg).addImm(4)
1863 .addImm(31).addImm(31);
1868 // Special case: op <const int>, Reg
1869 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0)) {
1870 // sub 0, X -> subfic
1871 if (OperatorClass == 1 && canUseAsImmediateForOpcode(CI, 0)) {
1872 unsigned Op1r = getReg(Op1, MBB, IP);
1873 int imm = CI->getRawValue() & 0xFFFF;
1875 if (Class == cLong) {
1876 BuildMI(*MBB, IP, PPC::SUBFIC, 2, DestReg+1).addReg(Op1r+1)
1878 BuildMI(*MBB, IP, PPC::SUBFZE, 1, DestReg).addReg(Op1r);
1880 BuildMI(*MBB, IP, PPC::SUBFIC, 2, DestReg).addReg(Op1r).addSImm(imm);
1885 // If it is easy to do, swap the operands and emit an immediate op
1886 if (Class != cLong && OperatorClass != 1 &&
1887 canUseAsImmediateForOpcode(CI, OperatorClass)) {
1888 unsigned Op1r = getReg(Op1, MBB, IP);
1889 int imm = CI->getRawValue() & 0xFFFF;
1891 if (OperatorClass < 2)
1892 BuildMI(*MBB, IP, RImmOpcodeTab[OperatorClass], 2, DestReg).addReg(Op1r)
1895 BuildMI(*MBB, IP, RImmOpcodeTab[OperatorClass], 2, DestReg).addReg(Op1r)
1901 // Special case: op Reg, <const int>
1902 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1903 unsigned Op0r = getReg(Op0, MBB, IP);
1905 // xor X, -1 -> not X
1906 if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
1907 BuildMI(*MBB, IP, PPC::NOR, 2, DestReg).addReg(Op0r).addReg(Op0r);
1908 if (Class == cLong) // Invert the low part too
1909 BuildMI(*MBB, IP, PPC::NOR, 2, DestReg+1).addReg(Op0r+1)
1914 if (Class != cLong) {
1915 if (canUseAsImmediateForOpcode(Op1C, OperatorClass)) {
1916 int immediate = Op1C->getRawValue() & 0xFFFF;
1918 if (OperatorClass < 2)
1919 BuildMI(*MBB, IP, ImmOpcodeTab[OperatorClass], 2,DestReg).addReg(Op0r)
1920 .addSImm(immediate);
1922 BuildMI(*MBB, IP, ImmOpcodeTab[OperatorClass], 2,DestReg).addReg(Op0r)
1923 .addZImm(immediate);
1925 unsigned Op1r = getReg(Op1, MBB, IP);
1926 BuildMI(*MBB, IP, OpcodeTab[OperatorClass], 2, DestReg).addReg(Op0r)
1932 unsigned Op1r = getReg(Op1, MBB, IP);
1934 BuildMI(*MBB, IP, BottomTab[OperatorClass], 2, DestReg+1).addReg(Op0r+1)
1936 BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg).addReg(Op0r)
1941 // We couldn't generate an immediate variant of the op, load both halves into
1942 // registers and emit the appropriate opcode.
1943 unsigned Op0r = getReg(Op0, MBB, IP);
1944 unsigned Op1r = getReg(Op1, MBB, IP);
1946 if (Class != cLong) {
1947 unsigned Opcode = OpcodeTab[OperatorClass];
1948 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1950 BuildMI(*MBB, IP, BottomTab[OperatorClass], 2, DestReg+1).addReg(Op0r+1)
1952 BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg).addReg(Op0r)
1958 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
1959 // returns zero when the input is not exactly a power of two.
1960 static unsigned ExactLog2(unsigned Val) {
1961 if (Val == 0 || (Val & (Val-1))) return 0;
1970 /// doMultiply - Emit appropriate instructions to multiply together the
1971 /// Values Op0 and Op1, and put the result in DestReg.
1973 void ISel::doMultiply(MachineBasicBlock *MBB,
1974 MachineBasicBlock::iterator IP,
1975 unsigned DestReg, Value *Op0, Value *Op1) {
1976 unsigned Class0 = getClass(Op0->getType());
1977 unsigned Class1 = getClass(Op1->getType());
1979 unsigned Op0r = getReg(Op0, MBB, IP);
1980 unsigned Op1r = getReg(Op1, MBB, IP);
1983 if (Class0 == cLong && Class1 == cLong) {
1984 unsigned Tmp1 = makeAnotherReg(Type::IntTy);
1985 unsigned Tmp2 = makeAnotherReg(Type::IntTy);
1986 unsigned Tmp3 = makeAnotherReg(Type::IntTy);
1987 unsigned Tmp4 = makeAnotherReg(Type::IntTy);
1988 BuildMI(*MBB, IP, PPC::MULHWU, 2, Tmp1).addReg(Op0r+1).addReg(Op1r+1);
1989 BuildMI(*MBB, IP, PPC::MULLW, 2, DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
1990 BuildMI(*MBB, IP, PPC::MULLW, 2, Tmp2).addReg(Op0r+1).addReg(Op1r);
1991 BuildMI(*MBB, IP, PPC::ADD, 2, Tmp3).addReg(Tmp1).addReg(Tmp2);
1992 BuildMI(*MBB, IP, PPC::MULLW, 2, Tmp4).addReg(Op0r).addReg(Op1r+1);
1993 BuildMI(*MBB, IP, PPC::ADD, 2, DestReg).addReg(Tmp3).addReg(Tmp4);
1997 // 64 x 32 or less, promote 32 to 64 and do a 64 x 64
1998 if (Class0 == cLong && Class1 <= cInt) {
1999 unsigned Tmp0 = makeAnotherReg(Type::IntTy);
2000 unsigned Tmp1 = makeAnotherReg(Type::IntTy);
2001 unsigned Tmp2 = makeAnotherReg(Type::IntTy);
2002 unsigned Tmp3 = makeAnotherReg(Type::IntTy);
2003 unsigned Tmp4 = makeAnotherReg(Type::IntTy);
2004 if (Op1->getType()->isSigned())
2005 BuildMI(*MBB, IP, PPC::SRAWI, 2, Tmp0).addReg(Op1r).addImm(31);
2007 BuildMI(*MBB, IP, PPC::LI, 2, Tmp0).addSImm(0);
2008 BuildMI(*MBB, IP, PPC::MULHWU, 2, Tmp1).addReg(Op0r+1).addReg(Op1r);
2009 BuildMI(*MBB, IP, PPC::MULLW, 2, DestReg+1).addReg(Op0r+1).addReg(Op1r);
2010 BuildMI(*MBB, IP, PPC::MULLW, 2, Tmp2).addReg(Op0r+1).addReg(Tmp0);
2011 BuildMI(*MBB, IP, PPC::ADD, 2, Tmp3).addReg(Tmp1).addReg(Tmp2);
2012 BuildMI(*MBB, IP, PPC::MULLW, 2, Tmp4).addReg(Op0r).addReg(Op1r);
2013 BuildMI(*MBB, IP, PPC::ADD, 2, DestReg).addReg(Tmp3).addReg(Tmp4);
2018 if (Class0 <= cInt && Class1 <= cInt) {
2019 BuildMI(*MBB, IP, PPC::MULLW, 2, DestReg).addReg(Op0r).addReg(Op1r);
2023 assert(0 && "doMultiply cannot operate on unknown type!");
2026 /// doMultiplyConst - This method will multiply the value in Op0 by the
2027 /// value of the ContantInt *CI
2028 void ISel::doMultiplyConst(MachineBasicBlock *MBB,
2029 MachineBasicBlock::iterator IP,
2030 unsigned DestReg, Value *Op0, ConstantInt *CI) {
2031 unsigned Class = getClass(Op0->getType());
2034 if (CI->isNullValue()) {
2035 BuildMI(*MBB, IP, PPC::LI, 1, DestReg).addSImm(0);
2037 BuildMI(*MBB, IP, PPC::LI, 1, DestReg+1).addSImm(0);
2041 // Mul op0, 1 ==> op0
2042 if (CI->equalsInt(1)) {
2043 unsigned Op0r = getReg(Op0, MBB, IP);
2044 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(Op0r).addReg(Op0r);
2046 BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(Op0r+1).addReg(Op0r+1);
2050 // If the element size is exactly a power of 2, use a shift to get it.
2051 if (unsigned Shift = ExactLog2(CI->getRawValue())) {
2052 ConstantUInt *ShiftCI = ConstantUInt::get(Type::UByteTy, Shift);
2053 emitShiftOperation(MBB, IP, Op0, ShiftCI, true, Op0->getType(), DestReg);
2057 // If 32 bits or less and immediate is in right range, emit mul by immediate
2058 if (Class == cByte || Class == cShort || Class == cInt) {
2059 if (canUseAsImmediateForOpcode(CI, 0)) {
2060 unsigned Op0r = getReg(Op0, MBB, IP);
2061 unsigned imm = CI->getRawValue() & 0xFFFF;
2062 BuildMI(*MBB, IP, PPC::MULLI, 2, DestReg).addReg(Op0r).addSImm(imm);
2067 doMultiply(MBB, IP, DestReg, Op0, CI);
2070 void ISel::visitMul(BinaryOperator &I) {
2071 unsigned ResultReg = getReg(I);
2073 Value *Op0 = I.getOperand(0);
2074 Value *Op1 = I.getOperand(1);
2076 MachineBasicBlock::iterator IP = BB->end();
2077 emitMultiply(BB, IP, Op0, Op1, ResultReg);
2080 void ISel::emitMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
2081 Value *Op0, Value *Op1, unsigned DestReg) {
2082 TypeClass Class = getClass(Op0->getType());
2089 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2090 doMultiplyConst(MBB, IP, DestReg, Op0, CI);
2092 doMultiply(MBB, IP, DestReg, Op0, Op1);
2097 emitBinaryFPOperation(MBB, IP, Op0, Op1, 2, DestReg);
2104 /// visitDivRem - Handle division and remainder instructions... these
2105 /// instruction both require the same instructions to be generated, they just
2106 /// select the result from a different register. Note that both of these
2107 /// instructions work differently for signed and unsigned operands.
2109 void ISel::visitDivRem(BinaryOperator &I) {
2110 unsigned ResultReg = getReg(I);
2111 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2113 MachineBasicBlock::iterator IP = BB->end();
2114 emitDivRemOperation(BB, IP, Op0, Op1, I.getOpcode() == Instruction::Div,
2118 void ISel::emitDivRemOperation(MachineBasicBlock *BB,
2119 MachineBasicBlock::iterator IP,
2120 Value *Op0, Value *Op1, bool isDiv,
2121 unsigned ResultReg) {
2122 const Type *Ty = Op0->getType();
2123 unsigned Class = getClass(Ty);
2127 // Floating point divide...
2128 emitBinaryFPOperation(BB, IP, Op0, Op1, 3, ResultReg);
2131 // Floating point remainder via fmodf(float x, float y);
2132 unsigned Op0Reg = getReg(Op0, BB, IP);
2133 unsigned Op1Reg = getReg(Op1, BB, IP);
2134 MachineInstr *TheCall =
2135 BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(fmodfFn, true);
2136 std::vector<ValueRecord> Args;
2137 Args.push_back(ValueRecord(Op0Reg, Type::FloatTy));
2138 Args.push_back(ValueRecord(Op1Reg, Type::FloatTy));
2139 doCall(ValueRecord(ResultReg, Type::FloatTy), TheCall, Args, false);
2140 TM.CalledFunctions.insert(fmodfFn);
2145 // Floating point divide...
2146 emitBinaryFPOperation(BB, IP, Op0, Op1, 3, ResultReg);
2149 // Floating point remainder via fmod(double x, double y);
2150 unsigned Op0Reg = getReg(Op0, BB, IP);
2151 unsigned Op1Reg = getReg(Op1, BB, IP);
2152 MachineInstr *TheCall =
2153 BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(fmodFn, true);
2154 std::vector<ValueRecord> Args;
2155 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
2156 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
2157 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args, false);
2158 TM.CalledFunctions.insert(fmodFn);
2162 static Function* const Funcs[] =
2163 { __moddi3Fn, __divdi3Fn, __umoddi3Fn, __udivdi3Fn };
2164 unsigned Op0Reg = getReg(Op0, BB, IP);
2165 unsigned Op1Reg = getReg(Op1, BB, IP);
2166 unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
2167 MachineInstr *TheCall =
2168 BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(Funcs[NameIdx], true);
2170 std::vector<ValueRecord> Args;
2171 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
2172 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
2173 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args, false);
2174 TM.CalledFunctions.insert(Funcs[NameIdx]);
2177 case cByte: case cShort: case cInt:
2178 break; // Small integrals, handled below...
2179 default: assert(0 && "Unknown class!");
2182 // Special case signed division by power of 2.
2184 if (ConstantSInt *CI = dyn_cast<ConstantSInt>(Op1)) {
2185 assert(Class != cLong && "This doesn't handle 64-bit divides!");
2186 int V = CI->getValue();
2188 if (V == 1) { // X /s 1 => X
2189 unsigned Op0Reg = getReg(Op0, BB, IP);
2190 BuildMI(*BB, IP, PPC::OR, 2, ResultReg).addReg(Op0Reg).addReg(Op0Reg);
2194 if (V == -1) { // X /s -1 => -X
2195 unsigned Op0Reg = getReg(Op0, BB, IP);
2196 BuildMI(*BB, IP, PPC::NEG, 1, ResultReg).addReg(Op0Reg);
2200 unsigned log2V = ExactLog2(V);
2201 if (log2V != 0 && Ty->isSigned()) {
2202 unsigned Op0Reg = getReg(Op0, BB, IP);
2203 unsigned TmpReg = makeAnotherReg(Op0->getType());
2205 BuildMI(*BB, IP, PPC::SRAWI, 2, TmpReg).addReg(Op0Reg).addImm(log2V);
2206 BuildMI(*BB, IP, PPC::ADDZE, 1, ResultReg).addReg(TmpReg);
2211 unsigned Op0Reg = getReg(Op0, BB, IP);
2212 unsigned Op1Reg = getReg(Op1, BB, IP);
2213 unsigned Opcode = Ty->isSigned() ? PPC::DIVW : PPC::DIVWU;
2216 BuildMI(*BB, IP, Opcode, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
2217 } else { // Remainder
2218 unsigned TmpReg1 = makeAnotherReg(Op0->getType());
2219 unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2221 BuildMI(*BB, IP, Opcode, 2, TmpReg1).addReg(Op0Reg).addReg(Op1Reg);
2222 BuildMI(*BB, IP, PPC::MULLW, 2, TmpReg2).addReg(TmpReg1).addReg(Op1Reg);
2223 BuildMI(*BB, IP, PPC::SUBF, 2, ResultReg).addReg(TmpReg2).addReg(Op0Reg);
2228 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
2229 /// for constant immediate shift values, and for constant immediate
2230 /// shift values equal to 1. Even the general case is sort of special,
2231 /// because the shift amount has to be in CL, not just any old register.
2233 void ISel::visitShiftInst(ShiftInst &I) {
2234 MachineBasicBlock::iterator IP = BB->end();
2235 emitShiftOperation(BB, IP, I.getOperand(0), I.getOperand(1),
2236 I.getOpcode() == Instruction::Shl, I.getType(),
2240 /// emitShiftOperation - Common code shared between visitShiftInst and
2241 /// constant expression support.
2243 void ISel::emitShiftOperation(MachineBasicBlock *MBB,
2244 MachineBasicBlock::iterator IP,
2245 Value *Op, Value *ShiftAmount, bool isLeftShift,
2246 const Type *ResultTy, unsigned DestReg) {
2247 unsigned SrcReg = getReg (Op, MBB, IP);
2248 bool isSigned = ResultTy->isSigned ();
2249 unsigned Class = getClass (ResultTy);
2251 // Longs, as usual, are handled specially...
2252 if (Class == cLong) {
2253 // If we have a constant shift, we can generate much more efficient code
2254 // than otherwise...
2256 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2257 unsigned Amount = CUI->getValue();
2260 // FIXME: RLWIMI is a use-and-def of DestReg+1, but that violates SSA
2261 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
2262 .addImm(Amount).addImm(0).addImm(31-Amount);
2263 BuildMI(*MBB, IP, PPC::RLWIMI, 5).addReg(DestReg).addReg(SrcReg+1)
2264 .addImm(Amount).addImm(32-Amount).addImm(31);
2265 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg+1).addReg(SrcReg+1)
2266 .addImm(Amount).addImm(0).addImm(31-Amount);
2268 // FIXME: RLWIMI is a use-and-def of DestReg, but that violates SSA
2269 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg+1).addReg(SrcReg+1)
2270 .addImm(32-Amount).addImm(Amount).addImm(31);
2271 BuildMI(*MBB, IP, PPC::RLWIMI, 5).addReg(DestReg+1).addReg(SrcReg)
2272 .addImm(32-Amount).addImm(0).addImm(Amount-1);
2273 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
2274 .addImm(32-Amount).addImm(Amount).addImm(31);
2276 } else { // Shifting more than 32 bits
2280 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg+1)
2281 .addImm(Amount).addImm(0).addImm(31-Amount);
2283 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg+1)
2286 BuildMI(*MBB, IP, PPC::LI, 1, DestReg+1).addSImm(0);
2290 BuildMI(*MBB, IP, PPC::SRAWI, 2, DestReg+1).addReg(SrcReg)
2293 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg+1).addReg(SrcReg)
2294 .addImm(32-Amount).addImm(Amount).addImm(31);
2296 BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(SrcReg)
2299 BuildMI(*MBB, IP,PPC::LI, 1, DestReg).addSImm(0);
2303 unsigned TmpReg1 = makeAnotherReg(Type::IntTy);
2304 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
2305 unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
2306 unsigned TmpReg4 = makeAnotherReg(Type::IntTy);
2307 unsigned TmpReg5 = makeAnotherReg(Type::IntTy);
2308 unsigned TmpReg6 = makeAnotherReg(Type::IntTy);
2309 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
2312 BuildMI(*MBB, IP, PPC::SUBFIC, 2, TmpReg1).addReg(ShiftAmountReg)
2314 BuildMI(*MBB, IP, PPC::SLW, 2, TmpReg2).addReg(SrcReg)
2315 .addReg(ShiftAmountReg);
2316 BuildMI(*MBB, IP, PPC::SRW, 2, TmpReg3).addReg(SrcReg+1)
2318 BuildMI(*MBB, IP, PPC::OR, 2,TmpReg4).addReg(TmpReg2).addReg(TmpReg3);
2319 BuildMI(*MBB, IP, PPC::ADDI, 2, TmpReg5).addReg(ShiftAmountReg)
2321 BuildMI(*MBB, IP, PPC::SLW, 2, TmpReg6).addReg(SrcReg+1)
2323 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(TmpReg4)
2325 BuildMI(*MBB, IP, PPC::SLW, 2, DestReg+1).addReg(SrcReg+1)
2326 .addReg(ShiftAmountReg);
2328 if (isSigned) { // shift right algebraic
2329 MachineBasicBlock *TmpMBB =new MachineBasicBlock(BB->getBasicBlock());
2330 MachineBasicBlock *PhiMBB =new MachineBasicBlock(BB->getBasicBlock());
2331 MachineBasicBlock *OldMBB = BB;
2332 ilist<MachineBasicBlock>::iterator It = BB; ++It;
2333 F->getBasicBlockList().insert(It, TmpMBB);
2334 F->getBasicBlockList().insert(It, PhiMBB);
2335 BB->addSuccessor(TmpMBB);
2336 BB->addSuccessor(PhiMBB);
2338 BuildMI(*MBB, IP, PPC::SUBFIC, 2, TmpReg1).addReg(ShiftAmountReg)
2340 BuildMI(*MBB, IP, PPC::SRW, 2, TmpReg2).addReg(SrcReg+1)
2341 .addReg(ShiftAmountReg);
2342 BuildMI(*MBB, IP, PPC::SLW, 2, TmpReg3).addReg(SrcReg)
2344 BuildMI(*MBB, IP, PPC::OR, 2, TmpReg4).addReg(TmpReg2)
2346 BuildMI(*MBB, IP, PPC::ADDICo, 2, TmpReg5).addReg(ShiftAmountReg)
2348 BuildMI(*MBB, IP, PPC::SRAW, 2, TmpReg6).addReg(SrcReg)
2350 BuildMI(*MBB, IP, PPC::SRAW, 2, DestReg).addReg(SrcReg)
2351 .addReg(ShiftAmountReg);
2352 BuildMI(*MBB, IP, PPC::BLE, 2).addReg(PPC::CR0).addMBB(PhiMBB);
2355 // Select correct least significant half if the shift amount > 32
2357 unsigned OrReg = makeAnotherReg(Type::IntTy);
2358 BuildMI(BB, PPC::OR, 2, OrReg).addReg(TmpReg6).addImm(TmpReg6);
2359 TmpMBB->addSuccessor(PhiMBB);
2362 BuildMI(BB, PPC::PHI, 4, DestReg+1).addReg(TmpReg4).addMBB(OldMBB)
2363 .addReg(OrReg).addMBB(TmpMBB);
2364 } else { // shift right logical
2365 BuildMI(*MBB, IP, PPC::SUBFIC, 2, TmpReg1).addReg(ShiftAmountReg)
2367 BuildMI(*MBB, IP, PPC::SRW, 2, TmpReg2).addReg(SrcReg+1)
2368 .addReg(ShiftAmountReg);
2369 BuildMI(*MBB, IP, PPC::SLW, 2, TmpReg3).addReg(SrcReg)
2371 BuildMI(*MBB, IP, PPC::OR, 2, TmpReg4).addReg(TmpReg2)
2373 BuildMI(*MBB, IP, PPC::ADDI, 2, TmpReg5).addReg(ShiftAmountReg)
2375 BuildMI(*MBB, IP, PPC::SRW, 2, TmpReg6).addReg(SrcReg)
2377 BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(TmpReg4)
2379 BuildMI(*MBB, IP, PPC::SRW, 2, DestReg).addReg(SrcReg)
2380 .addReg(ShiftAmountReg);
2387 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2388 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
2389 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
2390 unsigned Amount = CUI->getValue();
2393 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
2394 .addImm(Amount).addImm(0).addImm(31-Amount);
2397 BuildMI(*MBB, IP, PPC::SRAWI,2,DestReg).addReg(SrcReg).addImm(Amount);
2399 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
2400 .addImm(32-Amount).addImm(Amount).addImm(31);
2403 } else { // The shift amount is non-constant.
2404 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
2407 BuildMI(*MBB, IP, PPC::SLW, 2, DestReg).addReg(SrcReg)
2408 .addReg(ShiftAmountReg);
2410 BuildMI(*MBB, IP, isSigned ? PPC::SRAW : PPC::SRW, 2, DestReg)
2411 .addReg(SrcReg).addReg(ShiftAmountReg);
2416 /// LoadNeedsSignExtend - On PowerPC, there is no load byte with sign extend.
2417 /// Therefore, if this is a byte load and the destination type is signed, we
2418 /// would normall need to also emit a sign extend instruction after the load.
2419 /// However, store instructions don't care whether a signed type was sign
2420 /// extended across a whole register. Also, a SetCC instruction will emit its
2421 /// own sign extension to force the value into the appropriate range, so we
2422 /// need not emit it here. Ideally, this kind of thing wouldn't be necessary
2423 /// once LLVM's type system is improved.
2424 static bool LoadNeedsSignExtend(LoadInst &LI) {
2425 if (cByte == getClassB(LI.getType()) && LI.getType()->isSigned()) {
2426 bool AllUsesAreStoresOrSetCC = true;
2427 for (Value::use_iterator I = LI.use_begin(), E = LI.use_end(); I != E; ++I)
2428 if (!isa<StoreInst>(*I) && !isa<SetCondInst>(*I)) {
2429 AllUsesAreStoresOrSetCC = false;
2432 if (!AllUsesAreStoresOrSetCC)
2438 /// visitLoadInst - Implement LLVM load instructions. Pretty straightforward
2439 /// mapping of LLVM classes to PPC load instructions, with the exception of
2440 /// signed byte loads, which need a sign extension following them.
2442 void ISel::visitLoadInst(LoadInst &I) {
2443 // Immediate opcodes, for reg+imm addressing
2444 static const unsigned ImmOpcodes[] = {
2445 PPC::LBZ, PPC::LHZ, PPC::LWZ,
2446 PPC::LFS, PPC::LFD, PPC::LWZ
2448 // Indexed opcodes, for reg+reg addressing
2449 static const unsigned IdxOpcodes[] = {
2450 PPC::LBZX, PPC::LHZX, PPC::LWZX,
2451 PPC::LFSX, PPC::LFDX, PPC::LWZX
2454 unsigned Class = getClassB(I.getType());
2455 unsigned ImmOpcode = ImmOpcodes[Class];
2456 unsigned IdxOpcode = IdxOpcodes[Class];
2457 unsigned DestReg = getReg(I);
2458 Value *SourceAddr = I.getOperand(0);
2460 if (Class == cShort && I.getType()->isSigned()) ImmOpcode = PPC::LHA;
2461 if (Class == cShort && I.getType()->isSigned()) IdxOpcode = PPC::LHAX;
2463 if (AllocaInst *AI = dyn_castFixedAlloca(SourceAddr)) {
2464 unsigned FI = getFixedSizedAllocaFI(AI);
2465 if (Class == cLong) {
2466 addFrameReference(BuildMI(BB, ImmOpcode, 2, DestReg), FI);
2467 addFrameReference(BuildMI(BB, ImmOpcode, 2, DestReg+1), FI, 4);
2468 } else if (LoadNeedsSignExtend(I)) {
2469 unsigned TmpReg = makeAnotherReg(I.getType());
2470 addFrameReference(BuildMI(BB, ImmOpcode, 2, TmpReg), FI);
2471 BuildMI(BB, PPC::EXTSB, 1, DestReg).addReg(TmpReg);
2473 addFrameReference(BuildMI(BB, ImmOpcode, 2, DestReg), FI);
2478 // If this load is the only use of the GEP instruction that is its address,
2479 // then we can fold the GEP directly into the load instruction.
2480 // emitGEPOperation with a second to last arg of 'true' will place the
2481 // base register for the GEP into baseReg, and the constant offset from that
2482 // into offset. If the offset fits in 16 bits, we can emit a reg+imm store
2483 // otherwise, we copy the offset into another reg, and use reg+reg addressing.
2484 if (GetElementPtrInst *GEPI = canFoldGEPIntoLoadOrStore(SourceAddr)) {
2485 unsigned baseReg = getReg(GEPI);
2486 unsigned pendingAdd;
2487 ConstantSInt *offset;
2489 emitGEPOperation(BB, BB->end(), GEPI->getOperand(0), GEPI->op_begin()+1,
2490 GEPI->op_end(), baseReg, true, &offset, &pendingAdd);
2492 if (pendingAdd == 0 && Class != cLong &&
2493 canUseAsImmediateForOpcode(offset, 0)) {
2494 if (LoadNeedsSignExtend(I)) {
2495 unsigned TmpReg = makeAnotherReg(I.getType());
2496 BuildMI(BB, ImmOpcode, 2, TmpReg).addSImm(offset->getValue())
2498 BuildMI(BB, PPC::EXTSB, 1, DestReg).addReg(TmpReg);
2500 BuildMI(BB, ImmOpcode, 2, DestReg).addSImm(offset->getValue())
2506 unsigned indexReg = (pendingAdd != 0) ? pendingAdd : getReg(offset);
2508 if (Class == cLong) {
2509 unsigned indexPlus4 = makeAnotherReg(Type::IntTy);
2510 BuildMI(BB, PPC::ADDI, 2, indexPlus4).addReg(indexReg).addSImm(4);
2511 BuildMI(BB, IdxOpcode, 2, DestReg).addReg(indexReg).addReg(baseReg);
2512 BuildMI(BB, IdxOpcode, 2, DestReg+1).addReg(indexPlus4).addReg(baseReg);
2513 } else if (LoadNeedsSignExtend(I)) {
2514 unsigned TmpReg = makeAnotherReg(I.getType());
2515 BuildMI(BB, IdxOpcode, 2, TmpReg).addReg(indexReg).addReg(baseReg);
2516 BuildMI(BB, PPC::EXTSB, 1, DestReg).addReg(TmpReg);
2518 BuildMI(BB, IdxOpcode, 2, DestReg).addReg(indexReg).addReg(baseReg);
2523 // The fallback case, where the load was from a source that could not be
2524 // folded into the load instruction.
2525 unsigned SrcAddrReg = getReg(SourceAddr);
2527 if (Class == cLong) {
2528 BuildMI(BB, ImmOpcode, 2, DestReg).addSImm(0).addReg(SrcAddrReg);
2529 BuildMI(BB, ImmOpcode, 2, DestReg+1).addSImm(4).addReg(SrcAddrReg);
2530 } else if (LoadNeedsSignExtend(I)) {
2531 unsigned TmpReg = makeAnotherReg(I.getType());
2532 BuildMI(BB, ImmOpcode, 2, TmpReg).addSImm(0).addReg(SrcAddrReg);
2533 BuildMI(BB, PPC::EXTSB, 1, DestReg).addReg(TmpReg);
2535 BuildMI(BB, ImmOpcode, 2, DestReg).addSImm(0).addReg(SrcAddrReg);
2539 /// visitStoreInst - Implement LLVM store instructions
2541 void ISel::visitStoreInst(StoreInst &I) {
2542 // Immediate opcodes, for reg+imm addressing
2543 static const unsigned ImmOpcodes[] = {
2544 PPC::STB, PPC::STH, PPC::STW,
2545 PPC::STFS, PPC::STFD, PPC::STW
2547 // Indexed opcodes, for reg+reg addressing
2548 static const unsigned IdxOpcodes[] = {
2549 PPC::STBX, PPC::STHX, PPC::STWX,
2550 PPC::STFSX, PPC::STFDX, PPC::STWX
2553 Value *SourceAddr = I.getOperand(1);
2554 const Type *ValTy = I.getOperand(0)->getType();
2555 unsigned Class = getClassB(ValTy);
2556 unsigned ImmOpcode = ImmOpcodes[Class];
2557 unsigned IdxOpcode = IdxOpcodes[Class];
2558 unsigned ValReg = getReg(I.getOperand(0));
2560 // If this store is the only use of the GEP instruction that is its address,
2561 // then we can fold the GEP directly into the store instruction.
2562 // emitGEPOperation with a second to last arg of 'true' will place the
2563 // base register for the GEP into baseReg, and the constant offset from that
2564 // into offset. If the offset fits in 16 bits, we can emit a reg+imm store
2565 // otherwise, we copy the offset into another reg, and use reg+reg addressing.
2566 if (GetElementPtrInst *GEPI = canFoldGEPIntoLoadOrStore(SourceAddr)) {
2567 unsigned baseReg = getReg(GEPI);
2568 unsigned pendingAdd;
2569 ConstantSInt *offset;
2571 emitGEPOperation(BB, BB->end(), GEPI->getOperand(0), GEPI->op_begin()+1,
2572 GEPI->op_end(), baseReg, true, &offset, &pendingAdd);
2574 if (0 == pendingAdd && Class != cLong &&
2575 canUseAsImmediateForOpcode(offset, 0)) {
2576 BuildMI(BB, ImmOpcode, 3).addReg(ValReg).addSImm(offset->getValue())
2581 unsigned indexReg = (pendingAdd != 0) ? pendingAdd : getReg(offset);
2583 if (Class == cLong) {
2584 unsigned indexPlus4 = makeAnotherReg(Type::IntTy);
2585 BuildMI(BB, PPC::ADDI, 2, indexPlus4).addReg(indexReg).addSImm(4);
2586 BuildMI(BB, IdxOpcode, 3).addReg(ValReg).addReg(indexReg).addReg(baseReg);
2587 BuildMI(BB, IdxOpcode, 3).addReg(ValReg+1).addReg(indexPlus4)
2591 BuildMI(BB, IdxOpcode, 3).addReg(ValReg).addReg(indexReg).addReg(baseReg);
2595 // If the store address wasn't the only use of a GEP, we fall back to the
2596 // standard path: store the ValReg at the value in AddressReg.
2597 unsigned AddressReg = getReg(I.getOperand(1));
2598 if (Class == cLong) {
2599 BuildMI(BB, ImmOpcode, 3).addReg(ValReg).addSImm(0).addReg(AddressReg);
2600 BuildMI(BB, ImmOpcode, 3).addReg(ValReg+1).addSImm(4).addReg(AddressReg);
2603 BuildMI(BB, ImmOpcode, 3).addReg(ValReg).addSImm(0).addReg(AddressReg);
2607 /// visitCastInst - Here we have various kinds of copying with or without sign
2608 /// extension going on.
2610 void ISel::visitCastInst(CastInst &CI) {
2611 Value *Op = CI.getOperand(0);
2613 unsigned SrcClass = getClassB(Op->getType());
2614 unsigned DestClass = getClassB(CI.getType());
2616 // If this is a cast from a 32-bit integer to a Long type, and the only uses
2617 // of the cast are GEP instructions, then the cast does not need to be
2618 // generated explicitly, it will be folded into the GEP.
2619 if (DestClass == cLong && SrcClass == cInt) {
2620 bool AllUsesAreGEPs = true;
2621 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
2622 if (!isa<GetElementPtrInst>(*I)) {
2623 AllUsesAreGEPs = false;
2626 if (AllUsesAreGEPs) return;
2629 unsigned DestReg = getReg(CI);
2630 MachineBasicBlock::iterator MI = BB->end();
2632 // If this is a cast from an byte, short, or int to an integer type of equal
2633 // or lesser width, and all uses of the cast are store instructions then dont
2634 // emit them, as the store instruction will implicitly not store the zero or
2635 // sign extended bytes.
2636 if (SrcClass <= cInt && SrcClass >= DestClass) {
2637 bool AllUsesAreStoresOrSetCC = true;
2638 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
2639 if (!isa<StoreInst>(*I) && !isa<SetCondInst>(*I)) {
2640 AllUsesAreStoresOrSetCC = false;
2643 // Turn this cast directly into a move instruction, which the register
2644 // allocator will deal with.
2645 if (AllUsesAreStoresOrSetCC) {
2646 unsigned SrcReg = getReg(Op, BB, MI);
2647 BuildMI(*BB, MI, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2651 emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
2654 /// emitCastOperation - Common code shared between visitCastInst and constant
2655 /// expression cast support.
2657 void ISel::emitCastOperation(MachineBasicBlock *MBB,
2658 MachineBasicBlock::iterator IP,
2659 Value *Src, const Type *DestTy,
2661 const Type *SrcTy = Src->getType();
2662 unsigned SrcClass = getClassB(SrcTy);
2663 unsigned DestClass = getClassB(DestTy);
2664 unsigned SrcReg = getReg(Src, MBB, IP);
2666 // Implement casts to bool by using compare on the operand followed by set if
2667 // not zero on the result.
2668 if (DestTy == Type::BoolTy) {
2673 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2674 BuildMI(*MBB, IP, PPC::ADDIC, 2, TmpReg).addReg(SrcReg).addSImm(-1);
2675 BuildMI(*MBB, IP, PPC::SUBFE, 2, DestReg).addReg(TmpReg).addReg(SrcReg);
2679 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2680 unsigned SrcReg2 = makeAnotherReg(Type::IntTy);
2681 BuildMI(*MBB, IP, PPC::OR, 2, SrcReg2).addReg(SrcReg).addReg(SrcReg+1);
2682 BuildMI(*MBB, IP, PPC::ADDIC, 2, TmpReg).addReg(SrcReg2).addSImm(-1);
2683 BuildMI(*MBB, IP, PPC::SUBFE, 2, DestReg).addReg(TmpReg)
2689 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2690 unsigned ConstZero = getReg(ConstantFP::get(Type::DoubleTy, 0.0), BB, IP);
2691 BuildMI(*MBB, IP, PPC::FCMPU, PPC::CR7).addReg(SrcReg).addReg(ConstZero);
2692 BuildMI(*MBB, IP, PPC::MFCR, TmpReg);
2693 BuildMI(*MBB, IP, PPC::RLWINM, DestReg).addReg(TmpReg).addImm(31)
2694 .addImm(31).addImm(31);
2699 // Handle cast of Float -> Double
2700 if (SrcClass == cFP32 && DestClass == cFP64) {
2701 BuildMI(*MBB, IP, PPC::FMR, 1, DestReg).addReg(SrcReg);
2705 // Handle cast of Double -> Float
2706 if (SrcClass == cFP64 && DestClass == cFP32) {
2707 BuildMI(*MBB, IP, PPC::FRSP, 1, DestReg).addReg(SrcReg);
2711 // Handle casts from integer to floating point now...
2712 if (DestClass == cFP32 || DestClass == cFP64) {
2714 // Emit a library call for long to float conversion
2715 if (SrcClass == cLong) {
2716 Function *floatFn = (DestClass == cFP32) ? __floatdisfFn : __floatdidfFn;
2717 if (SrcTy->isSigned()) {
2718 std::vector<ValueRecord> Args;
2719 Args.push_back(ValueRecord(SrcReg, SrcTy));
2720 MachineInstr *TheCall =
2721 BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(floatFn, true);
2722 doCall(ValueRecord(DestReg, DestTy), TheCall, Args, false);
2723 TM.CalledFunctions.insert(floatFn);
2725 std::vector<ValueRecord> CmpArgs, ClrArgs, SetArgs;
2726 unsigned ZeroLong = getReg(ConstantUInt::get(SrcTy, 0));
2727 unsigned CondReg = makeAnotherReg(Type::IntTy);
2729 // Update machine-CFG edges
2730 MachineBasicBlock *ClrMBB = new MachineBasicBlock(BB->getBasicBlock());
2731 MachineBasicBlock *SetMBB = new MachineBasicBlock(BB->getBasicBlock());
2732 MachineBasicBlock *PhiMBB = new MachineBasicBlock(BB->getBasicBlock());
2733 MachineBasicBlock *OldMBB = BB;
2734 ilist<MachineBasicBlock>::iterator It = BB; ++It;
2735 F->getBasicBlockList().insert(It, ClrMBB);
2736 F->getBasicBlockList().insert(It, SetMBB);
2737 F->getBasicBlockList().insert(It, PhiMBB);
2738 BB->addSuccessor(ClrMBB);
2739 BB->addSuccessor(SetMBB);
2741 CmpArgs.push_back(ValueRecord(SrcReg, SrcTy));
2742 CmpArgs.push_back(ValueRecord(ZeroLong, SrcTy));
2743 MachineInstr *TheCall =
2744 BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(__cmpdi2Fn, true);
2745 doCall(ValueRecord(CondReg, Type::IntTy), TheCall, CmpArgs, false);
2746 TM.CalledFunctions.insert(__cmpdi2Fn);
2747 BuildMI(*MBB, IP, PPC::CMPWI, 2, PPC::CR0).addReg(CondReg).addSImm(0);
2748 BuildMI(*MBB, IP, PPC::BLE, 2).addReg(PPC::CR0).addMBB(SetMBB);
2752 unsigned ClrReg = makeAnotherReg(DestTy);
2753 ClrArgs.push_back(ValueRecord(SrcReg, SrcTy));
2754 TheCall = BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(floatFn, true);
2755 doCall(ValueRecord(ClrReg, DestTy), TheCall, ClrArgs, false);
2756 TM.CalledFunctions.insert(floatFn);
2757 BuildMI(BB, PPC::B, 1).addMBB(PhiMBB);
2758 BB->addSuccessor(PhiMBB);
2762 unsigned SetReg = makeAnotherReg(DestTy);
2763 unsigned CallReg = makeAnotherReg(DestTy);
2764 unsigned ShiftedReg = makeAnotherReg(SrcTy);
2765 ConstantSInt *Const1 = ConstantSInt::get(Type::IntTy, 1);
2766 emitShiftOperation(BB, BB->end(), Src, Const1, false, SrcTy, ShiftedReg);
2767 SetArgs.push_back(ValueRecord(ShiftedReg, SrcTy));
2768 TheCall = BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(floatFn, true);
2769 doCall(ValueRecord(CallReg, DestTy), TheCall, SetArgs, false);
2770 TM.CalledFunctions.insert(floatFn);
2771 unsigned SetOpcode = (DestClass == cFP32) ? PPC::FADDS : PPC::FADD;
2772 BuildMI(BB, SetOpcode, 2, SetReg).addReg(CallReg).addReg(CallReg);
2773 BB->addSuccessor(PhiMBB);
2777 BuildMI(BB, PPC::PHI, 4, DestReg).addReg(ClrReg).addMBB(ClrMBB)
2778 .addReg(SetReg).addMBB(SetMBB);
2783 // Make sure we're dealing with a full 32 bits
2784 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2785 promote32(TmpReg, ValueRecord(SrcReg, SrcTy));
2789 // Spill the integer to memory and reload it from there.
2790 // Also spill room for a special conversion constant
2792 F->getFrameInfo()->CreateStackObject(Type::DoubleTy, TM.getTargetData());
2794 MachineConstantPool *CP = F->getConstantPool();
2795 unsigned constantHi = makeAnotherReg(Type::IntTy);
2796 unsigned TempF = makeAnotherReg(Type::DoubleTy);
2798 if (!SrcTy->isSigned()) {
2799 ConstantFP *CFP = ConstantFP::get(Type::DoubleTy, 0x1.000000p52);
2800 unsigned ConstF = getReg(CFP, BB, IP);
2801 BuildMI(*MBB, IP, PPC::LIS, 1, constantHi).addSImm(0x4330);
2802 addFrameReference(BuildMI(*MBB, IP, PPC::STW, 3).addReg(constantHi),
2804 addFrameReference(BuildMI(*MBB, IP, PPC::STW, 3).addReg(SrcReg),
2806 addFrameReference(BuildMI(*MBB, IP, PPC::LFD, 2, TempF), ValueFrameIdx);
2807 BuildMI(*MBB, IP, PPC::FSUB, 2, DestReg).addReg(TempF).addReg(ConstF);
2809 ConstantFP *CFP = ConstantFP::get(Type::DoubleTy, 0x1.000008p52);
2810 unsigned ConstF = getReg(CFP, BB, IP);
2811 unsigned TempLo = makeAnotherReg(Type::IntTy);
2812 BuildMI(*MBB, IP, PPC::LIS, 1, constantHi).addSImm(0x4330);
2813 addFrameReference(BuildMI(*MBB, IP, PPC::STW, 3).addReg(constantHi),
2815 BuildMI(*MBB, IP, PPC::XORIS, 2, TempLo).addReg(SrcReg).addImm(0x8000);
2816 addFrameReference(BuildMI(*MBB, IP, PPC::STW, 3).addReg(TempLo),
2818 addFrameReference(BuildMI(*MBB, IP, PPC::LFD, 2, TempF), ValueFrameIdx);
2819 BuildMI(*MBB, IP, PPC::FSUB, 2, DestReg).addReg(TempF).addReg(ConstF);
2824 // Handle casts from floating point to integer now...
2825 if (SrcClass == cFP32 || SrcClass == cFP64) {
2826 static Function* const Funcs[] =
2827 { __fixsfdiFn, __fixdfdiFn, __fixunssfdiFn, __fixunsdfdiFn };
2828 // emit library call
2829 if (DestClass == cLong) {
2830 bool isDouble = SrcClass == cFP64;
2831 unsigned nameIndex = 2 * DestTy->isSigned() + isDouble;
2832 std::vector<ValueRecord> Args;
2833 Args.push_back(ValueRecord(SrcReg, SrcTy));
2834 Function *floatFn = Funcs[nameIndex];
2835 MachineInstr *TheCall =
2836 BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(floatFn, true);
2837 doCall(ValueRecord(DestReg, DestTy), TheCall, Args, false);
2838 TM.CalledFunctions.insert(floatFn);
2843 F->getFrameInfo()->CreateStackObject(Type::DoubleTy, TM.getTargetData());
2845 if (DestTy->isSigned()) {
2846 unsigned TempReg = makeAnotherReg(Type::DoubleTy);
2848 // Convert to integer in the FP reg and store it to a stack slot
2849 BuildMI(*MBB, IP, PPC::FCTIWZ, 1, TempReg).addReg(SrcReg);
2850 addFrameReference(BuildMI(*MBB, IP, PPC::STFD, 3)
2851 .addReg(TempReg), ValueFrameIdx);
2853 // There is no load signed byte opcode, so we must emit a sign extend for
2854 // that particular size. Make sure to source the new integer from the
2856 if (DestClass == cByte) {
2857 unsigned TempReg2 = makeAnotherReg(DestTy);
2858 addFrameReference(BuildMI(*MBB, IP, PPC::LBZ, 2, TempReg2),
2860 BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(TempReg2);
2862 int offset = (DestClass == cShort) ? 6 : 4;
2863 unsigned LoadOp = (DestClass == cShort) ? PPC::LHA : PPC::LWZ;
2864 addFrameReference(BuildMI(*MBB, IP, LoadOp, 2, DestReg),
2865 ValueFrameIdx, offset);
2868 unsigned Zero = getReg(ConstantFP::get(Type::DoubleTy, 0.0f));
2869 double maxInt = (1LL << 32) - 1;
2870 unsigned MaxInt = getReg(ConstantFP::get(Type::DoubleTy, maxInt));
2871 double border = 1LL << 31;
2872 unsigned Border = getReg(ConstantFP::get(Type::DoubleTy, border));
2873 unsigned UseZero = makeAnotherReg(Type::DoubleTy);
2874 unsigned UseMaxInt = makeAnotherReg(Type::DoubleTy);
2875 unsigned UseChoice = makeAnotherReg(Type::DoubleTy);
2876 unsigned TmpReg = makeAnotherReg(Type::DoubleTy);
2877 unsigned TmpReg2 = makeAnotherReg(Type::DoubleTy);
2878 unsigned ConvReg = makeAnotherReg(Type::DoubleTy);
2879 unsigned IntTmp = makeAnotherReg(Type::IntTy);
2880 unsigned XorReg = makeAnotherReg(Type::IntTy);
2882 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
2883 // Update machine-CFG edges
2884 MachineBasicBlock *XorMBB = new MachineBasicBlock(BB->getBasicBlock());
2885 MachineBasicBlock *PhiMBB = new MachineBasicBlock(BB->getBasicBlock());
2886 MachineBasicBlock *OldMBB = BB;
2887 ilist<MachineBasicBlock>::iterator It = BB; ++It;
2888 F->getBasicBlockList().insert(It, XorMBB);
2889 F->getBasicBlockList().insert(It, PhiMBB);
2890 BB->addSuccessor(XorMBB);
2891 BB->addSuccessor(PhiMBB);
2893 // Convert from floating point to unsigned 32-bit value
2894 // Use 0 if incoming value is < 0.0
2895 BuildMI(*MBB, IP, PPC::FSEL, 3, UseZero).addReg(SrcReg).addReg(SrcReg)
2897 // Use 2**32 - 1 if incoming value is >= 2**32
2898 BuildMI(*MBB, IP, PPC::FSUB, 2, UseMaxInt).addReg(MaxInt).addReg(SrcReg);
2899 BuildMI(*MBB, IP, PPC::FSEL, 3, UseChoice).addReg(UseMaxInt)
2900 .addReg(UseZero).addReg(MaxInt);
2902 BuildMI(*MBB, IP, PPC::FSUB, 2, TmpReg).addReg(UseChoice).addReg(Border);
2903 // Use difference if >= 2**31
2904 BuildMI(*MBB, IP, PPC::FCMPU, 2, PPC::CR0).addReg(UseChoice)
2906 BuildMI(*MBB, IP, PPC::FSEL, 3, TmpReg2).addReg(TmpReg).addReg(TmpReg)
2908 // Convert to integer
2909 BuildMI(*MBB, IP, PPC::FCTIWZ, 1, ConvReg).addReg(TmpReg2);
2910 addFrameReference(BuildMI(*MBB, IP, PPC::STFD, 3).addReg(ConvReg),
2912 if (DestClass == cByte) {
2913 addFrameReference(BuildMI(*MBB, IP, PPC::LBZ, 2, DestReg),
2915 } else if (DestClass == cShort) {
2916 addFrameReference(BuildMI(*MBB, IP, PPC::LHZ, 2, DestReg),
2918 } if (DestClass == cInt) {
2919 addFrameReference(BuildMI(*MBB, IP, PPC::LWZ, 2, IntTmp),
2921 BuildMI(*MBB, IP, PPC::BLT, 2).addReg(PPC::CR0).addMBB(PhiMBB);
2922 BuildMI(*MBB, IP, PPC::B, 1).addMBB(XorMBB);
2925 // add 2**31 if input was >= 2**31
2927 BuildMI(BB, PPC::XORIS, 2, XorReg).addReg(IntTmp).addImm(0x8000);
2928 XorMBB->addSuccessor(PhiMBB);
2931 // DestReg = phi [ IntTmp, OldMBB ], [ XorReg, XorMBB ]
2933 BuildMI(BB, PPC::PHI, 4, DestReg).addReg(IntTmp).addMBB(OldMBB)
2934 .addReg(XorReg).addMBB(XorMBB);
2940 // Check our invariants
2941 assert((SrcClass <= cInt || SrcClass == cLong) &&
2942 "Unhandled source class for cast operation!");
2943 assert((DestClass <= cInt || DestClass == cLong) &&
2944 "Unhandled destination class for cast operation!");
2946 bool sourceUnsigned = SrcTy->isUnsigned() || SrcTy == Type::BoolTy;
2947 bool destUnsigned = DestTy->isUnsigned();
2949 // Unsigned -> Unsigned, clear if larger,
2950 if (sourceUnsigned && destUnsigned) {
2951 // handle long dest class now to keep switch clean
2952 if (DestClass == cLong) {
2953 if (SrcClass == cLong) {
2954 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2955 BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(SrcReg+1)
2958 BuildMI(*MBB, IP, PPC::LI, 1, DestReg).addSImm(0);
2959 BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(SrcReg)
2965 // handle u{ byte, short, int } x u{ byte, short, int }
2966 unsigned clearBits = (SrcClass == cByte || DestClass == cByte) ? 24 : 16;
2970 if (SrcClass == DestClass)
2971 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2973 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
2974 .addImm(0).addImm(clearBits).addImm(31);
2980 if (DestClass == cInt)
2981 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2983 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
2984 .addImm(0).addImm(clearBits).addImm(31);
2991 if (!sourceUnsigned && !destUnsigned) {
2992 // handle long dest class now to keep switch clean
2993 if (DestClass == cLong) {
2994 if (SrcClass == cLong) {
2995 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2996 BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(SrcReg+1)
2999 BuildMI(*MBB, IP, PPC::SRAWI, 2, DestReg).addReg(SrcReg).addImm(31);
3000 BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(SrcReg)
3006 // handle { byte, short, int } x { byte, short, int }
3009 if (DestClass == cByte)
3010 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
3012 BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
3015 if (DestClass == cByte)
3016 BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
3017 else if (DestClass == cShort)
3018 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
3020 BuildMI(*MBB, IP, PPC::EXTSH, 1, DestReg).addReg(SrcReg);
3026 if (DestClass == cByte)
3027 BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
3028 else if (DestClass == cShort)
3029 BuildMI(*MBB, IP, PPC::EXTSH, 1, DestReg).addReg(SrcReg);
3031 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
3037 // Unsigned -> Signed
3038 if (sourceUnsigned && !destUnsigned) {
3039 // handle long dest class now to keep switch clean
3040 if (DestClass == cLong) {
3041 if (SrcClass == cLong) {
3042 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
3043 BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(SrcReg+1).
3046 BuildMI(*MBB, IP, PPC::LI, 1, DestReg).addSImm(0);
3047 BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(SrcReg)
3053 // handle u{ byte, short, int } -> { byte, short, int }
3056 if (DestClass == cByte)
3057 // uByte 255 -> signed byte == -1
3058 BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
3060 // uByte 255 -> signed short/int == 255
3061 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg).addImm(0)
3062 .addImm(24).addImm(31);
3065 if (DestClass == cByte)
3066 BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
3067 else if (DestClass == cShort)
3068 BuildMI(*MBB, IP, PPC::EXTSH, 1, DestReg).addReg(SrcReg);
3070 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg).addImm(0)
3071 .addImm(16).addImm(31);
3077 if (DestClass == cByte)
3078 BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
3079 else if (DestClass == cShort)
3080 BuildMI(*MBB, IP, PPC::EXTSH, 1, DestReg).addReg(SrcReg);
3082 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
3088 // Signed -> Unsigned
3089 if (!sourceUnsigned && destUnsigned) {
3090 // handle long dest class now to keep switch clean
3091 if (DestClass == cLong) {
3092 if (SrcClass == cLong) {
3093 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
3094 BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(SrcReg+1)
3097 BuildMI(*MBB, IP, PPC::SRAWI, 2, DestReg).addReg(SrcReg).addImm(31);
3098 BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(SrcReg)
3104 // handle { byte, short, int } -> u{ byte, short, int }
3105 unsigned clearBits = (DestClass == cByte) ? 24 : 16;
3109 if (DestClass == cByte || DestClass == cShort)
3110 // sbyte -1 -> ubyte 0x000000FF
3111 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
3112 .addImm(0).addImm(clearBits).addImm(31);
3114 // sbyte -1 -> ubyte 0xFFFFFFFF
3115 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
3121 if (DestClass == cInt)
3122 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
3124 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
3125 .addImm(0).addImm(clearBits).addImm(31);
3131 // Anything we haven't handled already, we can't (yet) handle at all.
3132 std::cerr << "Unhandled cast from " << SrcTy->getDescription()
3133 << "to " << DestTy->getDescription() << '\n';
3137 /// visitVANextInst - Implement the va_next instruction...
3139 void ISel::visitVANextInst(VANextInst &I) {
3140 unsigned VAList = getReg(I.getOperand(0));
3141 unsigned DestReg = getReg(I);
3144 switch (I.getArgType()->getTypeID()) {
3147 assert(0 && "Error: bad type for va_next instruction!");
3149 case Type::PointerTyID:
3150 case Type::UIntTyID:
3154 case Type::ULongTyID:
3155 case Type::LongTyID:
3156 case Type::DoubleTyID:
3161 // Increment the VAList pointer...
3162 BuildMI(BB, PPC::ADDI, 2, DestReg).addReg(VAList).addSImm(Size);
3165 void ISel::visitVAArgInst(VAArgInst &I) {
3166 unsigned VAList = getReg(I.getOperand(0));
3167 unsigned DestReg = getReg(I);
3169 switch (I.getType()->getTypeID()) {
3172 assert(0 && "Error: bad type for va_next instruction!");
3174 case Type::PointerTyID:
3175 case Type::UIntTyID:
3177 BuildMI(BB, PPC::LWZ, 2, DestReg).addSImm(0).addReg(VAList);
3179 case Type::ULongTyID:
3180 case Type::LongTyID:
3181 BuildMI(BB, PPC::LWZ, 2, DestReg).addSImm(0).addReg(VAList);
3182 BuildMI(BB, PPC::LWZ, 2, DestReg+1).addSImm(4).addReg(VAList);
3184 case Type::FloatTyID:
3185 BuildMI(BB, PPC::LFS, 2, DestReg).addSImm(0).addReg(VAList);
3187 case Type::DoubleTyID:
3188 BuildMI(BB, PPC::LFD, 2, DestReg).addSImm(0).addReg(VAList);
3193 /// visitGetElementPtrInst - instruction-select GEP instructions
3195 void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
3196 if (canFoldGEPIntoLoadOrStore(&I))
3199 unsigned outputReg = getReg(I);
3200 emitGEPOperation(BB, BB->end(), I.getOperand(0), I.op_begin()+1, I.op_end(),
3201 outputReg, false, 0, 0);
3204 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
3205 /// constant expression GEP support.
3207 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
3208 MachineBasicBlock::iterator IP,
3209 Value *Src, User::op_iterator IdxBegin,
3210 User::op_iterator IdxEnd, unsigned TargetReg,
3211 bool GEPIsFolded, ConstantSInt **RemainderPtr,
3212 unsigned *PendingAddReg) {
3213 const TargetData &TD = TM.getTargetData();
3214 const Type *Ty = Src->getType();
3215 unsigned basePtrReg = getReg(Src, MBB, IP);
3216 int64_t constValue = 0;
3218 // Record the operations to emit the GEP in a vector so that we can emit them
3219 // after having analyzed the entire instruction.
3220 std::vector<CollapsedGepOp> ops;
3222 // GEPs have zero or more indices; we must perform a struct access
3223 // or array access for each one.
3224 for (GetElementPtrInst::op_iterator oi = IdxBegin, oe = IdxEnd; oi != oe;
3227 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
3228 // It's a struct access. idx is the index into the structure,
3229 // which names the field. Use the TargetData structure to
3230 // pick out what the layout of the structure is in memory.
3231 // Use the (constant) structure index's value to find the
3232 // right byte offset from the StructLayout class's list of
3233 // structure member offsets.
3234 unsigned fieldIndex = cast<ConstantUInt>(idx)->getValue();
3235 unsigned memberOffset =
3236 TD.getStructLayout(StTy)->MemberOffsets[fieldIndex];
3238 // StructType member offsets are always constant values. Add it to the
3240 constValue += memberOffset;
3242 // The next type is the member of the structure selected by the
3244 Ty = StTy->getElementType (fieldIndex);
3245 } else if (const SequentialType *SqTy = dyn_cast<SequentialType> (Ty)) {
3246 // Many GEP instructions use a [cast (int/uint) to LongTy] as their
3247 // operand. Handle this case directly now...
3248 if (CastInst *CI = dyn_cast<CastInst>(idx))
3249 if (CI->getOperand(0)->getType() == Type::IntTy ||
3250 CI->getOperand(0)->getType() == Type::UIntTy)
3251 idx = CI->getOperand(0);
3253 // It's an array or pointer access: [ArraySize x ElementType].
3254 // We want to add basePtrReg to (idxReg * sizeof ElementType). First, we
3255 // must find the size of the pointed-to type (Not coincidentally, the next
3256 // type is the type of the elements in the array).
3257 Ty = SqTy->getElementType();
3258 unsigned elementSize = TD.getTypeSize(Ty);
3260 if (ConstantInt *C = dyn_cast<ConstantInt>(idx)) {
3261 if (ConstantSInt *CS = dyn_cast<ConstantSInt>(C))
3262 constValue += CS->getValue() * elementSize;
3263 else if (ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
3264 constValue += CU->getValue() * elementSize;
3266 assert(0 && "Invalid ConstantInt GEP index type!");
3268 // Push current gep state to this point as an add
3269 ops.push_back(CollapsedGepOp(false, 0,
3270 ConstantSInt::get(Type::IntTy,constValue)));
3272 // Push multiply gep op and reset constant value
3273 ops.push_back(CollapsedGepOp(true, idx,
3274 ConstantSInt::get(Type::IntTy, elementSize)));
3280 // Emit instructions for all the collapsed ops
3281 bool pendingAdd = false;
3282 unsigned pendingAddReg = 0;
3284 for(std::vector<CollapsedGepOp>::iterator cgo_i = ops.begin(),
3285 cgo_e = ops.end(); cgo_i != cgo_e; ++cgo_i) {
3286 CollapsedGepOp& cgo = *cgo_i;
3287 unsigned nextBasePtrReg = makeAnotherReg(Type::IntTy);
3289 // If we didn't emit an add last time through the loop, we need to now so
3290 // that the base reg is updated appropriately.
3292 assert(pendingAddReg != 0 && "Uninitialized register in pending add!");
3293 BuildMI(*MBB, IP, PPC::ADD, 2, nextBasePtrReg).addReg(basePtrReg)
3294 .addReg(pendingAddReg);
3295 basePtrReg = nextBasePtrReg;
3296 nextBasePtrReg = makeAnotherReg(Type::IntTy);
3302 // We know the elementSize is a constant, so we can emit a constant mul
3303 unsigned TmpReg = makeAnotherReg(Type::IntTy);
3304 doMultiplyConst(MBB, IP, nextBasePtrReg, cgo.index, cgo.size);
3305 pendingAddReg = basePtrReg;
3308 // Try and generate an immediate addition if possible
3309 if (cgo.size->isNullValue()) {
3310 BuildMI(*MBB, IP, PPC::OR, 2, nextBasePtrReg).addReg(basePtrReg)
3311 .addReg(basePtrReg);
3312 } else if (canUseAsImmediateForOpcode(cgo.size, 0)) {
3313 BuildMI(*MBB, IP, PPC::ADDI, 2, nextBasePtrReg).addReg(basePtrReg)
3314 .addSImm(cgo.size->getValue());
3316 unsigned Op1r = getReg(cgo.size, MBB, IP);
3317 BuildMI(*MBB, IP, PPC::ADD, 2, nextBasePtrReg).addReg(basePtrReg)
3322 basePtrReg = nextBasePtrReg;
3324 // Add the current base register plus any accumulated constant value
3325 ConstantSInt *remainder = ConstantSInt::get(Type::IntTy, constValue);
3327 // If we are emitting this during a fold, copy the current base register to
3328 // the target, and save the current constant offset so the folding load or
3329 // store can try and use it as an immediate.
3331 // If this is a folded GEP and the last element was an index, then we need
3332 // to do some extra work to turn a shift/add/stw into a shift/stwx
3333 if (pendingAdd && 0 == remainder->getValue()) {
3334 assert(pendingAddReg != 0 && "Uninitialized register in pending add!");
3335 *PendingAddReg = pendingAddReg;
3339 unsigned nextBasePtrReg = makeAnotherReg(Type::IntTy);
3340 assert(pendingAddReg != 0 && "Uninitialized register in pending add!");
3341 BuildMI(*MBB, IP, PPC::ADD, 2, nextBasePtrReg).addReg(basePtrReg)
3342 .addReg(pendingAddReg);
3343 basePtrReg = nextBasePtrReg;
3346 BuildMI (*MBB, IP, PPC::OR, 2, TargetReg).addReg(basePtrReg)
3347 .addReg(basePtrReg);
3348 *RemainderPtr = remainder;
3352 // If we still have a pending add at this point, emit it now
3354 unsigned TmpReg = makeAnotherReg(Type::IntTy);
3355 BuildMI(*MBB, IP, PPC::ADD, 2, TmpReg).addReg(pendingAddReg)
3356 .addReg(basePtrReg);
3357 basePtrReg = TmpReg;
3360 // After we have processed all the indices, the result is left in
3361 // basePtrReg. Move it to the register where we were expected to
3363 if (remainder->isNullValue()) {
3364 BuildMI (*MBB, IP, PPC::OR, 2, TargetReg).addReg(basePtrReg)
3365 .addReg(basePtrReg);
3366 } else if (canUseAsImmediateForOpcode(remainder, 0)) {
3367 BuildMI(*MBB, IP, PPC::ADDI, 2, TargetReg).addReg(basePtrReg)
3368 .addSImm(remainder->getValue());
3370 unsigned Op1r = getReg(remainder, MBB, IP);
3371 BuildMI(*MBB, IP, PPC::ADD, 2, TargetReg).addReg(basePtrReg).addReg(Op1r);
3375 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
3376 /// frame manager, otherwise do it the hard way.
3378 void ISel::visitAllocaInst(AllocaInst &I) {
3379 // If this is a fixed size alloca in the entry block for the function, we
3380 // statically stack allocate the space, so we don't need to do anything here.
3382 if (dyn_castFixedAlloca(&I)) return;
3384 // Find the data size of the alloca inst's getAllocatedType.
3385 const Type *Ty = I.getAllocatedType();
3386 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
3388 // Create a register to hold the temporary result of multiplying the type size
3389 // constant by the variable amount.
3390 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
3392 // TotalSizeReg = mul <numelements>, <TypeSize>
3393 MachineBasicBlock::iterator MBBI = BB->end();
3394 ConstantUInt *CUI = ConstantUInt::get(Type::UIntTy, TySize);
3395 doMultiplyConst(BB, MBBI, TotalSizeReg, I.getArraySize(), CUI);
3397 // AddedSize = add <TotalSizeReg>, 15
3398 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
3399 BuildMI(BB, PPC::ADDI, 2, AddedSizeReg).addReg(TotalSizeReg).addSImm(15);
3401 // AlignedSize = and <AddedSize>, ~15
3402 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
3403 BuildMI(BB, PPC::RLWINM, 4, AlignedSize).addReg(AddedSizeReg).addImm(0)
3404 .addImm(0).addImm(27);
3406 // Subtract size from stack pointer, thereby allocating some space.
3407 BuildMI(BB, PPC::SUB, 2, PPC::R1).addReg(PPC::R1).addReg(AlignedSize);
3409 // Put a pointer to the space into the result register, by copying
3410 // the stack pointer.
3411 BuildMI(BB, PPC::OR, 2, getReg(I)).addReg(PPC::R1).addReg(PPC::R1);
3413 // Inform the Frame Information that we have just allocated a variable-sized
3415 F->getFrameInfo()->CreateVariableSizedObject();
3418 /// visitMallocInst - Malloc instructions are code generated into direct calls
3419 /// to the library malloc.
3421 void ISel::visitMallocInst(MallocInst &I) {
3422 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
3425 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
3426 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
3428 Arg = makeAnotherReg(Type::UIntTy);
3429 MachineBasicBlock::iterator MBBI = BB->end();
3430 ConstantUInt *CUI = ConstantUInt::get(Type::UIntTy, AllocSize);
3431 doMultiplyConst(BB, MBBI, Arg, I.getOperand(0), CUI);
3434 std::vector<ValueRecord> Args;
3435 Args.push_back(ValueRecord(Arg, Type::UIntTy));
3436 MachineInstr *TheCall =
3437 BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(mallocFn, true);
3438 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args, false);
3439 TM.CalledFunctions.insert(mallocFn);
3443 /// visitFreeInst - Free instructions are code gen'd to call the free libc
3446 void ISel::visitFreeInst(FreeInst &I) {
3447 std::vector<ValueRecord> Args;
3448 Args.push_back(ValueRecord(I.getOperand(0)));
3449 MachineInstr *TheCall =
3450 BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(freeFn, true);
3451 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args, false);
3452 TM.CalledFunctions.insert(freeFn);
3455 /// createPPC32ISelSimple - This pass converts an LLVM function into a machine
3456 /// code representation is a very simple peep-hole fashion.
3458 FunctionPass *llvm::createPPC32ISelSimple(TargetMachine &TM) {
3459 return new ISel(TM);