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"
34 /// TypeClass - Used by the PowerPC backend to group LLVM types by their basic
35 /// PPC Representation.
38 cByte, cShort, cInt, cFP32, cFP64, cLong
42 /// getClass - Turn a primitive type into a "class" number which is based on the
43 /// size of the type, and whether or not it is floating point.
45 static inline TypeClass getClass(const Type *Ty) {
46 switch (Ty->getTypeID()) {
48 case Type::UByteTyID: return cByte; // Byte operands are class #0
50 case Type::UShortTyID: return cShort; // Short operands are class #1
53 case Type::PointerTyID: return cInt; // Ints and pointers are class #2
55 case Type::FloatTyID: return cFP32; // Single float is #3
56 case Type::DoubleTyID: return cFP64; // Double Point is #4
59 case Type::ULongTyID: return cLong; // Longs are class #5
61 assert(0 && "Invalid type to getClass!");
62 return cByte; // not reached
66 // getClassB - Just like getClass, but treat boolean values as ints.
67 static inline TypeClass getClassB(const Type *Ty) {
68 if (Ty == Type::BoolTy) return cInt;
73 struct ISel : public FunctionPass, InstVisitor<ISel> {
75 MachineFunction *F; // The function we are compiling into
76 MachineBasicBlock *BB; // The current MBB we are compiling
77 int VarArgsFrameIndex; // FrameIndex for start of varargs area
78 int ReturnAddressIndex; // FrameIndex for the return address
80 std::map<Value*, unsigned> RegMap; // Mapping between Values and SSA Regs
82 // External functions used in the Module
83 Function *fmodfFn, *fmodFn, *__moddi3Fn, *__divdi3Fn, *__umoddi3Fn,
84 *__udivdi3Fn, *__fixsfdiFn, *__fixdfdiFn, *__floatdisfFn, *__floatdidfFn,
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 ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
96 bool doInitialization(Module &M) {
97 // Add external functions that we may call
98 Type *d = Type::DoubleTy;
99 Type *f = Type::FloatTy;
100 Type *l = Type::LongTy;
101 Type *ul = Type::ULongTy;
102 Type *voidPtr = PointerType::get(Type::SByteTy);
103 // float fmodf(float, float);
104 fmodfFn = M.getOrInsertFunction("fmodf", f, f, f, 0);
105 // double fmod(double, double);
106 fmodFn = M.getOrInsertFunction("fmod", d, d, d, 0);
107 // long __moddi3(long, long);
108 __moddi3Fn = M.getOrInsertFunction("__moddi3", l, l, l, 0);
109 // long __divdi3(long, long);
110 __divdi3Fn = M.getOrInsertFunction("__divdi3", l, l, l, 0);
111 // unsigned long __umoddi3(unsigned long, unsigned long);
112 __umoddi3Fn = M.getOrInsertFunction("__umoddi3", ul, ul, ul, 0);
113 // unsigned long __udivdi3(unsigned long, unsigned long);
114 __udivdi3Fn = M.getOrInsertFunction("__udivdi3", ul, ul, ul, 0);
115 // long __fixsfdi(float)
116 __fixdfdiFn = M.getOrInsertFunction("__fixsfdi", l, f, 0);
117 // long __fixdfdi(double)
118 __fixdfdiFn = M.getOrInsertFunction("__fixdfdi", l, d, 0);
119 // float __floatdisf(long)
120 __floatdisfFn = M.getOrInsertFunction("__floatdisf", f, l, 0);
121 // double __floatdidf(long)
122 __floatdidfFn = M.getOrInsertFunction("__floatdidf", d, l, 0);
123 // void* malloc(size_t)
124 mallocFn = M.getOrInsertFunction("malloc", voidPtr, Type::UIntTy, 0);
126 freeFn = M.getOrInsertFunction("free", Type::VoidTy, voidPtr, 0);
130 /// runOnFunction - Top level implementation of instruction selection for
131 /// the entire function.
133 bool runOnFunction(Function &Fn) {
134 // First pass over the function, lower any unknown intrinsic functions
135 // with the IntrinsicLowering class.
136 LowerUnknownIntrinsicFunctionCalls(Fn);
138 F = &MachineFunction::construct(&Fn, TM);
140 // Create all of the machine basic blocks for the function...
141 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
142 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
146 // Set up a frame object for the return address. This is used by the
147 // llvm.returnaddress & llvm.frameaddress intrinisics.
148 ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
150 // Copy incoming arguments off of the stack...
151 LoadArgumentsToVirtualRegs(Fn);
153 // Instruction select everything except PHI nodes
156 // Select the PHI nodes
163 // We always build a machine code representation for the function
167 virtual const char *getPassName() const {
168 return "PowerPC Simple Instruction Selection";
171 /// visitBasicBlock - This method is called when we are visiting a new basic
172 /// block. This simply creates a new MachineBasicBlock to emit code into
173 /// and adds it to the current MachineFunction. Subsequent visit* for
174 /// instructions will be invoked for all instructions in the basic block.
176 void visitBasicBlock(BasicBlock &LLVM_BB) {
177 BB = MBBMap[&LLVM_BB];
180 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
181 /// function, lowering any calls to unknown intrinsic functions into the
182 /// equivalent LLVM code.
184 void LowerUnknownIntrinsicFunctionCalls(Function &F);
186 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
187 /// from the stack into virtual registers.
189 void LoadArgumentsToVirtualRegs(Function &F);
191 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
192 /// because we have to generate our sources into the source basic blocks,
193 /// not the current one.
195 void SelectPHINodes();
197 // Visitation methods for various instructions. These methods simply emit
198 // fixed PowerPC code for each instruction.
200 // Control flow operators
201 void visitReturnInst(ReturnInst &RI);
202 void visitBranchInst(BranchInst &BI);
208 ValueRecord(unsigned R, const Type *T) : Val(0), Reg(R), Ty(T) {}
209 ValueRecord(Value *V) : Val(V), Reg(0), Ty(V->getType()) {}
211 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
212 const std::vector<ValueRecord> &Args, bool isVarArg);
213 void visitCallInst(CallInst &I);
214 void visitIntrinsicCall(Intrinsic::ID ID, CallInst &I);
216 // Arithmetic operators
217 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
218 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
219 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
220 void visitMul(BinaryOperator &B);
222 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
223 void visitRem(BinaryOperator &B) { visitDivRem(B); }
224 void visitDivRem(BinaryOperator &B);
227 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
228 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
229 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
231 // Comparison operators...
232 void visitSetCondInst(SetCondInst &I);
233 unsigned EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
234 MachineBasicBlock *MBB,
235 MachineBasicBlock::iterator MBBI);
236 void visitSelectInst(SelectInst &SI);
239 // Memory Instructions
240 void visitLoadInst(LoadInst &I);
241 void visitStoreInst(StoreInst &I);
242 void visitGetElementPtrInst(GetElementPtrInst &I);
243 void visitAllocaInst(AllocaInst &I);
244 void visitMallocInst(MallocInst &I);
245 void visitFreeInst(FreeInst &I);
248 void visitShiftInst(ShiftInst &I);
249 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
250 void visitCastInst(CastInst &I);
251 void visitVANextInst(VANextInst &I);
252 void visitVAArgInst(VAArgInst &I);
254 void visitInstruction(Instruction &I) {
255 std::cerr << "Cannot instruction select: " << I;
259 /// promote32 - Make a value 32-bits wide, and put it somewhere.
261 void promote32(unsigned targetReg, const ValueRecord &VR);
263 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
264 /// constant expression GEP support.
266 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
267 Value *Src, User::op_iterator IdxBegin,
268 User::op_iterator IdxEnd, unsigned TargetReg);
270 /// emitCastOperation - Common code shared between visitCastInst and
271 /// constant expression cast support.
273 void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
274 Value *Src, const Type *DestTy, unsigned TargetReg);
276 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
277 /// and constant expression support.
279 void emitSimpleBinaryOperation(MachineBasicBlock *BB,
280 MachineBasicBlock::iterator IP,
281 Value *Op0, Value *Op1,
282 unsigned OperatorClass, unsigned TargetReg);
284 /// emitBinaryFPOperation - This method handles emission of floating point
285 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
286 void emitBinaryFPOperation(MachineBasicBlock *BB,
287 MachineBasicBlock::iterator IP,
288 Value *Op0, Value *Op1,
289 unsigned OperatorClass, unsigned TargetReg);
291 void emitMultiply(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
292 Value *Op0, Value *Op1, unsigned TargetReg);
294 void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
295 unsigned DestReg, const Type *DestTy,
296 unsigned Op0Reg, unsigned Op1Reg);
297 void doMultiplyConst(MachineBasicBlock *MBB,
298 MachineBasicBlock::iterator MBBI,
299 unsigned DestReg, const Type *DestTy,
300 unsigned Op0Reg, unsigned Op1Val);
302 void emitDivRemOperation(MachineBasicBlock *BB,
303 MachineBasicBlock::iterator IP,
304 Value *Op0, Value *Op1, bool isDiv,
307 /// emitSetCCOperation - Common code shared between visitSetCondInst and
308 /// constant expression support.
310 void emitSetCCOperation(MachineBasicBlock *BB,
311 MachineBasicBlock::iterator IP,
312 Value *Op0, Value *Op1, unsigned Opcode,
315 /// emitShiftOperation - Common code shared between visitShiftInst and
316 /// constant expression support.
318 void emitShiftOperation(MachineBasicBlock *MBB,
319 MachineBasicBlock::iterator IP,
320 Value *Op, Value *ShiftAmount, bool isLeftShift,
321 const Type *ResultTy, unsigned DestReg);
323 /// emitSelectOperation - Common code shared between visitSelectInst and the
324 /// constant expression support.
325 void emitSelectOperation(MachineBasicBlock *MBB,
326 MachineBasicBlock::iterator IP,
327 Value *Cond, Value *TrueVal, Value *FalseVal,
330 /// copyConstantToRegister - Output the instructions required to put the
331 /// specified constant into the specified register.
333 void copyConstantToRegister(MachineBasicBlock *MBB,
334 MachineBasicBlock::iterator MBBI,
335 Constant *C, unsigned Reg);
337 void emitUCOM(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
338 unsigned LHS, unsigned RHS);
340 /// makeAnotherReg - This method returns the next register number we haven't
343 /// Long values are handled somewhat specially. They are always allocated
344 /// as pairs of 32 bit integer values. The register number returned is the
345 /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
346 /// of the long value.
348 unsigned makeAnotherReg(const Type *Ty) {
349 assert(dynamic_cast<const PowerPCRegisterInfo*>(TM.getRegisterInfo()) &&
350 "Current target doesn't have PPC reg info??");
351 const PowerPCRegisterInfo *MRI =
352 static_cast<const PowerPCRegisterInfo*>(TM.getRegisterInfo());
353 if (Ty == Type::LongTy || Ty == Type::ULongTy) {
354 const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
355 // Create the lower part
356 F->getSSARegMap()->createVirtualRegister(RC);
357 // Create the upper part.
358 return F->getSSARegMap()->createVirtualRegister(RC)-1;
361 // Add the mapping of regnumber => reg class to MachineFunction
362 const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
363 return F->getSSARegMap()->createVirtualRegister(RC);
366 /// getReg - This method turns an LLVM value into a register number.
368 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
369 unsigned getReg(Value *V) {
370 // Just append to the end of the current bb.
371 MachineBasicBlock::iterator It = BB->end();
372 return getReg(V, BB, It);
374 unsigned getReg(Value *V, MachineBasicBlock *MBB,
375 MachineBasicBlock::iterator IPt);
377 /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
378 /// that is to be statically allocated with the initial stack frame
380 unsigned getFixedSizedAllocaFI(AllocaInst *AI);
384 /// dyn_castFixedAlloca - If the specified value is a fixed size alloca
385 /// instruction in the entry block, return it. Otherwise, return a null
387 static AllocaInst *dyn_castFixedAlloca(Value *V) {
388 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
389 BasicBlock *BB = AI->getParent();
390 if (isa<ConstantUInt>(AI->getArraySize()) && BB ==&BB->getParent()->front())
396 /// getReg - This method turns an LLVM value into a register number.
398 unsigned ISel::getReg(Value *V, MachineBasicBlock *MBB,
399 MachineBasicBlock::iterator IPt) {
400 if (Constant *C = dyn_cast<Constant>(V)) {
401 unsigned Reg = makeAnotherReg(V->getType());
402 copyConstantToRegister(MBB, IPt, C, Reg);
404 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
405 // Do not emit noop casts at all.
406 if (getClassB(CI->getType()) == getClassB(CI->getOperand(0)->getType()))
407 return getReg(CI->getOperand(0), MBB, IPt);
408 } else if (AllocaInst *AI = dyn_castFixedAlloca(V)) {
409 unsigned Reg = makeAnotherReg(V->getType());
410 unsigned FI = getFixedSizedAllocaFI(AI);
411 addFrameReference(BuildMI(*MBB, IPt, PPC32::ADDI, 2, Reg), FI, 0, false);
415 unsigned &Reg = RegMap[V];
417 Reg = makeAnotherReg(V->getType());
424 /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
425 /// that is to be statically allocated with the initial stack frame
427 unsigned ISel::getFixedSizedAllocaFI(AllocaInst *AI) {
428 // Already computed this?
429 std::map<AllocaInst*, unsigned>::iterator I = AllocaMap.lower_bound(AI);
430 if (I != AllocaMap.end() && I->first == AI) return I->second;
432 const Type *Ty = AI->getAllocatedType();
433 ConstantUInt *CUI = cast<ConstantUInt>(AI->getArraySize());
434 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
435 TySize *= CUI->getValue(); // Get total allocated size...
436 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
438 // Create a new stack object using the frame manager...
439 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
440 AllocaMap.insert(I, std::make_pair(AI, FrameIdx));
445 /// copyConstantToRegister - Output the instructions required to put the
446 /// specified constant into the specified register.
448 void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
449 MachineBasicBlock::iterator IP,
450 Constant *C, unsigned R) {
451 if (C->getType()->isIntegral()) {
452 unsigned Class = getClassB(C->getType());
454 if (Class == cLong) {
455 // Copy the value into the register pair.
456 uint64_t Val = cast<ConstantInt>(C)->getRawValue();
458 if (Val < (1ULL << 16)) {
459 BuildMI(*MBB, IP, PPC32::LI, 1, R).addImm(Val & 0xFFFF);
460 BuildMI(*MBB, IP, PPC32::LI, 1, R+1).addImm(0);
461 } else if (Val < (1ULL << 32)) {
462 unsigned Temp = makeAnotherReg(Type::IntTy);
463 BuildMI(*MBB, IP, PPC32::LIS, 1, Temp).addImm((Val >> 16) & 0xFFFF);
464 BuildMI(*MBB, IP, PPC32::ORI, 2, R).addReg(Temp).addImm(Val & 0xFFFF);
465 BuildMI(*MBB, IP, PPC32::LI, 1, R+1).addImm(0);
466 } else if (Val < (1ULL << 48)) {
467 unsigned Temp = makeAnotherReg(Type::IntTy);
468 BuildMI(*MBB, IP, PPC32::LIS, 1, Temp).addImm((Val >> 16) & 0xFFFF);
469 BuildMI(*MBB, IP, PPC32::ORI, 2, R).addReg(Temp).addImm(Val & 0xFFFF);
470 BuildMI(*MBB, IP, PPC32::LI, 1, R+1).addImm((Val >> 32) & 0xFFFF);
472 unsigned TempLo = makeAnotherReg(Type::IntTy);
473 unsigned TempHi = makeAnotherReg(Type::IntTy);
474 BuildMI(*MBB, IP, PPC32::LIS, 1, TempLo).addImm((Val >> 16) & 0xFFFF);
475 BuildMI(*MBB, IP, PPC32::ORI, 2, R).addReg(TempLo).addImm(Val & 0xFFFF);
476 BuildMI(*MBB, IP, PPC32::LIS, 1, TempHi).addImm((Val >> 48) & 0xFFFF);
477 BuildMI(*MBB, IP, PPC32::ORI, 2, R+1).addReg(TempHi)
478 .addImm((Val >> 32) & 0xFFFF);
483 assert(Class <= cInt && "Type not handled yet!");
485 if (C->getType() == Type::BoolTy) {
486 BuildMI(*MBB, IP, PPC32::LI, 1, R).addImm(C == ConstantBool::True);
487 } else if (Class == cByte || Class == cShort) {
488 ConstantInt *CI = cast<ConstantInt>(C);
489 BuildMI(*MBB, IP, PPC32::LI, 1, R).addImm(CI->getRawValue());
491 ConstantInt *CI = cast<ConstantInt>(C);
492 int TheVal = CI->getRawValue() & 0xFFFFFFFF;
493 if (TheVal < 32768 && TheVal >= -32768) {
494 BuildMI(*MBB, IP, PPC32::LI, 1, R).addImm(CI->getRawValue());
496 unsigned TmpReg = makeAnotherReg(Type::IntTy);
497 BuildMI(*MBB, IP, PPC32::LIS, 1, TmpReg)
498 .addImm(CI->getRawValue() >> 16);
499 BuildMI(*MBB, IP, PPC32::ORI, 2, R).addReg(TmpReg)
500 .addImm(CI->getRawValue() & 0xFFFF);
503 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
504 // We need to spill the constant to memory...
505 MachineConstantPool *CP = F->getConstantPool();
506 unsigned CPI = CP->getConstantPoolIndex(CFP);
507 const Type *Ty = CFP->getType();
509 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
511 // Load addr of constant to reg; constant is located at PC + distance
512 unsigned CurPC = makeAnotherReg(Type::IntTy);
513 unsigned Reg1 = makeAnotherReg(Type::IntTy);
514 unsigned Reg2 = makeAnotherReg(Type::IntTy);
515 // Move PC to destination reg
516 BuildMI(*MBB, IP, PPC32::MovePCtoLR, 0, CurPC);
517 // Move value at PC + distance into return reg
518 BuildMI(*MBB, IP, PPC32::LOADHiAddr, 2, Reg1).addReg(CurPC)
519 .addConstantPoolIndex(CPI);
520 BuildMI(*MBB, IP, PPC32::LOADLoAddr, 2, Reg2).addReg(Reg1)
521 .addConstantPoolIndex(CPI);
523 unsigned LoadOpcode = (Ty == Type::FloatTy) ? PPC32::LFS : PPC32::LFD;
524 BuildMI(*MBB, IP, LoadOpcode, 2, R).addImm(0).addReg(Reg2);
525 } else if (isa<ConstantPointerNull>(C)) {
526 // Copy zero (null pointer) to the register.
527 BuildMI(*MBB, IP, PPC32::LI, 1, R).addImm(0);
528 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
529 // GV is located at PC + distance
530 unsigned CurPC = makeAnotherReg(Type::IntTy);
531 unsigned TmpReg = makeAnotherReg(GV->getType());
532 // Move PC to destination reg
533 BuildMI(*MBB, IP, PPC32::MovePCtoLR, 0, CurPC);
534 // Move value at PC + distance into return reg
535 BuildMI(*MBB, IP, PPC32::LOADHiAddr, 2, TmpReg).addReg(CurPC)
536 .addGlobalAddress(GV);
537 BuildMI(*MBB, IP, PPC32::LOADLoAddr, 2, R).addReg(TmpReg)
538 .addGlobalAddress(GV);
540 std::cerr << "Offending constant: " << *C << "\n";
541 assert(0 && "Type not handled yet!");
545 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
546 /// the stack into virtual registers.
548 /// FIXME: When we can calculate which args are coming in via registers
549 /// source them from there instead.
550 void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
551 unsigned ArgOffset = 0; // Frame mechanisms handle retaddr slot
552 unsigned GPR_remaining = 8;
553 unsigned FPR_remaining = 13;
554 unsigned GPR_idx = 0, FPR_idx = 0;
555 static const unsigned GPR[] = {
556 PPC32::R3, PPC32::R4, PPC32::R5, PPC32::R6,
557 PPC32::R7, PPC32::R8, PPC32::R9, PPC32::R10,
559 static const unsigned FPR[] = {
560 PPC32::F1, PPC32::F2, PPC32::F3, PPC32::F4, PPC32::F5, PPC32::F6, PPC32::F7,
561 PPC32::F8, PPC32::F9, PPC32::F10, PPC32::F11, PPC32::F12, PPC32::F13
564 MachineFrameInfo *MFI = F->getFrameInfo();
566 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
567 bool ArgLive = !I->use_empty();
568 unsigned Reg = ArgLive ? getReg(*I) : 0;
569 int FI; // Frame object index
571 switch (getClassB(I->getType())) {
574 FI = MFI->CreateFixedObject(1, ArgOffset);
575 if (GPR_remaining > 0) {
576 BuildMI(BB, PPC32::IMPLICIT_DEF, 0, GPR[GPR_idx]);
577 BuildMI(BB, PPC32::OR, 2, Reg).addReg(GPR[GPR_idx])
578 .addReg(GPR[GPR_idx]);
580 addFrameReference(BuildMI(BB, PPC32::LBZ, 2, Reg), FI);
586 FI = MFI->CreateFixedObject(2, ArgOffset);
587 if (GPR_remaining > 0) {
588 BuildMI(BB, PPC32::IMPLICIT_DEF, 0, GPR[GPR_idx]);
589 BuildMI(BB, PPC32::OR, 2, Reg).addReg(GPR[GPR_idx])
590 .addReg(GPR[GPR_idx]);
592 addFrameReference(BuildMI(BB, PPC32::LHZ, 2, Reg), FI);
598 FI = MFI->CreateFixedObject(4, ArgOffset);
599 if (GPR_remaining > 0) {
600 BuildMI(BB, PPC32::IMPLICIT_DEF, 0, GPR[GPR_idx]);
601 BuildMI(BB, PPC32::OR, 2, Reg).addReg(GPR[GPR_idx])
602 .addReg(GPR[GPR_idx]);
604 addFrameReference(BuildMI(BB, PPC32::LWZ, 2, Reg), FI);
610 FI = MFI->CreateFixedObject(8, ArgOffset);
611 if (GPR_remaining > 1) {
612 BuildMI(BB, PPC32::IMPLICIT_DEF, 0, GPR[GPR_idx]);
613 BuildMI(BB, PPC32::IMPLICIT_DEF, 0, GPR[GPR_idx+1]);
614 BuildMI(BB, PPC32::OR, 2, Reg).addReg(GPR[GPR_idx])
615 .addReg(GPR[GPR_idx]);
616 BuildMI(BB, PPC32::OR, 2, Reg+1).addReg(GPR[GPR_idx+1])
617 .addReg(GPR[GPR_idx+1]);
619 addFrameReference(BuildMI(BB, PPC32::LWZ, 2, Reg), FI);
620 addFrameReference(BuildMI(BB, PPC32::LWZ, 2, Reg+1), FI, 4);
623 ArgOffset += 4; // longs require 4 additional bytes
624 if (GPR_remaining > 1) {
625 GPR_remaining--; // uses up 2 GPRs
631 FI = MFI->CreateFixedObject(4, ArgOffset);
633 if (FPR_remaining > 0) {
634 BuildMI(BB, PPC32::IMPLICIT_DEF, 0, FPR[FPR_idx]);
635 BuildMI(BB, PPC32::FMR, 1, Reg).addReg(FPR[FPR_idx]);
639 addFrameReference(BuildMI(BB, PPC32::LFS, 2, Reg), FI);
645 FI = MFI->CreateFixedObject(8, ArgOffset);
647 if (FPR_remaining > 0) {
648 BuildMI(BB, PPC32::IMPLICIT_DEF, 0, FPR[FPR_idx]);
649 BuildMI(BB, PPC32::FMR, 1, Reg).addReg(FPR[FPR_idx]);
653 addFrameReference(BuildMI(BB, PPC32::LFD, 2, Reg), FI);
657 // doubles require 4 additional bytes and use 2 GPRs of param space
659 if (GPR_remaining > 0) {
665 assert(0 && "Unhandled argument type!");
667 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
668 if (GPR_remaining > 0) {
669 GPR_remaining--; // uses up 2 GPRs
674 // If the function takes variable number of arguments, add a frame offset for
675 // the start of the first vararg value... this is used to expand
677 if (Fn.getFunctionType()->isVarArg())
678 VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
682 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
683 /// because we have to generate our sources into the source basic blocks, not
686 void ISel::SelectPHINodes() {
687 const TargetInstrInfo &TII = *TM.getInstrInfo();
688 const Function &LF = *F->getFunction(); // The LLVM function...
689 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
690 const BasicBlock *BB = I;
691 MachineBasicBlock &MBB = *MBBMap[I];
693 // Loop over all of the PHI nodes in the LLVM basic block...
694 MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
695 for (BasicBlock::const_iterator I = BB->begin();
696 PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
698 // Create a new machine instr PHI node, and insert it.
699 unsigned PHIReg = getReg(*PN);
700 MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
701 PPC32::PHI, PN->getNumOperands(), PHIReg);
703 MachineInstr *LongPhiMI = 0;
704 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
705 LongPhiMI = BuildMI(MBB, PHIInsertPoint,
706 PPC32::PHI, PN->getNumOperands(), PHIReg+1);
708 // PHIValues - Map of blocks to incoming virtual registers. We use this
709 // so that we only initialize one incoming value for a particular block,
710 // even if the block has multiple entries in the PHI node.
712 std::map<MachineBasicBlock*, unsigned> PHIValues;
714 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
715 MachineBasicBlock *PredMBB = 0;
716 for (MachineBasicBlock::pred_iterator PI = MBB.pred_begin (),
717 PE = MBB.pred_end (); PI != PE; ++PI)
718 if (PN->getIncomingBlock(i) == (*PI)->getBasicBlock()) {
722 assert (PredMBB && "Couldn't find incoming machine-cfg edge for phi");
725 std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
726 PHIValues.lower_bound(PredMBB);
728 if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
729 // We already inserted an initialization of the register for this
730 // predecessor. Recycle it.
731 ValReg = EntryIt->second;
734 // Get the incoming value into a virtual register.
736 Value *Val = PN->getIncomingValue(i);
738 // If this is a constant or GlobalValue, we may have to insert code
739 // into the basic block to compute it into a virtual register.
740 if ((isa<Constant>(Val) && !isa<ConstantExpr>(Val)) ||
741 isa<GlobalValue>(Val)) {
742 // Simple constants get emitted at the end of the basic block,
743 // before any terminator instructions. We "know" that the code to
744 // move a constant into a register will never clobber any flags.
745 ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
747 // Because we don't want to clobber any values which might be in
748 // physical registers with the computation of this constant (which
749 // might be arbitrarily complex if it is a constant expression),
750 // just insert the computation at the top of the basic block.
751 MachineBasicBlock::iterator PI = PredMBB->begin();
753 // Skip over any PHI nodes though!
754 while (PI != PredMBB->end() && PI->getOpcode() == PPC32::PHI)
757 ValReg = getReg(Val, PredMBB, PI);
760 // Remember that we inserted a value for this PHI for this predecessor
761 PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
764 PhiMI->addRegOperand(ValReg);
765 PhiMI->addMachineBasicBlockOperand(PredMBB);
767 LongPhiMI->addRegOperand(ValReg+1);
768 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
772 // Now that we emitted all of the incoming values for the PHI node, make
773 // sure to reposition the InsertPoint after the PHI that we just added.
774 // This is needed because we might have inserted a constant into this
775 // block, right after the PHI's which is before the old insert point!
776 PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
783 // canFoldSetCCIntoBranchOrSelect - Return the setcc instruction if we can fold
784 // it into the conditional branch or select instruction which is the only user
785 // of the cc instruction. This is the case if the conditional branch is the
786 // only user of the setcc, and if the setcc is in the same basic block as the
787 // conditional branch. We also don't handle long arguments below, so we reject
788 // them here as well.
790 static SetCondInst *canFoldSetCCIntoBranchOrSelect(Value *V) {
791 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
792 if (SCI->hasOneUse()) {
793 Instruction *User = cast<Instruction>(SCI->use_back());
794 if ((isa<BranchInst>(User) || isa<SelectInst>(User)) &&
795 SCI->getParent() == User->getParent())
801 // Return a fixed numbering for setcc instructions which does not depend on the
802 // order of the opcodes.
804 static unsigned getSetCCNumber(unsigned Opcode) {
806 default: assert(0 && "Unknown setcc instruction!");
807 case Instruction::SetEQ: return 0;
808 case Instruction::SetNE: return 1;
809 case Instruction::SetLT: return 2;
810 case Instruction::SetGE: return 3;
811 case Instruction::SetGT: return 4;
812 case Instruction::SetLE: return 5;
816 static unsigned getPPCOpcodeForSetCCNumber(unsigned Opcode) {
818 default: assert(0 && "Unknown setcc instruction!");
819 case Instruction::SetEQ: return PPC32::BEQ;
820 case Instruction::SetNE: return PPC32::BNE;
821 case Instruction::SetLT: return PPC32::BLT;
822 case Instruction::SetGE: return PPC32::BGE;
823 case Instruction::SetGT: return PPC32::BGT;
824 case Instruction::SetLE: return PPC32::BLE;
828 static unsigned invertPPCBranchOpcode(unsigned Opcode) {
830 default: assert(0 && "Unknown PPC32 branch opcode!");
831 case PPC32::BEQ: return PPC32::BNE;
832 case PPC32::BNE: return PPC32::BEQ;
833 case PPC32::BLT: return PPC32::BGE;
834 case PPC32::BGE: return PPC32::BLT;
835 case PPC32::BGT: return PPC32::BLE;
836 case PPC32::BLE: return PPC32::BGT;
840 /// emitUCOM - emits an unordered FP compare.
841 void ISel::emitUCOM(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
842 unsigned LHS, unsigned RHS) {
843 BuildMI(*MBB, IP, PPC32::FCMPU, 2, PPC32::CR0).addReg(LHS).addReg(RHS);
846 /// EmitComparison - emits a comparison of the two operands, returning the
847 /// extended setcc code to use. The result is in CR0.
849 unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
850 MachineBasicBlock *MBB,
851 MachineBasicBlock::iterator IP) {
852 // The arguments are already supposed to be of the same type.
853 const Type *CompTy = Op0->getType();
854 unsigned Class = getClassB(CompTy);
855 unsigned Op0r = getReg(Op0, MBB, IP);
857 // Special case handling of: cmp R, i
858 if (isa<ConstantPointerNull>(Op1)) {
859 BuildMI(*MBB, IP, PPC32::CMPI, 2, PPC32::CR0).addReg(Op0r).addImm(0);
860 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
861 if (Class == cByte || Class == cShort || Class == cInt) {
862 unsigned Op1v = CI->getRawValue();
864 // Mask off any upper bits of the constant, if there are any...
865 Op1v &= (1ULL << (8 << Class)) - 1;
867 // Compare immediate or promote to reg?
869 BuildMI(*MBB, IP, CompTy->isSigned() ? PPC32::CMPI : PPC32::CMPLI, 3,
870 PPC32::CR0).addImm(0).addReg(Op0r).addImm(Op1v);
872 unsigned Op1r = getReg(Op1, MBB, IP);
873 BuildMI(*MBB, IP, CompTy->isSigned() ? PPC32::CMP : PPC32::CMPL, 3,
874 PPC32::CR0).addImm(0).addReg(Op0r).addReg(Op1r);
878 assert(Class == cLong && "Unknown integer class!");
879 unsigned LowCst = CI->getRawValue();
880 unsigned HiCst = CI->getRawValue() >> 32;
881 if (OpNum < 2) { // seteq, setne
882 unsigned LoTmp = Op0r;
884 unsigned LoLow = makeAnotherReg(Type::IntTy);
885 unsigned LoTmp = makeAnotherReg(Type::IntTy);
886 BuildMI(*MBB, IP, PPC32::XORI, 2, LoLow).addReg(Op0r).addImm(LowCst);
887 BuildMI(*MBB, IP, PPC32::XORIS, 2, LoTmp).addReg(LoLow)
888 .addImm(LowCst >> 16);
890 unsigned HiTmp = Op0r+1;
892 unsigned HiLow = makeAnotherReg(Type::IntTy);
893 unsigned HiTmp = makeAnotherReg(Type::IntTy);
894 BuildMI(*MBB, IP, PPC32::XORI, 2, HiLow).addReg(Op0r+1).addImm(HiCst);
895 BuildMI(*MBB, IP, PPC32::XORIS, 2, HiTmp).addReg(HiLow)
896 .addImm(HiCst >> 16);
898 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
899 BuildMI(*MBB, IP, PPC32::ORo, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
902 unsigned ConstReg = makeAnotherReg(CompTy);
903 unsigned CondReg = makeAnotherReg(Type::IntTy);
904 unsigned TmpReg1 = makeAnotherReg(Type::IntTy);
905 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
906 copyConstantToRegister(MBB, IP, CI, ConstReg);
908 // FIXME: this is inefficient, but avoids branches
910 // compare hi word -> cr0
911 // compare lo word -> cr1
912 BuildMI(*MBB, IP, CompTy->isSigned() ? PPC32::CMPI : PPC32::CMPLI, 3,
913 PPC32::CR0).addImm(0).addReg(Op0r+1).addReg(ConstReg+1);
914 BuildMI(*MBB, IP, PPC32::CMPLI, 3, PPC32::CR1).addImm(0).addReg(Op0r)
916 BuildMI(*MBB, IP, PPC32::MFCR, 0, CondReg);
917 // shift amount = 4 * CR0[EQ]
918 BuildMI(*MBB, IP, PPC32::RLWINM, 4, TmpReg1).addReg(CondReg).addImm(5)
919 .addImm(29).addImm(29);
920 // shift cr1 into cr0 position if op0.hi and const.hi were equal
921 BuildMI(*MBB, IP, PPC32::SLW, 2, TmpReg2).addReg(CondReg)
923 // cr0 == ( op0.hi != const.hi ) ? cr0 : cr1
924 BuildMI(*MBB, IP, PPC32::MTCRF, 2).addImm(1).addReg(TmpReg2);
931 unsigned Op1r = getReg(Op1, MBB, IP);
933 default: assert(0 && "Unknown type class!");
937 BuildMI(*MBB, IP, CompTy->isSigned() ? PPC32::CMP : PPC32::CMPL, 2,
938 PPC32::CR0).addReg(Op0r).addReg(Op1r);
943 emitUCOM(MBB, IP, Op0r, Op1r);
947 if (OpNum < 2) { // seteq, setne
948 unsigned LoTmp = makeAnotherReg(Type::IntTy);
949 unsigned HiTmp = makeAnotherReg(Type::IntTy);
950 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
951 BuildMI(*MBB, IP, PPC32::XOR, 2, LoTmp).addReg(Op0r).addReg(Op1r);
952 BuildMI(*MBB, IP, PPC32::XOR, 2, HiTmp).addReg(Op0r+1).addReg(Op1r+1);
953 BuildMI(*MBB, IP, PPC32::ORo, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
954 break; // Allow the sete or setne to be generated from flags set by OR
956 unsigned CondReg = makeAnotherReg(Type::IntTy);
957 unsigned TmpReg1 = makeAnotherReg(Type::IntTy);
958 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
960 // FIXME: this is inefficient, but avoids branches
962 // compare hi word -> cr0
963 // compare lo word -> cr1
964 BuildMI(*MBB, IP, CompTy->isSigned() ? PPC32::CMPI : PPC32::CMPLI, 3,
965 PPC32::CR0).addImm(0).addReg(Op0r+1).addReg(Op1r+1);
966 BuildMI(*MBB, IP, PPC32::CMPLI, 3, PPC32::CR1).addImm(0).addReg(Op0r)
968 BuildMI(*MBB, IP, PPC32::MFCR, 0, CondReg);
969 // shift amount = 4 * CR0[EQ]
970 BuildMI(*MBB, IP, PPC32::RLWINM, 4, TmpReg1).addReg(CondReg).addImm(5)
971 .addImm(29).addImm(29);
972 // shift cr1 into cr0 position if op0.hi and op1.hi were equal
973 BuildMI(*MBB, IP, PPC32::SLW, 2, TmpReg2).addReg(CondReg)
975 // cr0 == ( op0.hi != op1.hi ) ? cr0 : cr1
976 BuildMI(*MBB, IP, PPC32::MTCRF, 2).addImm(1).addReg(TmpReg2);
984 /// visitSetCondInst - emit code to calculate the condition via
985 /// EmitComparison(), and possibly store a 0 or 1 to a register as a result
987 void ISel::visitSetCondInst(SetCondInst &I) {
988 if (canFoldSetCCIntoBranchOrSelect(&I))
991 unsigned DestReg = getReg(I);
992 unsigned OpNum = I.getOpcode();
993 const Type *Ty = I.getOperand (0)->getType();
995 EmitComparison(OpNum, I.getOperand(0), I.getOperand(1), BB, BB->end());
997 unsigned Opcode = getPPCOpcodeForSetCCNumber(OpNum);
998 MachineBasicBlock *thisMBB = BB;
999 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1000 ilist<MachineBasicBlock>::iterator It = BB;
1005 // cmpTY cr0, r1, r2
1009 // FIXME: we wouldn't need copy0MBB (we could fold it into thisMBB)
1010 // if we could insert other, non-terminator instructions after the
1011 // bCC. But MBB->getFirstTerminator() can't understand this.
1012 MachineBasicBlock *copy1MBB = new MachineBasicBlock(LLVM_BB);
1013 F->getBasicBlockList().insert(It, copy1MBB);
1014 BuildMI(BB, Opcode, 2).addReg(PPC32::CR0).addMBB(copy1MBB);
1015 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
1016 F->getBasicBlockList().insert(It, copy0MBB);
1017 BuildMI(BB, PPC32::B, 1).addMBB(copy0MBB);
1018 // Update machine-CFG edges
1019 BB->addSuccessor(copy1MBB);
1020 BB->addSuccessor(copy0MBB);
1023 // %FalseValue = li 0
1026 unsigned FalseValue = makeAnotherReg(I.getType());
1027 BuildMI(BB, PPC32::LI, 1, FalseValue).addImm(0);
1028 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
1029 F->getBasicBlockList().insert(It, sinkMBB);
1030 BuildMI(BB, PPC32::B, 1).addMBB(sinkMBB);
1031 // Update machine-CFG edges
1032 BB->addSuccessor(sinkMBB);
1034 DEBUG(std::cerr << "thisMBB is at " << (void*)thisMBB << "\n");
1035 DEBUG(std::cerr << "copy1MBB is at " << (void*)copy1MBB << "\n");
1036 DEBUG(std::cerr << "copy0MBB is at " << (void*)copy0MBB << "\n");
1037 DEBUG(std::cerr << "sinkMBB is at " << (void*)sinkMBB << "\n");
1040 // %TrueValue = li 1
1043 unsigned TrueValue = makeAnotherReg (I.getType ());
1044 BuildMI(BB, PPC32::LI, 1, TrueValue).addImm(1);
1045 BuildMI(BB, PPC32::B, 1).addMBB(sinkMBB);
1046 // Update machine-CFG edges
1047 BB->addSuccessor(sinkMBB);
1050 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, copy1MBB ]
1053 BuildMI(BB, PPC32::PHI, 4, DestReg).addReg(FalseValue)
1054 .addMBB(copy0MBB).addReg(TrueValue).addMBB(copy1MBB);
1057 void ISel::visitSelectInst(SelectInst &SI) {
1058 unsigned DestReg = getReg(SI);
1059 MachineBasicBlock::iterator MII = BB->end();
1060 emitSelectOperation(BB, MII, SI.getCondition(), SI.getTrueValue(),
1061 SI.getFalseValue(), DestReg);
1064 /// emitSelect - Common code shared between visitSelectInst and the constant
1065 /// expression support.
1066 /// FIXME: this is most likely broken in one or more ways. Namely, PowerPC has
1067 /// no select instruction. FSEL only works for comparisons against zero.
1068 void ISel::emitSelectOperation(MachineBasicBlock *MBB,
1069 MachineBasicBlock::iterator IP,
1070 Value *Cond, Value *TrueVal, Value *FalseVal,
1072 unsigned SelectClass = getClassB(TrueVal->getType());
1075 // See if we can fold the setcc into the select instruction, or if we have
1076 // to get the register of the Cond value
1077 if (SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(Cond)) {
1078 // We successfully folded the setcc into the select instruction.
1080 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1081 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), MBB,
1083 Opcode = getPPCOpcodeForSetCCNumber(SCI->getOpcode());
1085 unsigned CondReg = getReg(Cond, MBB, IP);
1087 BuildMI(*MBB, IP, PPC32::CMPI, 2, PPC32::CR0).addReg(CondReg).addImm(0);
1088 Opcode = getPPCOpcodeForSetCCNumber(Instruction::SetNE);
1093 // cmpTY cr0, r1, r2
1097 MachineBasicBlock *thisMBB = BB;
1098 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1099 ilist<MachineBasicBlock>::iterator It = BB;
1102 // FIXME: we wouldn't need copy0MBB (we could fold it into thisMBB)
1103 // if we could insert other, non-terminator instructions after the
1104 // bCC. But MBB->getFirstTerminator() can't understand this.
1105 MachineBasicBlock *copy1MBB = new MachineBasicBlock(LLVM_BB);
1106 F->getBasicBlockList().insert(It, copy1MBB);
1107 BuildMI(BB, Opcode, 2).addReg(PPC32::CR0).addMBB(copy1MBB);
1108 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
1109 F->getBasicBlockList().insert(It, copy0MBB);
1110 BuildMI(BB, PPC32::B, 1).addMBB(copy0MBB);
1111 // Update machine-CFG edges
1112 BB->addSuccessor(copy1MBB);
1113 BB->addSuccessor(copy0MBB);
1115 // FIXME: spill code is being generated after the branch and before copy1MBB
1116 // this is bad, since it will never be run
1119 // %FalseValue = ...
1122 unsigned FalseValue = getReg(FalseVal, BB, BB->begin());
1123 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
1124 F->getBasicBlockList().insert(It, sinkMBB);
1125 BuildMI(BB, PPC32::B, 1).addMBB(sinkMBB);
1126 // Update machine-CFG edges
1127 BB->addSuccessor(sinkMBB);
1133 unsigned TrueValue = getReg(TrueVal, BB, BB->begin());
1134 BuildMI(BB, PPC32::B, 1).addMBB(sinkMBB);
1135 // Update machine-CFG edges
1136 BB->addSuccessor(sinkMBB);
1139 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, copy1MBB ]
1142 BuildMI(BB, PPC32::PHI, 4, DestReg).addReg(FalseValue)
1143 .addMBB(copy0MBB).addReg(TrueValue).addMBB(copy1MBB);
1149 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
1150 /// operand, in the specified target register.
1152 void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
1153 bool isUnsigned = VR.Ty->isUnsigned() || VR.Ty == Type::BoolTy;
1155 Value *Val = VR.Val;
1156 const Type *Ty = VR.Ty;
1158 if (Constant *C = dyn_cast<Constant>(Val)) {
1159 Val = ConstantExpr::getCast(C, Type::IntTy);
1163 // If this is a simple constant, just emit a load directly to avoid the copy
1164 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
1165 int TheVal = CI->getRawValue() & 0xFFFFFFFF;
1167 if (TheVal < 32768 && TheVal >= -32768) {
1168 BuildMI(BB, PPC32::LI, 1, targetReg).addImm(TheVal);
1170 unsigned TmpReg = makeAnotherReg(Type::IntTy);
1171 BuildMI(BB, PPC32::LIS, 1, TmpReg).addImm(TheVal >> 16);
1172 BuildMI(BB, PPC32::ORI, 2, targetReg).addReg(TmpReg)
1173 .addImm(TheVal & 0xFFFF);
1179 // Make sure we have the register number for this value...
1180 unsigned Reg = Val ? getReg(Val) : VR.Reg;
1182 switch (getClassB(Ty)) {
1184 // Extend value into target register (8->32)
1186 BuildMI(BB, PPC32::RLWINM, 4, targetReg).addReg(Reg).addZImm(0)
1187 .addZImm(24).addZImm(31);
1189 BuildMI(BB, PPC32::EXTSB, 1, targetReg).addReg(Reg);
1192 // Extend value into target register (16->32)
1194 BuildMI(BB, PPC32::RLWINM, 4, targetReg).addReg(Reg).addZImm(0)
1195 .addZImm(16).addZImm(31);
1197 BuildMI(BB, PPC32::EXTSH, 1, targetReg).addReg(Reg);
1200 // Move value into target register (32->32)
1201 BuildMI(BB, PPC32::OR, 2, targetReg).addReg(Reg).addReg(Reg);
1204 assert(0 && "Unpromotable operand class in promote32");
1208 /// visitReturnInst - implemented with BLR
1210 void ISel::visitReturnInst(ReturnInst &I) {
1211 // Only do the processing if this is a non-void return
1212 if (I.getNumOperands() > 0) {
1213 Value *RetVal = I.getOperand(0);
1214 switch (getClassB(RetVal->getType())) {
1215 case cByte: // integral return values: extend or move into r3 and return
1218 promote32(PPC32::R3, ValueRecord(RetVal));
1221 case cFP64: { // Floats & Doubles: Return in f1
1222 unsigned RetReg = getReg(RetVal);
1223 BuildMI(BB, PPC32::FMR, 1, PPC32::F1).addReg(RetReg);
1227 unsigned RetReg = getReg(RetVal);
1228 BuildMI(BB, PPC32::OR, 2, PPC32::R3).addReg(RetReg).addReg(RetReg);
1229 BuildMI(BB, PPC32::OR, 2, PPC32::R4).addReg(RetReg+1).addReg(RetReg+1);
1233 visitInstruction(I);
1236 BuildMI(BB, PPC32::BLR, 1).addImm(0);
1239 // getBlockAfter - Return the basic block which occurs lexically after the
1241 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1242 Function::iterator I = BB; ++I; // Get iterator to next block
1243 return I != BB->getParent()->end() ? &*I : 0;
1246 /// visitBranchInst - Handle conditional and unconditional branches here. Note
1247 /// that since code layout is frozen at this point, that if we are trying to
1248 /// jump to a block that is the immediate successor of the current block, we can
1249 /// just make a fall-through (but we don't currently).
1251 void ISel::visitBranchInst(BranchInst &BI) {
1252 // Update machine-CFG edges
1253 BB->addSuccessor (MBBMap[BI.getSuccessor(0)]);
1254 if (BI.isConditional())
1255 BB->addSuccessor (MBBMap[BI.getSuccessor(1)]);
1257 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
1259 if (!BI.isConditional()) { // Unconditional branch?
1260 if (BI.getSuccessor(0) != NextBB)
1261 BuildMI(BB, PPC32::B, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1265 // See if we can fold the setcc into the branch itself...
1266 SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(BI.getCondition());
1268 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
1269 // computed some other way...
1270 unsigned condReg = getReg(BI.getCondition());
1271 BuildMI(BB, PPC32::CMPLI, 3, PPC32::CR1).addImm(0).addReg(condReg)
1273 if (BI.getSuccessor(1) == NextBB) {
1274 if (BI.getSuccessor(0) != NextBB)
1275 BuildMI(BB, PPC32::BNE, 2).addReg(PPC32::CR1)
1276 .addMBB(MBBMap[BI.getSuccessor(0)]);
1278 BuildMI(BB, PPC32::BEQ, 2).addReg(PPC32::CR1)
1279 .addMBB(MBBMap[BI.getSuccessor(1)]);
1281 if (BI.getSuccessor(0) != NextBB)
1282 BuildMI(BB, PPC32::B, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1287 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1288 unsigned Opcode = getPPCOpcodeForSetCCNumber(SCI->getOpcode());
1289 MachineBasicBlock::iterator MII = BB->end();
1290 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
1292 if (BI.getSuccessor(0) != NextBB) {
1293 BuildMI(BB, Opcode, 2).addReg(PPC32::CR0)
1294 .addMBB(MBBMap[BI.getSuccessor(0)]);
1295 if (BI.getSuccessor(1) != NextBB)
1296 BuildMI(BB, PPC32::B, 1).addMBB(MBBMap[BI.getSuccessor(1)]);
1298 // Change to the inverse condition...
1299 if (BI.getSuccessor(1) != NextBB) {
1300 Opcode = invertPPCBranchOpcode(Opcode);
1301 BuildMI(BB, Opcode, 2).addReg(PPC32::CR0)
1302 .addMBB(MBBMap[BI.getSuccessor(1)]);
1307 static Constant* minUConstantForValue(uint64_t val) {
1309 return ConstantBool::get(val);
1310 else if (ConstantUInt::isValueValidForType(Type::UShortTy, val))
1311 return ConstantUInt::get(Type::UShortTy, val);
1312 else if (ConstantUInt::isValueValidForType(Type::UIntTy, val))
1313 return ConstantUInt::get(Type::UIntTy, val);
1314 else if (ConstantUInt::isValueValidForType(Type::ULongTy, val))
1315 return ConstantUInt::get(Type::ULongTy, val);
1317 std::cerr << "Value: " << val << " not accepted for any integral type!\n";
1321 /// doCall - This emits an abstract call instruction, setting up the arguments
1322 /// and the return value as appropriate. For the actual function call itself,
1323 /// it inserts the specified CallMI instruction into the stream.
1325 /// FIXME: See Documentation at the following URL for "correct" behavior
1326 /// <http://developer.apple.com/documentation/DeveloperTools/Conceptual/MachORuntime/2rt_powerpc_abi/chapter_9_section_5.html>
1327 void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
1328 const std::vector<ValueRecord> &Args, bool isVarArg) {
1329 // Count how many bytes are to be pushed on the stack...
1330 unsigned NumBytes = 0;
1332 if (!Args.empty()) {
1333 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1334 switch (getClassB(Args[i].Ty)) {
1335 case cByte: case cShort: case cInt:
1336 NumBytes += 4; break;
1338 NumBytes += 8; break;
1340 NumBytes += 4; break;
1342 NumBytes += 8; break;
1344 default: assert(0 && "Unknown class!");
1347 // Adjust the stack pointer for the new arguments...
1348 BuildMI(BB, PPC32::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
1350 // Arguments go on the stack in reverse order, as specified by the ABI.
1351 // Offset to the paramater area on the stack is 24.
1352 unsigned ArgOffset = 24;
1353 int GPR_remaining = 8, FPR_remaining = 13;
1354 unsigned GPR_idx = 0, FPR_idx = 0;
1355 static const unsigned GPR[] = {
1356 PPC32::R3, PPC32::R4, PPC32::R5, PPC32::R6,
1357 PPC32::R7, PPC32::R8, PPC32::R9, PPC32::R10,
1359 static const unsigned FPR[] = {
1360 PPC32::F1, PPC32::F2, PPC32::F3, PPC32::F4, PPC32::F5, PPC32::F6,
1361 PPC32::F7, PPC32::F8, PPC32::F9, PPC32::F10, PPC32::F11, PPC32::F12,
1365 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1367 switch (getClassB(Args[i].Ty)) {
1370 // Promote arg to 32 bits wide into a temporary register...
1371 ArgReg = makeAnotherReg(Type::UIntTy);
1372 promote32(ArgReg, Args[i]);
1375 if (GPR_remaining > 0) {
1376 BuildMI(BB, PPC32::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1378 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1380 BuildMI(BB, PPC32::STW, 3).addReg(ArgReg).addImm(ArgOffset)
1385 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1388 if (GPR_remaining > 0) {
1389 BuildMI(BB, PPC32::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1391 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1393 BuildMI(BB, PPC32::STW, 3).addReg(ArgReg).addImm(ArgOffset)
1398 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1401 if (GPR_remaining > 1) {
1402 BuildMI(BB, PPC32::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1404 BuildMI(BB, PPC32::OR, 2, GPR[GPR_idx+1]).addReg(ArgReg+1)
1406 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1407 CallMI->addRegOperand(GPR[GPR_idx+1], MachineOperand::Use);
1409 BuildMI(BB, PPC32::STW, 3).addReg(ArgReg).addImm(ArgOffset)
1411 BuildMI(BB, PPC32::STW, 3).addReg(ArgReg+1).addImm(ArgOffset+4)
1415 ArgOffset += 4; // 8 byte entry, not 4.
1416 GPR_remaining -= 1; // uses up 2 GPRs
1420 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1422 if (FPR_remaining > 0) {
1423 BuildMI(BB, PPC32::FMR, 1, FPR[FPR_idx]).addReg(ArgReg);
1424 CallMI->addRegOperand(FPR[FPR_idx], MachineOperand::Use);
1428 // If this is a vararg function, and there are GPRs left, also
1429 // pass the float in an int. Otherwise, put it on the stack.
1431 BuildMI(BB, PPC32::STFS, 3).addReg(ArgReg).addImm(ArgOffset)
1433 if (GPR_remaining > 0) {
1434 BuildMI(BB, PPC32::LWZ, 2, GPR[GPR_idx])
1435 .addImm(ArgOffset).addReg(ArgReg);
1436 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1440 BuildMI(BB, PPC32::STFS, 3).addReg(ArgReg).addImm(ArgOffset)
1445 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1447 if (FPR_remaining > 0) {
1448 BuildMI(BB, PPC32::FMR, 1, FPR[FPR_idx]).addReg(ArgReg);
1449 CallMI->addRegOperand(FPR[FPR_idx], MachineOperand::Use);
1452 // For vararg functions, must pass doubles via int regs as well
1454 BuildMI(BB, PPC32::STFD, 3).addReg(ArgReg).addImm(ArgOffset)
1457 if (GPR_remaining > 1) {
1458 BuildMI(BB, PPC32::LWZ, 2, GPR[GPR_idx]).addImm(ArgOffset)
1460 BuildMI(BB, PPC32::LWZ, 2, GPR[GPR_idx+1])
1461 .addImm(ArgOffset+4).addReg(PPC32::R1);
1462 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1463 CallMI->addRegOperand(GPR[GPR_idx+1], MachineOperand::Use);
1467 BuildMI(BB, PPC32::STFD, 3).addReg(ArgReg).addImm(ArgOffset)
1470 // Doubles use 8 bytes, and 2 GPRs worth of param space
1476 default: assert(0 && "Unknown class!");
1483 BuildMI(BB, PPC32::ADJCALLSTACKDOWN, 1).addImm(0);
1486 BB->push_back(CallMI);
1487 BuildMI(BB, PPC32::ADJCALLSTACKUP, 1).addImm(NumBytes);
1489 // If there is a return value, scavenge the result from the location the call
1492 if (Ret.Ty != Type::VoidTy) {
1493 unsigned DestClass = getClassB(Ret.Ty);
1494 switch (DestClass) {
1498 // Integral results are in r3
1499 BuildMI(BB, PPC32::OR, 2, Ret.Reg).addReg(PPC32::R3).addReg(PPC32::R3);
1501 case cFP32: // Floating-point return values live in f1
1503 BuildMI(BB, PPC32::FMR, 1, Ret.Reg).addReg(PPC32::F1);
1505 case cLong: // Long values are in r3:r4
1506 BuildMI(BB, PPC32::OR, 2, Ret.Reg).addReg(PPC32::R3).addReg(PPC32::R3);
1507 BuildMI(BB, PPC32::OR, 2, Ret.Reg+1).addReg(PPC32::R4).addReg(PPC32::R4);
1509 default: assert(0 && "Unknown class!");
1515 /// visitCallInst - Push args on stack and do a procedure call instruction.
1516 void ISel::visitCallInst(CallInst &CI) {
1517 MachineInstr *TheCall;
1518 Function *F = CI.getCalledFunction();
1520 // Is it an intrinsic function call?
1521 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1522 visitIntrinsicCall(ID, CI); // Special intrinsics are not handled here
1526 // Emit a CALL instruction with PC-relative displacement.
1527 TheCall = BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(F, true);
1528 } else { // Emit an indirect call through the CTR
1529 unsigned Reg = getReg(CI.getCalledValue());
1530 BuildMI(BB, PPC32::MTCTR, 1).addReg(Reg);
1531 TheCall = BuildMI(PPC32::CALLindirect, 2).addZImm(20).addZImm(0);
1534 std::vector<ValueRecord> Args;
1535 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
1536 Args.push_back(ValueRecord(CI.getOperand(i)));
1538 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1539 bool isVarArg = F ? F->getFunctionType()->isVarArg() : true;
1540 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args, isVarArg);
1544 /// dyncastIsNan - Return the operand of an isnan operation if this is an isnan.
1546 static Value *dyncastIsNan(Value *V) {
1547 if (CallInst *CI = dyn_cast<CallInst>(V))
1548 if (Function *F = CI->getCalledFunction())
1549 if (F->getIntrinsicID() == Intrinsic::isunordered)
1550 return CI->getOperand(1);
1554 /// isOnlyUsedByUnorderedComparisons - Return true if this value is only used by
1555 /// or's whos operands are all calls to the isnan predicate.
1556 static bool isOnlyUsedByUnorderedComparisons(Value *V) {
1557 assert(dyncastIsNan(V) && "The value isn't an isnan call!");
1559 // Check all uses, which will be or's of isnans if this predicate is true.
1560 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1561 Instruction *I = cast<Instruction>(*UI);
1562 if (I->getOpcode() != Instruction::Or) return false;
1563 if (I->getOperand(0) != V && !dyncastIsNan(I->getOperand(0))) return false;
1564 if (I->getOperand(1) != V && !dyncastIsNan(I->getOperand(1))) return false;
1570 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1571 /// function, lowering any calls to unknown intrinsic functions into the
1572 /// equivalent LLVM code.
1574 void ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1575 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1576 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1577 if (CallInst *CI = dyn_cast<CallInst>(I++))
1578 if (Function *F = CI->getCalledFunction())
1579 switch (F->getIntrinsicID()) {
1580 case Intrinsic::not_intrinsic:
1581 case Intrinsic::vastart:
1582 case Intrinsic::vacopy:
1583 case Intrinsic::vaend:
1584 case Intrinsic::returnaddress:
1585 case Intrinsic::frameaddress:
1586 // FIXME: should lower this ourselves
1587 // case Intrinsic::isunordered:
1588 // We directly implement these intrinsics
1590 case Intrinsic::readio: {
1591 // On PPC, memory operations are in-order. Lower this intrinsic
1592 // into a volatile load.
1593 Instruction *Before = CI->getPrev();
1594 LoadInst * LI = new LoadInst(CI->getOperand(1), "", true, CI);
1595 CI->replaceAllUsesWith(LI);
1596 BB->getInstList().erase(CI);
1599 case Intrinsic::writeio: {
1600 // On PPC, memory operations are in-order. Lower this intrinsic
1601 // into a volatile store.
1602 Instruction *Before = CI->getPrev();
1603 StoreInst *SI = new StoreInst(CI->getOperand(1),
1604 CI->getOperand(2), true, CI);
1605 CI->replaceAllUsesWith(SI);
1606 BB->getInstList().erase(CI);
1610 // All other intrinsic calls we must lower.
1611 Instruction *Before = CI->getPrev();
1612 TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
1613 if (Before) { // Move iterator to instruction after call
1621 void ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
1622 unsigned TmpReg1, TmpReg2, TmpReg3;
1624 case Intrinsic::vastart:
1625 // Get the address of the first vararg value...
1626 TmpReg1 = getReg(CI);
1627 addFrameReference(BuildMI(BB, PPC32::ADDI, 2, TmpReg1), VarArgsFrameIndex);
1630 case Intrinsic::vacopy:
1631 TmpReg1 = getReg(CI);
1632 TmpReg2 = getReg(CI.getOperand(1));
1633 BuildMI(BB, PPC32::OR, 2, TmpReg1).addReg(TmpReg2).addReg(TmpReg2);
1635 case Intrinsic::vaend: return;
1637 case Intrinsic::returnaddress:
1638 case Intrinsic::frameaddress:
1639 TmpReg1 = getReg(CI);
1640 if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1641 if (ID == Intrinsic::returnaddress) {
1642 // Just load the return address
1643 addFrameReference(BuildMI(BB, PPC32::LWZ, 2, TmpReg1),
1644 ReturnAddressIndex);
1646 addFrameReference(BuildMI(BB, PPC32::ADDI, 2, TmpReg1),
1647 ReturnAddressIndex, -4, false);
1650 // Values other than zero are not implemented yet.
1651 BuildMI(BB, PPC32::LI, 1, TmpReg1).addImm(0);
1656 // This may be useful for supporting isunordered
1657 case Intrinsic::isnan:
1658 // If this is only used by 'isunordered' style comparisons, don't emit it.
1659 if (isOnlyUsedByUnorderedComparisons(&CI)) return;
1660 TmpReg1 = getReg(CI.getOperand(1));
1661 emitUCOM(BB, BB->end(), TmpReg1, TmpReg1);
1662 TmpReg2 = makeAnotherReg(Type::IntTy);
1663 BuildMI(BB, PPC32::MFCR, TmpReg2);
1664 TmpReg3 = getReg(CI);
1665 BuildMI(BB, PPC32::RLWINM, 4, TmpReg3).addReg(TmpReg2).addImm(4).addImm(31).addImm(31);
1669 default: assert(0 && "Error: unknown intrinsics should have been lowered!");
1673 /// visitSimpleBinary - Implement simple binary operators for integral types...
1674 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
1677 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
1678 unsigned DestReg = getReg(B);
1679 MachineBasicBlock::iterator MI = BB->end();
1680 Value *Op0 = B.getOperand(0), *Op1 = B.getOperand(1);
1681 unsigned Class = getClassB(B.getType());
1683 emitSimpleBinaryOperation(BB, MI, Op0, Op1, OperatorClass, DestReg);
1686 /// emitBinaryFPOperation - This method handles emission of floating point
1687 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
1688 void ISel::emitBinaryFPOperation(MachineBasicBlock *BB,
1689 MachineBasicBlock::iterator IP,
1690 Value *Op0, Value *Op1,
1691 unsigned OperatorClass, unsigned DestReg) {
1693 // Special case: op Reg, <const fp>
1694 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1695 // Create a constant pool entry for this constant.
1696 MachineConstantPool *CP = F->getConstantPool();
1697 unsigned CPI = CP->getConstantPoolIndex(Op1C);
1698 const Type *Ty = Op1->getType();
1699 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1701 static const unsigned OpcodeTab[][4] = {
1702 { PPC32::FADDS, PPC32::FSUBS, PPC32::FMULS, PPC32::FDIVS }, // Float
1703 { PPC32::FADD, PPC32::FSUB, PPC32::FMUL, PPC32::FDIV }, // Double
1706 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
1707 unsigned Op1Reg = getReg(Op1C, BB, IP);
1708 unsigned Op0r = getReg(Op0, BB, IP);
1709 BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1Reg);
1713 // Special case: R1 = op <const fp>, R2
1714 if (ConstantFP *Op0C = dyn_cast<ConstantFP>(Op0))
1715 if (Op0C->isExactlyValue(-0.0) && OperatorClass == 1) {
1717 unsigned op1Reg = getReg(Op1, BB, IP);
1718 BuildMI(*BB, IP, PPC32::FNEG, 1, DestReg).addReg(op1Reg);
1721 // R1 = op CST, R2 --> R1 = opr R2, CST
1723 // Create a constant pool entry for this constant.
1724 MachineConstantPool *CP = F->getConstantPool();
1725 unsigned CPI = CP->getConstantPoolIndex(Op0C);
1726 const Type *Ty = Op0C->getType();
1727 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1729 static const unsigned OpcodeTab[][4] = {
1730 { PPC32::FADDS, PPC32::FSUBS, PPC32::FMULS, PPC32::FDIVS }, // Float
1731 { PPC32::FADD, PPC32::FSUB, PPC32::FMUL, PPC32::FDIV }, // Double
1734 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
1735 unsigned Op0Reg = getReg(Op0C, BB, IP);
1736 unsigned Op1Reg = getReg(Op1, BB, IP);
1737 BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0Reg).addReg(Op1Reg);
1742 static const unsigned OpcodeTab[] = {
1743 PPC32::FADD, PPC32::FSUB, PPC32::FMUL, PPC32::FDIV
1746 unsigned Opcode = OpcodeTab[OperatorClass];
1747 unsigned Op0r = getReg(Op0, BB, IP);
1748 unsigned Op1r = getReg(Op1, BB, IP);
1749 BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1752 /// emitSimpleBinaryOperation - Implement simple binary operators for integral
1753 /// types... OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
1756 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
1757 /// and constant expression support.
1759 void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
1760 MachineBasicBlock::iterator IP,
1761 Value *Op0, Value *Op1,
1762 unsigned OperatorClass, unsigned DestReg) {
1763 unsigned Class = getClassB(Op0->getType());
1765 // Arithmetic and Bitwise operators
1766 static const unsigned OpcodeTab[] = {
1767 PPC32::ADD, PPC32::SUB, PPC32::AND, PPC32::OR, PPC32::XOR
1769 // Otherwise, code generate the full operation with a constant.
1770 static const unsigned BottomTab[] = {
1771 PPC32::ADDC, PPC32::SUBC, PPC32::AND, PPC32::OR, PPC32::XOR
1773 static const unsigned TopTab[] = {
1774 PPC32::ADDE, PPC32::SUBFE, PPC32::AND, PPC32::OR, PPC32::XOR
1777 if (Class == cFP32 || Class == cFP64) {
1778 assert(OperatorClass < 2 && "No logical ops for FP!");
1779 emitBinaryFPOperation(MBB, IP, Op0, Op1, OperatorClass, DestReg);
1783 if (Op0->getType() == Type::BoolTy) {
1784 if (OperatorClass == 3)
1785 // If this is an or of two isnan's, emit an FP comparison directly instead
1786 // of or'ing two isnan's together.
1787 if (Value *LHS = dyncastIsNan(Op0))
1788 if (Value *RHS = dyncastIsNan(Op1)) {
1789 unsigned Op0Reg = getReg(RHS, MBB, IP), Op1Reg = getReg(LHS, MBB, IP);
1790 unsigned TmpReg = makeAnotherReg(Type::IntTy);
1791 emitUCOM(MBB, IP, Op0Reg, Op1Reg);
1792 BuildMI(*MBB, IP, PPC32::MFCR, TmpReg);
1793 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(TmpReg).addImm(4)
1794 .addImm(31).addImm(31);
1799 // sub 0, X -> neg X
1800 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0))
1801 if (OperatorClass == 1 && CI->isNullValue()) {
1802 unsigned op1Reg = getReg(Op1, MBB, IP);
1803 BuildMI(*MBB, IP, PPC32::NEG, 1, DestReg).addReg(op1Reg);
1805 if (Class == cLong) {
1806 unsigned zeroes = makeAnotherReg(Type::IntTy);
1807 unsigned overflow = makeAnotherReg(Type::IntTy);
1808 unsigned T = makeAnotherReg(Type::IntTy);
1809 BuildMI(*MBB, IP, PPC32::CNTLZW, 1, zeroes).addReg(op1Reg);
1810 BuildMI(*MBB, IP, PPC32::RLWINM, 4, overflow).addReg(zeroes).addImm(27)
1811 .addImm(5).addImm(31);
1812 BuildMI(*MBB, IP, PPC32::ADD, 2, T).addReg(op1Reg+1).addReg(overflow);
1813 BuildMI(*MBB, IP, PPC32::NEG, 1, DestReg+1).addReg(T);
1818 // Special case: op Reg, <const int>
1819 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1820 unsigned Op0r = getReg(Op0, MBB, IP);
1822 // xor X, -1 -> not X
1823 if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
1824 BuildMI(*MBB, IP, PPC32::NOR, 2, DestReg).addReg(Op0r).addReg(Op0r);
1825 if (Class == cLong) // Invert the top part too
1826 BuildMI(*MBB, IP, PPC32::NOR, 2, DestReg+1).addReg(Op0r+1)
1831 unsigned Opcode = OpcodeTab[OperatorClass];
1832 unsigned Op1r = getReg(Op1, MBB, IP);
1834 if (Class != cLong) {
1835 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1839 // If the constant is zero in the low 32-bits, just copy the low part
1840 // across and apply the normal 32-bit operation to the high parts. There
1841 // will be no carry or borrow into the top.
1842 if (cast<ConstantInt>(Op1C)->getRawValue() == 0) {
1843 if (OperatorClass != 2) // All but and...
1844 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(Op0r).addReg(Op0r);
1846 BuildMI(*MBB, IP, PPC32::LI, 1, DestReg).addImm(0);
1847 BuildMI(*MBB, IP, Opcode, 2, DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
1851 // If this is a long value and the high or low bits have a special
1852 // property, emit some special cases.
1853 unsigned Op1h = cast<ConstantInt>(Op1C)->getRawValue() >> 32LL;
1855 // If this is a logical operation and the top 32-bits are zero, just
1856 // operate on the lower 32.
1857 if (Op1h == 0 && OperatorClass > 1) {
1858 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1859 if (OperatorClass != 2) // All but and
1860 BuildMI(*MBB, IP, PPC32::OR, 2,DestReg+1).addReg(Op0r+1).addReg(Op0r+1);
1862 BuildMI(*MBB, IP, PPC32::LI, 1,DestReg+1).addImm(0);
1866 // TODO: We could handle lots of other special cases here, such as AND'ing
1867 // with 0xFFFFFFFF00000000 -> noop, etc.
1869 BuildMI(*MBB, IP, BottomTab[OperatorClass], 2, DestReg).addReg(Op0r)
1871 BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg+1).addReg(Op0r+1)
1876 unsigned Op0r = getReg(Op0, MBB, IP);
1877 unsigned Op1r = getReg(Op1, MBB, IP);
1879 if (Class != cLong) {
1880 unsigned Opcode = OpcodeTab[OperatorClass];
1881 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1883 BuildMI(*MBB, IP, BottomTab[OperatorClass], 2, DestReg).addReg(Op0r)
1885 BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg+1).addReg(Op0r+1)
1891 /// doMultiply - Emit appropriate instructions to multiply together the
1892 /// registers op0Reg and op1Reg, and put the result in DestReg. The type of the
1893 /// result should be given as DestTy.
1895 void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
1896 unsigned DestReg, const Type *DestTy,
1897 unsigned op0Reg, unsigned op1Reg) {
1898 unsigned Class = getClass(DestTy);
1901 BuildMI(*MBB, MBBI, PPC32::MULHW, 2, DestReg+1).addReg(op0Reg+1)
1906 BuildMI(*MBB, MBBI, PPC32::MULLW, 2, DestReg).addReg(op0Reg).addReg(op1Reg);
1909 assert(0 && "doMultiply cannot operate on unknown type!");
1913 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
1914 // returns zero when the input is not exactly a power of two.
1915 static unsigned ExactLog2(unsigned Val) {
1916 if (Val == 0 || (Val & (Val-1))) return 0;
1926 /// doMultiplyConst - This function is specialized to efficiently codegen an 8,
1927 /// 16, or 32-bit integer multiply by a constant.
1929 void ISel::doMultiplyConst(MachineBasicBlock *MBB,
1930 MachineBasicBlock::iterator IP,
1931 unsigned DestReg, const Type *DestTy,
1932 unsigned op0Reg, unsigned ConstRHS) {
1933 unsigned Class = getClass(DestTy);
1934 // Handle special cases here.
1937 BuildMI(*MBB, IP, PPC32::LI, 1, DestReg).addImm(0);
1940 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(op0Reg).addReg(op0Reg);
1943 BuildMI(*MBB, IP, PPC32::ADD, 2,DestReg).addReg(op0Reg).addReg(op0Reg);
1947 // If the element size is exactly a power of 2, use a shift to get it.
1948 if (unsigned Shift = ExactLog2(ConstRHS)) {
1950 default: assert(0 && "Unknown class for this function!");
1954 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(op0Reg)
1955 .addImm(Shift-1).addImm(0).addImm(31-Shift+1);
1960 // Most general case, emit a normal multiply...
1961 unsigned TmpReg = makeAnotherReg(Type::IntTy);
1962 Constant *C = ConstantUInt::get(Type::UIntTy, ConstRHS);
1964 copyConstantToRegister(MBB, IP, C, TmpReg);
1965 doMultiply(MBB, IP, DestReg, DestTy, op0Reg, TmpReg);
1968 void ISel::visitMul(BinaryOperator &I) {
1969 unsigned ResultReg = getReg(I);
1971 Value *Op0 = I.getOperand(0);
1972 Value *Op1 = I.getOperand(1);
1974 MachineBasicBlock::iterator IP = BB->end();
1975 emitMultiply(BB, IP, Op0, Op1, ResultReg);
1978 void ISel::emitMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
1979 Value *Op0, Value *Op1, unsigned DestReg) {
1980 MachineBasicBlock &BB = *MBB;
1981 TypeClass Class = getClass(Op0->getType());
1983 // Simple scalar multiply?
1984 unsigned Op0Reg = getReg(Op0, &BB, IP);
1989 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1990 unsigned Val = (unsigned)CI->getRawValue(); // Isn't a 64-bit constant
1991 doMultiplyConst(&BB, IP, DestReg, Op0->getType(), Op0Reg, Val);
1993 unsigned Op1Reg = getReg(Op1, &BB, IP);
1994 doMultiply(&BB, IP, DestReg, Op1->getType(), Op0Reg, Op1Reg);
1999 emitBinaryFPOperation(MBB, IP, Op0, Op1, 2, DestReg);
2005 // Long value. We have to do things the hard way...
2006 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2007 unsigned CLow = CI->getRawValue();
2008 unsigned CHi = CI->getRawValue() >> 32;
2011 // If the low part of the constant is all zeros, things are simple.
2012 BuildMI(BB, IP, PPC32::LI, 1, DestReg).addImm(0);
2013 doMultiplyConst(&BB, IP, DestReg+1, Type::UIntTy, Op0Reg, CHi);
2017 // Multiply the two low parts
2018 unsigned OverflowReg = 0;
2020 BuildMI(BB, IP, PPC32::OR, 2, DestReg).addReg(Op0Reg).addReg(Op0Reg);
2022 unsigned TmpRegL = makeAnotherReg(Type::UIntTy);
2023 unsigned Op1RegL = makeAnotherReg(Type::UIntTy);
2024 OverflowReg = makeAnotherReg(Type::UIntTy);
2025 BuildMI(BB, IP, PPC32::LIS, 1, TmpRegL).addImm(CLow >> 16);
2026 BuildMI(BB, IP, PPC32::ORI, 2, Op1RegL).addReg(TmpRegL).addImm(CLow);
2027 BuildMI(BB, IP, PPC32::MULLW, 2, DestReg).addReg(Op0Reg).addReg(Op1RegL);
2028 BuildMI(BB, IP, PPC32::MULHW, 2, OverflowReg).addReg(Op0Reg)
2032 unsigned AHBLReg = makeAnotherReg(Type::UIntTy);
2033 doMultiplyConst(&BB, IP, AHBLReg, Type::UIntTy, Op0Reg+1, CLow);
2035 unsigned AHBLplusOverflowReg;
2037 AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
2038 BuildMI(BB, IP, PPC32::ADD, 2,
2039 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
2041 AHBLplusOverflowReg = AHBLReg;
2045 BuildMI(BB, IP, PPC32::OR, 2, DestReg+1).addReg(AHBLplusOverflowReg)
2046 .addReg(AHBLplusOverflowReg);
2048 unsigned ALBHReg = makeAnotherReg(Type::UIntTy);
2049 doMultiplyConst(&BB, IP, ALBHReg, Type::UIntTy, Op0Reg, CHi);
2051 BuildMI(BB, IP, PPC32::ADD, 2,
2052 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
2057 // General 64x64 multiply
2059 unsigned Op1Reg = getReg(Op1, &BB, IP);
2061 // Multiply the two low parts...
2062 BuildMI(BB, IP, PPC32::MULLW, 2, DestReg).addReg(Op0Reg).addReg(Op1Reg);
2064 unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
2065 BuildMI(BB, IP, PPC32::MULHW, 2, OverflowReg).addReg(Op0Reg).addReg(Op1Reg);
2067 unsigned AHBLReg = makeAnotherReg(Type::UIntTy);
2068 BuildMI(BB, IP, PPC32::MULLW, 2, AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
2070 unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
2071 BuildMI(BB, IP, PPC32::ADD, 2, AHBLplusOverflowReg).addReg(AHBLReg)
2072 .addReg(OverflowReg);
2074 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
2075 BuildMI(BB, IP, PPC32::MULLW, 2, ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
2077 BuildMI(BB, IP, PPC32::ADD, 2,
2078 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
2082 /// visitDivRem - Handle division and remainder instructions... these
2083 /// instruction both require the same instructions to be generated, they just
2084 /// select the result from a different register. Note that both of these
2085 /// instructions work differently for signed and unsigned operands.
2087 void ISel::visitDivRem(BinaryOperator &I) {
2088 unsigned ResultReg = getReg(I);
2089 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2091 MachineBasicBlock::iterator IP = BB->end();
2092 emitDivRemOperation(BB, IP, Op0, Op1, I.getOpcode() == Instruction::Div,
2096 void ISel::emitDivRemOperation(MachineBasicBlock *BB,
2097 MachineBasicBlock::iterator IP,
2098 Value *Op0, Value *Op1, bool isDiv,
2099 unsigned ResultReg) {
2100 const Type *Ty = Op0->getType();
2101 unsigned Class = getClass(Ty);
2105 // Floating point divide...
2106 emitBinaryFPOperation(BB, IP, Op0, Op1, 3, ResultReg);
2109 // Floating point remainder via fmodf(float x, float y);
2110 unsigned Op0Reg = getReg(Op0, BB, IP);
2111 unsigned Op1Reg = getReg(Op1, BB, IP);
2112 MachineInstr *TheCall =
2113 BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(fmodfFn, true);
2114 std::vector<ValueRecord> Args;
2115 Args.push_back(ValueRecord(Op0Reg, Type::FloatTy));
2116 Args.push_back(ValueRecord(Op1Reg, Type::FloatTy));
2117 doCall(ValueRecord(ResultReg, Type::FloatTy), TheCall, Args, false);
2122 // Floating point divide...
2123 emitBinaryFPOperation(BB, IP, Op0, Op1, 3, ResultReg);
2126 // Floating point remainder via fmod(double x, double y);
2127 unsigned Op0Reg = getReg(Op0, BB, IP);
2128 unsigned Op1Reg = getReg(Op1, BB, IP);
2129 MachineInstr *TheCall =
2130 BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(fmodFn, true);
2131 std::vector<ValueRecord> Args;
2132 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
2133 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
2134 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args, false);
2138 static Function* const Funcs[] =
2139 { __moddi3Fn, __divdi3Fn, __umoddi3Fn, __udivdi3Fn };
2140 unsigned Op0Reg = getReg(Op0, BB, IP);
2141 unsigned Op1Reg = getReg(Op1, BB, IP);
2142 unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
2143 MachineInstr *TheCall =
2144 BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(Funcs[NameIdx], true);
2146 std::vector<ValueRecord> Args;
2147 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
2148 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
2149 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args, false);
2152 case cByte: case cShort: case cInt:
2153 break; // Small integrals, handled below...
2154 default: assert(0 && "Unknown class!");
2157 // Special case signed division by power of 2.
2159 if (ConstantSInt *CI = dyn_cast<ConstantSInt>(Op1)) {
2160 assert(Class != cLong && "This doesn't handle 64-bit divides!");
2161 int V = CI->getValue();
2163 if (V == 1) { // X /s 1 => X
2164 unsigned Op0Reg = getReg(Op0, BB, IP);
2165 BuildMI(*BB, IP, PPC32::OR, 2, ResultReg).addReg(Op0Reg).addReg(Op0Reg);
2169 if (V == -1) { // X /s -1 => -X
2170 unsigned Op0Reg = getReg(Op0, BB, IP);
2171 BuildMI(*BB, IP, PPC32::NEG, 1, ResultReg).addReg(Op0Reg);
2176 if (V < 0) { // Not a positive power of 2?
2178 isNeg = true; // Maybe it's a negative power of 2.
2180 if (unsigned Log = ExactLog2(V)) {
2182 unsigned Op0Reg = getReg(Op0, BB, IP);
2183 unsigned TmpReg = makeAnotherReg(Op0->getType());
2185 BuildMI(*BB, IP, PPC32::SRAWI,2, TmpReg).addReg(Op0Reg).addImm(Log-1);
2187 BuildMI(*BB, IP, PPC32::OR, 2, TmpReg).addReg(Op0Reg).addReg(Op0Reg);
2189 unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2190 BuildMI(*BB, IP, PPC32::RLWINM, 4, TmpReg2).addReg(TmpReg).addImm(Log)
2191 .addImm(32-Log).addImm(31);
2193 unsigned TmpReg3 = makeAnotherReg(Op0->getType());
2194 BuildMI(*BB, IP, PPC32::ADD, 2, TmpReg3).addReg(Op0Reg).addReg(TmpReg2);
2196 unsigned TmpReg4 = isNeg ? makeAnotherReg(Op0->getType()) : ResultReg;
2197 BuildMI(*BB, IP, PPC32::SRAWI, 2, TmpReg4).addReg(Op0Reg).addImm(Log);
2200 BuildMI(*BB, IP, PPC32::NEG, 1, ResultReg).addReg(TmpReg4);
2205 unsigned Op0Reg = getReg(Op0, BB, IP);
2206 unsigned Op1Reg = getReg(Op1, BB, IP);
2209 if (Ty->isSigned()) {
2210 BuildMI(*BB, IP, PPC32::DIVW, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
2212 BuildMI(*BB, IP,PPC32::DIVWU, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
2214 } else { // Remainder
2215 unsigned TmpReg1 = makeAnotherReg(Op0->getType());
2216 unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2218 if (Ty->isSigned()) {
2219 BuildMI(*BB, IP, PPC32::DIVW, 2, TmpReg1).addReg(Op0Reg).addReg(Op1Reg);
2221 BuildMI(*BB, IP, PPC32::DIVWU, 2, TmpReg1).addReg(Op0Reg).addReg(Op1Reg);
2223 BuildMI(*BB, IP, PPC32::MULLW, 2, TmpReg2).addReg(TmpReg1).addReg(Op1Reg);
2224 BuildMI(*BB, IP, PPC32::SUBF, 2, ResultReg).addReg(TmpReg2).addReg(Op0Reg);
2229 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
2230 /// for constant immediate shift values, and for constant immediate
2231 /// shift values equal to 1. Even the general case is sort of special,
2232 /// because the shift amount has to be in CL, not just any old register.
2234 void ISel::visitShiftInst(ShiftInst &I) {
2235 MachineBasicBlock::iterator IP = BB->end ();
2236 emitShiftOperation(BB, IP, I.getOperand (0), I.getOperand (1),
2237 I.getOpcode () == Instruction::Shl, I.getType (),
2241 /// emitShiftOperation - Common code shared between visitShiftInst and
2242 /// constant expression support.
2244 void ISel::emitShiftOperation(MachineBasicBlock *MBB,
2245 MachineBasicBlock::iterator IP,
2246 Value *Op, Value *ShiftAmount, bool isLeftShift,
2247 const Type *ResultTy, unsigned DestReg) {
2248 unsigned SrcReg = getReg (Op, MBB, IP);
2249 bool isSigned = ResultTy->isSigned ();
2250 unsigned Class = getClass (ResultTy);
2252 // Longs, as usual, are handled specially...
2253 if (Class == cLong) {
2254 // If we have a constant shift, we can generate much more efficient code
2255 // than otherwise...
2257 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2258 unsigned Amount = CUI->getValue();
2261 // FIXME: RLWIMI is a use-and-def of DestReg+1, but that violates SSA
2262 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg+1).addReg(SrcReg+1)
2263 .addImm(Amount).addImm(0).addImm(31-Amount);
2264 BuildMI(*MBB, IP, PPC32::RLWIMI, 5).addReg(DestReg+1).addReg(SrcReg)
2265 .addImm(Amount).addImm(32-Amount).addImm(31);
2266 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg)
2267 .addImm(Amount).addImm(0).addImm(31-Amount);
2269 // FIXME: RLWIMI is a use-and-def of DestReg, but that violates SSA
2270 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg)
2271 .addImm(32-Amount).addImm(Amount).addImm(31);
2272 BuildMI(*MBB, IP, PPC32::RLWIMI, 5).addReg(DestReg).addReg(SrcReg+1)
2273 .addImm(32-Amount).addImm(0).addImm(Amount-1);
2274 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg+1).addReg(SrcReg+1)
2275 .addImm(32-Amount).addImm(Amount).addImm(31);
2277 } else { // Shifting more than 32 bits
2281 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg+1).addReg(SrcReg)
2282 .addImm(Amount).addImm(0).addImm(31-Amount);
2284 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg+1).addReg(SrcReg)
2287 BuildMI(*MBB, IP, PPC32::LI, 1, DestReg).addImm(0);
2291 BuildMI(*MBB, IP, PPC32::SRAWI, 2, DestReg).addReg(SrcReg+1)
2294 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg+1)
2295 .addImm(32-Amount).addImm(Amount).addImm(31);
2297 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg+1)
2300 BuildMI(*MBB, IP,PPC32::LI,1,DestReg+1).addImm(0);
2304 unsigned TmpReg1 = makeAnotherReg(Type::IntTy);
2305 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
2306 unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
2307 unsigned TmpReg4 = makeAnotherReg(Type::IntTy);
2308 unsigned TmpReg5 = makeAnotherReg(Type::IntTy);
2309 unsigned TmpReg6 = makeAnotherReg(Type::IntTy);
2310 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
2313 BuildMI(*MBB, IP, PPC32::SUBFIC, 2, TmpReg1).addReg(ShiftAmountReg)
2315 BuildMI(*MBB, IP, PPC32::SLW, 2, TmpReg2).addReg(SrcReg+1)
2316 .addReg(ShiftAmountReg);
2317 BuildMI(*MBB, IP, PPC32::SRW, 2,TmpReg3).addReg(SrcReg).addReg(TmpReg1);
2318 BuildMI(*MBB, IP, PPC32::OR, 2,TmpReg4).addReg(TmpReg2).addReg(TmpReg3);
2319 BuildMI(*MBB, IP, PPC32::ADDI, 2, TmpReg5).addReg(ShiftAmountReg)
2321 BuildMI(*MBB, IP, PPC32::SLW, 2,TmpReg6).addReg(SrcReg).addReg(TmpReg5);
2322 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg+1).addReg(TmpReg4)
2324 BuildMI(*MBB, IP, PPC32::SLW, 2, DestReg).addReg(SrcReg)
2325 .addReg(ShiftAmountReg);
2328 // FIXME: Unimplemented
2329 // Page C-3 of the PowerPC 32bit Programming Environments Manual
2330 std::cerr << "Unimplemented: signed right shift\n";
2333 BuildMI(*MBB, IP, PPC32::SUBFIC, 2, TmpReg1).addReg(ShiftAmountReg)
2335 BuildMI(*MBB, IP, PPC32::SRW, 2, TmpReg2).addReg(SrcReg)
2336 .addReg(ShiftAmountReg);
2337 BuildMI(*MBB, IP, PPC32::SLW, 2, TmpReg3).addReg(SrcReg+1)
2339 BuildMI(*MBB, IP, PPC32::OR, 2, TmpReg4).addReg(TmpReg2)
2341 BuildMI(*MBB, IP, PPC32::ADDI, 2, TmpReg5).addReg(ShiftAmountReg)
2343 BuildMI(*MBB, IP, PPC32::SRW, 2, TmpReg6).addReg(SrcReg+1)
2345 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(TmpReg4)
2347 BuildMI(*MBB, IP, PPC32::SRW, 2, DestReg+1).addReg(SrcReg+1)
2348 .addReg(ShiftAmountReg);
2355 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2356 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
2357 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
2358 unsigned Amount = CUI->getValue();
2361 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg)
2362 .addImm(Amount).addImm(0).addImm(31-Amount);
2365 BuildMI(*MBB, IP, PPC32::SRAWI,2,DestReg).addReg(SrcReg).addImm(Amount);
2367 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg)
2368 .addImm(32-Amount).addImm(Amount).addImm(31);
2371 } else { // The shift amount is non-constant.
2372 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
2375 BuildMI(*MBB, IP, PPC32::SLW, 2, DestReg).addReg(SrcReg)
2376 .addReg(ShiftAmountReg);
2378 BuildMI(*MBB, IP, isSigned ? PPC32::SRAW : PPC32::SRW, 2, DestReg)
2379 .addReg(SrcReg).addReg(ShiftAmountReg);
2385 /// visitLoadInst - Implement LLVM load instructions
2387 void ISel::visitLoadInst(LoadInst &I) {
2388 static const unsigned Opcodes[] = {
2389 PPC32::LBZ, PPC32::LHZ, PPC32::LWZ, PPC32::LFS
2391 unsigned Class = getClassB(I.getType());
2392 unsigned Opcode = Opcodes[Class];
2393 if (I.getType() == Type::DoubleTy) Opcode = PPC32::LFD;
2395 unsigned DestReg = getReg(I);
2397 if (AllocaInst *AI = dyn_castFixedAlloca(I.getOperand(0))) {
2398 unsigned FI = getFixedSizedAllocaFI(AI);
2399 if (Class == cLong) {
2400 addFrameReference(BuildMI(BB, PPC32::LWZ, 2, DestReg), FI);
2401 addFrameReference(BuildMI(BB, PPC32::LWZ, 2, DestReg+1), FI, 4);
2403 addFrameReference(BuildMI(BB, Opcode, 2, DestReg), FI);
2406 unsigned SrcAddrReg = getReg(I.getOperand(0));
2408 if (Class == cLong) {
2409 BuildMI(BB, PPC32::LWZ, 2, DestReg).addImm(0).addReg(SrcAddrReg);
2410 BuildMI(BB, PPC32::LWZ, 2, DestReg+1).addImm(4).addReg(SrcAddrReg);
2412 BuildMI(BB, Opcode, 2, DestReg).addImm(0).addReg(SrcAddrReg);
2417 /// visitStoreInst - Implement LLVM store instructions
2419 void ISel::visitStoreInst(StoreInst &I) {
2420 unsigned ValReg = getReg(I.getOperand(0));
2421 unsigned AddressReg = getReg(I.getOperand(1));
2423 const Type *ValTy = I.getOperand(0)->getType();
2424 unsigned Class = getClassB(ValTy);
2426 if (Class == cLong) {
2427 BuildMI(BB, PPC32::STW, 3).addReg(ValReg).addImm(0).addReg(AddressReg);
2428 BuildMI(BB, PPC32::STW, 3).addReg(ValReg+1).addImm(4).addReg(AddressReg);
2432 static const unsigned Opcodes[] = {
2433 PPC32::STB, PPC32::STH, PPC32::STW, PPC32::STFS
2435 unsigned Opcode = Opcodes[Class];
2436 if (ValTy == Type::DoubleTy) Opcode = PPC32::STFD;
2437 BuildMI(BB, Opcode, 3).addReg(ValReg).addImm(0).addReg(AddressReg);
2441 /// visitCastInst - Here we have various kinds of copying with or without sign
2442 /// extension going on.
2444 void ISel::visitCastInst(CastInst &CI) {
2445 Value *Op = CI.getOperand(0);
2447 unsigned SrcClass = getClassB(Op->getType());
2448 unsigned DestClass = getClassB(CI.getType());
2449 // Noop casts are not emitted: getReg will return the source operand as the
2450 // register to use for any uses of the noop cast.
2451 if (DestClass == SrcClass)
2454 // If this is a cast from a 32-bit integer to a Long type, and the only uses
2455 // of the case are GEP instructions, then the cast does not need to be
2456 // generated explicitly, it will be folded into the GEP.
2457 if (DestClass == cLong && SrcClass == cInt) {
2458 bool AllUsesAreGEPs = true;
2459 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
2460 if (!isa<GetElementPtrInst>(*I)) {
2461 AllUsesAreGEPs = false;
2465 // No need to codegen this cast if all users are getelementptr instrs...
2466 if (AllUsesAreGEPs) return;
2469 unsigned DestReg = getReg(CI);
2470 MachineBasicBlock::iterator MI = BB->end();
2471 emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
2474 /// emitCastOperation - Common code shared between visitCastInst and constant
2475 /// expression cast support.
2477 void ISel::emitCastOperation(MachineBasicBlock *MBB,
2478 MachineBasicBlock::iterator IP,
2479 Value *Src, const Type *DestTy,
2481 const Type *SrcTy = Src->getType();
2482 unsigned SrcClass = getClassB(SrcTy);
2483 unsigned DestClass = getClassB(DestTy);
2484 unsigned SrcReg = getReg(Src, MBB, IP);
2486 // Implement casts to bool by using compare on the operand followed by set if
2487 // not zero on the result.
2488 if (DestTy == Type::BoolTy) {
2493 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2494 BuildMI(*MBB, IP, PPC32::ADDIC, 2, TmpReg).addReg(SrcReg).addImm(-1);
2495 BuildMI(*MBB, IP, PPC32::SUBFE, 2, DestReg).addReg(TmpReg).addReg(SrcReg);
2499 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2500 unsigned SrcReg2 = makeAnotherReg(Type::IntTy);
2501 BuildMI(*MBB, IP, PPC32::OR, 2, SrcReg2).addReg(SrcReg).addReg(SrcReg+1);
2502 BuildMI(*MBB, IP, PPC32::ADDIC, 2, TmpReg).addReg(SrcReg2).addImm(-1);
2503 BuildMI(*MBB, IP, PPC32::SUBFE, 2, DestReg).addReg(TmpReg).addReg(SrcReg2);
2509 std::cerr << "Cast fp-to-bool not implemented!";
2515 // Implement casts between values of the same type class (as determined by
2516 // getClass) by using a register-to-register move.
2517 if (SrcClass == DestClass) {
2518 if (SrcClass <= cInt) {
2519 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2520 } else if (SrcClass == cFP32 || SrcClass == cFP64) {
2521 BuildMI(*MBB, IP, PPC32::FMR, 1, DestReg).addReg(SrcReg);
2522 } else if (SrcClass == cLong) {
2523 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2524 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg+1).addReg(SrcReg+1)
2527 assert(0 && "Cannot handle this type of cast instruction!");
2533 // Handle cast of Float -> Double
2534 if (SrcClass == cFP32 && DestClass == cFP64) {
2535 BuildMI(*MBB, IP, PPC32::FMR, 1, DestReg).addReg(SrcReg);
2539 // Handle cast of Double -> Float
2540 if (SrcClass == cFP64 && DestClass == cFP32) {
2541 BuildMI(*MBB, IP, PPC32::FRSP, 1, DestReg).addReg(SrcReg);
2545 // Handle cast of SMALLER int to LARGER int using a move with sign extension
2546 // or zero extension, depending on whether the source type was signed.
2547 if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
2548 SrcClass < DestClass) {
2549 bool isLong = DestClass == cLong;
2550 if (isLong) DestClass = cInt;
2552 bool isUnsigned = SrcTy->isUnsigned() || SrcTy == Type::BoolTy;
2553 if (SrcClass < cInt) {
2555 unsigned shift = (SrcClass == cByte) ? 24 : 16;
2556 BuildMI(*BB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg).addZImm(0)
2557 .addImm(shift).addImm(31);
2559 BuildMI(*BB, IP, (SrcClass == cByte) ? PPC32::EXTSB : PPC32::EXTSH,
2560 1, DestReg).addReg(SrcReg);
2563 BuildMI(*BB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2566 if (isLong) { // Handle upper 32 bits as appropriate...
2567 if (isUnsigned) // Zero out top bits...
2568 BuildMI(*BB, IP, PPC32::LI, 1, DestReg+1).addImm(0);
2569 else // Sign extend bottom half...
2570 BuildMI(*BB, IP, PPC32::SRAWI, 2, DestReg+1).addReg(DestReg).addImm(31);
2575 // Special case long -> int ...
2576 if (SrcClass == cLong && DestClass == cInt) {
2577 BuildMI(*BB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2581 // Handle cast of LARGER int to SMALLER int with a clear or sign extend
2582 if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
2583 && SrcClass > DestClass) {
2584 bool isUnsigned = SrcTy->isUnsigned() || SrcTy == Type::BoolTy;
2586 unsigned shift = (SrcClass == cByte) ? 24 : 16;
2587 BuildMI(*BB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg).addZImm(0)
2588 .addImm(shift).addImm(31);
2590 BuildMI(*BB, IP, (SrcClass == cByte) ? PPC32::EXTSB : PPC32::EXTSH, 1,
2591 DestReg).addReg(SrcReg);
2596 // Handle casts from integer to floating point now...
2597 if (DestClass == cFP32 || DestClass == cFP64) {
2599 // Emit a library call for long to float conversion
2600 if (SrcClass == cLong) {
2601 std::vector<ValueRecord> Args;
2602 Args.push_back(ValueRecord(SrcReg, SrcTy));
2603 Function *floatFn = (DestClass == cFP32) ? __floatdisfFn : __floatdidfFn;
2604 MachineInstr *TheCall =
2605 BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(floatFn, true);
2606 doCall(ValueRecord(DestReg, DestTy), TheCall, Args, false);
2610 // Make sure we're dealing with a full 32 bits
2611 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2612 promote32(TmpReg, ValueRecord(SrcReg, SrcTy));
2616 // Spill the integer to memory and reload it from there.
2617 // Also spill room for a special conversion constant
2618 int ConstantFrameIndex =
2619 F->getFrameInfo()->CreateStackObject(Type::DoubleTy, TM.getTargetData());
2621 F->getFrameInfo()->CreateStackObject(Type::DoubleTy, TM.getTargetData());
2623 unsigned constantHi = makeAnotherReg(Type::IntTy);
2624 unsigned constantLo = makeAnotherReg(Type::IntTy);
2625 unsigned ConstF = makeAnotherReg(Type::DoubleTy);
2626 unsigned TempF = makeAnotherReg(Type::DoubleTy);
2628 if (!SrcTy->isSigned()) {
2629 BuildMI(*BB, IP, PPC32::LIS, 1, constantHi).addImm(0x4330);
2630 BuildMI(*BB, IP, PPC32::LI, 1, constantLo).addImm(0);
2631 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantHi),
2632 ConstantFrameIndex);
2633 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantLo),
2634 ConstantFrameIndex, 4);
2635 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantHi),
2637 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(SrcReg),
2639 addFrameReference(BuildMI(*BB, IP, PPC32::LFD, 2, ConstF),
2640 ConstantFrameIndex);
2641 addFrameReference(BuildMI(*BB, IP, PPC32::LFD, 2, TempF), ValueFrameIdx);
2642 BuildMI(*BB, IP, PPC32::FSUB, 2, DestReg).addReg(TempF).addReg(ConstF);
2644 unsigned TempLo = makeAnotherReg(Type::IntTy);
2645 BuildMI(*BB, IP, PPC32::LIS, 1, constantHi).addImm(0x4330);
2646 BuildMI(*BB, IP, PPC32::LIS, 1, constantLo).addImm(0x8000);
2647 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantHi),
2648 ConstantFrameIndex);
2649 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantLo),
2650 ConstantFrameIndex, 4);
2651 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantHi),
2653 BuildMI(*BB, IP, PPC32::XORIS, 2, TempLo).addReg(SrcReg).addImm(0x8000);
2654 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(TempLo),
2656 addFrameReference(BuildMI(*BB, IP, PPC32::LFD, 2, ConstF),
2657 ConstantFrameIndex);
2658 addFrameReference(BuildMI(*BB, IP, PPC32::LFD, 2, TempF), ValueFrameIdx);
2659 BuildMI(*BB, IP, PPC32::FSUB, 2, DestReg).addReg(TempF ).addReg(ConstF);
2664 // Handle casts from floating point to integer now...
2665 if (SrcClass == cFP32 || SrcClass == cFP64) {
2666 // emit library call
2667 if (DestClass == cLong) {
2668 std::vector<ValueRecord> Args;
2669 Args.push_back(ValueRecord(SrcReg, SrcTy));
2670 Function *floatFn = (DestClass == cFP32) ? __fixsfdiFn : __fixdfdiFn;
2671 MachineInstr *TheCall =
2672 BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(floatFn, true);
2673 doCall(ValueRecord(DestReg, DestTy), TheCall, Args, false);
2678 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
2680 if (DestTy->isSigned()) {
2681 unsigned LoadOp = (DestClass == cShort) ? PPC32::LHA : PPC32::LWZ;
2682 unsigned TempReg = makeAnotherReg(Type::DoubleTy);
2684 // Convert to integer in the FP reg and store it to a stack slot
2685 BuildMI(*BB, IP, PPC32::FCTIWZ, 1, TempReg).addReg(SrcReg);
2686 addFrameReference(BuildMI(*BB, IP, PPC32::STFD, 3)
2687 .addReg(TempReg), ValueFrameIdx);
2689 // There is no load signed byte opcode, so we must emit a sign extend
2690 if (DestClass == cByte) {
2691 unsigned TempReg2 = makeAnotherReg(DestTy);
2692 addFrameReference(BuildMI(*BB, IP, LoadOp, 2, TempReg2),
2694 BuildMI(*MBB, IP, PPC32::EXTSB, DestReg).addReg(TempReg2);
2696 addFrameReference(BuildMI(*BB, IP, LoadOp, 2, DestReg),
2700 std::cerr << "Cast fp-to-unsigned not implemented!";
2706 // Anything we haven't handled already, we can't (yet) handle at all.
2707 assert(0 && "Unhandled cast instruction!");
2711 /// visitVANextInst - Implement the va_next instruction...
2713 void ISel::visitVANextInst(VANextInst &I) {
2714 unsigned VAList = getReg(I.getOperand(0));
2715 unsigned DestReg = getReg(I);
2718 switch (I.getArgType()->getTypeID()) {
2721 assert(0 && "Error: bad type for va_next instruction!");
2723 case Type::PointerTyID:
2724 case Type::UIntTyID:
2728 case Type::ULongTyID:
2729 case Type::LongTyID:
2730 case Type::DoubleTyID:
2735 // Increment the VAList pointer...
2736 BuildMI(BB, PPC32::ADDI, 2, DestReg).addReg(VAList).addImm(Size);
2739 void ISel::visitVAArgInst(VAArgInst &I) {
2740 unsigned VAList = getReg(I.getOperand(0));
2741 unsigned DestReg = getReg(I);
2743 switch (I.getType()->getTypeID()) {
2746 assert(0 && "Error: bad type for va_next instruction!");
2748 case Type::PointerTyID:
2749 case Type::UIntTyID:
2751 BuildMI(BB, PPC32::LWZ, 2, DestReg).addImm(0).addReg(VAList);
2753 case Type::ULongTyID:
2754 case Type::LongTyID:
2755 BuildMI(BB, PPC32::LWZ, 2, DestReg).addImm(0).addReg(VAList);
2756 BuildMI(BB, PPC32::LWZ, 2, DestReg+1).addImm(4).addReg(VAList);
2758 case Type::DoubleTyID:
2759 BuildMI(BB, PPC32::LFD, 2, DestReg).addImm(0).addReg(VAList);
2764 /// visitGetElementPtrInst - instruction-select GEP instructions
2766 void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
2767 unsigned outputReg = getReg(I);
2768 emitGEPOperation(BB, BB->end(), I.getOperand(0), I.op_begin()+1, I.op_end(),
2772 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
2773 MachineBasicBlock::iterator IP,
2774 Value *Src, User::op_iterator IdxBegin,
2775 User::op_iterator IdxEnd, unsigned TargetReg) {
2776 const TargetData &TD = TM.getTargetData();
2778 std::vector<Value*> GEPOps;
2779 GEPOps.resize(IdxEnd-IdxBegin+1);
2781 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
2783 std::vector<const Type*> GEPTypes;
2784 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
2785 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
2787 // Keep emitting instructions until we consume the entire GEP instruction.
2788 while (!GEPOps.empty()) {
2789 if (GEPTypes.empty()) {
2790 // Load the base pointer into a register.
2791 unsigned Reg = getReg(Src, MBB, IP);
2792 BuildMI(*MBB, IP, PPC32::OR, 2, TargetReg).addReg(Reg).addReg(Reg);
2793 break; // we are now done
2795 if (const StructType *StTy = dyn_cast<StructType>(GEPTypes.back())) {
2796 // It's a struct access. CUI is the index into the structure,
2797 // which names the field. This index must have unsigned type.
2798 const ConstantUInt *CUI = cast<ConstantUInt>(GEPOps.back());
2800 // Use the TargetData structure to pick out what the layout of the
2801 // structure is in memory. Since the structure index must be constant, we
2802 // can get its value and use it to find the right byte offset from the
2803 // StructLayout class's list of structure member offsets.
2804 unsigned Disp = TD.getStructLayout(StTy)->MemberOffsets[CUI->getValue()];
2805 GEPOps.pop_back(); // Consume a GEP operand
2806 GEPTypes.pop_back();
2807 unsigned Reg = makeAnotherReg(Type::UIntTy);
2808 unsigned DispReg = makeAnotherReg(Type::UIntTy);
2809 BuildMI(*MBB, IP, PPC32::LI, 1, DispReg).addImm(Disp);
2810 BuildMI(*MBB, IP, PPC32::ADD, 2, TargetReg).addReg(Reg).addReg(DispReg);
2811 --IP; // Insert the next instruction before this one.
2812 TargetReg = Reg; // Codegen the rest of the GEP into this
2814 // It's an array or pointer access: [ArraySize x ElementType].
2815 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
2816 Value *idx = GEPOps.back();
2817 GEPOps.pop_back(); // Consume a GEP operand
2818 GEPTypes.pop_back();
2820 // Many GEP instructions use a [cast (int/uint) to LongTy] as their
2821 // operand. Handle this case directly now...
2822 if (CastInst *CI = dyn_cast<CastInst>(idx))
2823 if (CI->getOperand(0)->getType() == Type::IntTy ||
2824 CI->getOperand(0)->getType() == Type::UIntTy)
2825 idx = CI->getOperand(0);
2827 // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
2828 // must find the size of the pointed-to type (Not coincidentally, the next
2829 // type is the type of the elements in the array).
2830 const Type *ElTy = SqTy->getElementType();
2831 unsigned elementSize = TD.getTypeSize(ElTy);
2833 if (idx == Constant::getNullValue(idx->getType())) {
2834 // GEP with idx 0 is a no-op
2835 } else if (elementSize == 1) {
2836 // If the element size is 1, we don't have to multiply, just add
2837 unsigned idxReg = getReg(idx, MBB, IP);
2838 unsigned Reg = makeAnotherReg(Type::UIntTy);
2839 BuildMI(*MBB, IP, PPC32::ADD, 2,TargetReg).addReg(Reg).addReg(idxReg);
2840 --IP; // Insert the next instruction before this one.
2841 TargetReg = Reg; // Codegen the rest of the GEP into this
2843 unsigned idxReg = getReg(idx, MBB, IP);
2844 unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
2846 // Make sure we can back the iterator up to point to the first
2847 // instruction emitted.
2848 MachineBasicBlock::iterator BeforeIt = IP;
2849 if (IP == MBB->begin())
2850 BeforeIt = MBB->end();
2853 doMultiplyConst(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSize);
2855 // Emit an ADD to add OffsetReg to the basePtr.
2856 unsigned Reg = makeAnotherReg(Type::UIntTy);
2857 BuildMI(*MBB, IP, PPC32::ADD,2,TargetReg).addReg(Reg).addReg(OffsetReg);
2859 // Step to the first instruction of the multiply.
2860 if (BeforeIt == MBB->end())
2865 TargetReg = Reg; // Codegen the rest of the GEP into this
2871 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
2872 /// frame manager, otherwise do it the hard way.
2874 void ISel::visitAllocaInst(AllocaInst &I) {
2875 // If this is a fixed size alloca in the entry block for the function, we
2876 // statically stack allocate the space, so we don't need to do anything here.
2878 if (dyn_castFixedAlloca(&I)) return;
2880 // Find the data size of the alloca inst's getAllocatedType.
2881 const Type *Ty = I.getAllocatedType();
2882 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
2884 // Create a register to hold the temporary result of multiplying the type size
2885 // constant by the variable amount.
2886 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
2887 unsigned SrcReg1 = getReg(I.getArraySize());
2889 // TotalSizeReg = mul <numelements>, <TypeSize>
2890 MachineBasicBlock::iterator MBBI = BB->end();
2891 doMultiplyConst(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, TySize);
2893 // AddedSize = add <TotalSizeReg>, 15
2894 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
2895 BuildMI(BB, PPC32::ADD, 2, AddedSizeReg).addReg(TotalSizeReg).addImm(15);
2897 // AlignedSize = and <AddedSize>, ~15
2898 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
2899 BuildMI(BB, PPC32::RLWNM, 4, AlignedSize).addReg(AddedSizeReg).addImm(0)
2900 .addImm(0).addImm(27);
2902 // Subtract size from stack pointer, thereby allocating some space.
2903 BuildMI(BB, PPC32::SUB, 2, PPC32::R1).addReg(PPC32::R1).addReg(AlignedSize);
2905 // Put a pointer to the space into the result register, by copying
2906 // the stack pointer.
2907 BuildMI(BB, PPC32::OR, 2, getReg(I)).addReg(PPC32::R1).addReg(PPC32::R1);
2909 // Inform the Frame Information that we have just allocated a variable-sized
2911 F->getFrameInfo()->CreateVariableSizedObject();
2914 /// visitMallocInst - Malloc instructions are code generated into direct calls
2915 /// to the library malloc.
2917 void ISel::visitMallocInst(MallocInst &I) {
2918 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
2921 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
2922 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
2924 Arg = makeAnotherReg(Type::UIntTy);
2925 unsigned Op0Reg = getReg(I.getOperand(0));
2926 MachineBasicBlock::iterator MBBI = BB->end();
2927 doMultiplyConst(BB, MBBI, Arg, Type::UIntTy, Op0Reg, AllocSize);
2930 std::vector<ValueRecord> Args;
2931 Args.push_back(ValueRecord(Arg, Type::UIntTy));
2932 MachineInstr *TheCall =
2933 BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(mallocFn, true);
2934 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args, false);
2938 /// visitFreeInst - Free instructions are code gen'd to call the free libc
2941 void ISel::visitFreeInst(FreeInst &I) {
2942 std::vector<ValueRecord> Args;
2943 Args.push_back(ValueRecord(I.getOperand(0)));
2944 MachineInstr *TheCall =
2945 BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(freeFn, true);
2946 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args, false);
2949 /// createPPC32SimpleInstructionSelector - This pass converts an LLVM function
2950 /// into a machine code representation is a very simple peep-hole fashion. The
2951 /// generated code sucks but the implementation is nice and simple.
2953 FunctionPass *llvm::createPPCSimpleInstructionSelector(TargetMachine &TM) {
2954 return new ISel(TM);