1 //===-- PPC64ISelSimple.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 "PPC64TargetMachine.h"
15 #include "llvm/Constants.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Function.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Pass.h"
20 #include "llvm/CodeGen/IntrinsicLowering.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/SSARegMap.h"
25 #include "llvm/Target/MRegisterInfo.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Support/GetElementPtrTypeIterator.h"
28 #include "llvm/Support/InstVisitor.h"
29 #include "Support/Debug.h"
30 #include "Support/Statistic.h"
35 Statistic<> GEPFolds("ppc64-codegen", "Number of GEPs folded");
37 /// TypeClass - Used by the PowerPC backend to group LLVM types by their basic
38 /// PPC Representation.
41 cByte, cShort, cInt, cFP32, cFP64, cLong
45 /// getClass - Turn a primitive type into a "class" number which is based on the
46 /// size of the type, and whether or not it is floating point.
48 static inline TypeClass getClass(const Type *Ty) {
49 switch (Ty->getTypeID()) {
51 case Type::UByteTyID: return cByte; // Byte operands are class #0
53 case Type::UShortTyID: return cShort; // Short operands are class #1
55 case Type::UIntTyID: return cInt; // Ints are class #2
57 case Type::FloatTyID: return cFP32; // Single float is #3
58 case Type::DoubleTyID: return cFP64; // Double Point is #4
60 case Type::PointerTyID:
62 case Type::ULongTyID: return cLong; // Longs and pointers are class #5
64 assert(0 && "Invalid type to getClass!");
65 return cByte; // not reached
69 // getClassB - Just like getClass, but treat boolean values as ints.
70 static inline TypeClass getClassB(const Type *Ty) {
71 if (Ty == Type::BoolTy) return cInt;
76 struct ISel : public FunctionPass, InstVisitor<ISel> {
77 PPC64TargetMachine &TM;
78 MachineFunction *F; // The function we are compiling into
79 MachineBasicBlock *BB; // The current MBB we are compiling
80 int VarArgsFrameIndex; // FrameIndex for start of varargs area
82 std::map<Value*, unsigned> RegMap; // Mapping between Values and SSA Regs
84 // External functions used in the Module
85 Function *fmodfFn, *fmodFn, *__cmpdi2Fn, *__moddi3Fn, *__divdi3Fn,
86 *__umoddi3Fn, *__udivdi3Fn, *__fixsfdiFn, *__fixdfdiFn, *__fixunssfdiFn,
87 *__fixunsdfdiFn, *__floatdisfFn, *__floatdidfFn, *mallocFn, *freeFn;
89 // MBBMap - Mapping between LLVM BB -> Machine BB
90 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
92 // AllocaMap - Mapping from fixed sized alloca instructions to the
93 // FrameIndex for the alloca.
94 std::map<AllocaInst*, unsigned> AllocaMap;
96 // A Reg to hold the base address used for global loads and stores, and a
97 // flag to set whether or not we need to emit it for this function.
98 unsigned GlobalBaseReg;
99 bool GlobalBaseInitialized;
101 ISel(TargetMachine &tm) : TM(reinterpret_cast<PPC64TargetMachine&>(tm)),
104 bool doInitialization(Module &M) {
105 // Add external functions that we may call
106 Type *i = Type::IntTy;
107 Type *d = Type::DoubleTy;
108 Type *f = Type::FloatTy;
109 Type *l = Type::LongTy;
110 Type *ul = Type::ULongTy;
111 Type *voidPtr = PointerType::get(Type::SByteTy);
112 // float fmodf(float, float);
113 fmodfFn = M.getOrInsertFunction("fmodf", f, f, f, 0);
114 // double fmod(double, double);
115 fmodFn = M.getOrInsertFunction("fmod", d, d, d, 0);
116 // int __cmpdi2(long, long);
117 __cmpdi2Fn = M.getOrInsertFunction("__cmpdi2", i, l, l, 0);
118 // long __moddi3(long, long);
119 __moddi3Fn = M.getOrInsertFunction("__moddi3", l, l, l, 0);
120 // long __divdi3(long, long);
121 __divdi3Fn = M.getOrInsertFunction("__divdi3", l, l, l, 0);
122 // unsigned long __umoddi3(unsigned long, unsigned long);
123 __umoddi3Fn = M.getOrInsertFunction("__umoddi3", ul, ul, ul, 0);
124 // unsigned long __udivdi3(unsigned long, unsigned long);
125 __udivdi3Fn = M.getOrInsertFunction("__udivdi3", ul, ul, ul, 0);
126 // long __fixsfdi(float)
127 __fixsfdiFn = M.getOrInsertFunction("__fixsfdi", l, f, 0);
128 // long __fixdfdi(double)
129 __fixdfdiFn = M.getOrInsertFunction("__fixdfdi", l, d, 0);
130 // unsigned long __fixunssfdi(float)
131 __fixunssfdiFn = M.getOrInsertFunction("__fixunssfdi", ul, f, 0);
132 // unsigned long __fixunsdfdi(double)
133 __fixunsdfdiFn = M.getOrInsertFunction("__fixunsdfdi", ul, d, 0);
134 // float __floatdisf(long)
135 __floatdisfFn = M.getOrInsertFunction("__floatdisf", f, l, 0);
136 // double __floatdidf(long)
137 __floatdidfFn = M.getOrInsertFunction("__floatdidf", d, l, 0);
138 // void* malloc(size_t)
139 mallocFn = M.getOrInsertFunction("malloc", voidPtr, Type::UIntTy, 0);
141 freeFn = M.getOrInsertFunction("free", Type::VoidTy, voidPtr, 0);
145 /// runOnFunction - Top level implementation of instruction selection for
146 /// the entire function.
148 bool runOnFunction(Function &Fn) {
149 // First pass over the function, lower any unknown intrinsic functions
150 // with the IntrinsicLowering class.
151 LowerUnknownIntrinsicFunctionCalls(Fn);
153 F = &MachineFunction::construct(&Fn, TM);
155 // Create all of the machine basic blocks for the function...
156 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
157 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
161 // Make sure we re-emit a set of the global base reg if necessary
162 GlobalBaseInitialized = false;
164 // Copy incoming arguments off of the stack...
165 LoadArgumentsToVirtualRegs(Fn);
167 // Instruction select everything except PHI nodes
170 // Select the PHI nodes
177 // We always build a machine code representation for the function
181 virtual const char *getPassName() const {
182 return "PowerPC Simple Instruction Selection";
185 /// visitBasicBlock - This method is called when we are visiting a new basic
186 /// block. This simply creates a new MachineBasicBlock to emit code into
187 /// and adds it to the current MachineFunction. Subsequent visit* for
188 /// instructions will be invoked for all instructions in the basic block.
190 void visitBasicBlock(BasicBlock &LLVM_BB) {
191 BB = MBBMap[&LLVM_BB];
194 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
195 /// function, lowering any calls to unknown intrinsic functions into the
196 /// equivalent LLVM code.
198 void LowerUnknownIntrinsicFunctionCalls(Function &F);
200 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
201 /// from the stack into virtual registers.
203 void LoadArgumentsToVirtualRegs(Function &F);
205 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
206 /// because we have to generate our sources into the source basic blocks,
207 /// not the current one.
209 void SelectPHINodes();
211 // Visitation methods for various instructions. These methods simply emit
212 // fixed PowerPC code for each instruction.
214 // Control flow operators
215 void visitReturnInst(ReturnInst &RI);
216 void visitBranchInst(BranchInst &BI);
222 ValueRecord(unsigned R, const Type *T) : Val(0), Reg(R), Ty(T) {}
223 ValueRecord(Value *V) : Val(V), Reg(0), Ty(V->getType()) {}
226 // This struct is for recording the necessary operations to emit the GEP
227 struct CollapsedGepOp {
231 CollapsedGepOp(bool mul, Value *i, ConstantSInt *s) :
232 isMul(mul), index(i), size(s) {}
235 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
236 const std::vector<ValueRecord> &Args, bool isVarArg);
237 void visitCallInst(CallInst &I);
238 void visitIntrinsicCall(Intrinsic::ID ID, CallInst &I);
240 // Arithmetic operators
241 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
242 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
243 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
244 void visitMul(BinaryOperator &B);
246 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
247 void visitRem(BinaryOperator &B) { visitDivRem(B); }
248 void visitDivRem(BinaryOperator &B);
251 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
252 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
253 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
255 // Comparison operators...
256 void visitSetCondInst(SetCondInst &I);
257 unsigned EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
258 MachineBasicBlock *MBB,
259 MachineBasicBlock::iterator MBBI);
260 void visitSelectInst(SelectInst &SI);
263 // Memory Instructions
264 void visitLoadInst(LoadInst &I);
265 void visitStoreInst(StoreInst &I);
266 void visitGetElementPtrInst(GetElementPtrInst &I);
267 void visitAllocaInst(AllocaInst &I);
268 void visitMallocInst(MallocInst &I);
269 void visitFreeInst(FreeInst &I);
272 void visitShiftInst(ShiftInst &I);
273 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
274 void visitCastInst(CastInst &I);
275 void visitVANextInst(VANextInst &I);
276 void visitVAArgInst(VAArgInst &I);
278 void visitInstruction(Instruction &I) {
279 std::cerr << "Cannot instruction select: " << I;
283 /// promote32 - Make a value 32-bits wide, and put it somewhere.
285 void promote32(unsigned targetReg, const ValueRecord &VR);
287 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
288 /// constant expression GEP support.
290 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
291 Value *Src, User::op_iterator IdxBegin,
292 User::op_iterator IdxEnd, unsigned TargetReg,
293 bool CollapseRemainder, ConstantSInt **Remainder,
294 unsigned *PendingAddReg);
296 /// emitCastOperation - Common code shared between visitCastInst and
297 /// constant expression cast support.
299 void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
300 Value *Src, const Type *DestTy, unsigned TargetReg);
302 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
303 /// and constant expression support.
305 void emitSimpleBinaryOperation(MachineBasicBlock *BB,
306 MachineBasicBlock::iterator IP,
307 Value *Op0, Value *Op1,
308 unsigned OperatorClass, unsigned TargetReg);
310 /// emitBinaryFPOperation - This method handles emission of floating point
311 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
312 void emitBinaryFPOperation(MachineBasicBlock *BB,
313 MachineBasicBlock::iterator IP,
314 Value *Op0, Value *Op1,
315 unsigned OperatorClass, unsigned TargetReg);
317 void emitMultiply(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
318 Value *Op0, Value *Op1, unsigned TargetReg);
320 void doMultiply(MachineBasicBlock *MBB,
321 MachineBasicBlock::iterator IP,
322 unsigned DestReg, Value *Op0, Value *Op1);
324 /// doMultiplyConst - This method will multiply the value in Op0Reg by the
325 /// value of the ContantInt *CI
326 void doMultiplyConst(MachineBasicBlock *MBB,
327 MachineBasicBlock::iterator IP,
328 unsigned DestReg, Value *Op0, ConstantInt *CI);
330 void emitDivRemOperation(MachineBasicBlock *BB,
331 MachineBasicBlock::iterator IP,
332 Value *Op0, Value *Op1, bool isDiv,
335 /// emitSetCCOperation - Common code shared between visitSetCondInst and
336 /// constant expression support.
338 void emitSetCCOperation(MachineBasicBlock *BB,
339 MachineBasicBlock::iterator IP,
340 Value *Op0, Value *Op1, unsigned Opcode,
343 /// emitShiftOperation - Common code shared between visitShiftInst and
344 /// constant expression support.
346 void emitShiftOperation(MachineBasicBlock *MBB,
347 MachineBasicBlock::iterator IP,
348 Value *Op, Value *ShiftAmount, bool isLeftShift,
349 const Type *ResultTy, unsigned DestReg);
351 /// emitSelectOperation - Common code shared between visitSelectInst and the
352 /// constant expression support.
354 void emitSelectOperation(MachineBasicBlock *MBB,
355 MachineBasicBlock::iterator IP,
356 Value *Cond, Value *TrueVal, Value *FalseVal,
359 /// copyGlobalBaseToRegister - Output the instructions required to put the
360 /// base address to use for accessing globals into a register.
362 void ISel::copyGlobalBaseToRegister(MachineBasicBlock *MBB,
363 MachineBasicBlock::iterator IP,
366 /// copyConstantToRegister - Output the instructions required to put the
367 /// specified constant into the specified register.
369 void copyConstantToRegister(MachineBasicBlock *MBB,
370 MachineBasicBlock::iterator MBBI,
371 Constant *C, unsigned Reg);
373 void emitUCOM(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
374 unsigned LHS, unsigned RHS);
376 /// makeAnotherReg - This method returns the next register number we haven't
379 unsigned makeAnotherReg(const Type *Ty) {
380 assert(dynamic_cast<const PowerPCRegisterInfo*>(TM.getRegisterInfo()) &&
381 "Current target doesn't have PPC reg info??");
382 const PowerPCRegisterInfo *PPCRI =
383 static_cast<const PowerPCRegisterInfo*>(TM.getRegisterInfo());
384 // Add the mapping of regnumber => reg class to MachineFunction
385 const TargetRegisterClass *RC = PPCRI->getRegClassForType(Ty);
386 return F->getSSARegMap()->createVirtualRegister(RC);
389 /// getReg - This method turns an LLVM value into a register number.
391 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
392 unsigned getReg(Value *V) {
393 // Just append to the end of the current bb.
394 MachineBasicBlock::iterator It = BB->end();
395 return getReg(V, BB, It);
397 unsigned getReg(Value *V, MachineBasicBlock *MBB,
398 MachineBasicBlock::iterator IPt);
400 /// canUseAsImmediateForOpcode - This method returns whether a ConstantInt
401 /// is okay to use as an immediate argument to a certain binary operation
402 bool canUseAsImmediateForOpcode(ConstantInt *CI, unsigned Opcode);
404 /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
405 /// that is to be statically allocated with the initial stack frame
407 unsigned getFixedSizedAllocaFI(AllocaInst *AI);
411 /// dyn_castFixedAlloca - If the specified value is a fixed size alloca
412 /// instruction in the entry block, return it. Otherwise, return a null
414 static AllocaInst *dyn_castFixedAlloca(Value *V) {
415 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
416 BasicBlock *BB = AI->getParent();
417 if (isa<ConstantUInt>(AI->getArraySize()) && BB ==&BB->getParent()->front())
423 /// getReg - This method turns an LLVM value into a register number.
425 unsigned ISel::getReg(Value *V, MachineBasicBlock *MBB,
426 MachineBasicBlock::iterator IPt) {
427 if (Constant *C = dyn_cast<Constant>(V)) {
428 unsigned Reg = makeAnotherReg(V->getType());
429 copyConstantToRegister(MBB, IPt, C, Reg);
431 } else if (AllocaInst *AI = dyn_castFixedAlloca(V)) {
432 unsigned Reg = makeAnotherReg(V->getType());
433 unsigned FI = getFixedSizedAllocaFI(AI);
434 addFrameReference(BuildMI(*MBB, IPt, PPC::ADDI, 2, Reg), FI, 0, false);
438 unsigned &Reg = RegMap[V];
440 Reg = makeAnotherReg(V->getType());
447 /// canUseAsImmediateForOpcode - This method returns whether a ConstantInt
448 /// is okay to use as an immediate argument to a certain binary operator.
450 /// Operator is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for Xor.
451 bool ISel::canUseAsImmediateForOpcode(ConstantInt *CI, unsigned Operator) {
455 // ADDI, Compare, and non-indexed Load take SIMM
456 bool cond1 = (Operator == 0)
457 && (Op1Cs = dyn_cast<ConstantSInt>(CI))
458 && (Op1Cs->getValue() <= 32767)
459 && (Op1Cs->getValue() >= -32768);
461 // SUBI takes -SIMM since it is a mnemonic for ADDI
462 bool cond2 = (Operator == 1)
463 && (Op1Cs = dyn_cast<ConstantSInt>(CI))
464 && (Op1Cs->getValue() <= 32768)
465 && (Op1Cs->getValue() >= -32767);
467 // ANDIo, ORI, and XORI take unsigned values
468 bool cond3 = (Operator >= 2)
469 && (Op1Cs = dyn_cast<ConstantSInt>(CI))
470 && (Op1Cs->getValue() >= 0)
471 && (Op1Cs->getValue() <= 32767);
473 // ADDI and SUBI take SIMMs, so we have to make sure the UInt would fit
474 bool cond4 = (Operator < 2)
475 && (Op1Cu = dyn_cast<ConstantUInt>(CI))
476 && (Op1Cu->getValue() <= 32767);
478 // ANDIo, ORI, and XORI take UIMMs, so they can be larger
479 bool cond5 = (Operator >= 2)
480 && (Op1Cu = dyn_cast<ConstantUInt>(CI))
481 && (Op1Cu->getValue() <= 65535);
483 if (cond1 || cond2 || cond3 || cond4 || cond5)
489 /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
490 /// that is to be statically allocated with the initial stack frame
492 unsigned ISel::getFixedSizedAllocaFI(AllocaInst *AI) {
493 // Already computed this?
494 std::map<AllocaInst*, unsigned>::iterator I = AllocaMap.lower_bound(AI);
495 if (I != AllocaMap.end() && I->first == AI) return I->second;
497 const Type *Ty = AI->getAllocatedType();
498 ConstantUInt *CUI = cast<ConstantUInt>(AI->getArraySize());
499 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
500 TySize *= CUI->getValue(); // Get total allocated size...
501 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
503 // Create a new stack object using the frame manager...
504 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
505 AllocaMap.insert(I, std::make_pair(AI, FrameIdx));
510 /// copyGlobalBaseToRegister - Output the instructions required to put the
511 /// base address to use for accessing globals into a register.
513 void ISel::copyGlobalBaseToRegister(MachineBasicBlock *MBB,
514 MachineBasicBlock::iterator IP,
516 if (!GlobalBaseInitialized) {
517 // Insert the set of GlobalBaseReg into the first MBB of the function
518 MachineBasicBlock &FirstMBB = F->front();
519 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
520 GlobalBaseReg = makeAnotherReg(Type::IntTy);
521 BuildMI(FirstMBB, MBBI, PPC::IMPLICIT_DEF, 0, PPC::LR);
522 BuildMI(FirstMBB, MBBI, PPC::MovePCtoLR, 0, GlobalBaseReg);
523 GlobalBaseInitialized = true;
525 // Emit our copy of GlobalBaseReg to the destination register in the
527 BuildMI(*MBB, IP, PPC::OR, 2, R).addReg(GlobalBaseReg)
528 .addReg(GlobalBaseReg);
531 /// copyConstantToRegister - Output the instructions required to put the
532 /// specified constant into the specified register.
534 void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
535 MachineBasicBlock::iterator IP,
536 Constant *C, unsigned R) {
537 if (C->getType()->isIntegral()) {
538 unsigned Class = getClassB(C->getType());
540 if (Class == cLong) {
541 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(C)) {
542 uint64_t uval = CUI->getValue();
543 if (uval < (1LL << 32)) {
544 ConstantUInt *CU = ConstantUInt::get(Type::UIntTy, uval);
545 copyConstantToRegister(MBB, IP, CU, R);
548 } else if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(C)) {
549 int64_t val = CUI->getValue();
550 if (val < (1LL << 31)) {
551 ConstantUInt *CU = ConstantUInt::get(Type::UIntTy, val);
552 copyConstantToRegister(MBB, IP, CU, R);
556 std::cerr << "Unhandled long constant type!\n";
559 // Spill long to the constant pool and load it
560 MachineConstantPool *CP = F->getConstantPool();
561 unsigned CPI = CP->getConstantPoolIndex(C);
562 BuildMI(*MBB, IP, PPC::LD, 1, R)
563 .addReg(PPC::R2).addConstantPoolIndex(CPI);
566 assert(Class <= cInt && "Type not handled yet!");
569 if (C->getType() == Type::BoolTy) {
570 BuildMI(*MBB, IP, PPC::LI, 1, R).addSImm(C == ConstantBool::True);
575 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(C)) {
576 unsigned uval = CUI->getValue();
578 BuildMI(*MBB, IP, PPC::LI, 1, R).addSImm(uval);
580 unsigned Temp = makeAnotherReg(Type::IntTy);
581 BuildMI(*MBB, IP, PPC::LIS, 1, Temp).addSImm(uval >> 16);
582 BuildMI(*MBB, IP, PPC::ORI, 2, R).addReg(Temp).addImm(uval);
585 } else if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(C)) {
586 int sval = CSI->getValue();
587 if (sval < 32768 && sval >= -32768) {
588 BuildMI(*MBB, IP, PPC::LI, 1, R).addSImm(sval);
590 unsigned Temp = makeAnotherReg(Type::IntTy);
591 BuildMI(*MBB, IP, PPC::LIS, 1, Temp).addSImm(sval >> 16);
592 BuildMI(*MBB, IP, PPC::ORI, 2, R).addReg(Temp).addImm(sval);
596 std::cerr << "Unhandled integer constant!\n";
598 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
599 // We need to spill the constant to memory...
600 MachineConstantPool *CP = F->getConstantPool();
601 unsigned CPI = CP->getConstantPoolIndex(CFP);
602 const Type *Ty = CFP->getType();
603 unsigned LoadOpcode = (Ty == Type::FloatTy) ? PPC::LFS : PPC::LFD;
604 BuildMI(*MBB,IP,LoadOpcode,2,R).addConstantPoolIndex(CPI).addReg(PPC::R2);
605 } else if (isa<ConstantPointerNull>(C)) {
606 // Copy zero (null pointer) to the register.
607 BuildMI(*MBB, IP, PPC::LI, 1, R).addSImm(0);
608 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
609 static unsigned OpcodeTable[] = {
610 PPC::LBZ, PPC::LHZ, PPC::LWZ, PPC::LFS, PPC::LFD, PPC::LD
612 unsigned Opcode = OpcodeTable[getClassB(GV->getType())];
613 BuildMI(*MBB, IP, Opcode, 2, R).addGlobalAddress(GV).addReg(PPC::R2);
615 std::cerr << "Offending constant: " << *C << "\n";
616 assert(0 && "Type not handled yet!");
620 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
621 /// the stack into virtual registers.
622 void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
623 unsigned ArgOffset = 24;
624 unsigned GPR_remaining = 8;
625 unsigned FPR_remaining = 13;
626 unsigned GPR_idx = 0, FPR_idx = 0;
627 static const unsigned GPR[] = {
628 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
629 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
631 static const unsigned FPR[] = {
632 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
633 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
636 MachineFrameInfo *MFI = F->getFrameInfo();
638 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
639 bool ArgLive = !I->use_empty();
640 unsigned Reg = ArgLive ? getReg(*I) : 0;
641 int FI; // Frame object index
643 switch (getClassB(I->getType())) {
646 FI = MFI->CreateFixedObject(4, ArgOffset);
647 if (GPR_remaining > 0) {
648 BuildMI(BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx]);
649 BuildMI(BB, PPC::OR, 2, Reg).addReg(GPR[GPR_idx])
650 .addReg(GPR[GPR_idx]);
652 addFrameReference(BuildMI(BB, PPC::LBZ, 2, Reg), FI);
658 FI = MFI->CreateFixedObject(4, ArgOffset);
659 if (GPR_remaining > 0) {
660 BuildMI(BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx]);
661 BuildMI(BB, PPC::OR, 2, Reg).addReg(GPR[GPR_idx])
662 .addReg(GPR[GPR_idx]);
664 addFrameReference(BuildMI(BB, PPC::LHZ, 2, Reg), FI);
670 FI = MFI->CreateFixedObject(4, ArgOffset);
671 if (GPR_remaining > 0) {
672 BuildMI(BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx]);
673 BuildMI(BB, PPC::OR, 2, Reg).addReg(GPR[GPR_idx])
674 .addReg(GPR[GPR_idx]);
676 addFrameReference(BuildMI(BB, PPC::LWZ, 2, Reg), FI);
682 FI = MFI->CreateFixedObject(8, ArgOffset);
683 if (GPR_remaining > 1) {
684 BuildMI(BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx]);
685 BuildMI(BB, PPC::OR, 2, Reg).addReg(GPR[GPR_idx])
686 .addReg(GPR[GPR_idx]);
688 addFrameReference(BuildMI(BB, PPC::LD, 2, Reg), FI);
691 // longs require 4 additional bytes
696 FI = MFI->CreateFixedObject(4, ArgOffset);
698 if (FPR_remaining > 0) {
699 BuildMI(BB, PPC::IMPLICIT_DEF, 0, FPR[FPR_idx]);
700 BuildMI(BB, PPC::FMR, 1, Reg).addReg(FPR[FPR_idx]);
704 addFrameReference(BuildMI(BB, PPC::LFS, 2, Reg), FI);
710 FI = MFI->CreateFixedObject(8, ArgOffset);
712 if (FPR_remaining > 0) {
713 BuildMI(BB, PPC::IMPLICIT_DEF, 0, FPR[FPR_idx]);
714 BuildMI(BB, PPC::FMR, 1, Reg).addReg(FPR[FPR_idx]);
718 addFrameReference(BuildMI(BB, PPC::LFD, 2, Reg), FI);
722 // doubles require 4 additional bytes and use 2 GPRs of param space
724 if (GPR_remaining > 0) {
730 assert(0 && "Unhandled argument type!");
732 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
733 if (GPR_remaining > 0) {
734 GPR_remaining--; // uses up 2 GPRs
739 // If the function takes variable number of arguments, add a frame offset for
740 // the start of the first vararg value... this is used to expand
742 if (Fn.getFunctionType()->isVarArg())
743 VarArgsFrameIndex = MFI->CreateFixedObject(4, ArgOffset);
747 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
748 /// because we have to generate our sources into the source basic blocks, not
751 void ISel::SelectPHINodes() {
752 const TargetInstrInfo &TII = *TM.getInstrInfo();
753 const Function &LF = *F->getFunction(); // The LLVM function...
754 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
755 const BasicBlock *BB = I;
756 MachineBasicBlock &MBB = *MBBMap[I];
758 // Loop over all of the PHI nodes in the LLVM basic block...
759 MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
760 for (BasicBlock::const_iterator I = BB->begin();
761 PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
763 // Create a new machine instr PHI node, and insert it.
764 unsigned PHIReg = getReg(*PN);
765 MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
766 PPC::PHI, PN->getNumOperands(), PHIReg);
768 // PHIValues - Map of blocks to incoming virtual registers. We use this
769 // so that we only initialize one incoming value for a particular block,
770 // even if the block has multiple entries in the PHI node.
772 std::map<MachineBasicBlock*, unsigned> PHIValues;
774 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
775 MachineBasicBlock *PredMBB = 0;
776 for (MachineBasicBlock::pred_iterator PI = MBB.pred_begin (),
777 PE = MBB.pred_end (); PI != PE; ++PI)
778 if (PN->getIncomingBlock(i) == (*PI)->getBasicBlock()) {
782 assert (PredMBB && "Couldn't find incoming machine-cfg edge for phi");
785 std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
786 PHIValues.lower_bound(PredMBB);
788 if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
789 // We already inserted an initialization of the register for this
790 // predecessor. Recycle it.
791 ValReg = EntryIt->second;
793 // Get the incoming value into a virtual register.
795 Value *Val = PN->getIncomingValue(i);
797 // If this is a constant or GlobalValue, we may have to insert code
798 // into the basic block to compute it into a virtual register.
799 if ((isa<Constant>(Val) && !isa<ConstantExpr>(Val)) ||
800 isa<GlobalValue>(Val)) {
801 // Simple constants get emitted at the end of the basic block,
802 // before any terminator instructions. We "know" that the code to
803 // move a constant into a register will never clobber any flags.
804 ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
806 // Because we don't want to clobber any values which might be in
807 // physical registers with the computation of this constant (which
808 // might be arbitrarily complex if it is a constant expression),
809 // just insert the computation at the top of the basic block.
810 MachineBasicBlock::iterator PI = PredMBB->begin();
812 // Skip over any PHI nodes though!
813 while (PI != PredMBB->end() && PI->getOpcode() == PPC::PHI)
816 ValReg = getReg(Val, PredMBB, PI);
819 // Remember that we inserted a value for this PHI for this predecessor
820 PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
823 PhiMI->addRegOperand(ValReg);
824 PhiMI->addMachineBasicBlockOperand(PredMBB);
827 // Now that we emitted all of the incoming values for the PHI node, make
828 // sure to reposition the InsertPoint after the PHI that we just added.
829 // This is needed because we might have inserted a constant into this
830 // block, right after the PHI's which is before the old insert point!
831 PHIInsertPoint = PhiMI;
838 // canFoldSetCCIntoBranchOrSelect - Return the setcc instruction if we can fold
839 // it into the conditional branch or select instruction which is the only user
840 // of the cc instruction. This is the case if the conditional branch is the
841 // only user of the setcc, and if the setcc is in the same basic block as the
842 // conditional branch.
844 static SetCondInst *canFoldSetCCIntoBranchOrSelect(Value *V) {
845 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
846 if (SCI->hasOneUse()) {
847 Instruction *User = cast<Instruction>(SCI->use_back());
848 if ((isa<BranchInst>(User) || isa<SelectInst>(User)) &&
849 SCI->getParent() == User->getParent())
856 // canFoldGEPIntoLoadOrStore - Return the GEP instruction if we can fold it into
857 // the load or store instruction that is the only user of the GEP.
859 static GetElementPtrInst *canFoldGEPIntoLoadOrStore(Value *V) {
860 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V))
861 if (GEPI->hasOneUse()) {
862 Instruction *User = cast<Instruction>(GEPI->use_back());
863 if (isa<StoreInst>(User) &&
864 GEPI->getParent() == User->getParent() &&
865 User->getOperand(0) != GEPI &&
866 User->getOperand(1) == GEPI) {
870 if (isa<LoadInst>(User) &&
871 GEPI->getParent() == User->getParent() &&
872 User->getOperand(0) == GEPI) {
881 // Return a fixed numbering for setcc instructions which does not depend on the
882 // order of the opcodes.
884 static unsigned getSetCCNumber(unsigned Opcode) {
886 default: assert(0 && "Unknown setcc instruction!");
887 case Instruction::SetEQ: return 0;
888 case Instruction::SetNE: return 1;
889 case Instruction::SetLT: return 2;
890 case Instruction::SetGE: return 3;
891 case Instruction::SetGT: return 4;
892 case Instruction::SetLE: return 5;
896 static unsigned getPPCOpcodeForSetCCNumber(unsigned Opcode) {
898 default: assert(0 && "Unknown setcc instruction!");
899 case Instruction::SetEQ: return PPC::BEQ;
900 case Instruction::SetNE: return PPC::BNE;
901 case Instruction::SetLT: return PPC::BLT;
902 case Instruction::SetGE: return PPC::BGE;
903 case Instruction::SetGT: return PPC::BGT;
904 case Instruction::SetLE: return PPC::BLE;
908 /// emitUCOM - emits an unordered FP compare.
909 void ISel::emitUCOM(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
910 unsigned LHS, unsigned RHS) {
911 BuildMI(*MBB, IP, PPC::FCMPU, 2, PPC::CR0).addReg(LHS).addReg(RHS);
914 /// EmitComparison - emits a comparison of the two operands, returning the
915 /// extended setcc code to use. The result is in CR0.
917 unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
918 MachineBasicBlock *MBB,
919 MachineBasicBlock::iterator IP) {
920 // The arguments are already supposed to be of the same type.
921 const Type *CompTy = Op0->getType();
922 unsigned Class = getClassB(CompTy);
923 unsigned Op0r = getReg(Op0, MBB, IP);
925 // Before we do a comparison, we have to make sure that we're truncating our
926 // registers appropriately.
927 if (Class == cByte) {
928 unsigned TmpReg = makeAnotherReg(CompTy);
929 if (CompTy->isSigned())
930 BuildMI(*MBB, IP, PPC::EXTSB, 1, TmpReg).addReg(Op0r);
932 BuildMI(*MBB, IP, PPC::RLWINM, 4, TmpReg).addReg(Op0r).addImm(0)
933 .addImm(24).addImm(31);
935 } else if (Class == cShort) {
936 unsigned TmpReg = makeAnotherReg(CompTy);
937 if (CompTy->isSigned())
938 BuildMI(*MBB, IP, PPC::EXTSH, 1, TmpReg).addReg(Op0r);
940 BuildMI(*MBB, IP, PPC::RLWINM, 4, TmpReg).addReg(Op0r).addImm(0)
941 .addImm(16).addImm(31);
945 // Use crand for lt, gt and crandc for le, ge
946 unsigned CROpcode = (OpNum == 2 || OpNum == 4) ? PPC::CRAND : PPC::CRANDC;
947 unsigned Opcode = CompTy->isSigned() ? PPC::CMPW : PPC::CMPLW;
948 unsigned OpcodeImm = CompTy->isSigned() ? PPC::CMPWI : PPC::CMPLWI;
949 if (Class == cLong) {
950 Opcode = CompTy->isSigned() ? PPC::CMPD : PPC::CMPLD;
951 OpcodeImm = CompTy->isSigned() ? PPC::CMPDI : PPC::CMPLDI;
954 // Special case handling of: cmp R, i
955 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
956 unsigned Op1v = CI->getRawValue() & 0xFFFF;
958 // Treat compare like ADDI for the purposes of immediate suitability
959 if (canUseAsImmediateForOpcode(CI, 0)) {
960 BuildMI(*MBB, IP, OpcodeImm, 2, PPC::CR0).addReg(Op0r).addSImm(Op1v);
962 unsigned Op1r = getReg(Op1, MBB, IP);
963 BuildMI(*MBB, IP, Opcode, 2, PPC::CR0).addReg(Op0r).addReg(Op1r);
968 unsigned Op1r = getReg(Op1, MBB, IP);
971 default: assert(0 && "Unknown type class!");
976 BuildMI(*MBB, IP, Opcode, 2, PPC::CR0).addReg(Op0r).addReg(Op1r);
981 emitUCOM(MBB, IP, Op0r, Op1r);
988 /// visitSetCondInst - emit code to calculate the condition via
989 /// EmitComparison(), and possibly store a 0 or 1 to a register as a result
991 void ISel::visitSetCondInst(SetCondInst &I) {
992 if (canFoldSetCCIntoBranchOrSelect(&I))
995 unsigned DestReg = getReg(I);
996 unsigned OpNum = I.getOpcode();
997 const Type *Ty = I.getOperand (0)->getType();
999 EmitComparison(OpNum, I.getOperand(0), I.getOperand(1), BB, BB->end());
1001 unsigned Opcode = getPPCOpcodeForSetCCNumber(OpNum);
1002 MachineBasicBlock *thisMBB = BB;
1003 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1004 ilist<MachineBasicBlock>::iterator It = BB;
1009 // cmpTY cr0, r1, r2
1013 // FIXME: we wouldn't need copy0MBB (we could fold it into thisMBB)
1014 // if we could insert other, non-terminator instructions after the
1015 // bCC. But MBB->getFirstTerminator() can't understand this.
1016 MachineBasicBlock *copy1MBB = new MachineBasicBlock(LLVM_BB);
1017 F->getBasicBlockList().insert(It, copy1MBB);
1018 BuildMI(BB, Opcode, 2).addReg(PPC::CR0).addMBB(copy1MBB);
1019 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
1020 F->getBasicBlockList().insert(It, copy0MBB);
1021 BuildMI(BB, PPC::B, 1).addMBB(copy0MBB);
1022 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
1023 F->getBasicBlockList().insert(It, sinkMBB);
1024 // Update machine-CFG edges
1025 BB->addSuccessor(copy1MBB);
1026 BB->addSuccessor(copy0MBB);
1029 // %TrueValue = li 1
1032 unsigned TrueValue = makeAnotherReg(I.getType());
1033 BuildMI(BB, PPC::LI, 1, TrueValue).addSImm(1);
1034 BuildMI(BB, PPC::B, 1).addMBB(sinkMBB);
1035 // Update machine-CFG edges
1036 BB->addSuccessor(sinkMBB);
1039 // %FalseValue = li 0
1042 unsigned FalseValue = makeAnotherReg(I.getType());
1043 BuildMI(BB, PPC::LI, 1, FalseValue).addSImm(0);
1044 // Update machine-CFG edges
1045 BB->addSuccessor(sinkMBB);
1048 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, copy1MBB ]
1051 BuildMI(BB, PPC::PHI, 4, DestReg).addReg(FalseValue)
1052 .addMBB(copy0MBB).addReg(TrueValue).addMBB(copy1MBB);
1055 void ISel::visitSelectInst(SelectInst &SI) {
1056 unsigned DestReg = getReg(SI);
1057 MachineBasicBlock::iterator MII = BB->end();
1058 emitSelectOperation(BB, MII, SI.getCondition(), SI.getTrueValue(),
1059 SI.getFalseValue(), DestReg);
1062 /// emitSelect - Common code shared between visitSelectInst and the constant
1063 /// expression support.
1064 /// FIXME: this is most likely broken in one or more ways. Namely, PowerPC has
1065 /// no select instruction. FSEL only works for comparisons against zero.
1066 void ISel::emitSelectOperation(MachineBasicBlock *MBB,
1067 MachineBasicBlock::iterator IP,
1068 Value *Cond, Value *TrueVal, Value *FalseVal,
1070 unsigned SelectClass = getClassB(TrueVal->getType());
1073 // See if we can fold the setcc into the select instruction, or if we have
1074 // to get the register of the Cond value
1075 if (SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(Cond)) {
1076 // We successfully folded the setcc into the select instruction.
1077 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1078 OpNum = EmitComparison(OpNum, SCI->getOperand(0),SCI->getOperand(1),MBB,IP);
1079 Opcode = getPPCOpcodeForSetCCNumber(SCI->getOpcode());
1081 unsigned CondReg = getReg(Cond, MBB, IP);
1082 BuildMI(*MBB, IP, PPC::CMPI, 2, PPC::CR0).addReg(CondReg).addSImm(0);
1083 Opcode = getPPCOpcodeForSetCCNumber(Instruction::SetNE);
1088 // cmpTY cr0, r1, r2
1092 MachineBasicBlock *thisMBB = BB;
1093 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1094 ilist<MachineBasicBlock>::iterator It = BB;
1097 // FIXME: we wouldn't need copy0MBB (we could fold it into thisMBB)
1098 // if we could insert other, non-terminator instructions after the
1099 // bCC. But MBB->getFirstTerminator() can't understand this.
1100 MachineBasicBlock *copy1MBB = new MachineBasicBlock(LLVM_BB);
1101 F->getBasicBlockList().insert(It, copy1MBB);
1102 BuildMI(BB, Opcode, 2).addReg(PPC::CR0).addMBB(copy1MBB);
1103 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
1104 F->getBasicBlockList().insert(It, copy0MBB);
1105 BuildMI(BB, PPC::B, 1).addMBB(copy0MBB);
1106 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
1107 F->getBasicBlockList().insert(It, sinkMBB);
1108 // Update machine-CFG edges
1109 BB->addSuccessor(copy1MBB);
1110 BB->addSuccessor(copy0MBB);
1116 unsigned TrueValue = getReg(TrueVal, BB, BB->begin());
1117 BuildMI(BB, PPC::B, 1).addMBB(sinkMBB);
1118 // Update machine-CFG edges
1119 BB->addSuccessor(sinkMBB);
1122 // %FalseValue = ...
1125 unsigned FalseValue = getReg(FalseVal, BB, BB->begin());
1126 // Update machine-CFG edges
1127 BB->addSuccessor(sinkMBB);
1130 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, copy1MBB ]
1133 BuildMI(BB, PPC::PHI, 4, DestReg).addReg(FalseValue)
1134 .addMBB(copy0MBB).addReg(TrueValue).addMBB(copy1MBB);
1140 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
1141 /// operand, in the specified target register.
1143 void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
1144 bool isUnsigned = VR.Ty->isUnsigned() || VR.Ty == Type::BoolTy;
1146 Value *Val = VR.Val;
1147 const Type *Ty = VR.Ty;
1149 if (Constant *C = dyn_cast<Constant>(Val)) {
1150 Val = ConstantExpr::getCast(C, Type::IntTy);
1151 if (isa<ConstantExpr>(Val)) // Could not fold
1154 Ty = Type::IntTy; // Folded!
1157 // If this is a simple constant, just emit a load directly to avoid the copy
1158 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
1159 int TheVal = CI->getRawValue() & 0xFFFFFFFF;
1161 if (TheVal < 32768 && TheVal >= -32768) {
1162 BuildMI(BB, PPC::LI, 1, targetReg).addSImm(TheVal);
1164 unsigned TmpReg = makeAnotherReg(Type::IntTy);
1165 BuildMI(BB, PPC::LIS, 1, TmpReg).addSImm(TheVal >> 16);
1166 BuildMI(BB, PPC::ORI, 2, targetReg).addReg(TmpReg)
1167 .addImm(TheVal & 0xFFFF);
1173 // Make sure we have the register number for this value...
1174 unsigned Reg = Val ? getReg(Val) : VR.Reg;
1175 switch (getClassB(Ty)) {
1177 // Extend value into target register (8->32)
1179 BuildMI(BB, PPC::RLWINM, 4, targetReg).addReg(Reg).addZImm(0)
1180 .addZImm(24).addZImm(31);
1182 BuildMI(BB, PPC::EXTSB, 1, targetReg).addReg(Reg);
1185 // Extend value into target register (16->32)
1187 BuildMI(BB, PPC::RLWINM, 4, targetReg).addReg(Reg).addZImm(0)
1188 .addZImm(16).addZImm(31);
1190 BuildMI(BB, PPC::EXTSH, 1, targetReg).addReg(Reg);
1194 // Move value into target register (32->32)
1195 BuildMI(BB, PPC::OR, 2, targetReg).addReg(Reg).addReg(Reg);
1198 assert(0 && "Unpromotable operand class in promote32");
1202 /// visitReturnInst - implemented with BLR
1204 void ISel::visitReturnInst(ReturnInst &I) {
1205 // Only do the processing if this is a non-void return
1206 if (I.getNumOperands() > 0) {
1207 Value *RetVal = I.getOperand(0);
1208 switch (getClassB(RetVal->getType())) {
1209 case cByte: // integral return values: extend or move into r3 and return
1213 promote32(PPC::R3, ValueRecord(RetVal));
1216 case cFP64: { // Floats & Doubles: Return in f1
1217 unsigned RetReg = getReg(RetVal);
1218 BuildMI(BB, PPC::FMR, 1, PPC::F1).addReg(RetReg);
1222 visitInstruction(I);
1225 BuildMI(BB, PPC::BLR, 1).addImm(1);
1228 // getBlockAfter - Return the basic block which occurs lexically after the
1230 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1231 Function::iterator I = BB; ++I; // Get iterator to next block
1232 return I != BB->getParent()->end() ? &*I : 0;
1235 /// visitBranchInst - Handle conditional and unconditional branches here. Note
1236 /// that since code layout is frozen at this point, that if we are trying to
1237 /// jump to a block that is the immediate successor of the current block, we can
1238 /// just make a fall-through (but we don't currently).
1240 void ISel::visitBranchInst(BranchInst &BI) {
1241 // Update machine-CFG edges
1242 BB->addSuccessor(MBBMap[BI.getSuccessor(0)]);
1243 if (BI.isConditional())
1244 BB->addSuccessor(MBBMap[BI.getSuccessor(1)]);
1246 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
1248 if (!BI.isConditional()) { // Unconditional branch?
1249 if (BI.getSuccessor(0) != NextBB)
1250 BuildMI(BB, PPC::B, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1254 // See if we can fold the setcc into the branch itself...
1255 SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(BI.getCondition());
1257 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
1258 // computed some other way...
1259 unsigned condReg = getReg(BI.getCondition());
1260 BuildMI(BB, PPC::CMPLI, 3, PPC::CR0).addImm(0).addReg(condReg)
1262 if (BI.getSuccessor(1) == NextBB) {
1263 if (BI.getSuccessor(0) != NextBB)
1264 BuildMI(BB, PPC::COND_BRANCH, 3).addReg(PPC::CR0).addImm(PPC::BNE)
1265 .addMBB(MBBMap[BI.getSuccessor(0)])
1266 .addMBB(MBBMap[BI.getSuccessor(1)]);
1268 BuildMI(BB, PPC::COND_BRANCH, 3).addReg(PPC::CR0).addImm(PPC::BEQ)
1269 .addMBB(MBBMap[BI.getSuccessor(1)])
1270 .addMBB(MBBMap[BI.getSuccessor(0)]);
1271 if (BI.getSuccessor(0) != NextBB)
1272 BuildMI(BB, PPC::B, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1277 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1278 unsigned Opcode = getPPCOpcodeForSetCCNumber(SCI->getOpcode());
1279 MachineBasicBlock::iterator MII = BB->end();
1280 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
1282 if (BI.getSuccessor(0) != NextBB) {
1283 BuildMI(BB, PPC::COND_BRANCH, 3).addReg(PPC::CR0).addImm(Opcode)
1284 .addMBB(MBBMap[BI.getSuccessor(0)])
1285 .addMBB(MBBMap[BI.getSuccessor(1)]);
1286 if (BI.getSuccessor(1) != NextBB)
1287 BuildMI(BB, PPC::B, 1).addMBB(MBBMap[BI.getSuccessor(1)]);
1289 // Change to the inverse condition...
1290 if (BI.getSuccessor(1) != NextBB) {
1291 Opcode = PowerPCInstrInfo::invertPPCBranchOpcode(Opcode);
1292 BuildMI(BB, PPC::COND_BRANCH, 3).addReg(PPC::CR0).addImm(Opcode)
1293 .addMBB(MBBMap[BI.getSuccessor(1)])
1294 .addMBB(MBBMap[BI.getSuccessor(0)]);
1299 /// doCall - This emits an abstract call instruction, setting up the arguments
1300 /// and the return value as appropriate. For the actual function call itself,
1301 /// it inserts the specified CallMI instruction into the stream.
1303 void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
1304 const std::vector<ValueRecord> &Args, bool isVarArg) {
1305 // Count how many bytes are to be pushed on the stack, including the linkage
1306 // area, and parameter passing area.
1307 unsigned NumBytes = 24;
1308 unsigned ArgOffset = 24;
1310 if (!Args.empty()) {
1311 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1312 switch (getClassB(Args[i].Ty)) {
1313 case cByte: case cShort: case cInt:
1314 NumBytes += 4; break;
1316 NumBytes += 8; break;
1318 NumBytes += 4; break;
1320 NumBytes += 8; break;
1322 default: assert(0 && "Unknown class!");
1325 // Just to be safe, we'll always reserve the full 32 bytes worth of
1326 // argument passing space in case any called code gets funky on us.
1327 if (NumBytes < 24 + 32) NumBytes = 24 + 32;
1329 // Adjust the stack pointer for the new arguments...
1330 // These functions are automatically eliminated by the prolog/epilog pass
1331 BuildMI(BB, PPC::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
1333 // Arguments go on the stack in reverse order, as specified by the ABI.
1334 // Offset to the paramater area on the stack is 24.
1335 int GPR_remaining = 8, FPR_remaining = 13;
1336 unsigned GPR_idx = 0, FPR_idx = 0;
1337 static const unsigned GPR[] = {
1338 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1339 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1341 static const unsigned FPR[] = {
1342 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6,
1343 PPC::F7, PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12,
1347 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1349 switch (getClassB(Args[i].Ty)) {
1352 // Promote arg to 32 bits wide into a temporary register...
1353 ArgReg = makeAnotherReg(Type::UIntTy);
1354 promote32(ArgReg, Args[i]);
1357 if (GPR_remaining > 0) {
1358 BuildMI(BB, PPC::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1360 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1362 if (GPR_remaining <= 0 || isVarArg) {
1363 BuildMI(BB, PPC::STW, 3).addReg(ArgReg).addSImm(ArgOffset)
1368 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1371 if (GPR_remaining > 0) {
1372 BuildMI(BB, PPC::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1374 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1376 if (GPR_remaining <= 0 || isVarArg) {
1377 BuildMI(BB, PPC::STW, 3).addReg(ArgReg).addSImm(ArgOffset)
1382 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1385 if (GPR_remaining > 0) {
1386 BuildMI(BB, PPC::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1388 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1390 if (GPR_remaining <= 0 || isVarArg) {
1391 BuildMI(BB, PPC::STD, 3).addReg(ArgReg).addSImm(ArgOffset)
1394 ArgOffset += 4; // 8 byte entry, not 4.
1397 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1399 if (FPR_remaining > 0) {
1400 BuildMI(BB, PPC::FMR, 1, FPR[FPR_idx]).addReg(ArgReg);
1401 CallMI->addRegOperand(FPR[FPR_idx], MachineOperand::Use);
1405 // If this is a vararg function, and there are GPRs left, also
1406 // pass the float in an int. Otherwise, put it on the stack.
1408 BuildMI(BB, PPC::STFS, 3).addReg(ArgReg).addSImm(ArgOffset)
1410 if (GPR_remaining > 0) {
1411 BuildMI(BB, PPC::LWZ, 2, GPR[GPR_idx])
1412 .addSImm(ArgOffset).addReg(ArgReg);
1413 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1417 BuildMI(BB, PPC::STFS, 3).addReg(ArgReg).addSImm(ArgOffset)
1422 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1424 if (FPR_remaining > 0) {
1425 BuildMI(BB, PPC::FMR, 1, FPR[FPR_idx]).addReg(ArgReg);
1426 CallMI->addRegOperand(FPR[FPR_idx], MachineOperand::Use);
1429 // For vararg functions, must pass doubles via int regs as well
1431 BuildMI(BB, PPC::STFD, 3).addReg(ArgReg).addSImm(ArgOffset)
1434 if (GPR_remaining > 0) {
1435 BuildMI(BB, PPC::LD, 2, GPR[GPR_idx]).addSImm(ArgOffset)
1437 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1441 BuildMI(BB, PPC::STFD, 3).addReg(ArgReg).addSImm(ArgOffset)
1444 // Doubles use 8 bytes
1448 default: assert(0 && "Unknown class!");
1455 BuildMI(BB, PPC::ADJCALLSTACKDOWN, 1).addImm(0);
1458 BuildMI(BB, PPC::IMPLICIT_DEF, 0, PPC::LR);
1459 BB->push_back(CallMI);
1460 BuildMI(BB, PPC::NOP, 0);
1462 // These functions are automatically eliminated by the prolog/epilog pass
1463 BuildMI(BB, PPC::ADJCALLSTACKUP, 1).addImm(NumBytes);
1465 // If there is a return value, scavenge the result from the location the call
1468 if (Ret.Ty != Type::VoidTy) {
1469 unsigned DestClass = getClassB(Ret.Ty);
1470 switch (DestClass) {
1475 // Integral results are in r3
1476 BuildMI(BB, PPC::OR, 2, Ret.Reg).addReg(PPC::R3).addReg(PPC::R3);
1478 case cFP32: // Floating-point return values live in f1
1480 BuildMI(BB, PPC::FMR, 1, Ret.Reg).addReg(PPC::F1);
1482 default: assert(0 && "Unknown class!");
1488 /// visitCallInst - Push args on stack and do a procedure call instruction.
1489 void ISel::visitCallInst(CallInst &CI) {
1490 MachineInstr *TheCall;
1491 Function *F = CI.getCalledFunction();
1493 // Is it an intrinsic function call?
1494 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1495 visitIntrinsicCall(ID, CI); // Special intrinsics are not handled here
1498 // Emit a CALL instruction with PC-relative displacement.
1499 TheCall = BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(F, true);
1500 // Add it to the set of functions called to be used by the Printer
1501 TM.CalledFunctions.insert(F);
1502 } else { // Emit an indirect call through the CTR
1503 unsigned Reg = getReg(CI.getCalledValue());
1504 BuildMI(BB, PPC::MTCTR, 1).addReg(Reg);
1505 TheCall = BuildMI(PPC::CALLindirect, 2).addZImm(20).addZImm(0);
1508 std::vector<ValueRecord> Args;
1509 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
1510 Args.push_back(ValueRecord(CI.getOperand(i)));
1512 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1513 bool isVarArg = F ? F->getFunctionType()->isVarArg() : true;
1514 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args, isVarArg);
1518 /// dyncastIsNan - Return the operand of an isnan operation if this is an isnan.
1520 static Value *dyncastIsNan(Value *V) {
1521 if (CallInst *CI = dyn_cast<CallInst>(V))
1522 if (Function *F = CI->getCalledFunction())
1523 if (F->getIntrinsicID() == Intrinsic::isunordered)
1524 return CI->getOperand(1);
1528 /// isOnlyUsedByUnorderedComparisons - Return true if this value is only used by
1529 /// or's whos operands are all calls to the isnan predicate.
1530 static bool isOnlyUsedByUnorderedComparisons(Value *V) {
1531 assert(dyncastIsNan(V) && "The value isn't an isnan call!");
1533 // Check all uses, which will be or's of isnans if this predicate is true.
1534 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1535 Instruction *I = cast<Instruction>(*UI);
1536 if (I->getOpcode() != Instruction::Or) return false;
1537 if (I->getOperand(0) != V && !dyncastIsNan(I->getOperand(0))) return false;
1538 if (I->getOperand(1) != V && !dyncastIsNan(I->getOperand(1))) return false;
1544 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1545 /// function, lowering any calls to unknown intrinsic functions into the
1546 /// equivalent LLVM code.
1548 void ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1549 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1550 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1551 if (CallInst *CI = dyn_cast<CallInst>(I++))
1552 if (Function *F = CI->getCalledFunction())
1553 switch (F->getIntrinsicID()) {
1554 case Intrinsic::not_intrinsic:
1555 case Intrinsic::vastart:
1556 case Intrinsic::vacopy:
1557 case Intrinsic::vaend:
1558 case Intrinsic::returnaddress:
1559 case Intrinsic::frameaddress:
1560 // FIXME: should lower these ourselves
1561 // case Intrinsic::isunordered:
1562 // case Intrinsic::memcpy: -> doCall(). system memcpy almost
1563 // guaranteed to be faster than anything we generate ourselves
1564 // We directly implement these intrinsics
1566 case Intrinsic::readio: {
1567 // On PPC, memory operations are in-order. Lower this intrinsic
1568 // into a volatile load.
1569 Instruction *Before = CI->getPrev();
1570 LoadInst * LI = new LoadInst(CI->getOperand(1), "", true, CI);
1571 CI->replaceAllUsesWith(LI);
1572 BB->getInstList().erase(CI);
1575 case Intrinsic::writeio: {
1576 // On PPC, memory operations are in-order. Lower this intrinsic
1577 // into a volatile store.
1578 Instruction *Before = CI->getPrev();
1579 StoreInst *SI = new StoreInst(CI->getOperand(1),
1580 CI->getOperand(2), true, CI);
1581 CI->replaceAllUsesWith(SI);
1582 BB->getInstList().erase(CI);
1586 // All other intrinsic calls we must lower.
1587 Instruction *Before = CI->getPrev();
1588 TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
1589 if (Before) { // Move iterator to instruction after call
1597 void ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
1598 unsigned TmpReg1, TmpReg2, TmpReg3;
1600 case Intrinsic::vastart:
1601 // Get the address of the first vararg value...
1602 TmpReg1 = getReg(CI);
1603 addFrameReference(BuildMI(BB, PPC::ADDI, 2, TmpReg1), VarArgsFrameIndex,
1607 case Intrinsic::vacopy:
1608 TmpReg1 = getReg(CI);
1609 TmpReg2 = getReg(CI.getOperand(1));
1610 BuildMI(BB, PPC::OR, 2, TmpReg1).addReg(TmpReg2).addReg(TmpReg2);
1612 case Intrinsic::vaend: return;
1614 case Intrinsic::returnaddress:
1615 TmpReg1 = getReg(CI);
1616 if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1617 MachineFrameInfo *MFI = F->getFrameInfo();
1618 unsigned NumBytes = MFI->getStackSize();
1620 BuildMI(BB, PPC::LWZ, 2, TmpReg1).addSImm(NumBytes+8)
1623 // Values other than zero are not implemented yet.
1624 BuildMI(BB, PPC::LI, 1, TmpReg1).addSImm(0);
1628 case Intrinsic::frameaddress:
1629 TmpReg1 = getReg(CI);
1630 if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1631 BuildMI(BB, PPC::OR, 2, TmpReg1).addReg(PPC::R1).addReg(PPC::R1);
1633 // Values other than zero are not implemented yet.
1634 BuildMI(BB, PPC::LI, 1, TmpReg1).addSImm(0);
1639 // This may be useful for supporting isunordered
1640 case Intrinsic::isnan:
1641 // If this is only used by 'isunordered' style comparisons, don't emit it.
1642 if (isOnlyUsedByUnorderedComparisons(&CI)) return;
1643 TmpReg1 = getReg(CI.getOperand(1));
1644 emitUCOM(BB, BB->end(), TmpReg1, TmpReg1);
1645 TmpReg2 = makeAnotherReg(Type::IntTy);
1646 BuildMI(BB, PPC::MFCR, TmpReg2);
1647 TmpReg3 = getReg(CI);
1648 BuildMI(BB, PPC::RLWINM, 4, TmpReg3).addReg(TmpReg2).addImm(4).addImm(31).addImm(31);
1652 default: assert(0 && "Error: unknown intrinsics should have been lowered!");
1656 /// visitSimpleBinary - Implement simple binary operators for integral types...
1657 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
1660 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
1661 unsigned DestReg = getReg(B);
1662 MachineBasicBlock::iterator MI = BB->end();
1663 Value *Op0 = B.getOperand(0), *Op1 = B.getOperand(1);
1664 unsigned Class = getClassB(B.getType());
1666 emitSimpleBinaryOperation(BB, MI, Op0, Op1, OperatorClass, DestReg);
1669 /// emitBinaryFPOperation - This method handles emission of floating point
1670 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
1671 void ISel::emitBinaryFPOperation(MachineBasicBlock *BB,
1672 MachineBasicBlock::iterator IP,
1673 Value *Op0, Value *Op1,
1674 unsigned OperatorClass, unsigned DestReg) {
1676 // Special case: op Reg, <const fp>
1677 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1678 // Create a constant pool entry for this constant.
1679 MachineConstantPool *CP = F->getConstantPool();
1680 unsigned CPI = CP->getConstantPoolIndex(Op1C);
1681 const Type *Ty = Op1->getType();
1682 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1684 static const unsigned OpcodeTab[][4] = {
1685 { PPC::FADDS, PPC::FSUBS, PPC::FMULS, PPC::FDIVS }, // Float
1686 { PPC::FADD, PPC::FSUB, PPC::FMUL, PPC::FDIV }, // Double
1689 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
1690 unsigned Op1Reg = getReg(Op1C, BB, IP);
1691 unsigned Op0r = getReg(Op0, BB, IP);
1692 BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1Reg);
1696 // Special case: R1 = op <const fp>, R2
1697 if (ConstantFP *Op0C = dyn_cast<ConstantFP>(Op0))
1698 if (Op0C->isExactlyValue(-0.0) && OperatorClass == 1) {
1700 unsigned op1Reg = getReg(Op1, BB, IP);
1701 BuildMI(*BB, IP, PPC::FNEG, 1, DestReg).addReg(op1Reg);
1704 // R1 = op CST, R2 --> R1 = opr R2, CST
1706 // Create a constant pool entry for this constant.
1707 MachineConstantPool *CP = F->getConstantPool();
1708 unsigned CPI = CP->getConstantPoolIndex(Op0C);
1709 const Type *Ty = Op0C->getType();
1710 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1712 static const unsigned OpcodeTab[][4] = {
1713 { PPC::FADDS, PPC::FSUBS, PPC::FMULS, PPC::FDIVS }, // Float
1714 { PPC::FADD, PPC::FSUB, PPC::FMUL, PPC::FDIV }, // Double
1717 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
1718 unsigned Op0Reg = getReg(Op0C, BB, IP);
1719 unsigned Op1Reg = getReg(Op1, BB, IP);
1720 BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0Reg).addReg(Op1Reg);
1725 static const unsigned OpcodeTab[] = {
1726 PPC::FADD, PPC::FSUB, PPC::FMUL, PPC::FDIV
1729 unsigned Opcode = OpcodeTab[OperatorClass];
1730 unsigned Op0r = getReg(Op0, BB, IP);
1731 unsigned Op1r = getReg(Op1, BB, IP);
1732 BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1735 /// emitSimpleBinaryOperation - Implement simple binary operators for integral
1736 /// types... OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
1739 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
1740 /// and constant expression support.
1742 void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
1743 MachineBasicBlock::iterator IP,
1744 Value *Op0, Value *Op1,
1745 unsigned OperatorClass, unsigned DestReg) {
1746 unsigned Class = getClassB(Op0->getType());
1748 // Arithmetic and Bitwise operators
1749 static const unsigned OpcodeTab[] = {
1750 PPC::ADD, PPC::SUB, PPC::AND, PPC::OR, PPC::XOR
1752 static const unsigned ImmOpcodeTab[] = {
1753 PPC::ADDI, PPC::SUBI, PPC::ANDIo, PPC::ORI, PPC::XORI
1755 static const unsigned RImmOpcodeTab[] = {
1756 PPC::ADDI, PPC::SUBFIC, PPC::ANDIo, PPC::ORI, PPC::XORI
1759 if (Class == cFP32 || Class == cFP64) {
1760 assert(OperatorClass < 2 && "No logical ops for FP!");
1761 emitBinaryFPOperation(MBB, IP, Op0, Op1, OperatorClass, DestReg);
1765 if (Op0->getType() == Type::BoolTy) {
1766 if (OperatorClass == 3)
1767 // If this is an or of two isnan's, emit an FP comparison directly instead
1768 // of or'ing two isnan's together.
1769 if (Value *LHS = dyncastIsNan(Op0))
1770 if (Value *RHS = dyncastIsNan(Op1)) {
1771 unsigned Op0Reg = getReg(RHS, MBB, IP), Op1Reg = getReg(LHS, MBB, IP);
1772 unsigned TmpReg = makeAnotherReg(Type::IntTy);
1773 emitUCOM(MBB, IP, Op0Reg, Op1Reg);
1774 BuildMI(*MBB, IP, PPC::MFCR, TmpReg);
1775 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(TmpReg).addImm(4)
1776 .addImm(31).addImm(31);
1781 // Special case: op <const int>, Reg
1782 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0)) {
1783 // sub 0, X -> subfic
1784 if (OperatorClass == 1 && canUseAsImmediateForOpcode(CI, 0)) {
1785 unsigned Op1r = getReg(Op1, MBB, IP);
1786 int imm = CI->getRawValue() & 0xFFFF;
1787 BuildMI(*MBB, IP, PPC::SUBFIC, 2, DestReg).addReg(Op1r).addSImm(imm);
1791 // If it is easy to do, swap the operands and emit an immediate op
1792 if (Class != cLong && OperatorClass != 1 &&
1793 canUseAsImmediateForOpcode(CI, OperatorClass)) {
1794 unsigned Op1r = getReg(Op1, MBB, IP);
1795 int imm = CI->getRawValue() & 0xFFFF;
1797 if (OperatorClass < 2)
1798 BuildMI(*MBB, IP, RImmOpcodeTab[OperatorClass], 2, DestReg).addReg(Op1r)
1801 BuildMI(*MBB, IP, RImmOpcodeTab[OperatorClass], 2, DestReg).addReg(Op1r)
1807 // Special case: op Reg, <const int>
1808 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1809 unsigned Op0r = getReg(Op0, MBB, IP);
1811 // xor X, -1 -> not X
1812 if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
1813 BuildMI(*MBB, IP, PPC::NOR, 2, DestReg).addReg(Op0r).addReg(Op0r);
1817 if (canUseAsImmediateForOpcode(Op1C, OperatorClass)) {
1818 int immediate = Op1C->getRawValue() & 0xFFFF;
1820 if (OperatorClass < 2)
1821 BuildMI(*MBB, IP, ImmOpcodeTab[OperatorClass], 2,DestReg).addReg(Op0r)
1822 .addSImm(immediate);
1824 BuildMI(*MBB, IP, ImmOpcodeTab[OperatorClass], 2,DestReg).addReg(Op0r)
1825 .addZImm(immediate);
1827 unsigned Op1r = getReg(Op1, MBB, IP);
1828 BuildMI(*MBB, IP, OpcodeTab[OperatorClass], 2, DestReg).addReg(Op0r)
1834 // We couldn't generate an immediate variant of the op, load both halves into
1835 // registers and emit the appropriate opcode.
1836 unsigned Op0r = getReg(Op0, MBB, IP);
1837 unsigned Op1r = getReg(Op1, MBB, IP);
1839 unsigned Opcode = OpcodeTab[OperatorClass];
1840 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1844 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
1845 // returns zero when the input is not exactly a power of two.
1846 static unsigned ExactLog2(unsigned Val) {
1847 if (Val == 0 || (Val & (Val-1))) return 0;
1856 /// doMultiply - Emit appropriate instructions to multiply together the
1857 /// Values Op0 and Op1, and put the result in DestReg.
1859 void ISel::doMultiply(MachineBasicBlock *MBB,
1860 MachineBasicBlock::iterator IP,
1861 unsigned DestReg, Value *Op0, Value *Op1) {
1862 unsigned Class0 = getClass(Op0->getType());
1863 unsigned Class1 = getClass(Op1->getType());
1865 unsigned Op0r = getReg(Op0, MBB, IP);
1866 unsigned Op1r = getReg(Op1, MBB, IP);
1869 if (Class0 == cLong && Class1 == cLong) {
1870 BuildMI(*MBB, IP, PPC::MULLD, 2, DestReg).addReg(Op0r).addReg(Op1r);
1874 // 64 x 32 or less, promote 32 to 64 and do a 64 x 64
1875 if (Class0 == cLong && Class1 <= cInt) {
1876 // FIXME: CLEAR or SIGN EXTEND Op1
1877 BuildMI(*MBB, IP, PPC::MULLD, 2, DestReg).addReg(Op0r).addReg(Op1r);
1882 if (Class0 <= cInt && Class1 <= cInt) {
1883 BuildMI(*MBB, IP, PPC::MULLW, 2, DestReg).addReg(Op0r).addReg(Op1r);
1887 assert(0 && "doMultiply cannot operate on unknown type!");
1890 /// doMultiplyConst - This method will multiply the value in Op0 by the
1891 /// value of the ContantInt *CI
1892 void ISel::doMultiplyConst(MachineBasicBlock *MBB,
1893 MachineBasicBlock::iterator IP,
1894 unsigned DestReg, Value *Op0, ConstantInt *CI) {
1895 unsigned Class = getClass(Op0->getType());
1898 if (CI->isNullValue()) {
1899 BuildMI(*MBB, IP, PPC::LI, 1, DestReg).addSImm(0);
1903 // Mul op0, 1 ==> op0
1904 if (CI->equalsInt(1)) {
1905 unsigned Op0r = getReg(Op0, MBB, IP);
1906 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(Op0r).addReg(Op0r);
1910 // If the element size is exactly a power of 2, use a shift to get it.
1911 if (unsigned Shift = ExactLog2(CI->getRawValue())) {
1912 ConstantUInt *ShiftCI = ConstantUInt::get(Type::UByteTy, Shift);
1913 emitShiftOperation(MBB, IP, Op0, ShiftCI, true, Op0->getType(), DestReg);
1917 // If 32 bits or less and immediate is in right range, emit mul by immediate
1918 if (Class == cByte || Class == cShort || Class == cInt) {
1919 if (canUseAsImmediateForOpcode(CI, 0)) {
1920 unsigned Op0r = getReg(Op0, MBB, IP);
1921 unsigned imm = CI->getRawValue() & 0xFFFF;
1922 BuildMI(*MBB, IP, PPC::MULLI, 2, DestReg).addReg(Op0r).addSImm(imm);
1927 doMultiply(MBB, IP, DestReg, Op0, CI);
1930 void ISel::visitMul(BinaryOperator &I) {
1931 unsigned ResultReg = getReg(I);
1933 Value *Op0 = I.getOperand(0);
1934 Value *Op1 = I.getOperand(1);
1936 MachineBasicBlock::iterator IP = BB->end();
1937 emitMultiply(BB, IP, Op0, Op1, ResultReg);
1940 void ISel::emitMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
1941 Value *Op0, Value *Op1, unsigned DestReg) {
1942 TypeClass Class = getClass(Op0->getType());
1949 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1950 doMultiplyConst(MBB, IP, DestReg, Op0, CI);
1952 doMultiply(MBB, IP, DestReg, Op0, Op1);
1957 emitBinaryFPOperation(MBB, IP, Op0, Op1, 2, DestReg);
1964 /// visitDivRem - Handle division and remainder instructions... these
1965 /// instruction both require the same instructions to be generated, they just
1966 /// select the result from a different register. Note that both of these
1967 /// instructions work differently for signed and unsigned operands.
1969 void ISel::visitDivRem(BinaryOperator &I) {
1970 unsigned ResultReg = getReg(I);
1971 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1973 MachineBasicBlock::iterator IP = BB->end();
1974 emitDivRemOperation(BB, IP, Op0, Op1, I.getOpcode() == Instruction::Div,
1978 void ISel::emitDivRemOperation(MachineBasicBlock *BB,
1979 MachineBasicBlock::iterator IP,
1980 Value *Op0, Value *Op1, bool isDiv,
1981 unsigned ResultReg) {
1982 const Type *Ty = Op0->getType();
1983 unsigned Class = getClass(Ty);
1987 // Floating point divide...
1988 emitBinaryFPOperation(BB, IP, Op0, Op1, 3, ResultReg);
1991 // Floating point remainder via fmodf(float x, float y);
1992 unsigned Op0Reg = getReg(Op0, BB, IP);
1993 unsigned Op1Reg = getReg(Op1, BB, IP);
1994 MachineInstr *TheCall =
1995 BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(fmodfFn, true);
1996 std::vector<ValueRecord> Args;
1997 Args.push_back(ValueRecord(Op0Reg, Type::FloatTy));
1998 Args.push_back(ValueRecord(Op1Reg, Type::FloatTy));
1999 doCall(ValueRecord(ResultReg, Type::FloatTy), TheCall, Args, false);
2000 TM.CalledFunctions.insert(fmodfFn);
2005 // Floating point divide...
2006 emitBinaryFPOperation(BB, IP, Op0, Op1, 3, ResultReg);
2009 // Floating point remainder via fmod(double x, double y);
2010 unsigned Op0Reg = getReg(Op0, BB, IP);
2011 unsigned Op1Reg = getReg(Op1, BB, IP);
2012 MachineInstr *TheCall =
2013 BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(fmodFn, true);
2014 std::vector<ValueRecord> Args;
2015 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
2016 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
2017 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args, false);
2018 TM.CalledFunctions.insert(fmodFn);
2022 static Function* const Funcs[] =
2023 { __moddi3Fn, __divdi3Fn, __umoddi3Fn, __udivdi3Fn };
2024 unsigned Op0Reg = getReg(Op0, BB, IP);
2025 unsigned Op1Reg = getReg(Op1, BB, IP);
2026 unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
2027 MachineInstr *TheCall =
2028 BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(Funcs[NameIdx], true);
2030 std::vector<ValueRecord> Args;
2031 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
2032 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
2033 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args, false);
2034 TM.CalledFunctions.insert(Funcs[NameIdx]);
2037 case cByte: case cShort: case cInt:
2038 break; // Small integrals, handled below...
2039 default: assert(0 && "Unknown class!");
2042 // Special case signed division by power of 2.
2044 if (ConstantSInt *CI = dyn_cast<ConstantSInt>(Op1)) {
2045 assert(Class != cLong && "This doesn't handle 64-bit divides!");
2046 int V = CI->getValue();
2048 if (V == 1) { // X /s 1 => X
2049 unsigned Op0Reg = getReg(Op0, BB, IP);
2050 BuildMI(*BB, IP, PPC::OR, 2, ResultReg).addReg(Op0Reg).addReg(Op0Reg);
2054 if (V == -1) { // X /s -1 => -X
2055 unsigned Op0Reg = getReg(Op0, BB, IP);
2056 BuildMI(*BB, IP, PPC::NEG, 1, ResultReg).addReg(Op0Reg);
2060 unsigned log2V = ExactLog2(V);
2061 if (log2V != 0 && Ty->isSigned()) {
2062 unsigned Op0Reg = getReg(Op0, BB, IP);
2063 unsigned TmpReg = makeAnotherReg(Op0->getType());
2065 BuildMI(*BB, IP, PPC::SRAWI, 2, TmpReg).addReg(Op0Reg).addImm(log2V);
2066 BuildMI(*BB, IP, PPC::ADDZE, 1, ResultReg).addReg(TmpReg);
2071 unsigned Op0Reg = getReg(Op0, BB, IP);
2072 unsigned Op1Reg = getReg(Op1, BB, IP);
2073 unsigned Opcode = Ty->isSigned() ? PPC::DIVW : PPC::DIVWU;
2076 BuildMI(*BB, IP, Opcode, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
2077 } else { // Remainder
2078 unsigned TmpReg1 = makeAnotherReg(Op0->getType());
2079 unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2081 BuildMI(*BB, IP, Opcode, 2, TmpReg1).addReg(Op0Reg).addReg(Op1Reg);
2082 BuildMI(*BB, IP, PPC::MULLW, 2, TmpReg2).addReg(TmpReg1).addReg(Op1Reg);
2083 BuildMI(*BB, IP, PPC::SUBF, 2, ResultReg).addReg(TmpReg2).addReg(Op0Reg);
2088 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
2089 /// for constant immediate shift values, and for constant immediate
2090 /// shift values equal to 1. Even the general case is sort of special,
2091 /// because the shift amount has to be in CL, not just any old register.
2093 void ISel::visitShiftInst(ShiftInst &I) {
2094 MachineBasicBlock::iterator IP = BB->end();
2095 emitShiftOperation(BB, IP, I.getOperand(0), I.getOperand(1),
2096 I.getOpcode() == Instruction::Shl, I.getType(),
2100 /// emitShiftOperation - Common code shared between visitShiftInst and
2101 /// constant expression support.
2103 void ISel::emitShiftOperation(MachineBasicBlock *MBB,
2104 MachineBasicBlock::iterator IP,
2105 Value *Op, Value *ShiftAmount, bool isLeftShift,
2106 const Type *ResultTy, unsigned DestReg) {
2107 unsigned SrcReg = getReg (Op, MBB, IP);
2108 bool isSigned = ResultTy->isSigned ();
2109 unsigned Class = getClass (ResultTy);
2111 // Longs, as usual, are handled specially...
2112 if (Class == cLong) {
2113 // If we have a constant shift, we can generate much more efficient code
2114 // than otherwise...
2116 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2117 unsigned Amount = CUI->getValue();
2118 assert(Amount < 64 && "Invalid immediate shift amount!");
2120 BuildMI(*MBB, IP, PPC::RLDICR, 3, DestReg).addReg(SrcReg).addImm(Amount)
2124 BuildMI(*MBB, IP, PPC::SRADI, 2, DestReg).addReg(SrcReg)
2127 BuildMI(*MBB, IP, PPC::RLDICL, 3, DestReg).addReg(SrcReg)
2128 .addImm(64-Amount).addImm(Amount);
2132 unsigned ShiftReg = getReg (ShiftAmount, MBB, IP);
2135 BuildMI(*MBB, IP, PPC::SLD, 2, DestReg).addReg(SrcReg).addReg(ShiftReg);
2137 unsigned Opcode = (isSigned) ? PPC::SRAD : PPC::SRD;
2138 BuildMI(*MBB, IP, Opcode, DestReg).addReg(SrcReg).addReg(ShiftReg);
2144 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2145 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
2146 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
2147 unsigned Amount = CUI->getValue();
2150 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
2151 .addImm(Amount).addImm(0).addImm(31-Amount);
2154 BuildMI(*MBB, IP, PPC::SRAWI,2,DestReg).addReg(SrcReg).addImm(Amount);
2156 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
2157 .addImm(32-Amount).addImm(Amount).addImm(31);
2160 } else { // The shift amount is non-constant.
2161 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
2164 BuildMI(*MBB, IP, PPC::SLW, 2, DestReg).addReg(SrcReg)
2165 .addReg(ShiftAmountReg);
2167 BuildMI(*MBB, IP, isSigned ? PPC::SRAW : PPC::SRW, 2, DestReg)
2168 .addReg(SrcReg).addReg(ShiftAmountReg);
2174 /// visitLoadInst - Implement LLVM load instructions. Pretty straightforward
2175 /// mapping of LLVM classes to PPC load instructions, with the exception of
2176 /// signed byte loads, which need a sign extension following them.
2178 void ISel::visitLoadInst(LoadInst &I) {
2179 // Immediate opcodes, for reg+imm addressing
2180 static const unsigned ImmOpcodes[] = {
2181 PPC::LBZ, PPC::LHZ, PPC::LWZ,
2182 PPC::LFS, PPC::LFD, PPC::LWZ
2184 // Indexed opcodes, for reg+reg addressing
2185 static const unsigned IdxOpcodes[] = {
2186 PPC::LBZX, PPC::LHZX, PPC::LWZX,
2187 PPC::LFSX, PPC::LFDX, PPC::LWZX
2190 unsigned Class = getClassB(I.getType());
2191 unsigned ImmOpcode = ImmOpcodes[Class];
2192 unsigned IdxOpcode = IdxOpcodes[Class];
2193 unsigned DestReg = getReg(I);
2194 Value *SourceAddr = I.getOperand(0);
2196 if (Class == cShort && I.getType()->isSigned()) ImmOpcode = PPC::LHA;
2197 if (Class == cShort && I.getType()->isSigned()) IdxOpcode = PPC::LHAX;
2199 if (AllocaInst *AI = dyn_castFixedAlloca(SourceAddr)) {
2200 unsigned FI = getFixedSizedAllocaFI(AI);
2201 if (Class == cByte && I.getType()->isSigned()) {
2202 unsigned TmpReg = makeAnotherReg(I.getType());
2203 addFrameReference(BuildMI(BB, ImmOpcode, 2, TmpReg), FI);
2204 BuildMI(BB, PPC::EXTSB, 1, DestReg).addReg(TmpReg);
2206 addFrameReference(BuildMI(BB, ImmOpcode, 2, DestReg), FI);
2211 // If this load is the only use of the GEP instruction that is its address,
2212 // then we can fold the GEP directly into the load instruction.
2213 // emitGEPOperation with a second to last arg of 'true' will place the
2214 // base register for the GEP into baseReg, and the constant offset from that
2215 // into offset. If the offset fits in 16 bits, we can emit a reg+imm store
2216 // otherwise, we copy the offset into another reg, and use reg+reg addressing.
2217 if (GetElementPtrInst *GEPI = canFoldGEPIntoLoadOrStore(SourceAddr)) {
2218 unsigned baseReg = getReg(GEPI);
2219 unsigned pendingAdd;
2220 ConstantSInt *offset;
2222 emitGEPOperation(BB, BB->end(), GEPI->getOperand(0), GEPI->op_begin()+1,
2223 GEPI->op_end(), baseReg, true, &offset, &pendingAdd);
2225 if (pendingAdd == 0 && Class != cLong &&
2226 canUseAsImmediateForOpcode(offset, 0)) {
2227 if (Class == cByte && I.getType()->isSigned()) {
2228 unsigned TmpReg = makeAnotherReg(I.getType());
2229 BuildMI(BB, ImmOpcode, 2, TmpReg).addSImm(offset->getValue())
2231 BuildMI(BB, PPC::EXTSB, 1, DestReg).addReg(TmpReg);
2233 BuildMI(BB, ImmOpcode, 2, DestReg).addSImm(offset->getValue())
2239 unsigned indexReg = (pendingAdd != 0) ? pendingAdd : getReg(offset);
2241 if (Class == cByte && I.getType()->isSigned()) {
2242 unsigned TmpReg = makeAnotherReg(I.getType());
2243 BuildMI(BB, IdxOpcode, 2, TmpReg).addReg(indexReg).addReg(baseReg);
2244 BuildMI(BB, PPC::EXTSB, 1, DestReg).addReg(TmpReg);
2246 BuildMI(BB, IdxOpcode, 2, DestReg).addReg(indexReg).addReg(baseReg);
2251 // The fallback case, where the load was from a source that could not be
2252 // folded into the load instruction.
2253 unsigned SrcAddrReg = getReg(SourceAddr);
2255 if (Class == cByte && I.getType()->isSigned()) {
2256 unsigned TmpReg = makeAnotherReg(I.getType());
2257 BuildMI(BB, ImmOpcode, 2, TmpReg).addSImm(0).addReg(SrcAddrReg);
2258 BuildMI(BB, PPC::EXTSB, 1, DestReg).addReg(TmpReg);
2260 BuildMI(BB, ImmOpcode, 2, DestReg).addSImm(0).addReg(SrcAddrReg);
2264 /// visitStoreInst - Implement LLVM store instructions
2266 void ISel::visitStoreInst(StoreInst &I) {
2267 // Immediate opcodes, for reg+imm addressing
2268 static const unsigned ImmOpcodes[] = {
2269 PPC::STB, PPC::STH, PPC::STW,
2270 PPC::STFS, PPC::STFD, PPC::STW
2272 // Indexed opcodes, for reg+reg addressing
2273 static const unsigned IdxOpcodes[] = {
2274 PPC::STBX, PPC::STHX, PPC::STWX,
2275 PPC::STFSX, PPC::STFDX, PPC::STWX
2278 Value *SourceAddr = I.getOperand(1);
2279 const Type *ValTy = I.getOperand(0)->getType();
2280 unsigned Class = getClassB(ValTy);
2281 unsigned ImmOpcode = ImmOpcodes[Class];
2282 unsigned IdxOpcode = IdxOpcodes[Class];
2283 unsigned ValReg = getReg(I.getOperand(0));
2285 // If this store is the only use of the GEP instruction that is its address,
2286 // then we can fold the GEP directly into the store instruction.
2287 // emitGEPOperation with a second to last arg of 'true' will place the
2288 // base register for the GEP into baseReg, and the constant offset from that
2289 // into offset. If the offset fits in 16 bits, we can emit a reg+imm store
2290 // otherwise, we copy the offset into another reg, and use reg+reg addressing.
2291 if (GetElementPtrInst *GEPI = canFoldGEPIntoLoadOrStore(SourceAddr)) {
2292 unsigned baseReg = getReg(GEPI);
2293 unsigned pendingAdd;
2294 ConstantSInt *offset;
2296 emitGEPOperation(BB, BB->end(), GEPI->getOperand(0), GEPI->op_begin()+1,
2297 GEPI->op_end(), baseReg, true, &offset, &pendingAdd);
2299 if (0 == pendingAdd && Class != cLong &&
2300 canUseAsImmediateForOpcode(offset, 0)) {
2301 BuildMI(BB, ImmOpcode, 3).addReg(ValReg).addSImm(offset->getValue())
2306 unsigned indexReg = (pendingAdd != 0) ? pendingAdd : getReg(offset);
2307 BuildMI(BB, IdxOpcode, 3).addReg(ValReg).addReg(indexReg).addReg(baseReg);
2311 // If the store address wasn't the only use of a GEP, we fall back to the
2312 // standard path: store the ValReg at the value in AddressReg.
2313 unsigned AddressReg = getReg(I.getOperand(1));
2314 BuildMI(BB, ImmOpcode, 3).addReg(ValReg).addSImm(0).addReg(AddressReg);
2318 /// visitCastInst - Here we have various kinds of copying with or without sign
2319 /// extension going on.
2321 void ISel::visitCastInst(CastInst &CI) {
2322 Value *Op = CI.getOperand(0);
2324 unsigned SrcClass = getClassB(Op->getType());
2325 unsigned DestClass = getClassB(CI.getType());
2327 // If this is a cast from a 32-bit integer to a Long type, and the only uses
2328 // of the case are GEP instructions, then the cast does not need to be
2329 // generated explicitly, it will be folded into the GEP.
2330 if (DestClass == cLong && SrcClass == cInt) {
2331 bool AllUsesAreGEPs = true;
2332 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
2333 if (!isa<GetElementPtrInst>(*I)) {
2334 AllUsesAreGEPs = false;
2338 // No need to codegen this cast if all users are getelementptr instrs...
2339 if (AllUsesAreGEPs) return;
2342 unsigned DestReg = getReg(CI);
2343 MachineBasicBlock::iterator MI = BB->end();
2344 emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
2347 /// emitCastOperation - Common code shared between visitCastInst and constant
2348 /// expression cast support.
2350 void ISel::emitCastOperation(MachineBasicBlock *MBB,
2351 MachineBasicBlock::iterator IP,
2352 Value *Src, const Type *DestTy,
2354 const Type *SrcTy = Src->getType();
2355 unsigned SrcClass = getClassB(SrcTy);
2356 unsigned DestClass = getClassB(DestTy);
2357 unsigned SrcReg = getReg(Src, MBB, IP);
2359 // Implement casts to bool by using compare on the operand followed by set if
2360 // not zero on the result.
2361 if (DestTy == Type::BoolTy) {
2367 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2368 BuildMI(*MBB, IP, PPC::ADDIC, 2, TmpReg).addReg(SrcReg).addSImm(-1);
2369 BuildMI(*MBB, IP, PPC::SUBFE, 2, DestReg).addReg(TmpReg).addReg(SrcReg);
2375 std::cerr << "ERROR: Cast fp-to-bool not implemented!\n";
2381 // Handle cast of Float -> Double
2382 if (SrcClass == cFP32 && DestClass == cFP64) {
2383 BuildMI(*MBB, IP, PPC::FMR, 1, DestReg).addReg(SrcReg);
2387 // Handle cast of Double -> Float
2388 if (SrcClass == cFP64 && DestClass == cFP32) {
2389 BuildMI(*MBB, IP, PPC::FRSP, 1, DestReg).addReg(SrcReg);
2393 // Handle casts from integer to floating point now...
2394 if (DestClass == cFP32 || DestClass == cFP64) {
2396 // Emit a library call for long to float conversion
2397 if (SrcClass == cLong) {
2398 std::vector<ValueRecord> Args;
2399 Args.push_back(ValueRecord(SrcReg, SrcTy));
2400 Function *floatFn = (DestClass == cFP32) ? __floatdisfFn : __floatdidfFn;
2401 MachineInstr *TheCall =
2402 BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(floatFn, true);
2403 doCall(ValueRecord(DestReg, DestTy), TheCall, Args, false);
2404 TM.CalledFunctions.insert(floatFn);
2408 // Make sure we're dealing with a full 32 bits
2409 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2410 promote32(TmpReg, ValueRecord(SrcReg, SrcTy));
2414 // Spill the integer to memory and reload it from there.
2415 // Also spill room for a special conversion constant
2416 int ConstantFrameIndex =
2417 F->getFrameInfo()->CreateStackObject(Type::DoubleTy, TM.getTargetData());
2419 F->getFrameInfo()->CreateStackObject(Type::DoubleTy, TM.getTargetData());
2421 unsigned constantHi = makeAnotherReg(Type::IntTy);
2422 unsigned constantLo = makeAnotherReg(Type::IntTy);
2423 unsigned ConstF = makeAnotherReg(Type::DoubleTy);
2424 unsigned TempF = makeAnotherReg(Type::DoubleTy);
2426 if (!SrcTy->isSigned()) {
2427 BuildMI(*BB, IP, PPC::LIS, 1, constantHi).addSImm(0x4330);
2428 BuildMI(*BB, IP, PPC::LI, 1, constantLo).addSImm(0);
2429 addFrameReference(BuildMI(*BB, IP, PPC::STW, 3).addReg(constantHi),
2430 ConstantFrameIndex);
2431 addFrameReference(BuildMI(*BB, IP, PPC::STW, 3).addReg(constantLo),
2432 ConstantFrameIndex, 4);
2433 addFrameReference(BuildMI(*BB, IP, PPC::STW, 3).addReg(constantHi),
2435 addFrameReference(BuildMI(*BB, IP, PPC::STW, 3).addReg(SrcReg),
2437 addFrameReference(BuildMI(*BB, IP, PPC::LFD, 2, ConstF),
2438 ConstantFrameIndex);
2439 addFrameReference(BuildMI(*BB, IP, PPC::LFD, 2, TempF), ValueFrameIdx);
2440 BuildMI(*BB, IP, PPC::FSUB, 2, DestReg).addReg(TempF).addReg(ConstF);
2442 unsigned TempLo = makeAnotherReg(Type::IntTy);
2443 BuildMI(*BB, IP, PPC::LIS, 1, constantHi).addSImm(0x4330);
2444 BuildMI(*BB, IP, PPC::LIS, 1, constantLo).addSImm(0x8000);
2445 addFrameReference(BuildMI(*BB, IP, PPC::STW, 3).addReg(constantHi),
2446 ConstantFrameIndex);
2447 addFrameReference(BuildMI(*BB, IP, PPC::STW, 3).addReg(constantLo),
2448 ConstantFrameIndex, 4);
2449 addFrameReference(BuildMI(*BB, IP, PPC::STW, 3).addReg(constantHi),
2451 BuildMI(*BB, IP, PPC::XORIS, 2, TempLo).addReg(SrcReg).addImm(0x8000);
2452 addFrameReference(BuildMI(*BB, IP, PPC::STW, 3).addReg(TempLo),
2454 addFrameReference(BuildMI(*BB, IP, PPC::LFD, 2, ConstF),
2455 ConstantFrameIndex);
2456 addFrameReference(BuildMI(*BB, IP, PPC::LFD, 2, TempF), ValueFrameIdx);
2457 BuildMI(*BB, IP, PPC::FSUB, 2, DestReg).addReg(TempF).addReg(ConstF);
2462 // Handle casts from floating point to integer now...
2463 if (SrcClass == cFP32 || SrcClass == cFP64) {
2464 static Function* const Funcs[] =
2465 { __fixsfdiFn, __fixdfdiFn, __fixunssfdiFn, __fixunsdfdiFn };
2466 // emit library call
2467 if (DestClass == cLong) {
2468 bool isDouble = SrcClass == cFP64;
2469 unsigned nameIndex = 2 * DestTy->isSigned() + isDouble;
2470 std::vector<ValueRecord> Args;
2471 Args.push_back(ValueRecord(SrcReg, SrcTy));
2472 Function *floatFn = Funcs[nameIndex];
2473 MachineInstr *TheCall =
2474 BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(floatFn, true);
2475 doCall(ValueRecord(DestReg, DestTy), TheCall, Args, false);
2476 TM.CalledFunctions.insert(floatFn);
2481 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
2483 if (DestTy->isSigned()) {
2484 unsigned TempReg = makeAnotherReg(Type::DoubleTy);
2486 // Convert to integer in the FP reg and store it to a stack slot
2487 BuildMI(*BB, IP, PPC::FCTIWZ, 1, TempReg).addReg(SrcReg);
2488 addFrameReference(BuildMI(*BB, IP, PPC::STFD, 3)
2489 .addReg(TempReg), ValueFrameIdx);
2491 // There is no load signed byte opcode, so we must emit a sign extend for
2492 // that particular size. Make sure to source the new integer from the
2494 if (DestClass == cByte) {
2495 unsigned TempReg2 = makeAnotherReg(DestTy);
2496 addFrameReference(BuildMI(*BB, IP, PPC::LBZ, 2, TempReg2),
2498 BuildMI(*MBB, IP, PPC::EXTSB, DestReg).addReg(TempReg2);
2500 int offset = (DestClass == cShort) ? 6 : 4;
2501 unsigned LoadOp = (DestClass == cShort) ? PPC::LHA : PPC::LWZ;
2502 addFrameReference(BuildMI(*BB, IP, LoadOp, 2, DestReg),
2503 ValueFrameIdx, offset);
2506 unsigned Zero = getReg(ConstantFP::get(Type::DoubleTy, 0.0f));
2507 double maxInt = (1LL << 32) - 1;
2508 unsigned MaxInt = getReg(ConstantFP::get(Type::DoubleTy, maxInt));
2509 double border = 1LL << 31;
2510 unsigned Border = getReg(ConstantFP::get(Type::DoubleTy, border));
2511 unsigned UseZero = makeAnotherReg(Type::DoubleTy);
2512 unsigned UseMaxInt = makeAnotherReg(Type::DoubleTy);
2513 unsigned UseChoice = makeAnotherReg(Type::DoubleTy);
2514 unsigned TmpReg = makeAnotherReg(Type::DoubleTy);
2515 unsigned TmpReg2 = makeAnotherReg(Type::DoubleTy);
2516 unsigned ConvReg = makeAnotherReg(Type::DoubleTy);
2517 unsigned IntTmp = makeAnotherReg(Type::IntTy);
2518 unsigned XorReg = makeAnotherReg(Type::IntTy);
2520 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
2521 // Update machine-CFG edges
2522 MachineBasicBlock *XorMBB = new MachineBasicBlock(BB->getBasicBlock());
2523 MachineBasicBlock *PhiMBB = new MachineBasicBlock(BB->getBasicBlock());
2524 MachineBasicBlock *OldMBB = BB;
2525 ilist<MachineBasicBlock>::iterator It = BB; ++It;
2526 F->getBasicBlockList().insert(It, XorMBB);
2527 F->getBasicBlockList().insert(It, PhiMBB);
2528 BB->addSuccessor(XorMBB);
2529 BB->addSuccessor(PhiMBB);
2531 // Convert from floating point to unsigned 32-bit value
2532 // Use 0 if incoming value is < 0.0
2533 BuildMI(*BB, IP, PPC::FSEL, 3, UseZero).addReg(SrcReg).addReg(SrcReg)
2535 // Use 2**32 - 1 if incoming value is >= 2**32
2536 BuildMI(*BB, IP, PPC::FSUB, 2, UseMaxInt).addReg(MaxInt).addReg(SrcReg);
2537 BuildMI(*BB, IP, PPC::FSEL, 3, UseChoice).addReg(UseMaxInt)
2538 .addReg(UseZero).addReg(MaxInt);
2540 BuildMI(*BB, IP, PPC::FSUB, 2, TmpReg).addReg(UseChoice).addReg(Border);
2541 // Use difference if >= 2**31
2542 BuildMI(*BB, IP, PPC::FCMPU, 2, PPC::CR0).addReg(UseChoice)
2544 BuildMI(*BB, IP, PPC::FSEL, 3, TmpReg2).addReg(TmpReg).addReg(TmpReg)
2546 // Convert to integer
2547 BuildMI(*BB, IP, PPC::FCTIWZ, 1, ConvReg).addReg(TmpReg2);
2548 addFrameReference(BuildMI(*BB, IP, PPC::STFD, 3).addReg(ConvReg),
2550 if (DestClass == cByte) {
2551 addFrameReference(BuildMI(*BB, IP, PPC::LBZ, 2, DestReg),
2553 } else if (DestClass == cShort) {
2554 addFrameReference(BuildMI(*BB, IP, PPC::LHZ, 2, DestReg),
2556 } if (DestClass == cInt) {
2557 addFrameReference(BuildMI(*BB, IP, PPC::LWZ, 2, IntTmp),
2559 BuildMI(*BB, IP, PPC::BLT, 2).addReg(PPC::CR0).addMBB(PhiMBB);
2560 BuildMI(*BB, IP, PPC::B, 1).addMBB(XorMBB);
2563 // add 2**31 if input was >= 2**31
2565 BuildMI(BB, PPC::XORIS, 2, XorReg).addReg(IntTmp).addImm(0x8000);
2566 XorMBB->addSuccessor(PhiMBB);
2569 // DestReg = phi [ IntTmp, OldMBB ], [ XorReg, XorMBB ]
2571 BuildMI(BB, PPC::PHI, 2, DestReg).addReg(IntTmp).addMBB(OldMBB)
2572 .addReg(XorReg).addMBB(XorMBB);
2578 // Check our invariants
2579 assert((SrcClass <= cInt || SrcClass == cLong) &&
2580 "Unhandled source class for cast operation!");
2581 assert((DestClass <= cInt || DestClass == cLong) &&
2582 "Unhandled destination class for cast operation!");
2584 bool sourceUnsigned = SrcTy->isUnsigned() || SrcTy == Type::BoolTy;
2585 bool destUnsigned = DestTy->isUnsigned();
2587 // Unsigned -> Unsigned, clear if larger
2588 if (sourceUnsigned && destUnsigned) {
2589 // handle long dest class now to keep switch clean
2590 if (DestClass == cLong) {
2591 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2595 // handle u{ byte, short, int } x u{ byte, short, int }
2596 unsigned clearBits = (SrcClass == cByte || DestClass == cByte) ? 24 : 16;
2600 if (SrcClass == DestClass)
2601 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2603 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
2604 .addImm(0).addImm(clearBits).addImm(31);
2610 if (DestClass == cInt)
2611 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2613 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
2614 .addImm(0).addImm(clearBits).addImm(31);
2621 if (!sourceUnsigned && !destUnsigned) {
2622 // handle long dest class now to keep switch clean
2623 if (DestClass == cLong) {
2624 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2628 // handle { byte, short, int } x { byte, short, int }
2631 if (DestClass == cByte)
2632 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2634 BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
2637 if (DestClass == cByte)
2638 BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
2639 else if (DestClass == cShort)
2640 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2642 BuildMI(*MBB, IP, PPC::EXTSH, 1, DestReg).addReg(SrcReg);
2648 if (DestClass == cByte)
2649 BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
2650 else if (DestClass == cShort)
2651 BuildMI(*MBB, IP, PPC::EXTSH, 1, DestReg).addReg(SrcReg);
2653 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2659 // Unsigned -> Signed
2660 if (sourceUnsigned && !destUnsigned) {
2661 // handle long dest class now to keep switch clean
2662 if (DestClass == cLong) {
2663 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2667 // handle u{ byte, short, int } -> { byte, short, int }
2670 if (DestClass == cByte)
2671 // uByte 255 -> signed byte == -1
2672 BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
2674 // uByte 255 -> signed short/int == 255
2675 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg).addImm(0)
2676 .addImm(24).addImm(31);
2679 if (DestClass == cByte)
2680 BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
2681 else if (DestClass == cShort)
2682 BuildMI(*MBB, IP, PPC::EXTSH, 1, DestReg).addReg(SrcReg);
2684 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg).addImm(0)
2685 .addImm(16).addImm(31);
2691 if (DestClass == cByte)
2692 BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
2693 else if (DestClass == cShort)
2694 BuildMI(*MBB, IP, PPC::EXTSH, 1, DestReg).addReg(SrcReg);
2696 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2702 // Signed -> Unsigned
2703 if (!sourceUnsigned && destUnsigned) {
2704 // handle long dest class now to keep switch clean
2705 if (DestClass == cLong) {
2706 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2710 // handle { byte, short, int } -> u{ byte, short, int }
2711 unsigned clearBits = (DestClass == cByte) ? 24 : 16;
2715 if (DestClass == cByte || DestClass == cShort)
2716 // sbyte -1 -> ubyte 0x000000FF
2717 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
2718 .addImm(0).addImm(clearBits).addImm(31);
2720 // sbyte -1 -> ubyte 0xFFFFFFFF
2721 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2727 if (DestClass == cInt)
2728 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2730 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
2731 .addImm(0).addImm(clearBits).addImm(31);
2737 // Anything we haven't handled already, we can't (yet) handle at all.
2738 std::cerr << "Unhandled cast from " << SrcTy->getDescription()
2739 << "to " << DestTy->getDescription() << '\n';
2743 /// visitVANextInst - Implement the va_next instruction...
2745 void ISel::visitVANextInst(VANextInst &I) {
2746 unsigned VAList = getReg(I.getOperand(0));
2747 unsigned DestReg = getReg(I);
2750 switch (I.getArgType()->getTypeID()) {
2753 assert(0 && "Error: bad type for va_next instruction!");
2755 case Type::PointerTyID:
2756 case Type::UIntTyID:
2760 case Type::ULongTyID:
2761 case Type::LongTyID:
2762 case Type::DoubleTyID:
2767 // Increment the VAList pointer...
2768 BuildMI(BB, PPC::ADDI, 2, DestReg).addReg(VAList).addSImm(Size);
2771 void ISel::visitVAArgInst(VAArgInst &I) {
2772 unsigned VAList = getReg(I.getOperand(0));
2773 unsigned DestReg = getReg(I);
2775 switch (I.getType()->getTypeID()) {
2778 assert(0 && "Error: bad type for va_next instruction!");
2780 case Type::PointerTyID:
2781 case Type::UIntTyID:
2783 BuildMI(BB, PPC::LWZ, 2, DestReg).addSImm(0).addReg(VAList);
2785 case Type::ULongTyID:
2786 case Type::LongTyID:
2787 BuildMI(BB, PPC::LD, 2, DestReg).addSImm(0).addReg(VAList);
2789 case Type::FloatTyID:
2790 BuildMI(BB, PPC::LFS, 2, DestReg).addSImm(0).addReg(VAList);
2792 case Type::DoubleTyID:
2793 BuildMI(BB, PPC::LFD, 2, DestReg).addSImm(0).addReg(VAList);
2798 /// visitGetElementPtrInst - instruction-select GEP instructions
2800 void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
2801 if (canFoldGEPIntoLoadOrStore(&I))
2804 unsigned outputReg = getReg(I);
2805 emitGEPOperation(BB, BB->end(), I.getOperand(0), I.op_begin()+1, I.op_end(),
2806 outputReg, false, 0, 0);
2809 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
2810 /// constant expression GEP support.
2812 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
2813 MachineBasicBlock::iterator IP,
2814 Value *Src, User::op_iterator IdxBegin,
2815 User::op_iterator IdxEnd, unsigned TargetReg,
2816 bool GEPIsFolded, ConstantSInt **RemainderPtr,
2817 unsigned *PendingAddReg) {
2818 const TargetData &TD = TM.getTargetData();
2819 const Type *Ty = Src->getType();
2820 unsigned basePtrReg = getReg(Src, MBB, IP);
2821 int64_t constValue = 0;
2823 // Record the operations to emit the GEP in a vector so that we can emit them
2824 // after having analyzed the entire instruction.
2825 std::vector<CollapsedGepOp> ops;
2827 // GEPs have zero or more indices; we must perform a struct access
2828 // or array access for each one.
2829 for (GetElementPtrInst::op_iterator oi = IdxBegin, oe = IdxEnd; oi != oe;
2832 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2833 // It's a struct access. idx is the index into the structure,
2834 // which names the field. Use the TargetData structure to
2835 // pick out what the layout of the structure is in memory.
2836 // Use the (constant) structure index's value to find the
2837 // right byte offset from the StructLayout class's list of
2838 // structure member offsets.
2839 unsigned fieldIndex = cast<ConstantUInt>(idx)->getValue();
2840 unsigned memberOffset =
2841 TD.getStructLayout(StTy)->MemberOffsets[fieldIndex];
2843 // StructType member offsets are always constant values. Add it to the
2845 constValue += memberOffset;
2847 // The next type is the member of the structure selected by the
2849 Ty = StTy->getElementType (fieldIndex);
2850 } else if (const SequentialType *SqTy = dyn_cast<SequentialType> (Ty)) {
2851 // Many GEP instructions use a [cast (int/uint) to LongTy] as their
2852 // operand. Handle this case directly now...
2853 if (CastInst *CI = dyn_cast<CastInst>(idx))
2854 if (CI->getOperand(0)->getType() == Type::IntTy ||
2855 CI->getOperand(0)->getType() == Type::UIntTy)
2856 idx = CI->getOperand(0);
2858 // It's an array or pointer access: [ArraySize x ElementType].
2859 // We want to add basePtrReg to (idxReg * sizeof ElementType). First, we
2860 // must find the size of the pointed-to type (Not coincidentally, the next
2861 // type is the type of the elements in the array).
2862 Ty = SqTy->getElementType();
2863 unsigned elementSize = TD.getTypeSize(Ty);
2865 if (ConstantInt *C = dyn_cast<ConstantInt>(idx)) {
2866 if (ConstantSInt *CS = dyn_cast<ConstantSInt>(C))
2867 constValue += CS->getValue() * elementSize;
2868 else if (ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2869 constValue += CU->getValue() * elementSize;
2871 assert(0 && "Invalid ConstantInt GEP index type!");
2873 // Push current gep state to this point as an add
2874 ops.push_back(CollapsedGepOp(false, 0,
2875 ConstantSInt::get(Type::IntTy,constValue)));
2877 // Push multiply gep op and reset constant value
2878 ops.push_back(CollapsedGepOp(true, idx,
2879 ConstantSInt::get(Type::IntTy, elementSize)));
2885 // Emit instructions for all the collapsed ops
2886 bool pendingAdd = false;
2887 unsigned pendingAddReg = 0;
2889 for(std::vector<CollapsedGepOp>::iterator cgo_i = ops.begin(),
2890 cgo_e = ops.end(); cgo_i != cgo_e; ++cgo_i) {
2891 CollapsedGepOp& cgo = *cgo_i;
2892 unsigned nextBasePtrReg = makeAnotherReg(Type::IntTy);
2894 // If we didn't emit an add last time through the loop, we need to now so
2895 // that the base reg is updated appropriately.
2897 assert(pendingAddReg != 0 && "Uninitialized register in pending add!");
2898 BuildMI(*MBB, IP, PPC::ADD, 2, nextBasePtrReg).addReg(basePtrReg)
2899 .addReg(pendingAddReg);
2900 basePtrReg = nextBasePtrReg;
2901 nextBasePtrReg = makeAnotherReg(Type::IntTy);
2907 // We know the elementSize is a constant, so we can emit a constant mul
2908 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2909 doMultiplyConst(MBB, IP, nextBasePtrReg, cgo.index, cgo.size);
2910 pendingAddReg = basePtrReg;
2913 // Try and generate an immediate addition if possible
2914 if (cgo.size->isNullValue()) {
2915 BuildMI(*MBB, IP, PPC::OR, 2, nextBasePtrReg).addReg(basePtrReg)
2916 .addReg(basePtrReg);
2917 } else if (canUseAsImmediateForOpcode(cgo.size, 0)) {
2918 BuildMI(*MBB, IP, PPC::ADDI, 2, nextBasePtrReg).addReg(basePtrReg)
2919 .addSImm(cgo.size->getValue());
2921 unsigned Op1r = getReg(cgo.size, MBB, IP);
2922 BuildMI(*MBB, IP, PPC::ADD, 2, nextBasePtrReg).addReg(basePtrReg)
2927 basePtrReg = nextBasePtrReg;
2929 // Add the current base register plus any accumulated constant value
2930 ConstantSInt *remainder = ConstantSInt::get(Type::IntTy, constValue);
2932 // If we are emitting this during a fold, copy the current base register to
2933 // the target, and save the current constant offset so the folding load or
2934 // store can try and use it as an immediate.
2936 // If this is a folded GEP and the last element was an index, then we need
2937 // to do some extra work to turn a shift/add/stw into a shift/stwx
2938 if (pendingAdd && 0 == remainder->getValue()) {
2939 assert(pendingAddReg != 0 && "Uninitialized register in pending add!");
2940 *PendingAddReg = pendingAddReg;
2944 unsigned nextBasePtrReg = makeAnotherReg(Type::IntTy);
2945 assert(pendingAddReg != 0 && "Uninitialized register in pending add!");
2946 BuildMI(*MBB, IP, PPC::ADD, 2, nextBasePtrReg).addReg(basePtrReg)
2947 .addReg(pendingAddReg);
2948 basePtrReg = nextBasePtrReg;
2951 BuildMI (*MBB, IP, PPC::OR, 2, TargetReg).addReg(basePtrReg)
2952 .addReg(basePtrReg);
2953 *RemainderPtr = remainder;
2957 // If we still have a pending add at this point, emit it now
2959 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2960 BuildMI(*MBB, IP, PPC::ADD, 2, TmpReg).addReg(pendingAddReg)
2961 .addReg(basePtrReg);
2962 basePtrReg = TmpReg;
2965 // After we have processed all the indices, the result is left in
2966 // basePtrReg. Move it to the register where we were expected to
2968 if (remainder->isNullValue()) {
2969 BuildMI (*MBB, IP, PPC::OR, 2, TargetReg).addReg(basePtrReg)
2970 .addReg(basePtrReg);
2971 } else if (canUseAsImmediateForOpcode(remainder, 0)) {
2972 BuildMI(*MBB, IP, PPC::ADDI, 2, TargetReg).addReg(basePtrReg)
2973 .addSImm(remainder->getValue());
2975 unsigned Op1r = getReg(remainder, MBB, IP);
2976 BuildMI(*MBB, IP, PPC::ADD, 2, TargetReg).addReg(basePtrReg).addReg(Op1r);
2980 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
2981 /// frame manager, otherwise do it the hard way.
2983 void ISel::visitAllocaInst(AllocaInst &I) {
2984 // If this is a fixed size alloca in the entry block for the function, we
2985 // statically stack allocate the space, so we don't need to do anything here.
2987 if (dyn_castFixedAlloca(&I)) return;
2989 // Find the data size of the alloca inst's getAllocatedType.
2990 const Type *Ty = I.getAllocatedType();
2991 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
2993 // Create a register to hold the temporary result of multiplying the type size
2994 // constant by the variable amount.
2995 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
2997 // TotalSizeReg = mul <numelements>, <TypeSize>
2998 MachineBasicBlock::iterator MBBI = BB->end();
2999 ConstantUInt *CUI = ConstantUInt::get(Type::UIntTy, TySize);
3000 doMultiplyConst(BB, MBBI, TotalSizeReg, I.getArraySize(), CUI);
3002 // AddedSize = add <TotalSizeReg>, 15
3003 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
3004 BuildMI(BB, PPC::ADDI, 2, AddedSizeReg).addReg(TotalSizeReg).addSImm(15);
3006 // AlignedSize = and <AddedSize>, ~15
3007 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
3008 BuildMI(BB, PPC::RLWINM, 4, AlignedSize).addReg(AddedSizeReg).addImm(0)
3009 .addImm(0).addImm(27);
3011 // Subtract size from stack pointer, thereby allocating some space.
3012 BuildMI(BB, PPC::SUB, 2, PPC::R1).addReg(PPC::R1).addReg(AlignedSize);
3014 // Put a pointer to the space into the result register, by copying
3015 // the stack pointer.
3016 BuildMI(BB, PPC::OR, 2, getReg(I)).addReg(PPC::R1).addReg(PPC::R1);
3018 // Inform the Frame Information that we have just allocated a variable-sized
3020 F->getFrameInfo()->CreateVariableSizedObject();
3023 /// visitMallocInst - Malloc instructions are code generated into direct calls
3024 /// to the library malloc.
3026 void ISel::visitMallocInst(MallocInst &I) {
3027 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
3030 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
3031 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
3033 Arg = makeAnotherReg(Type::UIntTy);
3034 MachineBasicBlock::iterator MBBI = BB->end();
3035 ConstantUInt *CUI = ConstantUInt::get(Type::UIntTy, AllocSize);
3036 doMultiplyConst(BB, MBBI, Arg, I.getOperand(0), CUI);
3039 std::vector<ValueRecord> Args;
3040 Args.push_back(ValueRecord(Arg, Type::UIntTy));
3041 MachineInstr *TheCall =
3042 BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(mallocFn, true);
3043 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args, false);
3044 TM.CalledFunctions.insert(mallocFn);
3048 /// visitFreeInst - Free instructions are code gen'd to call the free libc
3051 void ISel::visitFreeInst(FreeInst &I) {
3052 std::vector<ValueRecord> Args;
3053 Args.push_back(ValueRecord(I.getOperand(0)));
3054 MachineInstr *TheCall =
3055 BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(freeFn, true);
3056 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args, false);
3057 TM.CalledFunctions.insert(freeFn);
3060 /// createPPC64ISelSimple - This pass converts an LLVM function into a machine
3061 /// code representation is a very simple peep-hole fashion.
3063 FunctionPass *llvm::createPPC64ISelSimple(TargetMachine &TM) {
3064 return new ISel(TM);