1 //===-- InstSelectSimple.cpp - A simple instruction selector for PowerPC --===//
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 "llvm/Constants.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/Function.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Pass.h"
19 #include "llvm/CodeGen/IntrinsicLowering.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/SSARegMap.h"
24 #include "llvm/Target/MRegisterInfo.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Support/GetElementPtrTypeIterator.h"
27 #include "llvm/Support/InstVisitor.h"
28 #include "Support/Debug.h"
33 /// TypeClass - Used by the PowerPC backend to group LLVM types by their basic
34 /// PPC Representation.
37 cByte, cShort, cInt, cFP, cLong
41 /// getClass - Turn a primitive type into a "class" number which is based on the
42 /// size of the type, and whether or not it is floating point.
44 static inline TypeClass getClass(const Type *Ty) {
45 switch (Ty->getTypeID()) {
47 case Type::UByteTyID: return cByte; // Byte operands are class #0
49 case Type::UShortTyID: return cShort; // Short operands are class #1
52 case Type::PointerTyID: return cInt; // Int's and pointers are class #2
55 case Type::DoubleTyID: return cFP; // Floating Point is #3
58 case Type::ULongTyID: return cLong; // Longs are class #4
60 assert(0 && "Invalid type to getClass!");
61 return cByte; // not reached
65 // getClassB - Just like getClass, but treat boolean values as ints.
66 static inline TypeClass getClassB(const Type *Ty) {
67 if (Ty == Type::BoolTy) return cInt;
72 struct ISel : public FunctionPass, InstVisitor<ISel> {
74 MachineFunction *F; // The function we are compiling into
75 MachineBasicBlock *BB; // The current MBB we are compiling
76 int VarArgsFrameIndex; // FrameIndex for start of varargs area
77 int ReturnAddressIndex; // FrameIndex for the return address
79 std::map<Value*, unsigned> RegMap; // Mapping between Val's and SSA Regs
81 // MBBMap - Mapping between LLVM BB -> Machine BB
82 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
84 // AllocaMap - Mapping from fixed sized alloca instructions to the
85 // FrameIndex for the alloca.
86 std::map<AllocaInst*, unsigned> AllocaMap;
88 ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
90 /// runOnFunction - Top level implementation of instruction selection for
91 /// the entire function.
93 bool runOnFunction(Function &Fn) {
94 // First pass over the function, lower any unknown intrinsic functions
95 // with the IntrinsicLowering class.
96 LowerUnknownIntrinsicFunctionCalls(Fn);
98 F = &MachineFunction::construct(&Fn, TM);
100 // Create all of the machine basic blocks for the function...
101 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
102 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
106 // Set up a frame object for the return address. This is used by the
107 // llvm.returnaddress & llvm.frameaddress intrinisics.
108 ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
110 // Copy incoming arguments off of the stack...
111 LoadArgumentsToVirtualRegs(Fn);
113 // Instruction select everything except PHI nodes
116 // Select the PHI nodes
123 // We always build a machine code representation for the function
127 virtual const char *getPassName() const {
128 return "PowerPC Simple Instruction Selection";
131 /// visitBasicBlock - This method is called when we are visiting a new basic
132 /// block. This simply creates a new MachineBasicBlock to emit code into
133 /// and adds it to the current MachineFunction. Subsequent visit* for
134 /// instructions will be invoked for all instructions in the basic block.
136 void visitBasicBlock(BasicBlock &LLVM_BB) {
137 BB = MBBMap[&LLVM_BB];
140 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
141 /// function, lowering any calls to unknown intrinsic functions into the
142 /// equivalent LLVM code.
144 void LowerUnknownIntrinsicFunctionCalls(Function &F);
146 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
147 /// from the stack into virtual registers.
149 void LoadArgumentsToVirtualRegs(Function &F);
151 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
152 /// because we have to generate our sources into the source basic blocks,
153 /// not the current one.
155 void SelectPHINodes();
157 // Visitation methods for various instructions. These methods simply emit
158 // fixed PowerPC code for each instruction.
160 // Control flow operators
161 void visitReturnInst(ReturnInst &RI);
162 void visitBranchInst(BranchInst &BI);
168 ValueRecord(unsigned R, const Type *T) : Val(0), Reg(R), Ty(T) {}
169 ValueRecord(Value *V) : Val(V), Reg(0), Ty(V->getType()) {}
171 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
172 const std::vector<ValueRecord> &Args);
173 void visitCallInst(CallInst &I);
174 void visitIntrinsicCall(Intrinsic::ID ID, CallInst &I);
176 // Arithmetic operators
177 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
178 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
179 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
180 void visitMul(BinaryOperator &B);
182 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
183 void visitRem(BinaryOperator &B) { visitDivRem(B); }
184 void visitDivRem(BinaryOperator &B);
187 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
188 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
189 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
191 // Comparison operators...
192 void visitSetCondInst(SetCondInst &I);
193 unsigned EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
194 MachineBasicBlock *MBB,
195 MachineBasicBlock::iterator MBBI);
196 void visitSelectInst(SelectInst &SI);
199 // Memory Instructions
200 void visitLoadInst(LoadInst &I);
201 void visitStoreInst(StoreInst &I);
202 void visitGetElementPtrInst(GetElementPtrInst &I);
203 void visitAllocaInst(AllocaInst &I);
204 void visitMallocInst(MallocInst &I);
205 void visitFreeInst(FreeInst &I);
208 void visitShiftInst(ShiftInst &I);
209 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
210 void visitCastInst(CastInst &I);
211 void visitVANextInst(VANextInst &I);
212 void visitVAArgInst(VAArgInst &I);
214 void visitInstruction(Instruction &I) {
215 std::cerr << "Cannot instruction select: " << I;
219 /// promote32 - Make a value 32-bits wide, and put it somewhere.
221 void promote32(unsigned targetReg, const ValueRecord &VR);
223 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
224 /// constant expression GEP support.
226 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
227 Value *Src, User::op_iterator IdxBegin,
228 User::op_iterator IdxEnd, unsigned TargetReg);
230 /// emitCastOperation - Common code shared between visitCastInst and
231 /// constant expression cast support.
233 void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
234 Value *Src, const Type *DestTy, unsigned TargetReg);
236 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
237 /// and constant expression support.
239 void emitSimpleBinaryOperation(MachineBasicBlock *BB,
240 MachineBasicBlock::iterator IP,
241 Value *Op0, Value *Op1,
242 unsigned OperatorClass, unsigned TargetReg);
244 /// emitBinaryFPOperation - This method handles emission of floating point
245 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
246 void emitBinaryFPOperation(MachineBasicBlock *BB,
247 MachineBasicBlock::iterator IP,
248 Value *Op0, Value *Op1,
249 unsigned OperatorClass, unsigned TargetReg);
251 void emitMultiply(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
252 Value *Op0, Value *Op1, unsigned TargetReg);
254 void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
255 unsigned DestReg, const Type *DestTy,
256 unsigned Op0Reg, unsigned Op1Reg);
257 void doMultiplyConst(MachineBasicBlock *MBB,
258 MachineBasicBlock::iterator MBBI,
259 unsigned DestReg, const Type *DestTy,
260 unsigned Op0Reg, unsigned Op1Val);
262 void emitDivRemOperation(MachineBasicBlock *BB,
263 MachineBasicBlock::iterator IP,
264 Value *Op0, Value *Op1, bool isDiv,
267 /// emitSetCCOperation - Common code shared between visitSetCondInst and
268 /// constant expression support.
270 void emitSetCCOperation(MachineBasicBlock *BB,
271 MachineBasicBlock::iterator IP,
272 Value *Op0, Value *Op1, unsigned Opcode,
275 /// emitShiftOperation - Common code shared between visitShiftInst and
276 /// constant expression support.
278 void emitShiftOperation(MachineBasicBlock *MBB,
279 MachineBasicBlock::iterator IP,
280 Value *Op, Value *ShiftAmount, bool isLeftShift,
281 const Type *ResultTy, unsigned DestReg);
283 /// emitSelectOperation - Common code shared between visitSelectInst and the
284 /// constant expression support.
285 void emitSelectOperation(MachineBasicBlock *MBB,
286 MachineBasicBlock::iterator IP,
287 Value *Cond, Value *TrueVal, Value *FalseVal,
290 /// copyConstantToRegister - Output the instructions required to put the
291 /// specified constant into the specified register.
293 void copyConstantToRegister(MachineBasicBlock *MBB,
294 MachineBasicBlock::iterator MBBI,
295 Constant *C, unsigned Reg);
297 void emitUCOM(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
298 unsigned LHS, unsigned RHS);
300 /// makeAnotherReg - This method returns the next register number we haven't
303 /// Long values are handled somewhat specially. They are always allocated
304 /// as pairs of 32 bit integer values. The register number returned is the
305 /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
306 /// of the long value.
308 unsigned makeAnotherReg(const Type *Ty) {
309 assert(dynamic_cast<const PowerPCRegisterInfo*>(TM.getRegisterInfo()) &&
310 "Current target doesn't have PPC reg info??");
311 const PowerPCRegisterInfo *MRI =
312 static_cast<const PowerPCRegisterInfo*>(TM.getRegisterInfo());
313 if (Ty == Type::LongTy || Ty == Type::ULongTy) {
314 const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
315 // Create the lower part
316 F->getSSARegMap()->createVirtualRegister(RC);
317 // Create the upper part.
318 return F->getSSARegMap()->createVirtualRegister(RC)-1;
321 // Add the mapping of regnumber => reg class to MachineFunction
322 const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
323 return F->getSSARegMap()->createVirtualRegister(RC);
326 /// getReg - This method turns an LLVM value into a register number.
328 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
329 unsigned getReg(Value *V) {
330 // Just append to the end of the current bb.
331 MachineBasicBlock::iterator It = BB->end();
332 return getReg(V, BB, It);
334 unsigned getReg(Value *V, MachineBasicBlock *MBB,
335 MachineBasicBlock::iterator IPt);
337 /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
338 /// that is to be statically allocated with the initial stack frame
340 unsigned getFixedSizedAllocaFI(AllocaInst *AI);
344 /// dyn_castFixedAlloca - If the specified value is a fixed size alloca
345 /// instruction in the entry block, return it. Otherwise, return a null
347 static AllocaInst *dyn_castFixedAlloca(Value *V) {
348 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
349 BasicBlock *BB = AI->getParent();
350 if (isa<ConstantUInt>(AI->getArraySize()) && BB ==&BB->getParent()->front())
356 /// getReg - This method turns an LLVM value into a register number.
358 unsigned ISel::getReg(Value *V, MachineBasicBlock *MBB,
359 MachineBasicBlock::iterator IPt) {
360 // If this operand is a constant, emit the code to copy the constant into
361 // the register here...
363 if (Constant *C = dyn_cast<Constant>(V)) {
364 unsigned Reg = makeAnotherReg(V->getType());
365 copyConstantToRegister(MBB, IPt, C, Reg);
367 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
368 unsigned Reg1 = makeAnotherReg(V->getType());
369 unsigned Reg2 = makeAnotherReg(V->getType());
370 // Move the address of the global into the register
371 BuildMI(*MBB, IPt, PPC32::LOADHiAddr, 2, Reg1).addReg(PPC32::R0).addGlobalAddress(GV);
372 BuildMI(*MBB, IPt, PPC32::LOADLoAddr, 2, Reg2).addReg(Reg1).addGlobalAddress(GV);
374 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
375 // Do not emit noop casts at all.
376 if (getClassB(CI->getType()) == getClassB(CI->getOperand(0)->getType()))
377 return getReg(CI->getOperand(0), MBB, IPt);
378 } else if (AllocaInst *AI = dyn_castFixedAlloca(V)) {
379 unsigned Reg = makeAnotherReg(V->getType());
380 unsigned FI = getFixedSizedAllocaFI(AI);
381 addFrameReference(BuildMI(*MBB, IPt, PPC32::ADDI, 2, Reg), FI, 0, false);
385 unsigned &Reg = RegMap[V];
387 Reg = makeAnotherReg(V->getType());
394 /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
395 /// that is to be statically allocated with the initial stack frame
397 unsigned ISel::getFixedSizedAllocaFI(AllocaInst *AI) {
398 // Already computed this?
399 std::map<AllocaInst*, unsigned>::iterator I = AllocaMap.lower_bound(AI);
400 if (I != AllocaMap.end() && I->first == AI) return I->second;
402 const Type *Ty = AI->getAllocatedType();
403 ConstantUInt *CUI = cast<ConstantUInt>(AI->getArraySize());
404 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
405 TySize *= CUI->getValue(); // Get total allocated size...
406 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
408 // Create a new stack object using the frame manager...
409 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
410 AllocaMap.insert(I, std::make_pair(AI, FrameIdx));
415 /// copyConstantToRegister - Output the instructions required to put the
416 /// specified constant into the specified register.
418 void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
419 MachineBasicBlock::iterator IP,
420 Constant *C, unsigned R) {
421 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
423 switch (CE->getOpcode()) {
424 case Instruction::GetElementPtr:
425 emitGEPOperation(MBB, IP, CE->getOperand(0),
426 CE->op_begin()+1, CE->op_end(), R);
428 case Instruction::Cast:
429 emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
432 case Instruction::Xor: ++Class; // FALL THROUGH
433 case Instruction::Or: ++Class; // FALL THROUGH
434 case Instruction::And: ++Class; // FALL THROUGH
435 case Instruction::Sub: ++Class; // FALL THROUGH
436 case Instruction::Add:
437 emitSimpleBinaryOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
441 case Instruction::Mul:
442 emitMultiply(MBB, IP, CE->getOperand(0), CE->getOperand(1), R);
445 case Instruction::Div:
446 case Instruction::Rem:
447 emitDivRemOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
448 CE->getOpcode() == Instruction::Div, R);
451 case Instruction::SetNE:
452 case Instruction::SetEQ:
453 case Instruction::SetLT:
454 case Instruction::SetGT:
455 case Instruction::SetLE:
456 case Instruction::SetGE:
457 emitSetCCOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
461 case Instruction::Shl:
462 case Instruction::Shr:
463 emitShiftOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
464 CE->getOpcode() == Instruction::Shl, CE->getType(), R);
467 case Instruction::Select:
468 emitSelectOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
469 CE->getOperand(2), R);
473 std::cerr << "Offending expr: " << C << "\n";
474 assert(0 && "Constant expression not yet handled!\n");
478 if (C->getType()->isIntegral()) {
479 unsigned Class = getClassB(C->getType());
481 if (Class == cLong) {
482 // Copy the value into the register pair.
483 uint64_t Val = cast<ConstantInt>(C)->getRawValue();
484 unsigned hiTmp = makeAnotherReg(Type::IntTy);
485 unsigned loTmp = makeAnotherReg(Type::IntTy);
486 BuildMI(*MBB, IP, PPC32::ADDIS, 2, loTmp).addReg(PPC32::R0).addImm(Val >> 48);
487 BuildMI(*MBB, IP, PPC32::ORI, 2, R).addReg(loTmp).addImm((Val >> 32) & 0xFFFF);
488 BuildMI(*MBB, IP, PPC32::ADDIS, 2, hiTmp).addReg(PPC32::R0).addImm((Val >> 16) & 0xFFFF);
489 BuildMI(*MBB, IP, PPC32::ORI, 2, R+1).addReg(hiTmp).addImm(Val & 0xFFFF);
493 assert(Class <= cInt && "Type not handled yet!");
495 if (C->getType() == Type::BoolTy) {
496 BuildMI(*MBB, IP, PPC32::ADDI, 2, R).addReg(PPC32::R0).addImm(C == ConstantBool::True);
497 } else if (Class == cByte || Class == cShort) {
498 ConstantInt *CI = cast<ConstantInt>(C);
499 BuildMI(*MBB, IP, PPC32::ADDI, 2, R).addReg(PPC32::R0).addImm(CI->getRawValue());
501 ConstantInt *CI = cast<ConstantInt>(C);
502 int TheVal = CI->getRawValue() & 0xFFFFFFFF;
503 if (TheVal < 32768 && TheVal >= -32768) {
504 BuildMI(*MBB, IP, PPC32::ADDI, 2, R).addReg(PPC32::R0).addImm(CI->getRawValue());
506 unsigned TmpReg = makeAnotherReg(Type::IntTy);
507 BuildMI(*MBB, IP, PPC32::ADDIS, 2, TmpReg).addReg(PPC32::R0).addImm(CI->getRawValue() >> 16);
508 BuildMI(*MBB, IP, PPC32::ORI, 2, R).addReg(TmpReg).addImm(CI->getRawValue() & 0xFFFF);
511 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
512 // We need to spill the constant to memory...
513 MachineConstantPool *CP = F->getConstantPool();
514 unsigned CPI = CP->getConstantPoolIndex(CFP);
515 const Type *Ty = CFP->getType();
517 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
518 unsigned LoadOpcode = Ty == Type::FloatTy ? PPC32::LFS : PPC32::LFD;
519 addConstantPoolReference(BuildMI(*MBB, IP, LoadOpcode, 2, R), CPI);
520 } else if (isa<ConstantPointerNull>(C)) {
521 // Copy zero (null pointer) to the register.
522 BuildMI(*MBB, IP, PPC32::ADDI, 2, R).addReg(PPC32::R0).addImm(0);
523 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
524 BuildMI(*MBB, IP, PPC32::ADDIS, 2, R).addReg(PPC32::R0)
525 .addGlobalAddress(CPR->getValue());
526 BuildMI(*MBB, IP, PPC32::ORI, 2, R).addReg(PPC32::R0)
527 .addGlobalAddress(CPR->getValue());
529 std::cerr << "Offending constant: " << C << "\n";
530 assert(0 && "Type not handled yet!");
534 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
535 /// the stack into virtual registers.
537 /// FIXME: When we can calculate which args are coming in via registers
538 /// source them from there instead.
539 void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
540 unsigned ArgOffset = 0; // Frame mechanisms handle retaddr slot
541 unsigned GPR_remaining = 8;
542 unsigned FPR_remaining = 13;
543 unsigned GPR_idx = 3;
544 unsigned FPR_idx = 1;
546 MachineFrameInfo *MFI = F->getFrameInfo();
548 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
549 bool ArgLive = !I->use_empty();
550 unsigned Reg = ArgLive ? getReg(*I) : 0;
551 int FI; // Frame object index
553 switch (getClassB(I->getType())) {
556 FI = MFI->CreateFixedObject(1, ArgOffset);
557 if (GPR_remaining > 0) {
558 BuildMI(BB, PPC32::OR, 2, Reg).addReg(PPC32::R0+GPR_idx)
559 .addReg(PPC32::R0+GPR_idx);
561 addFrameReference(BuildMI(BB, PPC32::LBZ, 2, Reg), FI);
567 FI = MFI->CreateFixedObject(2, ArgOffset);
568 if (GPR_remaining > 0) {
569 BuildMI(BB, PPC32::OR, 2, Reg).addReg(PPC32::R0+GPR_idx)
570 .addReg(PPC32::R0+GPR_idx);
572 addFrameReference(BuildMI(BB, PPC32::LHZ, 2, Reg), FI);
578 FI = MFI->CreateFixedObject(4, ArgOffset);
579 if (GPR_remaining > 0) {
580 BuildMI(BB, PPC32::OR, 2, Reg).addReg(PPC32::R0+GPR_idx)
581 .addReg(PPC32::R0+GPR_idx);
583 addFrameReference(BuildMI(BB, PPC32::LWZ, 2, Reg), FI);
589 FI = MFI->CreateFixedObject(8, ArgOffset);
590 if (GPR_remaining > 1) {
591 BuildMI(BB, PPC32::OR, 2, Reg).addReg(PPC32::R0+GPR_idx)
592 .addReg(PPC32::R0+GPR_idx);
593 BuildMI(BB, PPC32::OR, 2, Reg+1).addReg(PPC32::R0+GPR_idx+1)
594 .addReg(PPC32::R0+GPR_idx+1);
596 addFrameReference(BuildMI(BB, PPC32::LWZ, 2, Reg), FI);
597 addFrameReference(BuildMI(BB, PPC32::LWZ, 2, Reg+1), FI, 4);
600 ArgOffset += 4; // longs require 4 additional bytes
601 if (GPR_remaining > 1) {
602 GPR_remaining--; // uses up 2 GPRs
609 if (I->getType() == Type::FloatTy) {
611 FI = MFI->CreateFixedObject(4, ArgOffset);
614 FI = MFI->CreateFixedObject(8, ArgOffset);
616 if (FPR_remaining > 0) {
617 BuildMI(BB, PPC32::FMR, 1, Reg).addReg(PPC32::F0+FPR_idx);
621 addFrameReference(BuildMI(BB, Opcode, 2, Reg), FI);
624 if (I->getType() == Type::DoubleTy) {
625 ArgOffset += 4; // doubles require 4 additional bytes
626 if (GPR_remaining > 0) {
627 GPR_remaining--; // uses up 2 GPRs
633 assert(0 && "Unhandled argument type!");
635 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
636 if (GPR_remaining > 0) {
637 GPR_remaining--; // uses up 2 GPRs
642 // If the function takes variable number of arguments, add a frame offset for
643 // the start of the first vararg value... this is used to expand
645 if (Fn.getFunctionType()->isVarArg())
646 VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
650 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
651 /// because we have to generate our sources into the source basic blocks, not
654 void ISel::SelectPHINodes() {
655 const TargetInstrInfo &TII = *TM.getInstrInfo();
656 const Function &LF = *F->getFunction(); // The LLVM function...
657 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
658 const BasicBlock *BB = I;
659 MachineBasicBlock &MBB = *MBBMap[I];
661 // Loop over all of the PHI nodes in the LLVM basic block...
662 MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
663 for (BasicBlock::const_iterator I = BB->begin();
664 PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
666 // Create a new machine instr PHI node, and insert it.
667 unsigned PHIReg = getReg(*PN);
668 MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
669 PPC32::PHI, PN->getNumOperands(), PHIReg);
671 MachineInstr *LongPhiMI = 0;
672 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
673 LongPhiMI = BuildMI(MBB, PHIInsertPoint,
674 PPC32::PHI, PN->getNumOperands(), PHIReg+1);
676 // PHIValues - Map of blocks to incoming virtual registers. We use this
677 // so that we only initialize one incoming value for a particular block,
678 // even if the block has multiple entries in the PHI node.
680 std::map<MachineBasicBlock*, unsigned> PHIValues;
682 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
683 MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
685 std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
686 PHIValues.lower_bound(PredMBB);
688 if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
689 // We already inserted an initialization of the register for this
690 // predecessor. Recycle it.
691 ValReg = EntryIt->second;
694 // Get the incoming value into a virtual register.
696 Value *Val = PN->getIncomingValue(i);
698 // If this is a constant or GlobalValue, we may have to insert code
699 // into the basic block to compute it into a virtual register.
700 if ((isa<Constant>(Val) && !isa<ConstantExpr>(Val)) ||
701 isa<GlobalValue>(Val)) {
702 // Simple constants get emitted at the end of the basic block,
703 // before any terminator instructions. We "know" that the code to
704 // move a constant into a register will never clobber any flags.
705 ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
707 // Because we don't want to clobber any values which might be in
708 // physical registers with the computation of this constant (which
709 // might be arbitrarily complex if it is a constant expression),
710 // just insert the computation at the top of the basic block.
711 MachineBasicBlock::iterator PI = PredMBB->begin();
713 // Skip over any PHI nodes though!
714 while (PI != PredMBB->end() && PI->getOpcode() == PPC32::PHI)
717 ValReg = getReg(Val, PredMBB, PI);
720 // Remember that we inserted a value for this PHI for this predecessor
721 PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
724 PhiMI->addRegOperand(ValReg);
725 PhiMI->addMachineBasicBlockOperand(PredMBB);
727 LongPhiMI->addRegOperand(ValReg+1);
728 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
732 // Now that we emitted all of the incoming values for the PHI node, make
733 // sure to reposition the InsertPoint after the PHI that we just added.
734 // This is needed because we might have inserted a constant into this
735 // block, right after the PHI's which is before the old insert point!
736 PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
743 // canFoldSetCCIntoBranchOrSelect - Return the setcc instruction if we can fold
744 // it into the conditional branch or select instruction which is the only user
745 // of the cc instruction. This is the case if the conditional branch is the
746 // only user of the setcc, and if the setcc is in the same basic block as the
747 // conditional branch. We also don't handle long arguments below, so we reject
748 // them here as well.
750 static SetCondInst *canFoldSetCCIntoBranchOrSelect(Value *V) {
751 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
752 if (SCI->hasOneUse()) {
753 Instruction *User = cast<Instruction>(SCI->use_back());
754 if ((isa<BranchInst>(User) || isa<SelectInst>(User)) &&
755 SCI->getParent() == User->getParent() &&
756 (getClassB(SCI->getOperand(0)->getType()) != cLong ||
757 SCI->getOpcode() == Instruction::SetEQ ||
758 SCI->getOpcode() == Instruction::SetNE))
764 // Return a fixed numbering for setcc instructions which does not depend on the
765 // order of the opcodes.
767 static unsigned getSetCCNumber(unsigned Opcode) {
769 default: assert(0 && "Unknown setcc instruction!");
770 case Instruction::SetEQ: return 0;
771 case Instruction::SetNE: return 1;
772 case Instruction::SetLT: return 2;
773 case Instruction::SetGE: return 3;
774 case Instruction::SetGT: return 4;
775 case Instruction::SetLE: return 5;
779 /// emitUCOM - emits an unordered FP compare.
780 void ISel::emitUCOM(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
781 unsigned LHS, unsigned RHS) {
782 BuildMI(*MBB, IP, PPC32::FCMPU, 2, PPC32::CR0).addReg(LHS).addReg(RHS);
785 // EmitComparison - This function emits a comparison of the two operands,
786 // returning the extended setcc code to use.
787 unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
788 MachineBasicBlock *MBB,
789 MachineBasicBlock::iterator IP) {
790 // The arguments are already supposed to be of the same type.
791 const Type *CompTy = Op0->getType();
792 unsigned Class = getClassB(CompTy);
793 unsigned Op0r = getReg(Op0, MBB, IP);
795 // Special case handling of: cmp R, i
796 if (isa<ConstantPointerNull>(Op1)) {
797 BuildMI(*MBB, IP, PPC32::CMPI, 2, PPC32::CR0).addReg(Op0r).addImm(0);
798 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
799 if (Class == cByte || Class == cShort || Class == cInt) {
800 unsigned Op1v = CI->getRawValue();
802 // Mask off any upper bits of the constant, if there are any...
803 Op1v &= (1ULL << (8 << Class)) - 1;
805 // Compare immediate or promote to reg?
807 BuildMI(*MBB, IP, CompTy->isSigned() ? PPC32::CMPI : PPC32::CMPLI, 3,
808 PPC32::CR0).addImm(0).addReg(Op0r).addImm(Op1v);
810 unsigned Op1r = getReg(Op1, MBB, IP);
811 BuildMI(*MBB, IP, CompTy->isSigned() ? PPC32::CMP : PPC32::CMPL, 3,
812 PPC32::CR0).addImm(0).addReg(Op0r).addReg(Op1r);
816 assert(Class == cLong && "Unknown integer class!");
817 unsigned LowCst = CI->getRawValue();
818 unsigned HiCst = CI->getRawValue() >> 32;
819 if (OpNum < 2) { // seteq, setne
820 unsigned LoTmp = Op0r;
822 unsigned LoLow = makeAnotherReg(Type::IntTy);
823 unsigned LoTmp = makeAnotherReg(Type::IntTy);
824 BuildMI(*MBB, IP, PPC32::XORI, 2, LoLow).addReg(Op0r).addImm(LowCst);
825 BuildMI(*MBB, IP, PPC32::XORIS, 2, LoTmp).addReg(LoLow)
826 .addImm(LowCst >> 16);
828 unsigned HiTmp = Op0r+1;
830 unsigned HiLow = makeAnotherReg(Type::IntTy);
831 unsigned HiTmp = makeAnotherReg(Type::IntTy);
832 BuildMI(*MBB, IP, PPC32::XORI, 2, HiLow).addReg(Op0r+1).addImm(HiCst);
833 BuildMI(*MBB, IP, PPC32::XORIS, 2, HiTmp).addReg(HiLow)
834 .addImm(HiCst >> 16);
836 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
837 BuildMI(*MBB, IP, PPC32::ORo, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
838 //BuildMI(*MBB, IP, PPC32::CMPLI, 2, PPC32::CR0).addReg(FinalTmp).addImm(0);
841 // Emit a sequence of code which compares the high and low parts once
842 // each, then uses a conditional move to handle the overflow case. For
843 // example, a setlt for long would generate code like this:
845 // AL = lo(op1) < lo(op2) // Always unsigned comparison
846 // BL = hi(op1) < hi(op2) // Signedness depends on operands
847 // dest = hi(op1) == hi(op2) ? BL : AL;
850 // FIXME: Not Yet Implemented
856 unsigned Op1r = getReg(Op1, MBB, IP);
858 default: assert(0 && "Unknown type class!");
862 BuildMI(*MBB, IP, CompTy->isSigned() ? PPC32::CMP : PPC32::CMPL, 2,
863 PPC32::CR0).addReg(Op0r).addReg(Op1r);
866 emitUCOM(MBB, IP, Op0r, Op1r);
870 if (OpNum < 2) { // seteq, setne
871 unsigned LoTmp = makeAnotherReg(Type::IntTy);
872 unsigned HiTmp = makeAnotherReg(Type::IntTy);
873 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
874 BuildMI(*MBB, IP, PPC32::XOR, 2, LoTmp).addReg(Op0r).addReg(Op1r);
875 BuildMI(*MBB, IP, PPC32::XOR, 2, HiTmp).addReg(Op0r+1).addReg(Op1r+1);
876 BuildMI(*MBB, IP, PPC32::ORo, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
877 //BuildMI(*MBB, IP, PPC32::CMPLI, 2, PPC32::CR0).addReg(FinalTmp).addImm(0);
878 break; // Allow the sete or setne to be generated from flags set by OR
880 // Emit a sequence of code which compares the high and low parts once
881 // each, then uses a conditional move to handle the overflow case. For
882 // example, a setlt for long would generate code like this:
884 // AL = lo(op1) < lo(op2) // Signedness depends on operands
885 // BL = hi(op1) < hi(op2) // Always unsigned comparison
886 // dest = hi(op1) == hi(op2) ? BL : AL;
889 // FIXME: Not Yet Implemented
896 /// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
897 /// register, then move it to wherever the result should be.
899 void ISel::visitSetCondInst(SetCondInst &I) {
900 if (canFoldSetCCIntoBranchOrSelect(&I))
901 return; // Fold this into a branch or select.
903 unsigned DestReg = getReg(I);
904 MachineBasicBlock::iterator MII = BB->end();
905 emitSetCCOperation(BB, MII, I.getOperand(0), I.getOperand(1), I.getOpcode(),
909 /// emitSetCCOperation - Common code shared between visitSetCondInst and
910 /// constant expression support.
912 /// FIXME: this is wrong. we should figure out a way to guarantee
913 /// TargetReg is a CR and then make it a no-op
914 void ISel::emitSetCCOperation(MachineBasicBlock *MBB,
915 MachineBasicBlock::iterator IP,
916 Value *Op0, Value *Op1, unsigned Opcode,
917 unsigned TargetReg) {
918 unsigned OpNum = getSetCCNumber(Opcode);
919 OpNum = EmitComparison(OpNum, Op0, Op1, MBB, IP);
921 // The value is already in CR0 at this point, do nothing.
925 void ISel::visitSelectInst(SelectInst &SI) {
926 unsigned DestReg = getReg(SI);
927 MachineBasicBlock::iterator MII = BB->end();
928 emitSelectOperation(BB, MII, SI.getCondition(), SI.getTrueValue(),
929 SI.getFalseValue(), DestReg);
932 /// emitSelect - Common code shared between visitSelectInst and the constant
933 /// expression support.
934 /// FIXME: this is most likely broken in one or more ways. Namely, PowerPC has
935 /// no select instruction. FSEL only works for comparisons against zero.
936 void ISel::emitSelectOperation(MachineBasicBlock *MBB,
937 MachineBasicBlock::iterator IP,
938 Value *Cond, Value *TrueVal, Value *FalseVal,
940 unsigned SelectClass = getClassB(TrueVal->getType());
942 unsigned TrueReg = getReg(TrueVal, MBB, IP);
943 unsigned FalseReg = getReg(FalseVal, MBB, IP);
945 if (TrueReg == FalseReg) {
946 if (SelectClass == cFP) {
947 BuildMI(*MBB, IP, PPC32::FMR, 1, DestReg).addReg(TrueReg);
949 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(TrueReg).addReg(TrueReg);
952 if (SelectClass == cLong)
953 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg+1).addReg(TrueReg+1)
958 unsigned CondReg = getReg(Cond, MBB, IP);
959 unsigned numZeros = makeAnotherReg(Type::IntTy);
960 unsigned falseHi = makeAnotherReg(Type::IntTy);
961 unsigned falseAll = makeAnotherReg(Type::IntTy);
962 unsigned trueAll = makeAnotherReg(Type::IntTy);
963 unsigned Temp1 = makeAnotherReg(Type::IntTy);
964 unsigned Temp2 = makeAnotherReg(Type::IntTy);
966 BuildMI(*MBB, IP, PPC32::CNTLZW, 1, numZeros).addReg(CondReg);
967 BuildMI(*MBB, IP, PPC32::RLWINM, 4, falseHi).addReg(numZeros).addImm(26)
968 .addImm(0).addImm(0);
969 BuildMI(*MBB, IP, PPC32::SRAWI, 2, falseAll).addReg(falseHi).addImm(31);
970 BuildMI(*MBB, IP, PPC32::NOR, 2, trueAll).addReg(falseAll).addReg(falseAll);
971 BuildMI(*MBB, IP, PPC32::AND, 2, Temp1).addReg(TrueReg).addReg(trueAll);
972 BuildMI(*MBB, IP, PPC32::AND, 2, Temp2).addReg(FalseReg).addReg(falseAll);
973 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(Temp1).addReg(Temp2);
975 if (SelectClass == cLong) {
976 unsigned Temp3 = makeAnotherReg(Type::IntTy);
977 unsigned Temp4 = makeAnotherReg(Type::IntTy);
978 BuildMI(*MBB, IP, PPC32::AND, 2, Temp3).addReg(TrueReg+1).addReg(trueAll);
979 BuildMI(*MBB, IP, PPC32::AND, 2, Temp4).addReg(FalseReg+1).addReg(falseAll);
980 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg+1).addReg(Temp3).addReg(Temp4);
988 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
989 /// operand, in the specified target register.
991 void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
992 bool isUnsigned = VR.Ty->isUnsigned() || VR.Ty == Type::BoolTy;
995 const Type *Ty = VR.Ty;
997 if (Constant *C = dyn_cast<Constant>(Val)) {
998 Val = ConstantExpr::getCast(C, Type::IntTy);
1002 // If this is a simple constant, just emit a load directly to avoid the copy
1003 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
1004 int TheVal = CI->getRawValue() & 0xFFFFFFFF;
1006 if (TheVal < 32768 && TheVal >= -32768) {
1007 BuildMI(BB, PPC32::ADDI, 2, targetReg).addReg(PPC32::R0).addImm(TheVal);
1009 unsigned TmpReg = makeAnotherReg(Type::IntTy);
1010 BuildMI(BB, PPC32::ADDIS, 2, TmpReg).addReg(PPC32::R0)
1011 .addImm(TheVal >> 16);
1012 BuildMI(BB, PPC32::ORI, 2, targetReg).addReg(TmpReg)
1013 .addImm(TheVal & 0xFFFF);
1019 // Make sure we have the register number for this value...
1020 unsigned Reg = Val ? getReg(Val) : VR.Reg;
1022 switch (getClassB(Ty)) {
1024 // Extend value into target register (8->32)
1026 BuildMI(BB, PPC32::RLWINM, 4, targetReg).addReg(Reg).addZImm(0)
1027 .addZImm(24).addZImm(31);
1029 BuildMI(BB, PPC32::EXTSB, 1, targetReg).addReg(Reg);
1032 // Extend value into target register (16->32)
1034 BuildMI(BB, PPC32::RLWINM, 4, targetReg).addReg(Reg).addZImm(0)
1035 .addZImm(16).addZImm(31);
1037 BuildMI(BB, PPC32::EXTSH, 1, targetReg).addReg(Reg);
1040 // Move value into target register (32->32)
1041 BuildMI(BB, PPC32::ORI, 2, targetReg).addReg(Reg).addReg(Reg);
1044 assert(0 && "Unpromotable operand class in promote32");
1048 /// visitReturnInst - implemented with BLR
1050 void ISel::visitReturnInst(ReturnInst &I) {
1051 Value *RetVal = I.getOperand(0);
1053 switch (getClassB(RetVal->getType())) {
1054 case cByte: // integral return values: extend or move into r3 and return
1057 promote32(PPC32::R3, ValueRecord(RetVal));
1059 case cFP: { // Floats & Doubles: Return in f1
1060 unsigned RetReg = getReg(RetVal);
1061 BuildMI(BB, PPC32::FMR, 1, PPC32::F1).addReg(RetReg);
1065 unsigned RetReg = getReg(RetVal);
1066 BuildMI(BB, PPC32::OR, 2, PPC32::R3).addReg(RetReg).addReg(RetReg);
1067 BuildMI(BB, PPC32::OR, 2, PPC32::R4).addReg(RetReg+1).addReg(RetReg+1);
1071 visitInstruction(I);
1073 BuildMI(BB, PPC32::BLR, 1).addImm(0);
1076 // getBlockAfter - Return the basic block which occurs lexically after the
1078 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1079 Function::iterator I = BB; ++I; // Get iterator to next block
1080 return I != BB->getParent()->end() ? &*I : 0;
1083 /// visitBranchInst - Handle conditional and unconditional branches here. Note
1084 /// that since code layout is frozen at this point, that if we are trying to
1085 /// jump to a block that is the immediate successor of the current block, we can
1086 /// just make a fall-through (but we don't currently).
1088 void ISel::visitBranchInst(BranchInst &BI) {
1089 // Update machine-CFG edges
1090 BB->addSuccessor (MBBMap[BI.getSuccessor(0)]);
1091 if (BI.isConditional())
1092 BB->addSuccessor (MBBMap[BI.getSuccessor(1)]);
1094 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
1096 if (!BI.isConditional()) { // Unconditional branch?
1097 if (BI.getSuccessor(0) != NextBB)
1098 BuildMI(BB, PPC32::B, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1102 // See if we can fold the setcc into the branch itself...
1103 SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(BI.getCondition());
1105 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
1106 // computed some other way...
1107 unsigned condReg = getReg(BI.getCondition());
1108 BuildMI(BB, PPC32::CMPLI, 3, PPC32::CR0).addImm(0).addReg(condReg)
1110 if (BI.getSuccessor(1) == NextBB) {
1111 if (BI.getSuccessor(0) != NextBB)
1112 BuildMI(BB, PPC32::BC, 3).addImm(4).addImm(2)
1113 .addMBB(MBBMap[BI.getSuccessor(0)]);
1115 BuildMI(BB, PPC32::BC, 3).addImm(12).addImm(2)
1116 .addMBB(MBBMap[BI.getSuccessor(1)]);
1118 if (BI.getSuccessor(0) != NextBB)
1119 BuildMI(BB, PPC32::B, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1125 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1126 MachineBasicBlock::iterator MII = BB->end();
1127 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
1129 const Type *CompTy = SCI->getOperand(0)->getType();
1130 bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
1132 // LLVM -> X86 signed X86 unsigned
1133 // ----- ---------- ------------
1141 static const unsigned BITab[6] = { 2, 2, 0, 0, 1, 1 };
1142 unsigned BO_true = (OpNum % 2 == 0) ? 12 : 4;
1143 unsigned BO_false = (OpNum % 2 == 0) ? 4 : 12;
1144 unsigned BIval = BITab[0];
1146 if (BI.getSuccessor(0) != NextBB) {
1147 BuildMI(BB, PPC32::BC, 3).addImm(BO_true).addImm(BIval)
1148 .addMBB(MBBMap[BI.getSuccessor(0)]);
1149 if (BI.getSuccessor(1) != NextBB)
1150 BuildMI(BB, PPC32::B, 1).addMBB(MBBMap[BI.getSuccessor(1)]);
1152 // Change to the inverse condition...
1153 if (BI.getSuccessor(1) != NextBB) {
1154 BuildMI(BB, PPC32::BC, 3).addImm(BO_false).addImm(BIval)
1155 .addMBB(MBBMap[BI.getSuccessor(1)]);
1161 /// doCall - This emits an abstract call instruction, setting up the arguments
1162 /// and the return value as appropriate. For the actual function call itself,
1163 /// it inserts the specified CallMI instruction into the stream.
1165 /// FIXME: See Documentation at the following URL for "correct" behavior
1166 /// <http://developer.apple.com/documentation/DeveloperTools/Conceptual/MachORuntime/2rt_powerpc_abi/chapter_9_section_5.html>
1167 void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
1168 const std::vector<ValueRecord> &Args) {
1169 // Count how many bytes are to be pushed on the stack...
1170 unsigned NumBytes = 0;
1172 if (!Args.empty()) {
1173 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1174 switch (getClassB(Args[i].Ty)) {
1175 case cByte: case cShort: case cInt:
1176 NumBytes += 4; break;
1178 NumBytes += 8; break;
1180 NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
1182 default: assert(0 && "Unknown class!");
1185 // Adjust the stack pointer for the new arguments...
1186 BuildMI(BB, PPC32::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
1188 // Arguments go on the stack in reverse order, as specified by the ABI.
1189 unsigned ArgOffset = 0;
1190 unsigned GPR_remaining = 8;
1191 unsigned FPR_remaining = 13;
1192 unsigned GPR_idx = 3;
1193 unsigned FPR_idx = 1;
1195 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1197 switch (getClassB(Args[i].Ty)) {
1200 // Promote arg to 32 bits wide into a temporary register...
1201 ArgReg = makeAnotherReg(Type::UIntTy);
1202 promote32(ArgReg, Args[i]);
1205 if (GPR_remaining > 0) {
1206 BuildMI(BB, PPC32::OR, 2, PPC32::R0 + GPR_idx).addReg(ArgReg)
1209 BuildMI(BB, PPC32::STW, 3).addReg(ArgReg).addImm(ArgOffset)
1214 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1217 if (GPR_remaining > 0) {
1218 BuildMI(BB, PPC32::OR, 2, PPC32::R0 + GPR_idx).addReg(ArgReg)
1221 BuildMI(BB, PPC32::STW, 3).addReg(ArgReg).addImm(ArgOffset)
1226 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1229 if (GPR_remaining > 1) {
1230 BuildMI(BB, PPC32::OR, 2, PPC32::R0 + GPR_idx).addReg(ArgReg)
1232 BuildMI(BB, PPC32::OR, 2, PPC32::R0 + GPR_idx + 1).addReg(ArgReg+1)
1235 BuildMI(BB, PPC32::STW, 3).addReg(ArgReg).addImm(ArgOffset)
1237 BuildMI(BB, PPC32::STW, 3).addReg(ArgReg+1).addImm(ArgOffset+4)
1241 ArgOffset += 4; // 8 byte entry, not 4.
1242 if (GPR_remaining > 0) {
1243 GPR_remaining -= 1; // uses up 2 GPRs
1248 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1249 if (Args[i].Ty == Type::FloatTy) {
1251 if (FPR_remaining > 0) {
1252 BuildMI(BB, PPC32::FMR, 1, PPC32::F0 + FPR_idx).addReg(ArgReg);
1256 BuildMI(BB, PPC32::STFS, 3).addReg(ArgReg).addImm(ArgOffset)
1260 assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
1262 if (FPR_remaining > 0) {
1263 BuildMI(BB, PPC32::FMR, 1, PPC32::F0 + FPR_idx).addReg(ArgReg);
1267 BuildMI(BB, PPC32::STFD, 3).addReg(ArgReg).addImm(ArgOffset)
1271 ArgOffset += 4; // 8 byte entry, not 4.
1272 if (GPR_remaining > 0) {
1273 GPR_remaining--; // uses up 2 GPRs
1279 default: assert(0 && "Unknown class!");
1282 if (GPR_remaining > 0) {
1283 GPR_remaining--; // uses up 2 GPRs
1288 BuildMI(BB, PPC32::ADJCALLSTACKDOWN, 1).addImm(0);
1291 BB->push_back(CallMI);
1293 BuildMI(BB, PPC32::ADJCALLSTACKUP, 1).addImm(NumBytes);
1295 // If there is a return value, scavenge the result from the location the call
1298 if (Ret.Ty != Type::VoidTy) {
1299 unsigned DestClass = getClassB(Ret.Ty);
1300 switch (DestClass) {
1304 // Integral results are in r3
1305 BuildMI(BB, PPC32::OR, 2, Ret.Reg).addReg(PPC32::R3).addReg(PPC32::R3);
1306 case cFP: // Floating-point return values live in f1
1307 BuildMI(BB, PPC32::FMR, 1, Ret.Reg).addReg(PPC32::F1);
1309 case cLong: // Long values are in r3:r4
1310 BuildMI(BB, PPC32::OR, 2, Ret.Reg).addReg(PPC32::R3).addReg(PPC32::R3);
1311 BuildMI(BB, PPC32::OR, 2, Ret.Reg+1).addReg(PPC32::R4).addReg(PPC32::R4);
1313 default: assert(0 && "Unknown class!");
1319 /// visitCallInst - Push args on stack and do a procedure call instruction.
1320 void ISel::visitCallInst(CallInst &CI) {
1321 MachineInstr *TheCall;
1322 if (Function *F = CI.getCalledFunction()) {
1323 // Is it an intrinsic function call?
1324 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1325 visitIntrinsicCall(ID, CI); // Special intrinsics are not handled here
1329 // Emit a CALL instruction with PC-relative displacement.
1330 TheCall = BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(F, true);
1331 } else { // Emit an indirect call through the CTR
1332 unsigned Reg = getReg(CI.getCalledValue());
1333 BuildMI(PPC32::MTSPR, 2).addZImm(9).addReg(Reg);
1334 TheCall = BuildMI(PPC32::CALLindirect, 1).addZImm(20).addZImm(0);
1337 std::vector<ValueRecord> Args;
1338 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
1339 Args.push_back(ValueRecord(CI.getOperand(i)));
1341 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1342 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
1346 /// dyncastIsNan - Return the operand of an isnan operation if this is an isnan.
1348 static Value *dyncastIsNan(Value *V) {
1349 if (CallInst *CI = dyn_cast<CallInst>(V))
1350 if (Function *F = CI->getCalledFunction())
1351 if (F->getIntrinsicID() == Intrinsic::isunordered)
1352 return CI->getOperand(1);
1356 /// isOnlyUsedByUnorderedComparisons - Return true if this value is only used by
1357 /// or's whos operands are all calls to the isnan predicate.
1358 static bool isOnlyUsedByUnorderedComparisons(Value *V) {
1359 assert(dyncastIsNan(V) && "The value isn't an isnan call!");
1361 // Check all uses, which will be or's of isnans if this predicate is true.
1362 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1363 Instruction *I = cast<Instruction>(*UI);
1364 if (I->getOpcode() != Instruction::Or) return false;
1365 if (I->getOperand(0) != V && !dyncastIsNan(I->getOperand(0))) return false;
1366 if (I->getOperand(1) != V && !dyncastIsNan(I->getOperand(1))) return false;
1372 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1373 /// function, lowering any calls to unknown intrinsic functions into the
1374 /// equivalent LLVM code.
1376 void ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1377 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1378 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1379 if (CallInst *CI = dyn_cast<CallInst>(I++))
1380 if (Function *F = CI->getCalledFunction())
1381 switch (F->getIntrinsicID()) {
1382 case Intrinsic::not_intrinsic:
1383 case Intrinsic::vastart:
1384 case Intrinsic::vacopy:
1385 case Intrinsic::vaend:
1386 case Intrinsic::returnaddress:
1387 case Intrinsic::frameaddress:
1388 // FIXME: should lower this ourselves
1389 // case Intrinsic::isunordered:
1390 // We directly implement these intrinsics
1392 case Intrinsic::readio: {
1393 // On PPC, memory operations are in-order. Lower this intrinsic
1394 // into a volatile load.
1395 Instruction *Before = CI->getPrev();
1396 LoadInst * LI = new LoadInst(CI->getOperand(1), "", true, CI);
1397 CI->replaceAllUsesWith(LI);
1398 BB->getInstList().erase(CI);
1401 case Intrinsic::writeio: {
1402 // On PPC, memory operations are in-order. Lower this intrinsic
1403 // into a volatile store.
1404 Instruction *Before = CI->getPrev();
1405 StoreInst *LI = new StoreInst(CI->getOperand(1),
1406 CI->getOperand(2), true, CI);
1407 CI->replaceAllUsesWith(LI);
1408 BB->getInstList().erase(CI);
1412 // All other intrinsic calls we must lower.
1413 Instruction *Before = CI->getPrev();
1414 TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
1415 if (Before) { // Move iterator to instruction after call
1423 void ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
1424 unsigned TmpReg1, TmpReg2, TmpReg3;
1426 case Intrinsic::vastart:
1427 // Get the address of the first vararg value...
1428 TmpReg1 = getReg(CI);
1429 addFrameReference(BuildMI(BB, PPC32::ADDI, 2, TmpReg1), VarArgsFrameIndex);
1432 case Intrinsic::vacopy:
1433 TmpReg1 = getReg(CI);
1434 TmpReg2 = getReg(CI.getOperand(1));
1435 BuildMI(BB, PPC32::OR, 2, TmpReg1).addReg(TmpReg2).addReg(TmpReg2);
1437 case Intrinsic::vaend: return;
1439 case Intrinsic::returnaddress:
1440 case Intrinsic::frameaddress:
1441 TmpReg1 = getReg(CI);
1442 if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1443 if (ID == Intrinsic::returnaddress) {
1444 // Just load the return address
1445 addFrameReference(BuildMI(BB, PPC32::LWZ, 2, TmpReg1),
1446 ReturnAddressIndex);
1448 addFrameReference(BuildMI(BB, PPC32::ADDI, 2, TmpReg1),
1449 ReturnAddressIndex, -4, false);
1452 // Values other than zero are not implemented yet.
1453 BuildMI(BB, PPC32::ADDI, 2, TmpReg1).addReg(PPC32::R0).addImm(0);
1458 // This may be useful for supporting isunordered
1459 case Intrinsic::isnan:
1460 // If this is only used by 'isunordered' style comparisons, don't emit it.
1461 if (isOnlyUsedByUnorderedComparisons(&CI)) return;
1462 TmpReg1 = getReg(CI.getOperand(1));
1463 emitUCOM(BB, BB->end(), TmpReg1, TmpReg1);
1464 TmpReg2 = makeAnotherReg(Type::IntTy);
1465 BuildMI(BB, PPC32::MFCR, TmpReg2);
1466 TmpReg3 = getReg(CI);
1467 BuildMI(BB, PPC32::RLWINM, 4, TmpReg3).addReg(TmpReg2).addImm(4).addImm(31).addImm(31);
1471 default: assert(0 && "Error: unknown intrinsics should have been lowered!");
1475 /// visitSimpleBinary - Implement simple binary operators for integral types...
1476 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
1479 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
1480 unsigned DestReg = getReg(B);
1481 MachineBasicBlock::iterator MI = BB->end();
1482 Value *Op0 = B.getOperand(0), *Op1 = B.getOperand(1);
1483 unsigned Class = getClassB(B.getType());
1485 emitSimpleBinaryOperation(BB, MI, Op0, Op1, OperatorClass, DestReg);
1488 /// emitBinaryFPOperation - This method handles emission of floating point
1489 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
1490 void ISel::emitBinaryFPOperation(MachineBasicBlock *BB,
1491 MachineBasicBlock::iterator IP,
1492 Value *Op0, Value *Op1,
1493 unsigned OperatorClass, unsigned DestReg) {
1495 // Special case: op Reg, <const fp>
1496 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1497 // Create a constant pool entry for this constant.
1498 MachineConstantPool *CP = F->getConstantPool();
1499 unsigned CPI = CP->getConstantPoolIndex(Op1C);
1500 const Type *Ty = Op1->getType();
1502 static const unsigned OpcodeTab[][4] = {
1503 { PPC32::FADDS, PPC32::FSUBS, PPC32::FMULS, PPC32::FDIVS }, // Float
1504 { PPC32::FADD, PPC32::FSUB, PPC32::FMUL, PPC32::FDIV }, // Double
1507 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1508 unsigned TempReg = makeAnotherReg(Ty);
1509 unsigned LoadOpcode = Ty == Type::FloatTy ? PPC32::LFS : PPC32::LFD;
1510 addConstantPoolReference(BuildMI(*BB, IP, LoadOpcode, 2, TempReg), CPI);
1512 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
1513 unsigned Op0r = getReg(Op0, BB, IP);
1514 BuildMI(*BB, IP, Opcode, DestReg).addReg(Op0r).addReg(TempReg);
1518 // Special case: R1 = op <const fp>, R2
1519 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op0))
1520 if (CFP->isExactlyValue(-0.0) && OperatorClass == 1) {
1522 unsigned op1Reg = getReg(Op1, BB, IP);
1523 BuildMI(*BB, IP, PPC32::FNEG, 1, DestReg).addReg(op1Reg);
1526 // R1 = op CST, R2 --> R1 = opr R2, CST
1528 // Create a constant pool entry for this constant.
1529 MachineConstantPool *CP = F->getConstantPool();
1530 unsigned CPI = CP->getConstantPoolIndex(CFP);
1531 const Type *Ty = CFP->getType();
1533 static const unsigned OpcodeTab[][4] = {
1534 { PPC32::FADDS, PPC32::FSUBS, PPC32::FMULS, PPC32::FDIVS }, // Float
1535 { PPC32::FADD, PPC32::FSUB, PPC32::FMUL, PPC32::FDIV }, // Double
1538 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1539 unsigned TempReg = makeAnotherReg(Ty);
1540 unsigned LoadOpcode = Ty == Type::FloatTy ? PPC32::LFS : PPC32::LFD;
1541 addConstantPoolReference(BuildMI(*BB, IP, LoadOpcode, 2, TempReg), CPI);
1543 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
1544 unsigned Op1r = getReg(Op1, BB, IP);
1545 BuildMI(*BB, IP, Opcode, DestReg).addReg(TempReg).addReg(Op1r);
1550 static const unsigned OpcodeTab[4] = {
1551 PPC32::FADD, PPC32::FSUB, PPC32::FMUL, PPC32::FDIV
1554 unsigned Opcode = OpcodeTab[OperatorClass];
1555 unsigned Op0r = getReg(Op0, BB, IP);
1556 unsigned Op1r = getReg(Op1, BB, IP);
1557 BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1560 /// emitSimpleBinaryOperation - Implement simple binary operators for integral
1561 /// types... OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
1564 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
1565 /// and constant expression support.
1567 void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
1568 MachineBasicBlock::iterator IP,
1569 Value *Op0, Value *Op1,
1570 unsigned OperatorClass, unsigned DestReg) {
1571 unsigned Class = getClassB(Op0->getType());
1573 // Arithmetic and Bitwise operators
1574 static const unsigned OpcodeTab[5] = {
1575 PPC32::ADD, PPC32::SUB, PPC32::AND, PPC32::OR, PPC32::XOR
1577 // Otherwise, code generate the full operation with a constant.
1578 static const unsigned BottomTab[] = {
1579 PPC32::ADDC, PPC32::SUBC, PPC32::AND, PPC32::OR, PPC32::XOR
1581 static const unsigned TopTab[] = {
1582 PPC32::ADDE, PPC32::SUBFE, PPC32::AND, PPC32::OR, PPC32::XOR
1586 assert(OperatorClass < 2 && "No logical ops for FP!");
1587 emitBinaryFPOperation(MBB, IP, Op0, Op1, OperatorClass, DestReg);
1591 if (Op0->getType() == Type::BoolTy) {
1592 if (OperatorClass == 3)
1593 // If this is an or of two isnan's, emit an FP comparison directly instead
1594 // of or'ing two isnan's together.
1595 if (Value *LHS = dyncastIsNan(Op0))
1596 if (Value *RHS = dyncastIsNan(Op1)) {
1597 unsigned Op0Reg = getReg(RHS, MBB, IP), Op1Reg = getReg(LHS, MBB, IP);
1598 unsigned TmpReg = makeAnotherReg(Type::IntTy);
1599 emitUCOM(MBB, IP, Op0Reg, Op1Reg);
1600 BuildMI(*MBB, IP, PPC32::MFCR, TmpReg);
1601 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(TmpReg).addImm(4)
1602 .addImm(31).addImm(31);
1607 // sub 0, X -> neg X
1608 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0))
1609 if (OperatorClass == 1 && CI->isNullValue()) {
1610 unsigned op1Reg = getReg(Op1, MBB, IP);
1611 BuildMI(*MBB, IP, PPC32::NEG, 1, DestReg).addReg(op1Reg);
1613 if (Class == cLong) {
1614 unsigned zeroes = makeAnotherReg(Type::IntTy);
1615 unsigned overflow = makeAnotherReg(Type::IntTy);
1616 unsigned T = makeAnotherReg(Type::IntTy);
1617 BuildMI(*MBB, IP, PPC32::CNTLZW, 1, zeroes).addReg(op1Reg);
1618 BuildMI(*MBB, IP, PPC32::RLWINM, 4, overflow).addReg(zeroes).addImm(27)
1619 .addImm(5).addImm(31);
1620 BuildMI(*MBB, IP, PPC32::ADD, 2, T).addReg(op1Reg+1).addReg(overflow);
1621 BuildMI(*MBB, IP, PPC32::NEG, 1, DestReg+1).addReg(T);
1626 // Special case: op Reg, <const int>
1627 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1628 unsigned Op0r = getReg(Op0, MBB, IP);
1630 // xor X, -1 -> not X
1631 if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
1632 BuildMI(*MBB, IP, PPC32::NOR, 2, DestReg).addReg(Op0r).addReg(Op0r);
1633 if (Class == cLong) // Invert the top part too
1634 BuildMI(*MBB, IP, PPC32::NOR, 2, DestReg+1).addReg(Op0r+1)
1639 unsigned Opcode = OpcodeTab[OperatorClass];
1640 unsigned Op1r = getReg(Op1, MBB, IP);
1642 if (Class != cLong) {
1643 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1647 // If the constant is zero in the low 32-bits, just copy the low part
1648 // across and apply the normal 32-bit operation to the high parts. There
1649 // will be no carry or borrow into the top.
1650 if (cast<ConstantInt>(Op1C)->getRawValue() == 0) {
1651 if (OperatorClass != 2) // All but and...
1652 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(Op0r).addReg(Op0r);
1654 BuildMI(*MBB, IP, PPC32::ADDI, 2, DestReg).addReg(PPC32::R0).addImm(0);
1655 BuildMI(*MBB, IP, Opcode, 2, DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
1659 // If this is a long value and the high or low bits have a special
1660 // property, emit some special cases.
1661 unsigned Op1h = cast<ConstantInt>(Op1C)->getRawValue() >> 32LL;
1663 // If this is a logical operation and the top 32-bits are zero, just
1664 // operate on the lower 32.
1665 if (Op1h == 0 && OperatorClass > 1) {
1666 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1667 if (OperatorClass != 2) // All but and
1668 BuildMI(*MBB, IP, PPC32::OR, 2,DestReg+1).addReg(Op0r+1).addReg(Op0r+1);
1670 BuildMI(*MBB, IP, PPC32::ADDI, 2,DestReg+1).addReg(PPC32::R0).addImm(0);
1674 // TODO: We could handle lots of other special cases here, such as AND'ing
1675 // with 0xFFFFFFFF00000000 -> noop, etc.
1677 BuildMI(*MBB, IP, BottomTab[OperatorClass], 2, DestReg).addReg(Op0r)
1679 BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg+1).addReg(Op0r+1)
1684 unsigned Op0r = getReg(Op0, MBB, IP);
1685 unsigned Op1r = getReg(Op1, MBB, IP);
1687 if (Class != cLong) {
1688 unsigned Opcode = OpcodeTab[OperatorClass];
1689 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1691 BuildMI(*MBB, IP, BottomTab[OperatorClass], 2, DestReg).addReg(Op0r)
1693 BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg+1).addReg(Op0r+1)
1699 /// doMultiply - Emit appropriate instructions to multiply together the
1700 /// registers op0Reg and op1Reg, and put the result in DestReg. The type of the
1701 /// result should be given as DestTy.
1703 void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
1704 unsigned DestReg, const Type *DestTy,
1705 unsigned op0Reg, unsigned op1Reg) {
1706 unsigned Class = getClass(DestTy);
1709 BuildMI(*MBB, MBBI, PPC32::MULHW, 2, DestReg+1).addReg(op0Reg+1)
1714 BuildMI(*MBB, MBBI, PPC32::MULLW, 2, DestReg).addReg(op0Reg).addReg(op1Reg);
1717 assert(0 && "doMultiply cannot operate on unknown type!");
1721 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
1722 // returns zero when the input is not exactly a power of two.
1723 static unsigned ExactLog2(unsigned Val) {
1724 if (Val == 0 || (Val & (Val-1))) return 0;
1734 /// doMultiplyConst - This function is specialized to efficiently codegen an 8,
1735 /// 16, or 32-bit integer multiply by a constant.
1737 void ISel::doMultiplyConst(MachineBasicBlock *MBB,
1738 MachineBasicBlock::iterator IP,
1739 unsigned DestReg, const Type *DestTy,
1740 unsigned op0Reg, unsigned ConstRHS) {
1741 unsigned Class = getClass(DestTy);
1742 // Handle special cases here.
1745 BuildMI(*MBB, IP, PPC32::ADDI, 2, DestReg).addReg(PPC32::R0).addImm(0);
1748 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(op0Reg).addReg(op0Reg);
1751 BuildMI(*MBB, IP, PPC32::ADD, 2,DestReg).addReg(op0Reg).addReg(op0Reg);
1755 // If the element size is exactly a power of 2, use a shift to get it.
1756 if (unsigned Shift = ExactLog2(ConstRHS)) {
1758 default: assert(0 && "Unknown class for this function!");
1762 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(op0Reg)
1763 .addImm(Shift-1).addImm(0).addImm(31-Shift-1);
1768 // Most general case, emit a normal multiply...
1769 unsigned TmpReg1 = makeAnotherReg(Type::IntTy);
1770 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
1771 BuildMI(*MBB, IP, PPC32::ADDIS, 2, TmpReg1).addReg(PPC32::R0)
1772 .addImm(ConstRHS >> 16);
1773 BuildMI(*MBB, IP, PPC32::ORI, 2, TmpReg2).addReg(TmpReg1).addImm(ConstRHS);
1775 // Emit a MUL to multiply the register holding the index by
1776 // elementSize, putting the result in OffsetReg.
1777 doMultiply(MBB, IP, DestReg, DestTy, op0Reg, TmpReg2);
1780 void ISel::visitMul(BinaryOperator &I) {
1781 unsigned ResultReg = getReg(I);
1783 Value *Op0 = I.getOperand(0);
1784 Value *Op1 = I.getOperand(1);
1786 MachineBasicBlock::iterator IP = BB->end();
1787 emitMultiply(BB, IP, Op0, Op1, ResultReg);
1790 void ISel::emitMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
1791 Value *Op0, Value *Op1, unsigned DestReg) {
1792 MachineBasicBlock &BB = *MBB;
1793 TypeClass Class = getClass(Op0->getType());
1795 // Simple scalar multiply?
1796 unsigned Op0Reg = getReg(Op0, &BB, IP);
1801 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1802 unsigned Val = (unsigned)CI->getRawValue(); // Isn't a 64-bit constant
1803 doMultiplyConst(&BB, IP, DestReg, Op0->getType(), Op0Reg, Val);
1805 unsigned Op1Reg = getReg(Op1, &BB, IP);
1806 doMultiply(&BB, IP, DestReg, Op1->getType(), Op0Reg, Op1Reg);
1810 emitBinaryFPOperation(MBB, IP, Op0, Op1, 2, DestReg);
1816 // Long value. We have to do things the hard way...
1817 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1818 unsigned CLow = CI->getRawValue();
1819 unsigned CHi = CI->getRawValue() >> 32;
1822 // If the low part of the constant is all zeros, things are simple.
1823 BuildMI(BB, IP, PPC32::ADDI, 2, DestReg).addReg(PPC32::R0).addImm(0);
1824 doMultiplyConst(&BB, IP, DestReg+1, Type::UIntTy, Op0Reg, CHi);
1828 // Multiply the two low parts
1829 unsigned OverflowReg = 0;
1831 BuildMI(BB, IP, PPC32::OR, 2, DestReg).addReg(Op0Reg).addReg(Op0Reg);
1833 unsigned TmpRegL = makeAnotherReg(Type::UIntTy);
1834 unsigned Op1RegL = makeAnotherReg(Type::UIntTy);
1835 OverflowReg = makeAnotherReg(Type::UIntTy);
1836 BuildMI(BB, IP, PPC32::ADDIS, 2, TmpRegL).addReg(PPC32::R0)
1837 .addImm(CLow >> 16);
1838 BuildMI(BB, IP, PPC32::ORI, 2, Op1RegL).addReg(TmpRegL).addImm(CLow);
1839 BuildMI(BB, IP, PPC32::MULLW, 2, DestReg).addReg(Op0Reg).addReg(Op1RegL);
1840 BuildMI(BB, IP, PPC32::MULHW, 2, OverflowReg).addReg(Op0Reg)
1844 unsigned AHBLReg = makeAnotherReg(Type::UIntTy);
1845 doMultiplyConst(&BB, IP, AHBLReg, Type::UIntTy, Op0Reg+1, CLow);
1847 unsigned AHBLplusOverflowReg;
1849 AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
1850 BuildMI(BB, IP, PPC32::ADD, 2, // AH*BL+(AL*BL >> 32)
1851 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
1853 AHBLplusOverflowReg = AHBLReg;
1857 BuildMI(BB, IP, PPC32::OR, 2, DestReg+1).addReg(AHBLplusOverflowReg)
1858 .addReg(AHBLplusOverflowReg);
1860 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
1861 doMultiplyConst(&BB, IP, ALBHReg, Type::UIntTy, Op0Reg, CHi);
1863 BuildMI(BB, IP, PPC32::ADD, 2, // AL*BH + AH*BL + (AL*BL >> 32)
1864 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
1869 // General 64x64 multiply
1871 unsigned Op1Reg = getReg(Op1, &BB, IP);
1873 // Multiply the two low parts... capturing carry into EDX
1874 BuildMI(BB, IP, PPC32::MULLW, 2, DestReg).addReg(Op0Reg).addReg(Op1Reg); // AL*BL
1876 unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
1877 BuildMI(BB, IP, PPC32::MULHW, 2, OverflowReg).addReg(Op0Reg).addReg(Op1Reg); // AL*BL >> 32
1879 unsigned AHBLReg = makeAnotherReg(Type::UIntTy); // AH*BL
1880 BuildMI(BB, IP, PPC32::MULLW, 2, AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
1882 unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
1883 BuildMI(BB, IP, PPC32::ADD, 2, // AH*BL+(AL*BL >> 32)
1884 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
1886 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
1887 BuildMI(BB, IP, PPC32::MULLW, 2, ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
1889 BuildMI(BB, IP, PPC32::ADD, 2, // AL*BH + AH*BL + (AL*BL >> 32)
1890 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
1894 /// visitDivRem - Handle division and remainder instructions... these
1895 /// instruction both require the same instructions to be generated, they just
1896 /// select the result from a different register. Note that both of these
1897 /// instructions work differently for signed and unsigned operands.
1899 void ISel::visitDivRem(BinaryOperator &I) {
1900 unsigned ResultReg = getReg(I);
1901 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1903 MachineBasicBlock::iterator IP = BB->end();
1904 emitDivRemOperation(BB, IP, Op0, Op1, I.getOpcode() == Instruction::Div,
1908 void ISel::emitDivRemOperation(MachineBasicBlock *BB,
1909 MachineBasicBlock::iterator IP,
1910 Value *Op0, Value *Op1, bool isDiv,
1911 unsigned ResultReg) {
1912 const Type *Ty = Op0->getType();
1913 unsigned Class = getClass(Ty);
1915 case cFP: // Floating point divide
1917 emitBinaryFPOperation(BB, IP, Op0, Op1, 3, ResultReg);
1919 } else { // Floating point remainder...
1920 unsigned Op0Reg = getReg(Op0, BB, IP);
1921 unsigned Op1Reg = getReg(Op1, BB, IP);
1922 MachineInstr *TheCall =
1923 BuildMI(PPC32::CALLpcrel, 1).addExternalSymbol("fmod", true);
1924 std::vector<ValueRecord> Args;
1925 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
1926 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
1927 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args);
1931 static const char *FnName[] =
1932 { "__moddi3", "__divdi3", "__umoddi3", "__udivdi3" };
1933 unsigned Op0Reg = getReg(Op0, BB, IP);
1934 unsigned Op1Reg = getReg(Op1, BB, IP);
1935 unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
1936 MachineInstr *TheCall =
1937 BuildMI(PPC32::CALLpcrel, 1).addExternalSymbol(FnName[NameIdx], true);
1939 std::vector<ValueRecord> Args;
1940 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
1941 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
1942 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args);
1945 case cByte: case cShort: case cInt:
1946 break; // Small integrals, handled below...
1947 default: assert(0 && "Unknown class!");
1950 // Special case signed division by power of 2.
1952 if (ConstantSInt *CI = dyn_cast<ConstantSInt>(Op1)) {
1953 assert(Class != cLong && "This doesn't handle 64-bit divides!");
1954 int V = CI->getValue();
1956 if (V == 1) { // X /s 1 => X
1957 unsigned Op0Reg = getReg(Op0, BB, IP);
1958 BuildMI(*BB, IP, PPC32::OR, 2, ResultReg).addReg(Op0Reg).addReg(Op0Reg);
1962 if (V == -1) { // X /s -1 => -X
1963 unsigned Op0Reg = getReg(Op0, BB, IP);
1964 BuildMI(*BB, IP, PPC32::NEG, 1, ResultReg).addReg(Op0Reg);
1969 if (V < 0) { // Not a positive power of 2?
1971 isNeg = true; // Maybe it's a negative power of 2.
1973 if (unsigned Log = ExactLog2(V)) {
1975 unsigned Op0Reg = getReg(Op0, BB, IP);
1976 unsigned TmpReg = makeAnotherReg(Op0->getType());
1978 BuildMI(*BB, IP, PPC32::SRAWI,2, TmpReg).addReg(Op0Reg).addImm(Log-1);
1980 BuildMI(*BB, IP, PPC32::OR, 2, TmpReg).addReg(Op0Reg).addReg(Op0Reg);
1982 unsigned TmpReg2 = makeAnotherReg(Op0->getType());
1983 BuildMI(*BB, IP, PPC32::RLWINM, 4, TmpReg2).addReg(TmpReg).addImm(Log)
1984 .addImm(32-Log).addImm(31);
1986 unsigned TmpReg3 = makeAnotherReg(Op0->getType());
1987 BuildMI(*BB, IP, PPC32::ADD, 2, TmpReg3).addReg(Op0Reg).addReg(TmpReg2);
1989 unsigned TmpReg4 = isNeg ? makeAnotherReg(Op0->getType()) : ResultReg;
1990 BuildMI(*BB, IP, PPC32::SRAWI, 2, TmpReg4).addReg(Op0Reg).addImm(Log);
1993 BuildMI(*BB, IP, PPC32::NEG, 1, ResultReg).addReg(TmpReg4);
1998 unsigned Op0Reg = getReg(Op0, BB, IP);
1999 unsigned Op1Reg = getReg(Op1, BB, IP);
2002 if (Ty->isSigned()) {
2003 BuildMI(*BB, IP, PPC32::DIVW, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
2005 BuildMI(*BB, IP,PPC32::DIVWU, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
2007 } else { // Remainder
2008 unsigned TmpReg1 = makeAnotherReg(Op0->getType());
2009 unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2011 if (Ty->isSigned()) {
2012 BuildMI(*BB, IP, PPC32::DIVW, 2, TmpReg1).addReg(Op0Reg).addReg(Op1Reg);
2014 BuildMI(*BB, IP, PPC32::DIVWU, 2, TmpReg1).addReg(Op0Reg).addReg(Op1Reg);
2016 BuildMI(*BB, IP, PPC32::MULLW, 2, TmpReg2).addReg(TmpReg1).addReg(Op1Reg);
2017 BuildMI(*BB, IP, PPC32::SUBF, 2, ResultReg).addReg(TmpReg2).addReg(Op0Reg);
2022 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
2023 /// for constant immediate shift values, and for constant immediate
2024 /// shift values equal to 1. Even the general case is sort of special,
2025 /// because the shift amount has to be in CL, not just any old register.
2027 void ISel::visitShiftInst(ShiftInst &I) {
2028 MachineBasicBlock::iterator IP = BB->end ();
2029 emitShiftOperation(BB, IP, I.getOperand (0), I.getOperand (1),
2030 I.getOpcode () == Instruction::Shl, I.getType (),
2034 /// emitShiftOperation - Common code shared between visitShiftInst and
2035 /// constant expression support.
2037 void ISel::emitShiftOperation(MachineBasicBlock *MBB,
2038 MachineBasicBlock::iterator IP,
2039 Value *Op, Value *ShiftAmount, bool isLeftShift,
2040 const Type *ResultTy, unsigned DestReg) {
2041 unsigned SrcReg = getReg (Op, MBB, IP);
2042 bool isSigned = ResultTy->isSigned ();
2043 unsigned Class = getClass (ResultTy);
2045 // Longs, as usual, are handled specially...
2046 if (Class == cLong) {
2047 // If we have a constant shift, we can generate much more efficient code
2048 // than otherwise...
2050 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2051 unsigned Amount = CUI->getValue();
2054 // FIXME: RLWIMI is a use-and-def of DestReg+1, but that violates SSA
2055 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg+1).addReg(SrcReg+1)
2056 .addImm(Amount).addImm(0).addImm(31-Amount);
2057 BuildMI(*MBB, IP, PPC32::RLWIMI, 5).addReg(DestReg+1).addReg(SrcReg)
2058 .addImm(Amount).addImm(32-Amount).addImm(31);
2059 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg)
2060 .addImm(Amount).addImm(0).addImm(31-Amount);
2062 // FIXME: RLWIMI is a use-and-def of DestReg, but that violates SSA
2063 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg)
2064 .addImm(32-Amount).addImm(Amount).addImm(31);
2065 BuildMI(*MBB, IP, PPC32::RLWIMI, 5).addReg(DestReg).addReg(SrcReg+1)
2066 .addImm(32-Amount).addImm(0).addImm(Amount-1);
2067 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg+1).addReg(SrcReg+1)
2068 .addImm(32-Amount).addImm(Amount).addImm(31);
2070 } else { // Shifting more than 32 bits
2074 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg+1).addReg(SrcReg)
2075 .addImm(Amount).addImm(0).addImm(31-Amount);
2077 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg+1).addReg(SrcReg)
2080 BuildMI(*MBB, IP, PPC32::ADDI, 2,DestReg).addReg(PPC32::R0).addImm(0);
2084 BuildMI(*MBB, IP, PPC32::SRAWI, 2, DestReg).addReg(SrcReg+1)
2087 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg+1)
2088 .addImm(32-Amount).addImm(Amount).addImm(31);
2090 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg+1)
2093 BuildMI(*MBB, IP,PPC32::ADDI,2,DestReg+1).addReg(PPC32::R0).addImm(0);
2097 unsigned TmpReg1 = makeAnotherReg(Type::IntTy);
2098 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
2099 unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
2100 unsigned TmpReg4 = makeAnotherReg(Type::IntTy);
2101 unsigned TmpReg5 = makeAnotherReg(Type::IntTy);
2102 unsigned TmpReg6 = makeAnotherReg(Type::IntTy);
2103 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
2106 BuildMI(*MBB, IP, PPC32::SUBFIC, 2, TmpReg1).addReg(ShiftAmountReg)
2108 BuildMI(*MBB, IP, PPC32::SLW, 2, TmpReg2).addReg(SrcReg+1)
2109 .addReg(ShiftAmountReg);
2110 BuildMI(*MBB, IP, PPC32::SRW, 2,TmpReg3).addReg(SrcReg).addReg(TmpReg1);
2111 BuildMI(*MBB, IP, PPC32::OR, 2,TmpReg4).addReg(TmpReg2).addReg(TmpReg3);
2112 BuildMI(*MBB, IP, PPC32::ADDI, 2, TmpReg5).addReg(ShiftAmountReg)
2114 BuildMI(*MBB, IP, PPC32::SLW, 2,TmpReg6).addReg(SrcReg).addReg(TmpReg5);
2115 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg+1).addReg(TmpReg4)
2117 BuildMI(*MBB, IP, PPC32::SLW, 2, DestReg).addReg(SrcReg)
2118 .addReg(ShiftAmountReg);
2121 // FIXME: Unimplmented
2122 // Page C-3 of the PowerPC 32bit Programming Environments Manual
2124 BuildMI(*MBB, IP, PPC32::SUBFIC, 2, TmpReg1).addReg(ShiftAmountReg)
2126 BuildMI(*MBB, IP, PPC32::SRW, 2, TmpReg2).addReg(SrcReg)
2127 .addReg(ShiftAmountReg);
2128 BuildMI(*MBB, IP, PPC32::SLW, 2, TmpReg3).addReg(SrcReg+1)
2130 BuildMI(*MBB, IP, PPC32::OR, 2, TmpReg4).addReg(TmpReg2)
2132 BuildMI(*MBB, IP, PPC32::ADDI, 2, TmpReg5).addReg(ShiftAmountReg)
2134 BuildMI(*MBB, IP, PPC32::SRW, 2, TmpReg6).addReg(SrcReg+1)
2136 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(TmpReg4)
2138 BuildMI(*MBB, IP, PPC32::SRW, 2, DestReg+1).addReg(SrcReg+1)
2139 .addReg(ShiftAmountReg);
2146 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2147 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
2148 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
2149 unsigned Amount = CUI->getValue();
2152 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg)
2153 .addImm(Amount).addImm(0).addImm(31-Amount);
2156 BuildMI(*MBB, IP, PPC32::SRAWI,2,DestReg).addReg(SrcReg).addImm(Amount);
2158 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg)
2159 .addImm(32-Amount).addImm(Amount).addImm(31);
2162 } else { // The shift amount is non-constant.
2163 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
2166 BuildMI(*MBB, IP, PPC32::SLW, 2, DestReg).addReg(SrcReg)
2167 .addReg(ShiftAmountReg);
2169 BuildMI(*MBB, IP, isSigned ? PPC32::SRAW : PPC32::SRW, 2, DestReg)
2170 .addReg(SrcReg).addReg(ShiftAmountReg);
2176 /// visitLoadInst - Implement LLVM load instructions
2178 void ISel::visitLoadInst(LoadInst &I) {
2179 static const unsigned Opcodes[] = {
2180 PPC32::LBZ, PPC32::LHZ, PPC32::LWZ, PPC32::LFS
2182 unsigned Class = getClassB(I.getType());
2183 unsigned Opcode = Opcodes[Class];
2184 if (I.getType() == Type::DoubleTy) Opcode = PPC32::LFD;
2186 unsigned DestReg = getReg(I);
2188 if (AllocaInst *AI = dyn_castFixedAlloca(I.getOperand(0))) {
2189 unsigned FI = getFixedSizedAllocaFI(AI);
2190 if (Class == cLong) {
2191 addFrameReference(BuildMI(BB, PPC32::LWZ, 2, DestReg), FI);
2192 addFrameReference(BuildMI(BB, PPC32::LWZ, 2, DestReg+1), FI, 4);
2194 addFrameReference(BuildMI(BB, Opcode, 2, DestReg), FI);
2197 unsigned SrcAddrReg = getReg(I.getOperand(0));
2199 if (Class == cLong) {
2200 BuildMI(BB, PPC32::LWZ, 2, DestReg).addImm(0).addReg(SrcAddrReg);
2201 BuildMI(BB, PPC32::LWZ, 2, DestReg+1).addImm(4).addReg(SrcAddrReg);
2203 BuildMI(BB, Opcode, 2, DestReg).addImm(0).addReg(SrcAddrReg);
2208 /// visitStoreInst - Implement LLVM store instructions
2210 void ISel::visitStoreInst(StoreInst &I) {
2211 unsigned ValReg = getReg(I.getOperand(0));
2212 unsigned AddressReg = getReg(I.getOperand(1));
2214 const Type *ValTy = I.getOperand(0)->getType();
2215 unsigned Class = getClassB(ValTy);
2217 if (Class == cLong) {
2218 BuildMI(BB, PPC32::STW, 3).addReg(ValReg).addImm(0).addReg(AddressReg);
2219 BuildMI(BB, PPC32::STW, 3).addReg(ValReg+1).addImm(4).addReg(AddressReg);
2223 static const unsigned Opcodes[] = {
2224 PPC32::STB, PPC32::STH, PPC32::STW, PPC32::STFS
2226 unsigned Opcode = Opcodes[Class];
2227 if (ValTy == Type::DoubleTy) Opcode = PPC32::STFD;
2228 BuildMI(BB, Opcode, 3).addReg(ValReg).addImm(0).addReg(AddressReg);
2232 /// visitCastInst - Here we have various kinds of copying with or without sign
2233 /// extension going on.
2235 void ISel::visitCastInst(CastInst &CI) {
2236 Value *Op = CI.getOperand(0);
2238 unsigned SrcClass = getClassB(Op->getType());
2239 unsigned DestClass = getClassB(CI.getType());
2240 // Noop casts are not emitted: getReg will return the source operand as the
2241 // register to use for any uses of the noop cast.
2242 if (DestClass == SrcClass)
2245 // If this is a cast from a 32-bit integer to a Long type, and the only uses
2246 // of the case are GEP instructions, then the cast does not need to be
2247 // generated explicitly, it will be folded into the GEP.
2248 if (DestClass == cLong && SrcClass == cInt) {
2249 bool AllUsesAreGEPs = true;
2250 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
2251 if (!isa<GetElementPtrInst>(*I)) {
2252 AllUsesAreGEPs = false;
2256 // No need to codegen this cast if all users are getelementptr instrs...
2257 if (AllUsesAreGEPs) return;
2260 unsigned DestReg = getReg(CI);
2261 MachineBasicBlock::iterator MI = BB->end();
2262 emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
2265 /// emitCastOperation - Common code shared between visitCastInst and constant
2266 /// expression cast support.
2268 void ISel::emitCastOperation(MachineBasicBlock *BB,
2269 MachineBasicBlock::iterator IP,
2270 Value *Src, const Type *DestTy,
2272 const Type *SrcTy = Src->getType();
2273 unsigned SrcClass = getClassB(SrcTy);
2274 unsigned DestClass = getClassB(DestTy);
2275 unsigned SrcReg = getReg(Src, BB, IP);
2277 // Implement casts to bool by using compare on the operand followed by set if
2278 // not zero on the result.
2279 if (DestTy == Type::BoolTy) {
2284 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2285 BuildMI(*BB, IP, PPC32::ADDIC, 2, TmpReg).addReg(SrcReg).addImm(-1);
2286 BuildMI(*BB, IP, PPC32::SUBFE, 2, DestReg).addReg(TmpReg).addReg(SrcReg);
2290 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2291 unsigned SrcReg2 = makeAnotherReg(Type::IntTy);
2292 BuildMI(*BB, IP, PPC32::OR, 2, SrcReg2).addReg(SrcReg).addReg(SrcReg+1);
2293 BuildMI(*BB, IP, PPC32::ADDIC, 2, TmpReg).addReg(SrcReg2).addImm(-1);
2294 BuildMI(*BB, IP, PPC32::SUBFE, 2, DestReg).addReg(TmpReg).addReg(SrcReg2);
2313 // Implement casts between values of the same type class (as determined by
2314 // getClass) by using a register-to-register move.
2315 if (SrcClass == DestClass) {
2316 if (SrcClass <= cInt) {
2317 BuildMI(*BB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2318 } else if (SrcClass == cFP && SrcTy == DestTy) {
2319 BuildMI(*BB, IP, PPC32::FMR, 1, DestReg).addReg(SrcReg);
2320 } else if (SrcClass == cFP) {
2321 if (SrcTy == Type::FloatTy) { // float -> double
2322 assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
2323 BuildMI(*BB, IP, PPC32::FMR, 1, DestReg).addReg(SrcReg);
2324 } else { // double -> float
2325 assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
2326 "Unknown cFP member!");
2327 BuildMI(*BB, IP, PPC32::FRSP, 1, DestReg).addReg(SrcReg);
2329 } else if (SrcClass == cLong) {
2330 BuildMI(*BB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2331 BuildMI(*BB, IP, PPC32::OR, 2, DestReg+1).addReg(SrcReg+1)
2334 assert(0 && "Cannot handle this type of cast instruction!");
2340 // Handle cast of SMALLER int to LARGER int using a move with sign extension
2341 // or zero extension, depending on whether the source type was signed.
2342 if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
2343 SrcClass < DestClass) {
2344 bool isLong = DestClass == cLong;
2345 if (isLong) DestClass = cInt;
2347 bool isUnsigned = SrcTy->isUnsigned() || SrcTy == Type::BoolTy;
2348 if (SrcClass < cInt) {
2350 unsigned shift = (SrcClass == cByte) ? 24 : 16;
2351 BuildMI(*BB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg).addZImm(0)
2352 .addImm(shift).addImm(31);
2354 BuildMI(*BB, IP, (SrcClass == cByte) ? PPC32::EXTSB : PPC32::EXTSH,
2355 1, DestReg).addReg(SrcReg);
2358 BuildMI(*BB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2361 if (isLong) { // Handle upper 32 bits as appropriate...
2362 if (isUnsigned) // Zero out top bits...
2363 BuildMI(*BB, IP, PPC32::ADDI, 2, DestReg+1).addReg(PPC32::R0).addImm(0);
2364 else // Sign extend bottom half...
2365 BuildMI(*BB, IP, PPC32::SRAWI, 2, DestReg+1).addReg(DestReg).addImm(31);
2370 // Special case long -> int ...
2371 if (SrcClass == cLong && DestClass == cInt) {
2372 BuildMI(*BB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2376 // Handle cast of LARGER int to SMALLER int with a clear or sign extend
2377 if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
2378 && SrcClass > DestClass) {
2379 bool isUnsigned = SrcTy->isUnsigned() || SrcTy == Type::BoolTy;
2381 unsigned shift = (SrcClass == cByte) ? 24 : 16;
2382 BuildMI(*BB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg).addZImm(0)
2383 .addImm(shift).addImm(31);
2385 BuildMI(*BB, IP, (SrcClass == cByte) ? PPC32::EXTSB : PPC32::EXTSH, 1,
2386 DestReg).addReg(SrcReg);
2391 // Handle casts from integer to floating point now...
2392 if (DestClass == cFP) {
2394 // Emit a library call for long to float conversion
2395 if (SrcClass == cLong) {
2396 std::vector<ValueRecord> Args;
2397 Args.push_back(ValueRecord(SrcReg, SrcTy));
2398 MachineInstr *TheCall =
2399 BuildMI(PPC32::CALLpcrel, 1).addExternalSymbol("__floatdidf", true);
2400 doCall(ValueRecord(DestReg, DestTy), TheCall, Args);
2404 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2405 switch (SrcTy->getTypeID()) {
2406 case Type::BoolTyID:
2407 case Type::SByteTyID:
2408 BuildMI(*BB, IP, PPC32::EXTSB, 1, TmpReg).addReg(SrcReg);
2410 case Type::UByteTyID:
2411 BuildMI(*BB, IP, PPC32::RLWINM, 4, TmpReg).addReg(SrcReg).addZImm(0)
2412 .addImm(24).addImm(31);
2414 case Type::ShortTyID:
2415 BuildMI(*BB, IP, PPC32::EXTSB, 1, TmpReg).addReg(SrcReg);
2417 case Type::UShortTyID:
2418 BuildMI(*BB, IP, PPC32::RLWINM, 4, TmpReg).addReg(SrcReg).addZImm(0)
2419 .addImm(16).addImm(31);
2422 BuildMI(*BB, IP, PPC32::OR, 2, TmpReg).addReg(SrcReg).addReg(SrcReg);
2424 case Type::UIntTyID:
2425 BuildMI(*BB, IP, PPC32::OR, 2, TmpReg).addReg(SrcReg).addReg(SrcReg);
2427 default: // No promotion needed...
2433 // Spill the integer to memory and reload it from there.
2434 // Also spill room for a special conversion constant
2435 int ConstantFrameIndex =
2436 F->getFrameInfo()->CreateStackObject(Type::DoubleTy, TM.getTargetData());
2438 F->getFrameInfo()->CreateStackObject(Type::DoubleTy, TM.getTargetData());
2440 unsigned constantHi = makeAnotherReg(Type::IntTy);
2441 unsigned constantLo = makeAnotherReg(Type::IntTy);
2442 unsigned ConstF = makeAnotherReg(Type::DoubleTy);
2443 unsigned TempF = makeAnotherReg(Type::DoubleTy);
2445 if (!SrcTy->isSigned()) {
2446 BuildMI(*BB, IP, PPC32::ADDIS, 2, constantHi).addReg(PPC32::R0)
2448 BuildMI(*BB, IP, PPC32::ADDI, 2, constantLo).addReg(PPC32::R0).addImm(0);
2449 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantHi),
2450 ConstantFrameIndex);
2451 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantLo),
2452 ConstantFrameIndex, 4);
2453 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantHi),
2455 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(SrcReg),
2457 addFrameReference(BuildMI(*BB, IP, PPC32::LFD, 2, ConstF),
2458 ConstantFrameIndex);
2459 addFrameReference(BuildMI(*BB, IP, PPC32::LFD, 2, TempF), ValueFrameIdx);
2460 BuildMI(*BB, IP, PPC32::FSUB, 2, DestReg).addReg(TempF).addReg(ConstF);
2462 unsigned TempLo = makeAnotherReg(Type::IntTy);
2463 BuildMI(*BB, IP, PPC32::ADDIS, 2, constantHi).addReg(PPC32::R0)
2465 BuildMI(*BB, IP, PPC32::ADDIS, 2, constantLo).addReg(PPC32::R0)
2467 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantHi),
2468 ConstantFrameIndex);
2469 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantLo),
2470 ConstantFrameIndex, 4);
2471 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantHi),
2473 BuildMI(*BB, IP, PPC32::XORIS, 2, TempLo).addReg(SrcReg).addImm(0x8000);
2474 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(TempLo),
2476 addFrameReference(BuildMI(*BB, IP, PPC32::LFD, 2, ConstF),
2477 ConstantFrameIndex);
2478 addFrameReference(BuildMI(*BB, IP, PPC32::LFD, 2, TempF), ValueFrameIdx);
2479 BuildMI(*BB, IP, PPC32::FSUB, 2, DestReg).addReg(TempF ).addReg(ConstF);
2484 // Handle casts from floating point to integer now...
2485 if (SrcClass == cFP) {
2487 // emit library call
2488 if (DestClass == cLong) {
2489 std::vector<ValueRecord> Args;
2490 Args.push_back(ValueRecord(SrcReg, SrcTy));
2491 MachineInstr *TheCall =
2492 BuildMI(PPC32::CALLpcrel, 1).addExternalSymbol("__fixdfdi", true);
2493 doCall(ValueRecord(DestReg, DestTy), TheCall, Args);
2498 F->getFrameInfo()->CreateStackObject(Type::DoubleTy, TM.getTargetData());
2500 // load into 32 bit value, and then truncate as necessary
2501 // FIXME: This is wrong for unsigned dest types
2502 //if (DestTy->isSigned()) {
2503 unsigned TempReg = makeAnotherReg(Type::DoubleTy);
2504 BuildMI(*BB, IP, PPC32::FCTIWZ, 1, TempReg).addReg(SrcReg);
2505 addFrameReference(BuildMI(*BB, IP, PPC32::STFD, 3)
2506 .addReg(TempReg), ValueFrameIdx);
2507 addFrameReference(BuildMI(*BB, IP, PPC32::LWZ, 2, DestReg),
2512 // FIXME: Truncate return value
2516 // Anything we haven't handled already, we can't (yet) handle at all.
2517 assert(0 && "Unhandled cast instruction!");
2521 /// visitVANextInst - Implement the va_next instruction...
2523 void ISel::visitVANextInst(VANextInst &I) {
2524 unsigned VAList = getReg(I.getOperand(0));
2525 unsigned DestReg = getReg(I);
2528 switch (I.getArgType()->getTypeID()) {
2531 assert(0 && "Error: bad type for va_next instruction!");
2533 case Type::PointerTyID:
2534 case Type::UIntTyID:
2538 case Type::ULongTyID:
2539 case Type::LongTyID:
2540 case Type::DoubleTyID:
2545 // Increment the VAList pointer...
2546 BuildMI(BB, PPC32::ADDI, 2, DestReg).addReg(VAList).addImm(Size);
2549 void ISel::visitVAArgInst(VAArgInst &I) {
2550 unsigned VAList = getReg(I.getOperand(0));
2551 unsigned DestReg = getReg(I);
2553 switch (I.getType()->getTypeID()) {
2556 assert(0 && "Error: bad type for va_next instruction!");
2558 case Type::PointerTyID:
2559 case Type::UIntTyID:
2561 BuildMI(BB, PPC32::LWZ, 2, DestReg).addImm(0).addReg(VAList);
2563 case Type::ULongTyID:
2564 case Type::LongTyID:
2565 BuildMI(BB, PPC32::LWZ, 2, DestReg).addImm(0).addReg(VAList);
2566 BuildMI(BB, PPC32::LWZ, 2, DestReg+1).addImm(4).addReg(VAList);
2568 case Type::DoubleTyID:
2569 BuildMI(BB, PPC32::LFD, 2, DestReg).addImm(0).addReg(VAList);
2574 /// visitGetElementPtrInst - instruction-select GEP instructions
2576 void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
2577 unsigned outputReg = getReg(I);
2578 emitGEPOperation(BB, BB->end(), I.getOperand(0), I.op_begin()+1, I.op_end(),
2582 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
2583 MachineBasicBlock::iterator IP,
2584 Value *Src, User::op_iterator IdxBegin,
2585 User::op_iterator IdxEnd, unsigned TargetReg) {
2586 const TargetData &TD = TM.getTargetData();
2587 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
2588 Src = CPR->getValue();
2590 std::vector<Value*> GEPOps;
2591 GEPOps.resize(IdxEnd-IdxBegin+1);
2593 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
2595 std::vector<const Type*> GEPTypes;
2596 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
2597 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
2599 // Keep emitting instructions until we consume the entire GEP instruction.
2600 while (!GEPTypes.empty()) {
2601 // It's an array or pointer access: [ArraySize x ElementType].
2602 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
2603 Value *idx = GEPOps.back();
2604 GEPOps.pop_back(); // Consume a GEP operand
2605 GEPTypes.pop_back();
2607 // Many GEP instructions use a [cast (int/uint) to LongTy] as their
2608 // operand on X86. Handle this case directly now...
2609 if (CastInst *CI = dyn_cast<CastInst>(idx))
2610 if (CI->getOperand(0)->getType() == Type::IntTy ||
2611 CI->getOperand(0)->getType() == Type::UIntTy)
2612 idx = CI->getOperand(0);
2614 // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
2615 // must find the size of the pointed-to type (Not coincidentally, the next
2616 // type is the type of the elements in the array).
2617 const Type *ElTy = SqTy->getElementType();
2618 unsigned elementSize = TD.getTypeSize(ElTy);
2620 if (elementSize == 1) {
2621 // If the element size is 1, we don't have to multiply, just add
2622 unsigned idxReg = getReg(idx, MBB, IP);
2623 unsigned Reg = makeAnotherReg(Type::UIntTy);
2624 BuildMI(*MBB, IP, PPC32::ADD, 2,TargetReg).addReg(Reg).addReg(idxReg);
2625 --IP; // Insert the next instruction before this one.
2626 TargetReg = Reg; // Codegen the rest of the GEP into this
2628 unsigned idxReg = getReg(idx, MBB, IP);
2629 unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
2631 // Make sure we can back the iterator up to point to the first
2632 // instruction emitted.
2633 MachineBasicBlock::iterator BeforeIt = IP;
2634 if (IP == MBB->begin())
2635 BeforeIt = MBB->end();
2638 doMultiplyConst(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSize);
2640 // Emit an ADD to add OffsetReg to the basePtr.
2641 unsigned Reg = makeAnotherReg(Type::UIntTy);
2642 BuildMI(*MBB, IP, PPC32::ADD, 2, TargetReg).addReg(Reg).addReg(OffsetReg);
2644 // Step to the first instruction of the multiply.
2645 if (BeforeIt == MBB->end())
2650 TargetReg = Reg; // Codegen the rest of the GEP into this
2655 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
2656 /// frame manager, otherwise do it the hard way.
2658 void ISel::visitAllocaInst(AllocaInst &I) {
2659 // If this is a fixed size alloca in the entry block for the function, we
2660 // statically stack allocate the space, so we don't need to do anything here.
2662 if (dyn_castFixedAlloca(&I)) return;
2664 // Find the data size of the alloca inst's getAllocatedType.
2665 const Type *Ty = I.getAllocatedType();
2666 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
2668 // Create a register to hold the temporary result of multiplying the type size
2669 // constant by the variable amount.
2670 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
2671 unsigned SrcReg1 = getReg(I.getArraySize());
2673 // TotalSizeReg = mul <numelements>, <TypeSize>
2674 MachineBasicBlock::iterator MBBI = BB->end();
2675 doMultiplyConst(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, TySize);
2677 // AddedSize = add <TotalSizeReg>, 15
2678 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
2679 BuildMI(BB, PPC32::ADD, 2, AddedSizeReg).addReg(TotalSizeReg).addImm(15);
2681 // AlignedSize = and <AddedSize>, ~15
2682 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
2683 BuildMI(BB, PPC32::RLWNM, 4, AlignedSize).addReg(AddedSizeReg).addImm(0)
2684 .addImm(0).addImm(27);
2686 // Subtract size from stack pointer, thereby allocating some space.
2687 BuildMI(BB, PPC32::SUB, 2, PPC32::R1).addReg(PPC32::R1).addReg(AlignedSize);
2689 // Put a pointer to the space into the result register, by copying
2690 // the stack pointer.
2691 BuildMI(BB, PPC32::OR, 2, getReg(I)).addReg(PPC32::R1).addReg(PPC32::R1);
2693 // Inform the Frame Information that we have just allocated a variable-sized
2695 F->getFrameInfo()->CreateVariableSizedObject();
2698 /// visitMallocInst - Malloc instructions are code generated into direct calls
2699 /// to the library malloc.
2701 void ISel::visitMallocInst(MallocInst &I) {
2702 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
2705 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
2706 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
2708 Arg = makeAnotherReg(Type::UIntTy);
2709 unsigned Op0Reg = getReg(I.getOperand(0));
2710 MachineBasicBlock::iterator MBBI = BB->end();
2711 doMultiplyConst(BB, MBBI, Arg, Type::UIntTy, Op0Reg, AllocSize);
2714 std::vector<ValueRecord> Args;
2715 Args.push_back(ValueRecord(Arg, Type::UIntTy));
2716 MachineInstr *TheCall =
2717 BuildMI(PPC32::CALLpcrel, 1).addExternalSymbol("malloc", true);
2718 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args);
2722 /// visitFreeInst - Free instructions are code gen'd to call the free libc
2725 void ISel::visitFreeInst(FreeInst &I) {
2726 std::vector<ValueRecord> Args;
2727 Args.push_back(ValueRecord(I.getOperand(0)));
2728 MachineInstr *TheCall =
2729 BuildMI(PPC32::CALLpcrel, 1).addExternalSymbol("free", true);
2730 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
2733 /// createPPC32SimpleInstructionSelector - This pass converts an LLVM function
2734 /// into a machine code representation is a very simple peep-hole fashion. The
2735 /// generated code sucks but the implementation is nice and simple.
2737 FunctionPass *llvm::createPPCSimpleInstructionSelector(TargetMachine &TM) {
2738 return new ISel(TM);