1 //===-- InstSelectSimple.cpp - A simple instruction selector for PowerPC --===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #define DEBUG_TYPE "isel"
12 #include "PowerPCInstrBuilder.h"
13 #include "PowerPCInstrInfo.h"
14 #include "llvm/Constants.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/Function.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Pass.h"
19 #include "llvm/CodeGen/IntrinsicLowering.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/SSARegMap.h"
24 #include "llvm/Target/MRegisterInfo.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Support/GetElementPtrTypeIterator.h"
27 #include "llvm/Support/InstVisitor.h"
28 #include "Support/Debug.h"
34 /// TypeClass - Used by the PowerPC backend to group LLVM types by their basic
35 /// PPC Representation.
38 cByte, cShort, cInt, cFP32, cFP64, cLong
42 /// getClass - Turn a primitive type into a "class" number which is based on the
43 /// size of the type, and whether or not it is floating point.
45 static inline TypeClass getClass(const Type *Ty) {
46 switch (Ty->getTypeID()) {
48 case Type::UByteTyID: return cByte; // Byte operands are class #0
50 case Type::UShortTyID: return cShort; // Short operands are class #1
53 case Type::PointerTyID: return cInt; // Ints and pointers are class #2
55 case Type::FloatTyID: return cFP32; // Single float is #3
56 case Type::DoubleTyID: return cFP64; // Double Point is #4
59 case Type::ULongTyID: return cLong; // Longs are class #5
61 assert(0 && "Invalid type to getClass!");
62 return cByte; // not reached
66 // getClassB - Just like getClass, but treat boolean values as ints.
67 static inline TypeClass getClassB(const Type *Ty) {
68 if (Ty == Type::BoolTy) return cByte;
73 struct ISel : public FunctionPass, InstVisitor<ISel> {
75 MachineFunction *F; // The function we are compiling into
76 MachineBasicBlock *BB; // The current MBB we are compiling
77 int VarArgsFrameIndex; // FrameIndex for start of varargs area
79 std::map<Value*, unsigned> RegMap; // Mapping between Values and SSA Regs
81 // External functions used in the Module
82 Function *fmodfFn, *fmodFn, *__moddi3Fn, *__divdi3Fn, *__umoddi3Fn,
83 *__udivdi3Fn, *__fixsfdiFn, *__fixdfdiFn, *__floatdisfFn, *__floatdidfFn,
86 // MBBMap - Mapping between LLVM BB -> Machine BB
87 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
89 // AllocaMap - Mapping from fixed sized alloca instructions to the
90 // FrameIndex for the alloca.
91 std::map<AllocaInst*, unsigned> AllocaMap;
93 ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
95 bool doInitialization(Module &M) {
96 // Add external functions that we may call
97 Type *d = Type::DoubleTy;
98 Type *f = Type::FloatTy;
99 Type *l = Type::LongTy;
100 Type *ul = Type::ULongTy;
101 Type *voidPtr = PointerType::get(Type::SByteTy);
102 // float fmodf(float, float);
103 fmodfFn = M.getOrInsertFunction("fmodf", f, f, f, 0);
104 // double fmod(double, double);
105 fmodFn = M.getOrInsertFunction("fmod", d, d, d, 0);
106 // long __moddi3(long, long);
107 __moddi3Fn = M.getOrInsertFunction("__moddi3", l, l, l, 0);
108 // long __divdi3(long, long);
109 __divdi3Fn = M.getOrInsertFunction("__divdi3", l, l, l, 0);
110 // unsigned long __umoddi3(unsigned long, unsigned long);
111 __umoddi3Fn = M.getOrInsertFunction("__umoddi3", ul, ul, ul, 0);
112 // unsigned long __udivdi3(unsigned long, unsigned long);
113 __udivdi3Fn = M.getOrInsertFunction("__udivdi3", ul, ul, ul, 0);
114 // long __fixsfdi(float)
115 __fixdfdiFn = M.getOrInsertFunction("__fixsfdi", l, f, 0);
116 // long __fixdfdi(double)
117 __fixdfdiFn = M.getOrInsertFunction("__fixdfdi", l, d, 0);
118 // float __floatdisf(long)
119 __floatdisfFn = M.getOrInsertFunction("__floatdisf", f, l, 0);
120 // double __floatdidf(long)
121 __floatdidfFn = M.getOrInsertFunction("__floatdidf", d, l, 0);
122 // void* malloc(size_t)
123 mallocFn = M.getOrInsertFunction("malloc", voidPtr, Type::UIntTy, 0);
125 freeFn = M.getOrInsertFunction("free", Type::VoidTy, voidPtr, 0);
129 /// runOnFunction - Top level implementation of instruction selection for
130 /// the entire function.
132 bool runOnFunction(Function &Fn) {
133 // First pass over the function, lower any unknown intrinsic functions
134 // with the IntrinsicLowering class.
135 LowerUnknownIntrinsicFunctionCalls(Fn);
137 F = &MachineFunction::construct(&Fn, TM);
139 // Create all of the machine basic blocks for the function...
140 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
141 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
145 // Copy incoming arguments off of the stack...
146 LoadArgumentsToVirtualRegs(Fn);
148 // Instruction select everything except PHI nodes
151 // Select the PHI nodes
158 // We always build a machine code representation for the function
162 virtual const char *getPassName() const {
163 return "PowerPC Simple Instruction Selection";
166 /// visitBasicBlock - This method is called when we are visiting a new basic
167 /// block. This simply creates a new MachineBasicBlock to emit code into
168 /// and adds it to the current MachineFunction. Subsequent visit* for
169 /// instructions will be invoked for all instructions in the basic block.
171 void visitBasicBlock(BasicBlock &LLVM_BB) {
172 BB = MBBMap[&LLVM_BB];
175 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
176 /// function, lowering any calls to unknown intrinsic functions into the
177 /// equivalent LLVM code.
179 void LowerUnknownIntrinsicFunctionCalls(Function &F);
181 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
182 /// from the stack into virtual registers.
184 void LoadArgumentsToVirtualRegs(Function &F);
186 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
187 /// because we have to generate our sources into the source basic blocks,
188 /// not the current one.
190 void SelectPHINodes();
192 // Visitation methods for various instructions. These methods simply emit
193 // fixed PowerPC code for each instruction.
195 // Control flow operators
196 void visitReturnInst(ReturnInst &RI);
197 void visitBranchInst(BranchInst &BI);
203 ValueRecord(unsigned R, const Type *T) : Val(0), Reg(R), Ty(T) {}
204 ValueRecord(Value *V) : Val(V), Reg(0), Ty(V->getType()) {}
206 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
207 const std::vector<ValueRecord> &Args, bool isVarArg);
208 void visitCallInst(CallInst &I);
209 void visitIntrinsicCall(Intrinsic::ID ID, CallInst &I);
211 // Arithmetic operators
212 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
213 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
214 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
215 void visitMul(BinaryOperator &B);
217 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
218 void visitRem(BinaryOperator &B) { visitDivRem(B); }
219 void visitDivRem(BinaryOperator &B);
222 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
223 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
224 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
226 // Comparison operators...
227 void visitSetCondInst(SetCondInst &I);
228 unsigned EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
229 MachineBasicBlock *MBB,
230 MachineBasicBlock::iterator MBBI);
231 void visitSelectInst(SelectInst &SI);
234 // Memory Instructions
235 void visitLoadInst(LoadInst &I);
236 void visitStoreInst(StoreInst &I);
237 void visitGetElementPtrInst(GetElementPtrInst &I);
238 void visitAllocaInst(AllocaInst &I);
239 void visitMallocInst(MallocInst &I);
240 void visitFreeInst(FreeInst &I);
243 void visitShiftInst(ShiftInst &I);
244 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
245 void visitCastInst(CastInst &I);
246 void visitVANextInst(VANextInst &I);
247 void visitVAArgInst(VAArgInst &I);
249 void visitInstruction(Instruction &I) {
250 std::cerr << "Cannot instruction select: " << I;
254 /// promote32 - Make a value 32-bits wide, and put it somewhere.
256 void promote32(unsigned targetReg, const ValueRecord &VR);
258 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
259 /// constant expression GEP support.
261 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
262 Value *Src, User::op_iterator IdxBegin,
263 User::op_iterator IdxEnd, unsigned TargetReg);
265 /// emitCastOperation - Common code shared between visitCastInst and
266 /// constant expression cast support.
268 void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
269 Value *Src, const Type *DestTy, unsigned TargetReg);
271 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
272 /// and constant expression support.
274 void emitSimpleBinaryOperation(MachineBasicBlock *BB,
275 MachineBasicBlock::iterator IP,
276 Value *Op0, Value *Op1,
277 unsigned OperatorClass, unsigned TargetReg);
279 /// emitBinaryFPOperation - This method handles emission of floating point
280 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
281 void emitBinaryFPOperation(MachineBasicBlock *BB,
282 MachineBasicBlock::iterator IP,
283 Value *Op0, Value *Op1,
284 unsigned OperatorClass, unsigned TargetReg);
286 void emitMultiply(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
287 Value *Op0, Value *Op1, unsigned TargetReg);
289 void doMultiply(MachineBasicBlock *MBB,
290 MachineBasicBlock::iterator IP,
291 unsigned DestReg, Value *Op0, Value *Op1);
293 /// doMultiplyConst - This method will multiply the value in Op0Reg by the
294 /// value of the ContantInt *CI
295 void doMultiplyConst(MachineBasicBlock *MBB,
296 MachineBasicBlock::iterator IP,
297 unsigned DestReg, Value *Op0, ConstantInt *CI);
299 void emitDivRemOperation(MachineBasicBlock *BB,
300 MachineBasicBlock::iterator IP,
301 Value *Op0, Value *Op1, bool isDiv,
304 /// emitSetCCOperation - Common code shared between visitSetCondInst and
305 /// constant expression support.
307 void emitSetCCOperation(MachineBasicBlock *BB,
308 MachineBasicBlock::iterator IP,
309 Value *Op0, Value *Op1, unsigned Opcode,
312 /// emitShiftOperation - Common code shared between visitShiftInst and
313 /// constant expression support.
315 void emitShiftOperation(MachineBasicBlock *MBB,
316 MachineBasicBlock::iterator IP,
317 Value *Op, Value *ShiftAmount, bool isLeftShift,
318 const Type *ResultTy, unsigned DestReg);
320 /// emitSelectOperation - Common code shared between visitSelectInst and the
321 /// constant expression support.
322 void emitSelectOperation(MachineBasicBlock *MBB,
323 MachineBasicBlock::iterator IP,
324 Value *Cond, Value *TrueVal, Value *FalseVal,
327 /// copyConstantToRegister - Output the instructions required to put the
328 /// specified constant into the specified register.
330 void copyConstantToRegister(MachineBasicBlock *MBB,
331 MachineBasicBlock::iterator MBBI,
332 Constant *C, unsigned Reg);
334 void emitUCOM(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
335 unsigned LHS, unsigned RHS);
337 /// makeAnotherReg - This method returns the next register number we haven't
340 /// Long values are handled somewhat specially. They are always allocated
341 /// as pairs of 32 bit integer values. The register number returned is the
342 /// high 32 bits of the long value, and the regNum+1 is the low 32 bits.
344 unsigned makeAnotherReg(const Type *Ty) {
345 assert(dynamic_cast<const PowerPCRegisterInfo*>(TM.getRegisterInfo()) &&
346 "Current target doesn't have PPC reg info??");
347 const PowerPCRegisterInfo *MRI =
348 static_cast<const PowerPCRegisterInfo*>(TM.getRegisterInfo());
349 if (Ty == Type::LongTy || Ty == Type::ULongTy) {
350 const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
351 // Create the lower part
352 F->getSSARegMap()->createVirtualRegister(RC);
353 // Create the upper part.
354 return F->getSSARegMap()->createVirtualRegister(RC)-1;
357 // Add the mapping of regnumber => reg class to MachineFunction
358 const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
359 return F->getSSARegMap()->createVirtualRegister(RC);
362 /// getReg - This method turns an LLVM value into a register number.
364 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
365 unsigned getReg(Value *V) {
366 // Just append to the end of the current bb.
367 MachineBasicBlock::iterator It = BB->end();
368 return getReg(V, BB, It);
370 unsigned getReg(Value *V, MachineBasicBlock *MBB,
371 MachineBasicBlock::iterator IPt);
373 /// canUseAsImmediateForOpcode - This method returns whether a ConstantInt
374 /// is okay to use as an immediate argument to a certain binary operation
375 bool canUseAsImmediateForOpcode(ConstantInt *CI, unsigned Opcode);
377 /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
378 /// that is to be statically allocated with the initial stack frame
380 unsigned getFixedSizedAllocaFI(AllocaInst *AI);
384 /// dyn_castFixedAlloca - If the specified value is a fixed size alloca
385 /// instruction in the entry block, return it. Otherwise, return a null
387 static AllocaInst *dyn_castFixedAlloca(Value *V) {
388 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
389 BasicBlock *BB = AI->getParent();
390 if (isa<ConstantUInt>(AI->getArraySize()) && BB ==&BB->getParent()->front())
396 /// getReg - This method turns an LLVM value into a register number.
398 unsigned ISel::getReg(Value *V, MachineBasicBlock *MBB,
399 MachineBasicBlock::iterator IPt) {
400 if (Constant *C = dyn_cast<Constant>(V)) {
401 unsigned Reg = makeAnotherReg(V->getType());
402 copyConstantToRegister(MBB, IPt, C, Reg);
404 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
405 // Do not emit noop casts at all.
406 if (getClassB(CI->getType()) == getClassB(CI->getOperand(0)->getType()))
407 return getReg(CI->getOperand(0), MBB, IPt);
408 } else if (AllocaInst *AI = dyn_castFixedAlloca(V)) {
409 unsigned Reg = makeAnotherReg(V->getType());
410 unsigned FI = getFixedSizedAllocaFI(AI);
411 addFrameReference(BuildMI(*MBB, IPt, PPC32::ADDI, 2, Reg), FI, 0, false);
415 unsigned &Reg = RegMap[V];
417 Reg = makeAnotherReg(V->getType());
424 /// canUseAsImmediateForOpcode - This method returns whether a ConstantInt
425 /// is okay to use as an immediate argument to a certain binary operator.
427 /// Operator is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for Xor.
428 bool ISel::canUseAsImmediateForOpcode(ConstantInt *CI, unsigned Operator)
433 // ADDI, Compare, and non-indexed Load take SIMM
434 bool cond1 = (Operator == 0)
435 && (Op1Cs = dyn_cast<ConstantSInt>(CI))
436 && (Op1Cs->getValue() <= 32767)
437 && (Op1Cs->getValue() >= -32768);
439 // SUBI takes -SIMM since it is a mnemonic for ADDI
440 bool cond2 = (Operator == 1)
441 && (Op1Cs = dyn_cast<ConstantSInt>(CI))
442 && (Op1Cs->getValue() <= 32768)
443 && (Op1Cs->getValue() >= -32767);
445 // ANDIo, ORI, and XORI take unsigned values
446 bool cond3 = (Operator >= 2)
447 && (Op1Cs = dyn_cast<ConstantSInt>(CI))
448 && (Op1Cs->getValue() >= 0)
449 && (Op1Cs->getValue() <= 32767);
451 // ADDI and SUBI take SIMMs, so we have to make sure the UInt would fit
452 bool cond4 = (Operator < 2)
453 && (Op1Cu = dyn_cast<ConstantUInt>(CI))
454 && (Op1Cu->getValue() <= 32767);
456 // ANDIo, ORI, and XORI take UIMMs, so they can be larger
457 bool cond5 = (Operator >= 2)
458 && (Op1Cu = dyn_cast<ConstantUInt>(CI))
459 && (Op1Cu->getValue() <= 65535);
461 if (cond1 || cond2 || cond3 || cond4 || cond5)
467 /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
468 /// that is to be statically allocated with the initial stack frame
470 unsigned ISel::getFixedSizedAllocaFI(AllocaInst *AI) {
471 // Already computed this?
472 std::map<AllocaInst*, unsigned>::iterator I = AllocaMap.lower_bound(AI);
473 if (I != AllocaMap.end() && I->first == AI) return I->second;
475 const Type *Ty = AI->getAllocatedType();
476 ConstantUInt *CUI = cast<ConstantUInt>(AI->getArraySize());
477 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
478 TySize *= CUI->getValue(); // Get total allocated size...
479 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
481 // Create a new stack object using the frame manager...
482 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
483 AllocaMap.insert(I, std::make_pair(AI, FrameIdx));
488 /// copyConstantToRegister - Output the instructions required to put the
489 /// specified constant into the specified register.
491 void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
492 MachineBasicBlock::iterator IP,
493 Constant *C, unsigned R) {
494 if (C->getType()->isIntegral()) {
495 unsigned Class = getClassB(C->getType());
497 if (Class == cLong) {
498 // Copy the value into the register pair.
499 uint64_t Val = cast<ConstantInt>(C)->getRawValue();
501 if (Val < (1ULL << 16)) {
502 BuildMI(*MBB, IP, PPC32::LI, 1, R).addSImm(0);
503 BuildMI(*MBB, IP, PPC32::LI, 1, R+1).addSImm(Val & 0xFFFF);
504 } else if (Val < (1ULL << 32)) {
505 unsigned Temp = makeAnotherReg(Type::IntTy);
506 BuildMI(*MBB, IP, PPC32::LI, 1, R).addSImm(0);
507 BuildMI(*MBB, IP, PPC32::LIS, 1, Temp).addSImm((Val >> 16) & 0xFFFF);
508 BuildMI(*MBB, IP, PPC32::ORI, 2, R+1).addReg(Temp).addImm(Val & 0xFFFF);
509 } else if (Val < (1ULL << 48)) {
510 unsigned Temp = makeAnotherReg(Type::IntTy);
511 BuildMI(*MBB, IP, PPC32::LI, 1, R).addSImm((Val >> 32) & 0xFFFF);
512 BuildMI(*MBB, IP, PPC32::LIS, 1, Temp).addSImm((Val >> 16) & 0xFFFF);
513 BuildMI(*MBB, IP, PPC32::ORI, 2, R+1).addReg(Temp).addImm(Val & 0xFFFF);
515 unsigned TempLo = makeAnotherReg(Type::IntTy);
516 unsigned TempHi = makeAnotherReg(Type::IntTy);
517 BuildMI(*MBB, IP, PPC32::LIS, 1, TempHi).addSImm((Val >> 48) & 0xFFFF);
518 BuildMI(*MBB, IP, PPC32::ORI, 2, R).addReg(TempHi)
519 .addImm((Val >> 32) & 0xFFFF);
520 BuildMI(*MBB, IP, PPC32::LIS, 1, TempLo).addSImm((Val >> 16) & 0xFFFF);
521 BuildMI(*MBB, IP, PPC32::ORI, 2, R+1).addReg(TempLo)
522 .addImm(Val & 0xFFFF);
527 assert(Class <= cInt && "Type not handled yet!");
529 if (C->getType() == Type::BoolTy) {
530 BuildMI(*MBB, IP, PPC32::LI, 1, R).addSImm(C == ConstantBool::True);
531 } else if (Class == cByte || Class == cShort) {
532 ConstantInt *CI = cast<ConstantInt>(C);
533 BuildMI(*MBB, IP, PPC32::LI, 1, R).addSImm(CI->getRawValue());
535 ConstantInt *CI = cast<ConstantInt>(C);
536 int TheVal = CI->getRawValue() & 0xFFFFFFFF;
537 if (TheVal < 32768 && TheVal >= -32768) {
538 BuildMI(*MBB, IP, PPC32::LI, 1, R).addSImm(CI->getRawValue());
540 unsigned TmpReg = makeAnotherReg(Type::IntTy);
541 BuildMI(*MBB, IP, PPC32::LIS, 1, TmpReg)
542 .addSImm(CI->getRawValue() >> 16);
543 BuildMI(*MBB, IP, PPC32::ORI, 2, R).addReg(TmpReg)
544 .addImm(CI->getRawValue() & 0xFFFF);
547 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
548 // We need to spill the constant to memory...
549 MachineConstantPool *CP = F->getConstantPool();
550 unsigned CPI = CP->getConstantPoolIndex(CFP);
551 const Type *Ty = CFP->getType();
553 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
555 // Load addr of constant to reg; constant is located at PC + distance
556 unsigned CurPC = makeAnotherReg(Type::IntTy);
557 unsigned Reg1 = makeAnotherReg(Type::IntTy);
558 unsigned Reg2 = makeAnotherReg(Type::IntTy);
559 // Move PC to destination reg
560 BuildMI(*MBB, IP, PPC32::MovePCtoLR, 0, CurPC);
561 // Move value at PC + distance into return reg
562 BuildMI(*MBB, IP, PPC32::LOADHiAddr, 2, Reg1).addReg(CurPC)
563 .addConstantPoolIndex(CPI);
564 BuildMI(*MBB, IP, PPC32::LOADLoDirect, 2, Reg2).addReg(Reg1)
565 .addConstantPoolIndex(CPI);
567 unsigned LoadOpcode = (Ty == Type::FloatTy) ? PPC32::LFS : PPC32::LFD;
568 BuildMI(*MBB, IP, LoadOpcode, 2, R).addSImm(0).addReg(Reg2);
569 } else if (isa<ConstantPointerNull>(C)) {
570 // Copy zero (null pointer) to the register.
571 BuildMI(*MBB, IP, PPC32::LI, 1, R).addSImm(0);
572 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
573 // GV is located at PC + distance
574 unsigned CurPC = makeAnotherReg(Type::IntTy);
575 unsigned TmpReg = makeAnotherReg(GV->getType());
576 unsigned Opcode = (GV->hasWeakLinkage() || GV->isExternal()) ?
577 PPC32::LOADLoIndirect : PPC32::LOADLoDirect;
579 // Move PC to destination reg
580 BuildMI(*MBB, IP, PPC32::MovePCtoLR, 0, CurPC);
581 // Move value at PC + distance into return reg
582 BuildMI(*MBB, IP, PPC32::LOADHiAddr, 2, TmpReg).addReg(CurPC)
583 .addGlobalAddress(GV);
584 BuildMI(*MBB, IP, Opcode, 2, R).addReg(TmpReg).addGlobalAddress(GV);
586 std::cerr << "Offending constant: " << *C << "\n";
587 assert(0 && "Type not handled yet!");
591 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
592 /// the stack into virtual registers.
594 /// FIXME: When we can calculate which args are coming in via registers
595 /// source them from there instead.
596 void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
597 unsigned ArgOffset = 20; // FIXME why is this not 24?
598 unsigned GPR_remaining = 8;
599 unsigned FPR_remaining = 13;
600 unsigned GPR_idx = 0, FPR_idx = 0;
601 static const unsigned GPR[] = {
602 PPC32::R3, PPC32::R4, PPC32::R5, PPC32::R6,
603 PPC32::R7, PPC32::R8, PPC32::R9, PPC32::R10,
605 static const unsigned FPR[] = {
606 PPC32::F1, PPC32::F2, PPC32::F3, PPC32::F4, PPC32::F5, PPC32::F6, PPC32::F7,
607 PPC32::F8, PPC32::F9, PPC32::F10, PPC32::F11, PPC32::F12, PPC32::F13
610 MachineFrameInfo *MFI = F->getFrameInfo();
612 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
613 bool ArgLive = !I->use_empty();
614 unsigned Reg = ArgLive ? getReg(*I) : 0;
615 int FI; // Frame object index
617 switch (getClassB(I->getType())) {
620 FI = MFI->CreateFixedObject(4, ArgOffset);
621 if (GPR_remaining > 0) {
622 BuildMI(BB, PPC32::IMPLICIT_DEF, 0, GPR[GPR_idx]);
623 BuildMI(BB, PPC32::OR, 2, Reg).addReg(GPR[GPR_idx])
624 .addReg(GPR[GPR_idx]);
626 addFrameReference(BuildMI(BB, PPC32::LBZ, 2, Reg), FI);
632 FI = MFI->CreateFixedObject(4, ArgOffset);
633 if (GPR_remaining > 0) {
634 BuildMI(BB, PPC32::IMPLICIT_DEF, 0, GPR[GPR_idx]);
635 BuildMI(BB, PPC32::OR, 2, Reg).addReg(GPR[GPR_idx])
636 .addReg(GPR[GPR_idx]);
638 addFrameReference(BuildMI(BB, PPC32::LHZ, 2, Reg), FI);
644 FI = MFI->CreateFixedObject(4, ArgOffset);
645 if (GPR_remaining > 0) {
646 BuildMI(BB, PPC32::IMPLICIT_DEF, 0, GPR[GPR_idx]);
647 BuildMI(BB, PPC32::OR, 2, Reg).addReg(GPR[GPR_idx])
648 .addReg(GPR[GPR_idx]);
650 addFrameReference(BuildMI(BB, PPC32::LWZ, 2, Reg), FI);
656 FI = MFI->CreateFixedObject(8, ArgOffset);
657 if (GPR_remaining > 1) {
658 BuildMI(BB, PPC32::IMPLICIT_DEF, 0, GPR[GPR_idx]);
659 BuildMI(BB, PPC32::IMPLICIT_DEF, 0, GPR[GPR_idx+1]);
660 BuildMI(BB, PPC32::OR, 2, Reg).addReg(GPR[GPR_idx])
661 .addReg(GPR[GPR_idx]);
662 BuildMI(BB, PPC32::OR, 2, Reg+1).addReg(GPR[GPR_idx+1])
663 .addReg(GPR[GPR_idx+1]);
665 addFrameReference(BuildMI(BB, PPC32::LWZ, 2, Reg), FI);
666 addFrameReference(BuildMI(BB, PPC32::LWZ, 2, Reg+1), FI, 4);
669 // longs require 4 additional bytes and use 2 GPRs
671 if (GPR_remaining > 1) {
678 FI = MFI->CreateFixedObject(4, ArgOffset);
680 if (FPR_remaining > 0) {
681 BuildMI(BB, PPC32::IMPLICIT_DEF, 0, FPR[FPR_idx]);
682 BuildMI(BB, PPC32::FMR, 1, Reg).addReg(FPR[FPR_idx]);
686 addFrameReference(BuildMI(BB, PPC32::LFS, 2, Reg), FI);
692 FI = MFI->CreateFixedObject(8, ArgOffset);
694 if (FPR_remaining > 0) {
695 BuildMI(BB, PPC32::IMPLICIT_DEF, 0, FPR[FPR_idx]);
696 BuildMI(BB, PPC32::FMR, 1, Reg).addReg(FPR[FPR_idx]);
700 addFrameReference(BuildMI(BB, PPC32::LFD, 2, Reg), FI);
704 // doubles require 4 additional bytes and use 2 GPRs of param space
706 if (GPR_remaining > 0) {
712 assert(0 && "Unhandled argument type!");
714 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
715 if (GPR_remaining > 0) {
716 GPR_remaining--; // uses up 2 GPRs
721 // If the function takes variable number of arguments, add a frame offset for
722 // the start of the first vararg value... this is used to expand
724 if (Fn.getFunctionType()->isVarArg())
725 VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
729 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
730 /// because we have to generate our sources into the source basic blocks, not
733 void ISel::SelectPHINodes() {
734 const TargetInstrInfo &TII = *TM.getInstrInfo();
735 const Function &LF = *F->getFunction(); // The LLVM function...
736 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
737 const BasicBlock *BB = I;
738 MachineBasicBlock &MBB = *MBBMap[I];
740 // Loop over all of the PHI nodes in the LLVM basic block...
741 MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
742 for (BasicBlock::const_iterator I = BB->begin();
743 PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
745 // Create a new machine instr PHI node, and insert it.
746 unsigned PHIReg = getReg(*PN);
747 MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
748 PPC32::PHI, PN->getNumOperands(), PHIReg);
750 MachineInstr *LongPhiMI = 0;
751 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
752 LongPhiMI = BuildMI(MBB, PHIInsertPoint,
753 PPC32::PHI, PN->getNumOperands(), PHIReg+1);
755 // PHIValues - Map of blocks to incoming virtual registers. We use this
756 // so that we only initialize one incoming value for a particular block,
757 // even if the block has multiple entries in the PHI node.
759 std::map<MachineBasicBlock*, unsigned> PHIValues;
761 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
762 MachineBasicBlock *PredMBB = 0;
763 for (MachineBasicBlock::pred_iterator PI = MBB.pred_begin (),
764 PE = MBB.pred_end (); PI != PE; ++PI)
765 if (PN->getIncomingBlock(i) == (*PI)->getBasicBlock()) {
769 assert (PredMBB && "Couldn't find incoming machine-cfg edge for phi");
772 std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
773 PHIValues.lower_bound(PredMBB);
775 if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
776 // We already inserted an initialization of the register for this
777 // predecessor. Recycle it.
778 ValReg = EntryIt->second;
781 // Get the incoming value into a virtual register.
783 Value *Val = PN->getIncomingValue(i);
785 // If this is a constant or GlobalValue, we may have to insert code
786 // into the basic block to compute it into a virtual register.
787 if ((isa<Constant>(Val) && !isa<ConstantExpr>(Val)) ||
788 isa<GlobalValue>(Val)) {
789 // Simple constants get emitted at the end of the basic block,
790 // before any terminator instructions. We "know" that the code to
791 // move a constant into a register will never clobber any flags.
792 ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
794 // Because we don't want to clobber any values which might be in
795 // physical registers with the computation of this constant (which
796 // might be arbitrarily complex if it is a constant expression),
797 // just insert the computation at the top of the basic block.
798 MachineBasicBlock::iterator PI = PredMBB->begin();
800 // Skip over any PHI nodes though!
801 while (PI != PredMBB->end() && PI->getOpcode() == PPC32::PHI)
804 ValReg = getReg(Val, PredMBB, PI);
807 // Remember that we inserted a value for this PHI for this predecessor
808 PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
811 PhiMI->addRegOperand(ValReg);
812 PhiMI->addMachineBasicBlockOperand(PredMBB);
814 LongPhiMI->addRegOperand(ValReg+1);
815 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
819 // Now that we emitted all of the incoming values for the PHI node, make
820 // sure to reposition the InsertPoint after the PHI that we just added.
821 // This is needed because we might have inserted a constant into this
822 // block, right after the PHI's which is before the old insert point!
823 PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
830 // canFoldSetCCIntoBranchOrSelect - Return the setcc instruction if we can fold
831 // it into the conditional branch or select instruction which is the only user
832 // of the cc instruction. This is the case if the conditional branch is the
833 // only user of the setcc, and if the setcc is in the same basic block as the
834 // conditional branch.
836 static SetCondInst *canFoldSetCCIntoBranchOrSelect(Value *V) {
837 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
838 if (SCI->hasOneUse()) {
839 Instruction *User = cast<Instruction>(SCI->use_back());
840 if ((isa<BranchInst>(User) || isa<SelectInst>(User)) &&
841 SCI->getParent() == User->getParent())
847 // Return a fixed numbering for setcc instructions which does not depend on the
848 // order of the opcodes.
850 static unsigned getSetCCNumber(unsigned Opcode) {
852 default: assert(0 && "Unknown setcc instruction!");
853 case Instruction::SetEQ: return 0;
854 case Instruction::SetNE: return 1;
855 case Instruction::SetLT: return 2;
856 case Instruction::SetGE: return 3;
857 case Instruction::SetGT: return 4;
858 case Instruction::SetLE: return 5;
862 static unsigned getPPCOpcodeForSetCCNumber(unsigned Opcode) {
864 default: assert(0 && "Unknown setcc instruction!");
865 case Instruction::SetEQ: return PPC32::BEQ;
866 case Instruction::SetNE: return PPC32::BNE;
867 case Instruction::SetLT: return PPC32::BLT;
868 case Instruction::SetGE: return PPC32::BGE;
869 case Instruction::SetGT: return PPC32::BGT;
870 case Instruction::SetLE: return PPC32::BLE;
874 static unsigned invertPPCBranchOpcode(unsigned Opcode) {
876 default: assert(0 && "Unknown PPC32 branch opcode!");
877 case PPC32::BEQ: return PPC32::BNE;
878 case PPC32::BNE: return PPC32::BEQ;
879 case PPC32::BLT: return PPC32::BGE;
880 case PPC32::BGE: return PPC32::BLT;
881 case PPC32::BGT: return PPC32::BLE;
882 case PPC32::BLE: return PPC32::BGT;
886 /// emitUCOM - emits an unordered FP compare.
887 void ISel::emitUCOM(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
888 unsigned LHS, unsigned RHS) {
889 BuildMI(*MBB, IP, PPC32::FCMPU, 2, PPC32::CR0).addReg(LHS).addReg(RHS);
892 /// EmitComparison - emits a comparison of the two operands, returning the
893 /// extended setcc code to use. The result is in CR0.
895 unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
896 MachineBasicBlock *MBB,
897 MachineBasicBlock::iterator IP) {
898 // The arguments are already supposed to be of the same type.
899 const Type *CompTy = Op0->getType();
900 unsigned Class = getClassB(CompTy);
901 unsigned Op0r = getReg(Op0, MBB, IP);
903 // Use crand for lt, gt and crandc for le, ge
904 unsigned CROpcode = (OpNum == 2 || OpNum == 4) ? PPC32::CRAND : PPC32::CRANDC;
905 // ? cr1[lt] : cr1[gt]
906 unsigned CR1field = (OpNum == 2 || OpNum == 3) ? 4 : 5;
907 // ? cr0[lt] : cr0[gt]
908 unsigned CR0field = (OpNum == 2 || OpNum == 5) ? 0 : 1;
909 unsigned Opcode = CompTy->isSigned() ? PPC32::CMPW : PPC32::CMPLW;
910 unsigned OpcodeImm = CompTy->isSigned() ? PPC32::CMPWI : PPC32::CMPLWI;
912 // Special case handling of: cmp R, i
913 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
914 if (Class == cByte || Class == cShort || Class == cInt) {
915 unsigned Op1v = CI->getRawValue() & 0xFFFF;
917 // Treat compare like ADDI for the purposes of immediate suitability
918 if (canUseAsImmediateForOpcode(CI, 0)) {
919 BuildMI(*MBB, IP, OpcodeImm, 2, PPC32::CR0).addReg(Op0r).addSImm(Op1v);
921 unsigned Op1r = getReg(Op1, MBB, IP);
922 BuildMI(*MBB, IP, Opcode, 2, PPC32::CR0).addReg(Op0r).addReg(Op1r);
926 assert(Class == cLong && "Unknown integer class!");
927 unsigned LowCst = CI->getRawValue();
928 unsigned HiCst = CI->getRawValue() >> 32;
929 if (OpNum < 2) { // seteq, setne
930 unsigned LoLow = makeAnotherReg(Type::IntTy);
931 unsigned LoTmp = makeAnotherReg(Type::IntTy);
932 unsigned HiLow = makeAnotherReg(Type::IntTy);
933 unsigned HiTmp = makeAnotherReg(Type::IntTy);
934 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
936 BuildMI(*MBB, IP, PPC32::XORI, 2, LoLow).addReg(Op0r+1)
937 .addImm(LowCst & 0xFFFF);
938 BuildMI(*MBB, IP, PPC32::XORIS, 2, LoTmp).addReg(LoLow)
939 .addImm(LowCst >> 16);
940 BuildMI(*MBB, IP, PPC32::XORI, 2, HiLow).addReg(Op0r)
941 .addImm(HiCst & 0xFFFF);
942 BuildMI(*MBB, IP, PPC32::XORIS, 2, HiTmp).addReg(HiLow)
943 .addImm(HiCst >> 16);
944 BuildMI(*MBB, IP, PPC32::ORo, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
947 unsigned ConstReg = makeAnotherReg(CompTy);
948 copyConstantToRegister(MBB, IP, CI, ConstReg);
950 // cr0 = r3 ccOpcode r5 or (r3 == r5 AND r4 ccOpcode r6)
951 BuildMI(*MBB, IP, Opcode, 2, PPC32::CR0).addReg(Op0r)
953 BuildMI(*MBB, IP, Opcode, 2, PPC32::CR1).addReg(Op0r+1)
955 BuildMI(*MBB, IP, PPC32::CRAND, 3).addImm(2).addImm(2).addImm(CR1field);
956 BuildMI(*MBB, IP, PPC32::CROR, 3).addImm(CR0field).addImm(CR0field)
963 unsigned Op1r = getReg(Op1, MBB, IP);
966 default: assert(0 && "Unknown type class!");
970 BuildMI(*MBB, IP, Opcode, 2, PPC32::CR0).addReg(Op0r).addReg(Op1r);
975 emitUCOM(MBB, IP, Op0r, Op1r);
979 if (OpNum < 2) { // seteq, setne
980 unsigned LoTmp = makeAnotherReg(Type::IntTy);
981 unsigned HiTmp = makeAnotherReg(Type::IntTy);
982 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
983 BuildMI(*MBB, IP, PPC32::XOR, 2, HiTmp).addReg(Op0r).addReg(Op1r);
984 BuildMI(*MBB, IP, PPC32::XOR, 2, LoTmp).addReg(Op0r+1).addReg(Op1r+1);
985 BuildMI(*MBB, IP, PPC32::ORo, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
986 break; // Allow the sete or setne to be generated from flags set by OR
988 unsigned TmpReg1 = makeAnotherReg(Type::IntTy);
989 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
991 // cr0 = r3 ccOpcode r5 or (r3 == r5 AND r4 ccOpcode r6)
992 BuildMI(*MBB, IP, Opcode, 2, PPC32::CR0).addReg(Op0r).addReg(Op1r);
993 BuildMI(*MBB, IP, Opcode, 2, PPC32::CR1).addReg(Op0r+1).addReg(Op1r+1);
994 BuildMI(*MBB, IP, PPC32::CRAND, 3).addImm(2).addImm(2).addImm(CR1field);
995 BuildMI(*MBB, IP, PPC32::CROR, 3).addImm(CR0field).addImm(CR0field)
1003 /// visitSetCondInst - emit code to calculate the condition via
1004 /// EmitComparison(), and possibly store a 0 or 1 to a register as a result
1006 void ISel::visitSetCondInst(SetCondInst &I) {
1007 if (canFoldSetCCIntoBranchOrSelect(&I))
1010 unsigned DestReg = getReg(I);
1011 unsigned OpNum = I.getOpcode();
1012 const Type *Ty = I.getOperand (0)->getType();
1014 EmitComparison(OpNum, I.getOperand(0), I.getOperand(1), BB, BB->end());
1016 unsigned Opcode = getPPCOpcodeForSetCCNumber(OpNum);
1017 MachineBasicBlock *thisMBB = BB;
1018 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1019 ilist<MachineBasicBlock>::iterator It = BB;
1024 // cmpTY cr0, r1, r2
1028 // FIXME: we wouldn't need copy0MBB (we could fold it into thisMBB)
1029 // if we could insert other, non-terminator instructions after the
1030 // bCC. But MBB->getFirstTerminator() can't understand this.
1031 MachineBasicBlock *copy1MBB = new MachineBasicBlock(LLVM_BB);
1032 F->getBasicBlockList().insert(It, copy1MBB);
1033 BuildMI(BB, Opcode, 2).addReg(PPC32::CR0).addMBB(copy1MBB);
1034 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
1035 F->getBasicBlockList().insert(It, copy0MBB);
1036 BuildMI(BB, PPC32::B, 1).addMBB(copy0MBB);
1037 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
1038 F->getBasicBlockList().insert(It, sinkMBB);
1039 // Update machine-CFG edges
1040 BB->addSuccessor(copy1MBB);
1041 BB->addSuccessor(copy0MBB);
1044 // %TrueValue = li 1
1047 unsigned TrueValue = makeAnotherReg (I.getType ());
1048 BuildMI(BB, PPC32::LI, 1, TrueValue).addSImm(1);
1049 BuildMI(BB, PPC32::B, 1).addMBB(sinkMBB);
1050 // Update machine-CFG edges
1051 BB->addSuccessor(sinkMBB);
1054 // %FalseValue = li 0
1057 unsigned FalseValue = makeAnotherReg(I.getType());
1058 BuildMI(BB, PPC32::LI, 1, FalseValue).addSImm(0);
1059 // Update machine-CFG edges
1060 BB->addSuccessor(sinkMBB);
1063 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, copy1MBB ]
1066 BuildMI(BB, PPC32::PHI, 4, DestReg).addReg(FalseValue)
1067 .addMBB(copy0MBB).addReg(TrueValue).addMBB(copy1MBB);
1070 void ISel::visitSelectInst(SelectInst &SI) {
1071 unsigned DestReg = getReg(SI);
1072 MachineBasicBlock::iterator MII = BB->end();
1073 emitSelectOperation(BB, MII, SI.getCondition(), SI.getTrueValue(),
1074 SI.getFalseValue(), DestReg);
1077 /// emitSelect - Common code shared between visitSelectInst and the constant
1078 /// expression support.
1079 /// FIXME: this is most likely broken in one or more ways. Namely, PowerPC has
1080 /// no select instruction. FSEL only works for comparisons against zero.
1081 void ISel::emitSelectOperation(MachineBasicBlock *MBB,
1082 MachineBasicBlock::iterator IP,
1083 Value *Cond, Value *TrueVal, Value *FalseVal,
1085 unsigned SelectClass = getClassB(TrueVal->getType());
1088 // See if we can fold the setcc into the select instruction, or if we have
1089 // to get the register of the Cond value
1090 if (SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(Cond)) {
1091 // We successfully folded the setcc into the select instruction.
1093 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1094 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), MBB,
1096 Opcode = getPPCOpcodeForSetCCNumber(SCI->getOpcode());
1098 unsigned CondReg = getReg(Cond, MBB, IP);
1100 BuildMI(*MBB, IP, PPC32::CMPI, 2, PPC32::CR0).addReg(CondReg).addSImm(0);
1101 Opcode = getPPCOpcodeForSetCCNumber(Instruction::SetNE);
1106 // cmpTY cr0, r1, r2
1110 MachineBasicBlock *thisMBB = BB;
1111 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1112 ilist<MachineBasicBlock>::iterator It = BB;
1115 // FIXME: we wouldn't need copy0MBB (we could fold it into thisMBB)
1116 // if we could insert other, non-terminator instructions after the
1117 // bCC. But MBB->getFirstTerminator() can't understand this.
1118 MachineBasicBlock *copy1MBB = new MachineBasicBlock(LLVM_BB);
1119 F->getBasicBlockList().insert(It, copy1MBB);
1120 BuildMI(BB, Opcode, 2).addReg(PPC32::CR0).addMBB(copy1MBB);
1121 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
1122 F->getBasicBlockList().insert(It, copy0MBB);
1123 BuildMI(BB, PPC32::B, 1).addMBB(copy0MBB);
1124 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
1125 F->getBasicBlockList().insert(It, sinkMBB);
1126 // Update machine-CFG edges
1127 BB->addSuccessor(copy1MBB);
1128 BB->addSuccessor(copy0MBB);
1134 unsigned TrueValue = getReg(TrueVal, BB, BB->begin());
1135 BuildMI(BB, PPC32::B, 1).addMBB(sinkMBB);
1136 // Update machine-CFG edges
1137 BB->addSuccessor(sinkMBB);
1140 // %FalseValue = ...
1143 unsigned FalseValue = getReg(FalseVal, BB, BB->begin());
1144 // Update machine-CFG edges
1145 BB->addSuccessor(sinkMBB);
1148 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, copy1MBB ]
1151 BuildMI(BB, PPC32::PHI, 4, DestReg).addReg(FalseValue)
1152 .addMBB(copy0MBB).addReg(TrueValue).addMBB(copy1MBB);
1153 // For a register pair representing a long value, define the second reg
1154 if (getClass(TrueVal->getType()) == cLong)
1155 BuildMI(BB, PPC32::LI, 1, DestReg+1).addImm(0);
1161 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
1162 /// operand, in the specified target register.
1164 void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
1165 bool isUnsigned = VR.Ty->isUnsigned() || VR.Ty == Type::BoolTy;
1167 Value *Val = VR.Val;
1168 const Type *Ty = VR.Ty;
1170 if (Constant *C = dyn_cast<Constant>(Val)) {
1171 Val = ConstantExpr::getCast(C, Type::IntTy);
1175 // If this is a simple constant, just emit a load directly to avoid the copy
1176 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
1177 int TheVal = CI->getRawValue() & 0xFFFFFFFF;
1179 if (TheVal < 32768 && TheVal >= -32768) {
1180 BuildMI(BB, PPC32::LI, 1, targetReg).addSImm(TheVal);
1182 unsigned TmpReg = makeAnotherReg(Type::IntTy);
1183 BuildMI(BB, PPC32::LIS, 1, TmpReg).addSImm(TheVal >> 16);
1184 BuildMI(BB, PPC32::ORI, 2, targetReg).addReg(TmpReg)
1185 .addImm(TheVal & 0xFFFF);
1191 // Make sure we have the register number for this value...
1192 unsigned Reg = Val ? getReg(Val) : VR.Reg;
1194 switch (getClassB(Ty)) {
1196 // Extend value into target register (8->32)
1198 BuildMI(BB, PPC32::RLWINM, 4, targetReg).addReg(Reg).addZImm(0)
1199 .addZImm(24).addZImm(31);
1201 BuildMI(BB, PPC32::EXTSB, 1, targetReg).addReg(Reg);
1204 // Extend value into target register (16->32)
1206 BuildMI(BB, PPC32::RLWINM, 4, targetReg).addReg(Reg).addZImm(0)
1207 .addZImm(16).addZImm(31);
1209 BuildMI(BB, PPC32::EXTSH, 1, targetReg).addReg(Reg);
1212 // Move value into target register (32->32)
1213 BuildMI(BB, PPC32::OR, 2, targetReg).addReg(Reg).addReg(Reg);
1216 assert(0 && "Unpromotable operand class in promote32");
1220 /// visitReturnInst - implemented with BLR
1222 void ISel::visitReturnInst(ReturnInst &I) {
1223 // Only do the processing if this is a non-void return
1224 if (I.getNumOperands() > 0) {
1225 Value *RetVal = I.getOperand(0);
1226 switch (getClassB(RetVal->getType())) {
1227 case cByte: // integral return values: extend or move into r3 and return
1230 promote32(PPC32::R3, ValueRecord(RetVal));
1233 case cFP64: { // Floats & Doubles: Return in f1
1234 unsigned RetReg = getReg(RetVal);
1235 BuildMI(BB, PPC32::FMR, 1, PPC32::F1).addReg(RetReg);
1239 unsigned RetReg = getReg(RetVal);
1240 BuildMI(BB, PPC32::OR, 2, PPC32::R3).addReg(RetReg).addReg(RetReg);
1241 BuildMI(BB, PPC32::OR, 2, PPC32::R4).addReg(RetReg+1).addReg(RetReg+1);
1245 visitInstruction(I);
1248 BuildMI(BB, PPC32::BLR, 1).addImm(0);
1251 // getBlockAfter - Return the basic block which occurs lexically after the
1253 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1254 Function::iterator I = BB; ++I; // Get iterator to next block
1255 return I != BB->getParent()->end() ? &*I : 0;
1258 /// visitBranchInst - Handle conditional and unconditional branches here. Note
1259 /// that since code layout is frozen at this point, that if we are trying to
1260 /// jump to a block that is the immediate successor of the current block, we can
1261 /// just make a fall-through (but we don't currently).
1263 void ISel::visitBranchInst(BranchInst &BI) {
1264 // Update machine-CFG edges
1265 BB->addSuccessor (MBBMap[BI.getSuccessor(0)]);
1266 if (BI.isConditional())
1267 BB->addSuccessor (MBBMap[BI.getSuccessor(1)]);
1269 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
1271 if (!BI.isConditional()) { // Unconditional branch?
1272 if (BI.getSuccessor(0) != NextBB)
1273 BuildMI(BB, PPC32::B, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1277 // See if we can fold the setcc into the branch itself...
1278 SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(BI.getCondition());
1280 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
1281 // computed some other way...
1282 unsigned condReg = getReg(BI.getCondition());
1283 BuildMI(BB, PPC32::CMPLI, 3, PPC32::CR1).addImm(0).addReg(condReg)
1285 if (BI.getSuccessor(1) == NextBB) {
1286 if (BI.getSuccessor(0) != NextBB)
1287 BuildMI(BB, PPC32::BNE, 2).addReg(PPC32::CR1)
1288 .addMBB(MBBMap[BI.getSuccessor(0)]);
1290 BuildMI(BB, PPC32::BEQ, 2).addReg(PPC32::CR1)
1291 .addMBB(MBBMap[BI.getSuccessor(1)]);
1293 if (BI.getSuccessor(0) != NextBB)
1294 BuildMI(BB, PPC32::B, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1299 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1300 unsigned Opcode = getPPCOpcodeForSetCCNumber(SCI->getOpcode());
1301 MachineBasicBlock::iterator MII = BB->end();
1302 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
1304 if (BI.getSuccessor(0) != NextBB) {
1305 BuildMI(BB, Opcode, 2).addReg(PPC32::CR0)
1306 .addMBB(MBBMap[BI.getSuccessor(0)]);
1307 if (BI.getSuccessor(1) != NextBB)
1308 BuildMI(BB, PPC32::B, 1).addMBB(MBBMap[BI.getSuccessor(1)]);
1310 // Change to the inverse condition...
1311 if (BI.getSuccessor(1) != NextBB) {
1312 Opcode = invertPPCBranchOpcode(Opcode);
1313 BuildMI(BB, Opcode, 2).addReg(PPC32::CR0)
1314 .addMBB(MBBMap[BI.getSuccessor(1)]);
1319 /// doCall - This emits an abstract call instruction, setting up the arguments
1320 /// and the return value as appropriate. For the actual function call itself,
1321 /// it inserts the specified CallMI instruction into the stream.
1323 /// FIXME: See Documentation at the following URL for "correct" behavior
1324 /// <http://developer.apple.com/documentation/DeveloperTools/Conceptual/MachORuntime/2rt_powerpc_abi/chapter_9_section_5.html>
1325 void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
1326 const std::vector<ValueRecord> &Args, bool isVarArg) {
1327 // Count how many bytes are to be pushed on the stack...
1328 unsigned NumBytes = 0;
1330 if (!Args.empty()) {
1331 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1332 switch (getClassB(Args[i].Ty)) {
1333 case cByte: case cShort: case cInt:
1334 NumBytes += 4; break;
1336 NumBytes += 8; break;
1338 NumBytes += 4; break;
1340 NumBytes += 8; break;
1342 default: assert(0 && "Unknown class!");
1345 // Adjust the stack pointer for the new arguments...
1346 BuildMI(BB, PPC32::ADJCALLSTACKDOWN, 1).addSImm(NumBytes);
1348 // Arguments go on the stack in reverse order, as specified by the ABI.
1349 // Offset to the paramater area on the stack is 24.
1350 unsigned ArgOffset = 24;
1351 int GPR_remaining = 8, FPR_remaining = 13;
1352 unsigned GPR_idx = 0, FPR_idx = 0;
1353 static const unsigned GPR[] = {
1354 PPC32::R3, PPC32::R4, PPC32::R5, PPC32::R6,
1355 PPC32::R7, PPC32::R8, PPC32::R9, PPC32::R10,
1357 static const unsigned FPR[] = {
1358 PPC32::F1, PPC32::F2, PPC32::F3, PPC32::F4, PPC32::F5, PPC32::F6,
1359 PPC32::F7, PPC32::F8, PPC32::F9, PPC32::F10, PPC32::F11, PPC32::F12,
1363 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1365 switch (getClassB(Args[i].Ty)) {
1368 // Promote arg to 32 bits wide into a temporary register...
1369 ArgReg = makeAnotherReg(Type::UIntTy);
1370 promote32(ArgReg, Args[i]);
1373 if (GPR_remaining > 0) {
1374 BuildMI(BB, PPC32::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1376 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1378 BuildMI(BB, PPC32::STW, 3).addReg(ArgReg).addSImm(ArgOffset)
1383 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1386 if (GPR_remaining > 0) {
1387 BuildMI(BB, PPC32::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1389 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1391 BuildMI(BB, PPC32::STW, 3).addReg(ArgReg).addSImm(ArgOffset)
1396 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1398 // Reg or stack? Note that PPC calling conventions state that long args
1399 // are passed rN = hi, rN+1 = lo, opposite of LLVM.
1400 if (GPR_remaining > 1) {
1401 BuildMI(BB, PPC32::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1403 BuildMI(BB, PPC32::OR, 2, GPR[GPR_idx+1]).addReg(ArgReg+1)
1405 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1406 CallMI->addRegOperand(GPR[GPR_idx+1], MachineOperand::Use);
1408 BuildMI(BB, PPC32::STW, 3).addReg(ArgReg).addSImm(ArgOffset)
1410 BuildMI(BB, PPC32::STW, 3).addReg(ArgReg+1).addSImm(ArgOffset+4)
1414 ArgOffset += 4; // 8 byte entry, not 4.
1415 GPR_remaining -= 1; // uses up 2 GPRs
1419 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1421 if (FPR_remaining > 0) {
1422 BuildMI(BB, PPC32::FMR, 1, FPR[FPR_idx]).addReg(ArgReg);
1423 CallMI->addRegOperand(FPR[FPR_idx], MachineOperand::Use);
1427 // If this is a vararg function, and there are GPRs left, also
1428 // pass the float in an int. Otherwise, put it on the stack.
1430 BuildMI(BB, PPC32::STFS, 3).addReg(ArgReg).addSImm(ArgOffset)
1432 if (GPR_remaining > 0) {
1433 BuildMI(BB, PPC32::LWZ, 2, GPR[GPR_idx])
1434 .addSImm(ArgOffset).addReg(ArgReg);
1435 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1439 BuildMI(BB, PPC32::STFS, 3).addReg(ArgReg).addSImm(ArgOffset)
1444 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1446 if (FPR_remaining > 0) {
1447 BuildMI(BB, PPC32::FMR, 1, FPR[FPR_idx]).addReg(ArgReg);
1448 CallMI->addRegOperand(FPR[FPR_idx], MachineOperand::Use);
1451 // For vararg functions, must pass doubles via int regs as well
1453 BuildMI(BB, PPC32::STFD, 3).addReg(ArgReg).addSImm(ArgOffset)
1456 // Doubles can be split across reg + stack for varargs
1457 if (GPR_remaining > 0) {
1458 BuildMI(BB, PPC32::LWZ, 2, GPR[GPR_idx]).addSImm(ArgOffset)
1460 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1462 if (GPR_remaining > 1) {
1463 BuildMI(BB, PPC32::LWZ, 2, GPR[GPR_idx+1])
1464 .addSImm(ArgOffset+4).addReg(PPC32::R1);
1465 CallMI->addRegOperand(GPR[GPR_idx+1], MachineOperand::Use);
1469 BuildMI(BB, PPC32::STFD, 3).addReg(ArgReg).addSImm(ArgOffset)
1472 // Doubles use 8 bytes, and 2 GPRs worth of param space
1478 default: assert(0 && "Unknown class!");
1485 BuildMI(BB, PPC32::ADJCALLSTACKDOWN, 1).addSImm(0);
1488 BB->push_back(CallMI);
1489 BuildMI(BB, PPC32::ADJCALLSTACKUP, 1).addSImm(NumBytes);
1491 // If there is a return value, scavenge the result from the location the call
1494 if (Ret.Ty != Type::VoidTy) {
1495 unsigned DestClass = getClassB(Ret.Ty);
1496 switch (DestClass) {
1500 // Integral results are in r3
1501 BuildMI(BB, PPC32::OR, 2, Ret.Reg).addReg(PPC32::R3).addReg(PPC32::R3);
1503 case cFP32: // Floating-point return values live in f1
1505 BuildMI(BB, PPC32::FMR, 1, Ret.Reg).addReg(PPC32::F1);
1507 case cLong: // Long values are in r3 hi:r4 lo
1508 BuildMI(BB, PPC32::OR, 2, Ret.Reg).addReg(PPC32::R3).addReg(PPC32::R3);
1509 BuildMI(BB, PPC32::OR, 2, Ret.Reg+1).addReg(PPC32::R4).addReg(PPC32::R4);
1511 default: assert(0 && "Unknown class!");
1517 /// visitCallInst - Push args on stack and do a procedure call instruction.
1518 void ISel::visitCallInst(CallInst &CI) {
1519 MachineInstr *TheCall;
1520 Function *F = CI.getCalledFunction();
1522 // Is it an intrinsic function call?
1523 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1524 visitIntrinsicCall(ID, CI); // Special intrinsics are not handled here
1528 // Emit a CALL instruction with PC-relative displacement.
1529 TheCall = BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(F, true);
1530 } else { // Emit an indirect call through the CTR
1531 unsigned Reg = getReg(CI.getCalledValue());
1532 BuildMI(BB, PPC32::MTCTR, 1).addReg(Reg);
1533 TheCall = BuildMI(PPC32::CALLindirect, 2).addZImm(20).addZImm(0);
1536 std::vector<ValueRecord> Args;
1537 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
1538 Args.push_back(ValueRecord(CI.getOperand(i)));
1540 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1541 bool isVarArg = F ? F->getFunctionType()->isVarArg() : true;
1542 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args, isVarArg);
1546 /// dyncastIsNan - Return the operand of an isnan operation if this is an isnan.
1548 static Value *dyncastIsNan(Value *V) {
1549 if (CallInst *CI = dyn_cast<CallInst>(V))
1550 if (Function *F = CI->getCalledFunction())
1551 if (F->getIntrinsicID() == Intrinsic::isunordered)
1552 return CI->getOperand(1);
1556 /// isOnlyUsedByUnorderedComparisons - Return true if this value is only used by
1557 /// or's whos operands are all calls to the isnan predicate.
1558 static bool isOnlyUsedByUnorderedComparisons(Value *V) {
1559 assert(dyncastIsNan(V) && "The value isn't an isnan call!");
1561 // Check all uses, which will be or's of isnans if this predicate is true.
1562 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1563 Instruction *I = cast<Instruction>(*UI);
1564 if (I->getOpcode() != Instruction::Or) return false;
1565 if (I->getOperand(0) != V && !dyncastIsNan(I->getOperand(0))) return false;
1566 if (I->getOperand(1) != V && !dyncastIsNan(I->getOperand(1))) return false;
1572 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1573 /// function, lowering any calls to unknown intrinsic functions into the
1574 /// equivalent LLVM code.
1576 void ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1577 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1578 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1579 if (CallInst *CI = dyn_cast<CallInst>(I++))
1580 if (Function *F = CI->getCalledFunction())
1581 switch (F->getIntrinsicID()) {
1582 case Intrinsic::not_intrinsic:
1583 case Intrinsic::vastart:
1584 case Intrinsic::vacopy:
1585 case Intrinsic::vaend:
1586 case Intrinsic::returnaddress:
1587 case Intrinsic::frameaddress:
1588 // FIXME: should lower this ourselves
1589 // case Intrinsic::isunordered:
1590 // We directly implement these intrinsics
1592 case Intrinsic::readio: {
1593 // On PPC, memory operations are in-order. Lower this intrinsic
1594 // into a volatile load.
1595 Instruction *Before = CI->getPrev();
1596 LoadInst * LI = new LoadInst(CI->getOperand(1), "", true, CI);
1597 CI->replaceAllUsesWith(LI);
1598 BB->getInstList().erase(CI);
1601 case Intrinsic::writeio: {
1602 // On PPC, memory operations are in-order. Lower this intrinsic
1603 // into a volatile store.
1604 Instruction *Before = CI->getPrev();
1605 StoreInst *SI = new StoreInst(CI->getOperand(1),
1606 CI->getOperand(2), true, CI);
1607 CI->replaceAllUsesWith(SI);
1608 BB->getInstList().erase(CI);
1612 // All other intrinsic calls we must lower.
1613 Instruction *Before = CI->getPrev();
1614 TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
1615 if (Before) { // Move iterator to instruction after call
1623 void ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
1624 unsigned TmpReg1, TmpReg2, TmpReg3;
1626 case Intrinsic::vastart:
1627 // Get the address of the first vararg value...
1628 TmpReg1 = getReg(CI);
1629 addFrameReference(BuildMI(BB, PPC32::ADDI, 2, TmpReg1), VarArgsFrameIndex,
1633 case Intrinsic::vacopy:
1634 TmpReg1 = getReg(CI);
1635 TmpReg2 = getReg(CI.getOperand(1));
1636 BuildMI(BB, PPC32::OR, 2, TmpReg1).addReg(TmpReg2).addReg(TmpReg2);
1638 case Intrinsic::vaend: return;
1640 case Intrinsic::returnaddress:
1641 TmpReg1 = getReg(CI);
1642 if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1643 MachineFrameInfo *MFI = F->getFrameInfo();
1644 unsigned NumBytes = MFI->getStackSize();
1646 BuildMI(BB, PPC32::LWZ, 2, TmpReg1).addSImm(NumBytes+8)
1649 // Values other than zero are not implemented yet.
1650 BuildMI(BB, PPC32::LI, 1, TmpReg1).addSImm(0);
1654 case Intrinsic::frameaddress:
1655 TmpReg1 = getReg(CI);
1656 if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1657 BuildMI(BB, PPC32::OR, 2, TmpReg1).addReg(PPC32::R1).addReg(PPC32::R1);
1659 // Values other than zero are not implemented yet.
1660 BuildMI(BB, PPC32::LI, 1, TmpReg1).addSImm(0);
1665 // This may be useful for supporting isunordered
1666 case Intrinsic::isnan:
1667 // If this is only used by 'isunordered' style comparisons, don't emit it.
1668 if (isOnlyUsedByUnorderedComparisons(&CI)) return;
1669 TmpReg1 = getReg(CI.getOperand(1));
1670 emitUCOM(BB, BB->end(), TmpReg1, TmpReg1);
1671 TmpReg2 = makeAnotherReg(Type::IntTy);
1672 BuildMI(BB, PPC32::MFCR, TmpReg2);
1673 TmpReg3 = getReg(CI);
1674 BuildMI(BB, PPC32::RLWINM, 4, TmpReg3).addReg(TmpReg2).addImm(4).addImm(31).addImm(31);
1678 default: assert(0 && "Error: unknown intrinsics should have been lowered!");
1682 /// visitSimpleBinary - Implement simple binary operators for integral types...
1683 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
1686 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
1687 unsigned DestReg = getReg(B);
1688 MachineBasicBlock::iterator MI = BB->end();
1689 Value *Op0 = B.getOperand(0), *Op1 = B.getOperand(1);
1690 unsigned Class = getClassB(B.getType());
1692 emitSimpleBinaryOperation(BB, MI, Op0, Op1, OperatorClass, DestReg);
1695 /// emitBinaryFPOperation - This method handles emission of floating point
1696 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
1697 void ISel::emitBinaryFPOperation(MachineBasicBlock *BB,
1698 MachineBasicBlock::iterator IP,
1699 Value *Op0, Value *Op1,
1700 unsigned OperatorClass, unsigned DestReg) {
1702 // Special case: op Reg, <const fp>
1703 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1704 // Create a constant pool entry for this constant.
1705 MachineConstantPool *CP = F->getConstantPool();
1706 unsigned CPI = CP->getConstantPoolIndex(Op1C);
1707 const Type *Ty = Op1->getType();
1708 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1710 static const unsigned OpcodeTab[][4] = {
1711 { PPC32::FADDS, PPC32::FSUBS, PPC32::FMULS, PPC32::FDIVS }, // Float
1712 { PPC32::FADD, PPC32::FSUB, PPC32::FMUL, PPC32::FDIV }, // Double
1715 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
1716 unsigned Op1Reg = getReg(Op1C, BB, IP);
1717 unsigned Op0r = getReg(Op0, BB, IP);
1718 BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1Reg);
1722 // Special case: R1 = op <const fp>, R2
1723 if (ConstantFP *Op0C = dyn_cast<ConstantFP>(Op0))
1724 if (Op0C->isExactlyValue(-0.0) && OperatorClass == 1) {
1726 unsigned op1Reg = getReg(Op1, BB, IP);
1727 BuildMI(*BB, IP, PPC32::FNEG, 1, DestReg).addReg(op1Reg);
1730 // R1 = op CST, R2 --> R1 = opr R2, CST
1732 // Create a constant pool entry for this constant.
1733 MachineConstantPool *CP = F->getConstantPool();
1734 unsigned CPI = CP->getConstantPoolIndex(Op0C);
1735 const Type *Ty = Op0C->getType();
1736 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1738 static const unsigned OpcodeTab[][4] = {
1739 { PPC32::FADDS, PPC32::FSUBS, PPC32::FMULS, PPC32::FDIVS }, // Float
1740 { PPC32::FADD, PPC32::FSUB, PPC32::FMUL, PPC32::FDIV }, // Double
1743 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
1744 unsigned Op0Reg = getReg(Op0C, BB, IP);
1745 unsigned Op1Reg = getReg(Op1, BB, IP);
1746 BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0Reg).addReg(Op1Reg);
1751 static const unsigned OpcodeTab[] = {
1752 PPC32::FADD, PPC32::FSUB, PPC32::FMUL, PPC32::FDIV
1755 unsigned Opcode = OpcodeTab[OperatorClass];
1756 unsigned Op0r = getReg(Op0, BB, IP);
1757 unsigned Op1r = getReg(Op1, BB, IP);
1758 BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1761 /// emitSimpleBinaryOperation - Implement simple binary operators for integral
1762 /// types... OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
1765 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
1766 /// and constant expression support.
1768 void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
1769 MachineBasicBlock::iterator IP,
1770 Value *Op0, Value *Op1,
1771 unsigned OperatorClass, unsigned DestReg) {
1772 unsigned Class = getClassB(Op0->getType());
1774 // Arithmetic and Bitwise operators
1775 static const unsigned OpcodeTab[] = {
1776 PPC32::ADD, PPC32::SUB, PPC32::AND, PPC32::OR, PPC32::XOR
1778 static const unsigned ImmOpcodeTab[] = {
1779 PPC32::ADDI, PPC32::SUBI, PPC32::ANDIo, PPC32::ORI, PPC32::XORI
1781 static const unsigned RImmOpcodeTab[] = {
1782 PPC32::ADDI, PPC32::SUBFIC, PPC32::ANDIo, PPC32::ORI, PPC32::XORI
1785 // Otherwise, code generate the full operation with a constant.
1786 static const unsigned BottomTab[] = {
1787 PPC32::ADDC, PPC32::SUBC, PPC32::AND, PPC32::OR, PPC32::XOR
1789 static const unsigned TopTab[] = {
1790 PPC32::ADDE, PPC32::SUBFE, PPC32::AND, PPC32::OR, PPC32::XOR
1793 if (Class == cFP32 || Class == cFP64) {
1794 assert(OperatorClass < 2 && "No logical ops for FP!");
1795 emitBinaryFPOperation(MBB, IP, Op0, Op1, OperatorClass, DestReg);
1799 if (Op0->getType() == Type::BoolTy) {
1800 if (OperatorClass == 3)
1801 // If this is an or of two isnan's, emit an FP comparison directly instead
1802 // of or'ing two isnan's together.
1803 if (Value *LHS = dyncastIsNan(Op0))
1804 if (Value *RHS = dyncastIsNan(Op1)) {
1805 unsigned Op0Reg = getReg(RHS, MBB, IP), Op1Reg = getReg(LHS, MBB, IP);
1806 unsigned TmpReg = makeAnotherReg(Type::IntTy);
1807 emitUCOM(MBB, IP, Op0Reg, Op1Reg);
1808 BuildMI(*MBB, IP, PPC32::MFCR, TmpReg);
1809 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(TmpReg).addImm(4)
1810 .addImm(31).addImm(31);
1815 // Special case: op <const int>, Reg
1816 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0)) {
1817 // sub 0, X -> subfic
1818 if (OperatorClass == 1 && canUseAsImmediateForOpcode(CI, 0)) {
1819 unsigned Op1r = getReg(Op1, MBB, IP);
1820 int imm = CI->getRawValue() & 0xFFFF;
1822 if (Class == cLong) {
1823 BuildMI(*MBB, IP, PPC32::SUBFIC, 2, DestReg+1).addReg(Op1r+1)
1825 BuildMI(*MBB, IP, PPC32::SUBFZE, 1, DestReg).addReg(Op1r);
1827 BuildMI(*MBB, IP, PPC32::SUBFIC, 2, DestReg).addReg(Op1r).addSImm(imm);
1832 // If it is easy to do, swap the operands and emit an immediate op
1833 if (Class != cLong && OperatorClass != 1 &&
1834 canUseAsImmediateForOpcode(CI, OperatorClass)) {
1835 unsigned Op1r = getReg(Op1, MBB, IP);
1836 int imm = CI->getRawValue() & 0xFFFF;
1838 if (OperatorClass < 2)
1839 BuildMI(*MBB, IP, RImmOpcodeTab[OperatorClass], 2, DestReg).addReg(Op1r)
1842 BuildMI(*MBB, IP, RImmOpcodeTab[OperatorClass], 2, DestReg).addReg(Op1r)
1848 // Special case: op Reg, <const int>
1849 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1850 unsigned Op0r = getReg(Op0, MBB, IP);
1852 // xor X, -1 -> not X
1853 if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
1854 BuildMI(*MBB, IP, PPC32::NOR, 2, DestReg).addReg(Op0r).addReg(Op0r);
1855 if (Class == cLong) // Invert the low part too
1856 BuildMI(*MBB, IP, PPC32::NOR, 2, DestReg+1).addReg(Op0r+1)
1861 if (Class != cLong) {
1862 if (canUseAsImmediateForOpcode(Op1C, OperatorClass)) {
1863 int immediate = Op1C->getRawValue() & 0xFFFF;
1865 if (OperatorClass < 2)
1866 BuildMI(*MBB, IP, ImmOpcodeTab[OperatorClass], 2,DestReg).addReg(Op0r)
1867 .addSImm(immediate);
1869 BuildMI(*MBB, IP, ImmOpcodeTab[OperatorClass], 2,DestReg).addReg(Op0r)
1870 .addZImm(immediate);
1872 unsigned Op1r = getReg(Op1, MBB, IP);
1873 BuildMI(*MBB, IP, OpcodeTab[OperatorClass], 2, DestReg).addReg(Op0r)
1879 unsigned Op1r = getReg(Op1, MBB, IP);
1881 BuildMI(*MBB, IP, BottomTab[OperatorClass], 2, DestReg+1).addReg(Op0r+1)
1883 BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg).addReg(Op0r)
1888 // We couldn't generate an immediate variant of the op, load both halves into
1889 // registers and emit the appropriate opcode.
1890 unsigned Op0r = getReg(Op0, MBB, IP);
1891 unsigned Op1r = getReg(Op1, MBB, IP);
1893 if (Class != cLong) {
1894 unsigned Opcode = OpcodeTab[OperatorClass];
1895 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1897 BuildMI(*MBB, IP, BottomTab[OperatorClass], 2, DestReg+1).addReg(Op0r+1)
1899 BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg).addReg(Op0r)
1905 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
1906 // returns zero when the input is not exactly a power of two.
1907 static unsigned ExactLog2(unsigned Val) {
1908 if (Val == 0 || (Val & (Val-1))) return 0;
1917 /// doMultiply - Emit appropriate instructions to multiply together the
1918 /// Values Op0 and Op1, and put the result in DestReg.
1920 void ISel::doMultiply(MachineBasicBlock *MBB,
1921 MachineBasicBlock::iterator IP,
1922 unsigned DestReg, Value *Op0, Value *Op1) {
1923 unsigned Class0 = getClass(Op0->getType());
1924 unsigned Class1 = getClass(Op1->getType());
1926 unsigned Op0r = getReg(Op0, MBB, IP);
1927 unsigned Op1r = getReg(Op1, MBB, IP);
1930 if (Class0 == cLong && Class1 == cLong) {
1931 unsigned Tmp1 = makeAnotherReg(Type::IntTy);
1932 unsigned Tmp2 = makeAnotherReg(Type::IntTy);
1933 unsigned Tmp3 = makeAnotherReg(Type::IntTy);
1934 unsigned Tmp4 = makeAnotherReg(Type::IntTy);
1935 BuildMI(*MBB, IP, PPC32::MULHWU, 2, Tmp1).addReg(Op0r+1).addReg(Op1r+1);
1936 BuildMI(*MBB, IP, PPC32::MULLW, 2, DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
1937 BuildMI(*MBB, IP, PPC32::MULLW, 2, Tmp2).addReg(Op0r+1).addReg(Op1r);
1938 BuildMI(*MBB, IP, PPC32::ADD, 2, Tmp3).addReg(Tmp1).addReg(Tmp2);
1939 BuildMI(*MBB, IP, PPC32::MULLW, 2, Tmp4).addReg(Op0r).addReg(Op1r+1);
1940 BuildMI(*MBB, IP, PPC32::ADD, 2, DestReg).addReg(Tmp3).addReg(Tmp4);
1944 // 64 x 32 or less, promote 32 to 64 and do a 64 x 64
1945 if (Class0 == cLong && Class1 <= cInt) {
1946 unsigned Tmp0 = makeAnotherReg(Type::IntTy);
1947 unsigned Tmp1 = makeAnotherReg(Type::IntTy);
1948 unsigned Tmp2 = makeAnotherReg(Type::IntTy);
1949 unsigned Tmp3 = makeAnotherReg(Type::IntTy);
1950 unsigned Tmp4 = makeAnotherReg(Type::IntTy);
1951 if (Op1->getType()->isSigned())
1952 BuildMI(*MBB, IP, PPC32::SRAWI, 2, Tmp0).addReg(Op1r).addImm(31);
1954 BuildMI(*MBB, IP, PPC32::LI, 2, Tmp0).addSImm(0);
1955 BuildMI(*MBB, IP, PPC32::MULHWU, 2, Tmp1).addReg(Op0r+1).addReg(Op1r);
1956 BuildMI(*MBB, IP, PPC32::MULLW, 2, DestReg+1).addReg(Op0r+1).addReg(Op1r);
1957 BuildMI(*MBB, IP, PPC32::MULLW, 2, Tmp2).addReg(Op0r+1).addReg(Tmp0);
1958 BuildMI(*MBB, IP, PPC32::ADD, 2, Tmp3).addReg(Tmp1).addReg(Tmp2);
1959 BuildMI(*MBB, IP, PPC32::MULLW, 2, Tmp4).addReg(Op0r).addReg(Op1r);
1960 BuildMI(*MBB, IP, PPC32::ADD, 2, DestReg).addReg(Tmp3).addReg(Tmp4);
1965 if (Class0 <= cInt && Class1 <= cInt) {
1966 BuildMI(*MBB, IP, PPC32::MULLW, 2, DestReg).addReg(Op0r).addReg(Op1r);
1970 assert(0 && "doMultiply cannot operate on unknown type!");
1973 /// doMultiplyConst - This method will multiply the value in Op0 by the
1974 /// value of the ContantInt *CI
1975 void ISel::doMultiplyConst(MachineBasicBlock *MBB,
1976 MachineBasicBlock::iterator IP,
1977 unsigned DestReg, Value *Op0, ConstantInt *CI) {
1978 unsigned Class = getClass(Op0->getType());
1981 if (CI->isNullValue()) {
1982 BuildMI(*MBB, IP, PPC32::LI, 1, DestReg).addSImm(0);
1984 BuildMI(*MBB, IP, PPC32::LI, 1, DestReg+1).addSImm(0);
1988 // Mul op0, 1 ==> op0
1989 if (CI->equalsInt(1)) {
1990 unsigned Op0r = getReg(Op0, MBB, IP);
1991 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(Op0r).addReg(Op0r);
1993 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg+1).addReg(Op0r+1).addReg(Op0r+1);
1997 // If the element size is exactly a power of 2, use a shift to get it.
1998 if (unsigned Shift = ExactLog2(CI->getRawValue())) {
1999 ConstantUInt *ShiftCI = ConstantUInt::get(Type::UByteTy, Shift);
2000 emitShiftOperation(MBB, IP, Op0, ShiftCI, true, Op0->getType(), DestReg);
2004 // If 32 bits or less and immediate is in right range, emit mul by immediate
2005 if (Class == cByte || Class == cShort || Class == cInt) {
2006 if (canUseAsImmediateForOpcode(CI, 0)) {
2007 unsigned Op0r = getReg(Op0, MBB, IP);
2008 unsigned imm = CI->getRawValue() & 0xFFFF;
2009 BuildMI(*MBB, IP, PPC32::MULLI, 2, DestReg).addReg(Op0r).addSImm(imm);
2014 doMultiply(MBB, IP, DestReg, Op0, CI);
2017 void ISel::visitMul(BinaryOperator &I) {
2018 unsigned ResultReg = getReg(I);
2020 Value *Op0 = I.getOperand(0);
2021 Value *Op1 = I.getOperand(1);
2023 MachineBasicBlock::iterator IP = BB->end();
2024 emitMultiply(BB, IP, Op0, Op1, ResultReg);
2027 void ISel::emitMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
2028 Value *Op0, Value *Op1, unsigned DestReg) {
2029 TypeClass Class = getClass(Op0->getType());
2036 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2037 doMultiplyConst(MBB, IP, DestReg, Op0, CI);
2039 doMultiply(MBB, IP, DestReg, Op0, Op1);
2044 emitBinaryFPOperation(MBB, IP, Op0, Op1, 2, DestReg);
2051 /// visitDivRem - Handle division and remainder instructions... these
2052 /// instruction both require the same instructions to be generated, they just
2053 /// select the result from a different register. Note that both of these
2054 /// instructions work differently for signed and unsigned operands.
2056 void ISel::visitDivRem(BinaryOperator &I) {
2057 unsigned ResultReg = getReg(I);
2058 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2060 MachineBasicBlock::iterator IP = BB->end();
2061 emitDivRemOperation(BB, IP, Op0, Op1, I.getOpcode() == Instruction::Div,
2065 void ISel::emitDivRemOperation(MachineBasicBlock *BB,
2066 MachineBasicBlock::iterator IP,
2067 Value *Op0, Value *Op1, bool isDiv,
2068 unsigned ResultReg) {
2069 const Type *Ty = Op0->getType();
2070 unsigned Class = getClass(Ty);
2074 // Floating point divide...
2075 emitBinaryFPOperation(BB, IP, Op0, Op1, 3, ResultReg);
2078 // Floating point remainder via fmodf(float x, float y);
2079 unsigned Op0Reg = getReg(Op0, BB, IP);
2080 unsigned Op1Reg = getReg(Op1, BB, IP);
2081 MachineInstr *TheCall =
2082 BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(fmodfFn, true);
2083 std::vector<ValueRecord> Args;
2084 Args.push_back(ValueRecord(Op0Reg, Type::FloatTy));
2085 Args.push_back(ValueRecord(Op1Reg, Type::FloatTy));
2086 doCall(ValueRecord(ResultReg, Type::FloatTy), TheCall, Args, false);
2091 // Floating point divide...
2092 emitBinaryFPOperation(BB, IP, Op0, Op1, 3, ResultReg);
2095 // Floating point remainder via fmod(double x, double y);
2096 unsigned Op0Reg = getReg(Op0, BB, IP);
2097 unsigned Op1Reg = getReg(Op1, BB, IP);
2098 MachineInstr *TheCall =
2099 BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(fmodFn, true);
2100 std::vector<ValueRecord> Args;
2101 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
2102 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
2103 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args, false);
2107 static Function* const Funcs[] =
2108 { __moddi3Fn, __divdi3Fn, __umoddi3Fn, __udivdi3Fn };
2109 unsigned Op0Reg = getReg(Op0, BB, IP);
2110 unsigned Op1Reg = getReg(Op1, BB, IP);
2111 unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
2112 MachineInstr *TheCall =
2113 BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(Funcs[NameIdx], true);
2115 std::vector<ValueRecord> Args;
2116 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
2117 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
2118 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args, false);
2121 case cByte: case cShort: case cInt:
2122 break; // Small integrals, handled below...
2123 default: assert(0 && "Unknown class!");
2126 // Special case signed division by power of 2.
2128 if (ConstantSInt *CI = dyn_cast<ConstantSInt>(Op1)) {
2129 assert(Class != cLong && "This doesn't handle 64-bit divides!");
2130 int V = CI->getValue();
2132 if (V == 1) { // X /s 1 => X
2133 unsigned Op0Reg = getReg(Op0, BB, IP);
2134 BuildMI(*BB, IP, PPC32::OR, 2, ResultReg).addReg(Op0Reg).addReg(Op0Reg);
2138 if (V == -1) { // X /s -1 => -X
2139 unsigned Op0Reg = getReg(Op0, BB, IP);
2140 BuildMI(*BB, IP, PPC32::NEG, 1, ResultReg).addReg(Op0Reg);
2144 unsigned log2V = ExactLog2(V);
2145 if (log2V != 0 && Ty->isSigned()) {
2146 unsigned Op0Reg = getReg(Op0, BB, IP);
2147 unsigned TmpReg = makeAnotherReg(Op0->getType());
2149 BuildMI(*BB, IP, PPC32::SRAWI, 2, TmpReg).addReg(Op0Reg).addImm(log2V);
2150 BuildMI(*BB, IP, PPC32::ADDZE, 1, ResultReg).addReg(TmpReg);
2155 unsigned Op0Reg = getReg(Op0, BB, IP);
2156 unsigned Op1Reg = getReg(Op1, BB, IP);
2157 unsigned Opcode = Ty->isSigned() ? PPC32::DIVW : PPC32::DIVWU;
2160 BuildMI(*BB, IP, Opcode, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
2161 } else { // Remainder
2162 unsigned TmpReg1 = makeAnotherReg(Op0->getType());
2163 unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2165 BuildMI(*BB, IP, Opcode, 2, TmpReg1).addReg(Op0Reg).addReg(Op1Reg);
2166 BuildMI(*BB, IP, PPC32::MULLW, 2, TmpReg2).addReg(TmpReg1).addReg(Op1Reg);
2167 BuildMI(*BB, IP, PPC32::SUBF, 2, ResultReg).addReg(TmpReg2).addReg(Op0Reg);
2172 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
2173 /// for constant immediate shift values, and for constant immediate
2174 /// shift values equal to 1. Even the general case is sort of special,
2175 /// because the shift amount has to be in CL, not just any old register.
2177 void ISel::visitShiftInst(ShiftInst &I) {
2178 MachineBasicBlock::iterator IP = BB->end ();
2179 emitShiftOperation(BB, IP, I.getOperand (0), I.getOperand (1),
2180 I.getOpcode () == Instruction::Shl, I.getType (),
2184 /// emitShiftOperation - Common code shared between visitShiftInst and
2185 /// constant expression support.
2187 void ISel::emitShiftOperation(MachineBasicBlock *MBB,
2188 MachineBasicBlock::iterator IP,
2189 Value *Op, Value *ShiftAmount, bool isLeftShift,
2190 const Type *ResultTy, unsigned DestReg) {
2191 unsigned SrcReg = getReg (Op, MBB, IP);
2192 bool isSigned = ResultTy->isSigned ();
2193 unsigned Class = getClass (ResultTy);
2195 // Longs, as usual, are handled specially...
2196 if (Class == cLong) {
2197 // If we have a constant shift, we can generate much more efficient code
2198 // than otherwise...
2200 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2201 unsigned Amount = CUI->getValue();
2204 // FIXME: RLWIMI is a use-and-def of DestReg+1, but that violates SSA
2205 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg)
2206 .addImm(Amount).addImm(0).addImm(31-Amount);
2207 BuildMI(*MBB, IP, PPC32::RLWIMI, 5).addReg(DestReg).addReg(SrcReg+1)
2208 .addImm(Amount).addImm(32-Amount).addImm(31);
2209 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg+1).addReg(SrcReg+1)
2210 .addImm(Amount).addImm(0).addImm(31-Amount);
2212 // FIXME: RLWIMI is a use-and-def of DestReg, but that violates SSA
2213 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg+1).addReg(SrcReg+1)
2214 .addImm(32-Amount).addImm(Amount).addImm(31);
2215 BuildMI(*MBB, IP, PPC32::RLWIMI, 5).addReg(DestReg+1).addReg(SrcReg)
2216 .addImm(32-Amount).addImm(0).addImm(Amount-1);
2217 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg)
2218 .addImm(32-Amount).addImm(Amount).addImm(31);
2220 } else { // Shifting more than 32 bits
2224 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg+1)
2225 .addImm(Amount).addImm(0).addImm(31-Amount);
2227 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg+1)
2230 BuildMI(*MBB, IP, PPC32::LI, 1, DestReg+1).addSImm(0);
2234 BuildMI(*MBB, IP, PPC32::SRAWI, 2, DestReg+1).addReg(SrcReg)
2237 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg+1).addReg(SrcReg)
2238 .addImm(32-Amount).addImm(Amount).addImm(31);
2240 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg+1).addReg(SrcReg)
2243 BuildMI(*MBB, IP,PPC32::LI, 1, DestReg).addSImm(0);
2247 unsigned TmpReg1 = makeAnotherReg(Type::IntTy);
2248 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
2249 unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
2250 unsigned TmpReg4 = makeAnotherReg(Type::IntTy);
2251 unsigned TmpReg5 = makeAnotherReg(Type::IntTy);
2252 unsigned TmpReg6 = makeAnotherReg(Type::IntTy);
2253 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
2256 BuildMI(*MBB, IP, PPC32::SUBFIC, 2, TmpReg1).addReg(ShiftAmountReg)
2258 BuildMI(*MBB, IP, PPC32::SLW, 2, TmpReg2).addReg(SrcReg)
2259 .addReg(ShiftAmountReg);
2260 BuildMI(*MBB, IP, PPC32::SRW, 2, TmpReg3).addReg(SrcReg+1)
2262 BuildMI(*MBB, IP, PPC32::OR, 2,TmpReg4).addReg(TmpReg2).addReg(TmpReg3);
2263 BuildMI(*MBB, IP, PPC32::ADDI, 2, TmpReg5).addReg(ShiftAmountReg)
2265 BuildMI(*MBB, IP, PPC32::SLW, 2, TmpReg6).addReg(SrcReg+1)
2267 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(TmpReg4)
2269 BuildMI(*MBB, IP, PPC32::SLW, 2, DestReg+1).addReg(SrcReg+1)
2270 .addReg(ShiftAmountReg);
2273 // FIXME: Unimplemented
2274 // Page C-3 of the PowerPC 32bit Programming Environments Manual
2275 std::cerr << "Unimplemented: signed right shift\n";
2278 BuildMI(*MBB, IP, PPC32::SUBFIC, 2, TmpReg1).addReg(ShiftAmountReg)
2280 BuildMI(*MBB, IP, PPC32::SRW, 2, TmpReg2).addReg(SrcReg+1)
2281 .addReg(ShiftAmountReg);
2282 BuildMI(*MBB, IP, PPC32::SLW, 2, TmpReg3).addReg(SrcReg)
2284 BuildMI(*MBB, IP, PPC32::OR, 2, TmpReg4).addReg(TmpReg2)
2286 BuildMI(*MBB, IP, PPC32::ADDI, 2, TmpReg5).addReg(ShiftAmountReg)
2288 BuildMI(*MBB, IP, PPC32::SRW, 2, TmpReg6).addReg(SrcReg)
2290 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg+1).addReg(TmpReg4)
2292 BuildMI(*MBB, IP, PPC32::SRW, 2, DestReg).addReg(SrcReg)
2293 .addReg(ShiftAmountReg);
2300 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2301 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
2302 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
2303 unsigned Amount = CUI->getValue();
2306 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg)
2307 .addImm(Amount).addImm(0).addImm(31-Amount);
2310 BuildMI(*MBB, IP, PPC32::SRAWI,2,DestReg).addReg(SrcReg).addImm(Amount);
2312 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg)
2313 .addImm(32-Amount).addImm(Amount).addImm(31);
2316 } else { // The shift amount is non-constant.
2317 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
2320 BuildMI(*MBB, IP, PPC32::SLW, 2, DestReg).addReg(SrcReg)
2321 .addReg(ShiftAmountReg);
2323 BuildMI(*MBB, IP, isSigned ? PPC32::SRAW : PPC32::SRW, 2, DestReg)
2324 .addReg(SrcReg).addReg(ShiftAmountReg);
2330 /// visitLoadInst - Implement LLVM load instructions
2332 void ISel::visitLoadInst(LoadInst &I) {
2333 static const unsigned Opcodes[] = {
2334 PPC32::LBZ, PPC32::LHZ, PPC32::LWZ, PPC32::LFS
2337 unsigned Class = getClassB(I.getType());
2338 unsigned Opcode = Opcodes[Class];
2339 if (I.getType() == Type::DoubleTy) Opcode = PPC32::LFD;
2340 if (Class == cShort && I.getType()->isSigned()) Opcode = PPC32::LHA;
2341 unsigned DestReg = getReg(I);
2343 if (AllocaInst *AI = dyn_castFixedAlloca(I.getOperand(0))) {
2344 unsigned FI = getFixedSizedAllocaFI(AI);
2345 if (Class == cLong) {
2346 addFrameReference(BuildMI(BB, PPC32::LWZ, 2, DestReg), FI);
2347 addFrameReference(BuildMI(BB, PPC32::LWZ, 2, DestReg+1), FI, 4);
2348 } else if (Class == cByte && I.getType()->isSigned()) {
2349 unsigned TmpReg = makeAnotherReg(I.getType());
2350 addFrameReference(BuildMI(BB, Opcode, 2, TmpReg), FI);
2351 BuildMI(BB, PPC32::EXTSB, 1, DestReg).addReg(TmpReg);
2353 addFrameReference(BuildMI(BB, Opcode, 2, DestReg), FI);
2356 unsigned SrcAddrReg = getReg(I.getOperand(0));
2358 if (Class == cLong) {
2359 BuildMI(BB, PPC32::LWZ, 2, DestReg).addSImm(0).addReg(SrcAddrReg);
2360 BuildMI(BB, PPC32::LWZ, 2, DestReg+1).addSImm(4).addReg(SrcAddrReg);
2361 } else if (Class == cByte && I.getType()->isSigned()) {
2362 unsigned TmpReg = makeAnotherReg(I.getType());
2363 BuildMI(BB, Opcode, 2, TmpReg).addSImm(0).addReg(SrcAddrReg);
2364 BuildMI(BB, PPC32::EXTSB, 1, DestReg).addReg(TmpReg);
2366 BuildMI(BB, Opcode, 2, DestReg).addSImm(0).addReg(SrcAddrReg);
2371 /// visitStoreInst - Implement LLVM store instructions
2373 void ISel::visitStoreInst(StoreInst &I) {
2374 unsigned ValReg = getReg(I.getOperand(0));
2375 unsigned AddressReg = getReg(I.getOperand(1));
2377 const Type *ValTy = I.getOperand(0)->getType();
2378 unsigned Class = getClassB(ValTy);
2380 if (Class == cLong) {
2381 BuildMI(BB, PPC32::STW, 3).addReg(ValReg).addSImm(0).addReg(AddressReg);
2382 BuildMI(BB, PPC32::STW, 3).addReg(ValReg+1).addSImm(4).addReg(AddressReg);
2386 static const unsigned Opcodes[] = {
2387 PPC32::STB, PPC32::STH, PPC32::STW, PPC32::STFS
2389 unsigned Opcode = Opcodes[Class];
2390 if (ValTy == Type::DoubleTy) Opcode = PPC32::STFD;
2391 BuildMI(BB, Opcode, 3).addReg(ValReg).addSImm(0).addReg(AddressReg);
2395 /// visitCastInst - Here we have various kinds of copying with or without sign
2396 /// extension going on.
2398 void ISel::visitCastInst(CastInst &CI) {
2399 Value *Op = CI.getOperand(0);
2401 unsigned SrcClass = getClassB(Op->getType());
2402 unsigned DestClass = getClassB(CI.getType());
2403 // Noop casts are not emitted: getReg will return the source operand as the
2404 // register to use for any uses of the noop cast.
2405 if (DestClass == SrcClass)
2408 // If this is a cast from a 32-bit integer to a Long type, and the only uses
2409 // of the case are GEP instructions, then the cast does not need to be
2410 // generated explicitly, it will be folded into the GEP.
2411 if (DestClass == cLong && SrcClass == cInt) {
2412 bool AllUsesAreGEPs = true;
2413 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
2414 if (!isa<GetElementPtrInst>(*I)) {
2415 AllUsesAreGEPs = false;
2419 // No need to codegen this cast if all users are getelementptr instrs...
2420 if (AllUsesAreGEPs) return;
2423 unsigned DestReg = getReg(CI);
2424 MachineBasicBlock::iterator MI = BB->end();
2425 emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
2428 /// emitCastOperation - Common code shared between visitCastInst and constant
2429 /// expression cast support.
2431 void ISel::emitCastOperation(MachineBasicBlock *MBB,
2432 MachineBasicBlock::iterator IP,
2433 Value *Src, const Type *DestTy,
2435 const Type *SrcTy = Src->getType();
2436 unsigned SrcClass = getClassB(SrcTy);
2437 unsigned DestClass = getClassB(DestTy);
2438 unsigned SrcReg = getReg(Src, MBB, IP);
2440 // Implement casts to bool by using compare on the operand followed by set if
2441 // not zero on the result.
2442 if (DestTy == Type::BoolTy) {
2447 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2448 BuildMI(*MBB, IP, PPC32::ADDIC, 2, TmpReg).addReg(SrcReg).addSImm(-1);
2449 BuildMI(*MBB, IP, PPC32::SUBFE, 2, DestReg).addReg(TmpReg).addReg(SrcReg);
2453 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2454 unsigned SrcReg2 = makeAnotherReg(Type::IntTy);
2455 BuildMI(*MBB, IP, PPC32::OR, 2, SrcReg2).addReg(SrcReg).addReg(SrcReg+1);
2456 BuildMI(*MBB, IP, PPC32::ADDIC, 2, TmpReg).addReg(SrcReg2).addSImm(-1);
2457 BuildMI(*MBB, IP, PPC32::SUBFE, 2, DestReg).addReg(TmpReg)
2464 std::cerr << "ERROR: Cast fp-to-bool not implemented!\n";
2470 // Implement casts between values of the same type class (as determined by
2471 // getClass) by using a register-to-register move.
2472 if (SrcClass == DestClass) {
2473 if (SrcClass <= cInt) {
2474 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2475 } else if (SrcClass == cFP32 || SrcClass == cFP64) {
2476 BuildMI(*MBB, IP, PPC32::FMR, 1, DestReg).addReg(SrcReg);
2477 } else if (SrcClass == cLong) {
2478 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2479 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg+1).addReg(SrcReg+1)
2482 assert(0 && "Cannot handle this type of cast instruction!");
2488 // Handle cast of Float -> Double
2489 if (SrcClass == cFP32 && DestClass == cFP64) {
2490 BuildMI(*MBB, IP, PPC32::FMR, 1, DestReg).addReg(SrcReg);
2494 // Handle cast of Double -> Float
2495 if (SrcClass == cFP64 && DestClass == cFP32) {
2496 BuildMI(*MBB, IP, PPC32::FRSP, 1, DestReg).addReg(SrcReg);
2500 // Handle cast of SMALLER int to LARGER int using a move with sign extension
2501 // or zero extension, depending on whether the source type was signed.
2502 if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
2503 SrcClass < DestClass) {
2504 bool isLong = DestClass == cLong;
2510 bool isUnsigned = DestTy->isUnsigned() || DestTy == Type::BoolTy;
2511 BuildMI(*BB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2513 if (isLong) { // Handle upper 32 bits as appropriate...
2515 if (isUnsigned) // Zero out top bits...
2516 BuildMI(*BB, IP, PPC32::LI, 1, DestReg).addSImm(0);
2517 else // Sign extend bottom half...
2518 BuildMI(*BB, IP, PPC32::SRAWI, 2, DestReg).addReg(SrcReg).addImm(31);
2523 // Special case long -> int ...
2524 if (SrcClass == cLong && DestClass == cInt) {
2525 BuildMI(*BB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg+1).addReg(SrcReg+1);
2529 // Handle cast of LARGER int to SMALLER int with a clear or sign extend
2530 if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
2531 && SrcClass > DestClass) {
2532 bool isUnsigned = DestTy->isUnsigned() || DestTy == Type::BoolTy;
2533 unsigned source = (SrcClass == cLong) ? SrcReg+1 : SrcReg;
2536 unsigned shift = (SrcClass == cByte) ? 24 : 16;
2537 BuildMI(*BB, IP, PPC32::RLWINM, 4, DestReg).addReg(source).addZImm(0)
2538 .addImm(shift).addImm(31);
2540 BuildMI(*BB, IP, (SrcClass == cByte) ? PPC32::EXTSB : PPC32::EXTSH, 1,
2541 DestReg).addReg(source);
2546 // Handle casts from integer to floating point now...
2547 if (DestClass == cFP32 || DestClass == cFP64) {
2549 // Emit a library call for long to float conversion
2550 if (SrcClass == cLong) {
2551 std::vector<ValueRecord> Args;
2552 Args.push_back(ValueRecord(SrcReg, SrcTy));
2553 Function *floatFn = (DestClass == cFP32) ? __floatdisfFn : __floatdidfFn;
2554 MachineInstr *TheCall =
2555 BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(floatFn, true);
2556 doCall(ValueRecord(DestReg, DestTy), TheCall, Args, false);
2560 // Make sure we're dealing with a full 32 bits
2561 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2562 promote32(TmpReg, ValueRecord(SrcReg, SrcTy));
2566 // Spill the integer to memory and reload it from there.
2567 // Also spill room for a special conversion constant
2568 int ConstantFrameIndex =
2569 F->getFrameInfo()->CreateStackObject(Type::DoubleTy, TM.getTargetData());
2571 F->getFrameInfo()->CreateStackObject(Type::DoubleTy, TM.getTargetData());
2573 unsigned constantHi = makeAnotherReg(Type::IntTy);
2574 unsigned constantLo = makeAnotherReg(Type::IntTy);
2575 unsigned ConstF = makeAnotherReg(Type::DoubleTy);
2576 unsigned TempF = makeAnotherReg(Type::DoubleTy);
2578 if (!SrcTy->isSigned()) {
2579 BuildMI(*BB, IP, PPC32::LIS, 1, constantHi).addSImm(0x4330);
2580 BuildMI(*BB, IP, PPC32::LI, 1, constantLo).addSImm(0);
2581 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantHi),
2582 ConstantFrameIndex);
2583 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantLo),
2584 ConstantFrameIndex, 4);
2585 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantHi),
2587 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(SrcReg),
2589 addFrameReference(BuildMI(*BB, IP, PPC32::LFD, 2, ConstF),
2590 ConstantFrameIndex);
2591 addFrameReference(BuildMI(*BB, IP, PPC32::LFD, 2, TempF), ValueFrameIdx);
2592 BuildMI(*BB, IP, PPC32::FSUB, 2, DestReg).addReg(TempF).addReg(ConstF);
2594 unsigned TempLo = makeAnotherReg(Type::IntTy);
2595 BuildMI(*BB, IP, PPC32::LIS, 1, constantHi).addSImm(0x4330);
2596 BuildMI(*BB, IP, PPC32::LIS, 1, constantLo).addSImm(0x8000);
2597 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantHi),
2598 ConstantFrameIndex);
2599 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantLo),
2600 ConstantFrameIndex, 4);
2601 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantHi),
2603 BuildMI(*BB, IP, PPC32::XORIS, 2, TempLo).addReg(SrcReg).addImm(0x8000);
2604 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(TempLo),
2606 addFrameReference(BuildMI(*BB, IP, PPC32::LFD, 2, ConstF),
2607 ConstantFrameIndex);
2608 addFrameReference(BuildMI(*BB, IP, PPC32::LFD, 2, TempF), ValueFrameIdx);
2609 BuildMI(*BB, IP, PPC32::FSUB, 2, DestReg).addReg(TempF ).addReg(ConstF);
2614 // Handle casts from floating point to integer now...
2615 if (SrcClass == cFP32 || SrcClass == cFP64) {
2616 // emit library call
2617 if (DestClass == cLong) {
2618 std::vector<ValueRecord> Args;
2619 Args.push_back(ValueRecord(SrcReg, SrcTy));
2620 Function *floatFn = (DestClass == cFP32) ? __fixsfdiFn : __fixdfdiFn;
2621 MachineInstr *TheCall =
2622 BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(floatFn, true);
2623 doCall(ValueRecord(DestReg, DestTy), TheCall, Args, false);
2628 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
2630 if (DestTy->isSigned()) {
2631 unsigned LoadOp = (DestClass == cShort) ? PPC32::LHA : PPC32::LWZ;
2632 unsigned TempReg = makeAnotherReg(Type::DoubleTy);
2634 // Convert to integer in the FP reg and store it to a stack slot
2635 BuildMI(*BB, IP, PPC32::FCTIWZ, 1, TempReg).addReg(SrcReg);
2636 addFrameReference(BuildMI(*BB, IP, PPC32::STFD, 3)
2637 .addReg(TempReg), ValueFrameIdx);
2639 // There is no load signed byte opcode, so we must emit a sign extend
2640 if (DestClass == cByte) {
2641 unsigned TempReg2 = makeAnotherReg(DestTy);
2642 addFrameReference(BuildMI(*BB, IP, LoadOp, 2, TempReg2),
2644 BuildMI(*MBB, IP, PPC32::EXTSB, DestReg).addReg(TempReg2);
2646 addFrameReference(BuildMI(*BB, IP, LoadOp, 2, DestReg),
2650 std::cerr << "ERROR: Cast fp-to-unsigned not implemented!\n";
2656 // Anything we haven't handled already, we can't (yet) handle at all.
2657 assert(0 && "Unhandled cast instruction!");
2661 /// visitVANextInst - Implement the va_next instruction...
2663 void ISel::visitVANextInst(VANextInst &I) {
2664 unsigned VAList = getReg(I.getOperand(0));
2665 unsigned DestReg = getReg(I);
2668 switch (I.getArgType()->getTypeID()) {
2671 assert(0 && "Error: bad type for va_next instruction!");
2673 case Type::PointerTyID:
2674 case Type::UIntTyID:
2678 case Type::ULongTyID:
2679 case Type::LongTyID:
2680 case Type::DoubleTyID:
2685 // Increment the VAList pointer...
2686 BuildMI(BB, PPC32::ADDI, 2, DestReg).addReg(VAList).addSImm(Size);
2689 void ISel::visitVAArgInst(VAArgInst &I) {
2690 unsigned VAList = getReg(I.getOperand(0));
2691 unsigned DestReg = getReg(I);
2693 switch (I.getType()->getTypeID()) {
2696 assert(0 && "Error: bad type for va_next instruction!");
2698 case Type::PointerTyID:
2699 case Type::UIntTyID:
2701 BuildMI(BB, PPC32::LWZ, 2, DestReg).addSImm(0).addReg(VAList);
2703 case Type::ULongTyID:
2704 case Type::LongTyID:
2705 BuildMI(BB, PPC32::LWZ, 2, DestReg).addSImm(0).addReg(VAList);
2706 BuildMI(BB, PPC32::LWZ, 2, DestReg+1).addSImm(4).addReg(VAList);
2708 case Type::DoubleTyID:
2709 BuildMI(BB, PPC32::LFD, 2, DestReg).addSImm(0).addReg(VAList);
2714 /// visitGetElementPtrInst - instruction-select GEP instructions
2716 void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
2717 unsigned outputReg = getReg(I);
2718 emitGEPOperation(BB, BB->end(), I.getOperand(0), I.op_begin()+1, I.op_end(),
2722 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
2723 /// constant expression GEP support.
2725 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
2726 MachineBasicBlock::iterator IP,
2727 Value *Src, User::op_iterator IdxBegin,
2728 User::op_iterator IdxEnd, unsigned TargetReg) {
2729 const TargetData &TD = TM.getTargetData();
2730 const Type *Ty = Src->getType();
2731 unsigned basePtrReg = getReg(Src, MBB, IP);
2733 // GEPs have zero or more indices; we must perform a struct access
2734 // or array access for each one.
2735 for (GetElementPtrInst::op_iterator oi = IdxBegin, oe = IdxEnd; oi != oe;
2738 unsigned nextBasePtrReg = makeAnotherReg(Type::UIntTy);
2739 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2740 // It's a struct access. idx is the index into the structure,
2741 // which names the field. Use the TargetData structure to
2742 // pick out what the layout of the structure is in memory.
2743 // Use the (constant) structure index's value to find the
2744 // right byte offset from the StructLayout class's list of
2745 // structure member offsets.
2746 unsigned fieldIndex = cast<ConstantUInt>(idx)->getValue();
2747 unsigned memberOffset =
2748 TD.getStructLayout(StTy)->MemberOffsets[fieldIndex];
2750 if (0 == memberOffset) { // No-op
2751 nextBasePtrReg = basePtrReg;
2753 // Emit an ADDI to add memberOffset to the basePtr.
2754 BuildMI (*MBB, IP, PPC32::ADDI, 2, nextBasePtrReg).addReg(basePtrReg)
2755 .addSImm(memberOffset);
2757 // The next type is the member of the structure selected by the index.
2758 Ty = StTy->getElementType(fieldIndex);
2759 } else if (const SequentialType *SqTy = dyn_cast<SequentialType>(Ty)) {
2760 // Many GEP instructions use a [cast (int/uint) to LongTy] as their
2761 // operand. Handle this case directly now...
2762 if (CastInst *CI = dyn_cast<CastInst>(idx))
2763 if (CI->getOperand(0)->getType() == Type::IntTy ||
2764 CI->getOperand(0)->getType() == Type::UIntTy)
2765 idx = CI->getOperand(0);
2767 Ty = SqTy->getElementType();
2768 unsigned elementSize = TD.getTypeSize(Ty);
2770 if (idx == Constant::getNullValue(idx->getType())) { // No-op
2771 nextBasePtrReg = basePtrReg;
2772 } else if (elementSize == 1) {
2773 // If the element size is 1, we don't have to multiply, just add
2774 unsigned idxReg = getReg(idx, MBB, IP);
2775 BuildMI(*MBB, IP, PPC32::ADD, 2, nextBasePtrReg).addReg(basePtrReg)
2778 // It's an array or pointer access: [ArraySize x ElementType].
2779 // We want to add basePtrReg to (idxReg * sizeof ElementType). First, we
2780 // must find the size of the pointed-to type (Not coincidentally, the
2781 // next type is the type of the elements in the array).
2782 unsigned OffsetReg = makeAnotherReg(idx->getType());
2783 ConstantUInt *CUI = ConstantUInt::get(Type::UIntTy, elementSize);
2784 doMultiplyConst(MBB, IP, OffsetReg, idx, CUI);
2786 // Deal with long indices
2787 if (getClass(idx->getType()) == cLong) ++OffsetReg;
2789 // Emit an ADD to add OffsetReg to the basePtr.
2790 BuildMI (*MBB, IP, PPC32::ADD, 2, nextBasePtrReg).addReg(basePtrReg)
2794 basePtrReg = nextBasePtrReg;
2796 // After we have processed all the indices, the result is left in
2797 // basePtrReg. Move it to the register where we were expected to
2799 BuildMI(BB, PPC32::OR, 2, TargetReg).addReg(basePtrReg).addReg(basePtrReg);
2802 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
2803 /// frame manager, otherwise do it the hard way.
2805 void ISel::visitAllocaInst(AllocaInst &I) {
2806 // If this is a fixed size alloca in the entry block for the function, we
2807 // statically stack allocate the space, so we don't need to do anything here.
2809 if (dyn_castFixedAlloca(&I)) return;
2811 // Find the data size of the alloca inst's getAllocatedType.
2812 const Type *Ty = I.getAllocatedType();
2813 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
2815 // Create a register to hold the temporary result of multiplying the type size
2816 // constant by the variable amount.
2817 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
2819 // TotalSizeReg = mul <numelements>, <TypeSize>
2820 MachineBasicBlock::iterator MBBI = BB->end();
2821 ConstantUInt *CUI = ConstantUInt::get(Type::UIntTy, TySize);
2822 doMultiplyConst(BB, MBBI, TotalSizeReg, I.getArraySize(), CUI);
2824 // AddedSize = add <TotalSizeReg>, 15
2825 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
2826 BuildMI(BB, PPC32::ADDI, 2, AddedSizeReg).addReg(TotalSizeReg).addSImm(15);
2828 // AlignedSize = and <AddedSize>, ~15
2829 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
2830 BuildMI(BB, PPC32::RLWINM, 4, AlignedSize).addReg(AddedSizeReg).addImm(0)
2831 .addImm(0).addImm(27);
2833 // Subtract size from stack pointer, thereby allocating some space.
2834 BuildMI(BB, PPC32::SUB, 2, PPC32::R1).addReg(PPC32::R1).addReg(AlignedSize);
2836 // Put a pointer to the space into the result register, by copying
2837 // the stack pointer.
2838 BuildMI(BB, PPC32::OR, 2, getReg(I)).addReg(PPC32::R1).addReg(PPC32::R1);
2840 // Inform the Frame Information that we have just allocated a variable-sized
2842 F->getFrameInfo()->CreateVariableSizedObject();
2845 /// visitMallocInst - Malloc instructions are code generated into direct calls
2846 /// to the library malloc.
2848 void ISel::visitMallocInst(MallocInst &I) {
2849 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
2852 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
2853 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
2855 Arg = makeAnotherReg(Type::UIntTy);
2856 MachineBasicBlock::iterator MBBI = BB->end();
2857 ConstantUInt *CUI = ConstantUInt::get(Type::UIntTy, AllocSize);
2858 doMultiplyConst(BB, MBBI, Arg, I.getOperand(0), CUI);
2861 std::vector<ValueRecord> Args;
2862 Args.push_back(ValueRecord(Arg, Type::UIntTy));
2863 MachineInstr *TheCall =
2864 BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(mallocFn, true);
2865 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args, false);
2869 /// visitFreeInst - Free instructions are code gen'd to call the free libc
2872 void ISel::visitFreeInst(FreeInst &I) {
2873 std::vector<ValueRecord> Args;
2874 Args.push_back(ValueRecord(I.getOperand(0)));
2875 MachineInstr *TheCall =
2876 BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(freeFn, true);
2877 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args, false);
2880 /// createPPC32SimpleInstructionSelector - This pass converts an LLVM function
2881 /// into a machine code representation is a very simple peep-hole fashion. The
2882 /// generated code sucks but the implementation is nice and simple.
2884 FunctionPass *llvm::createPPCSimpleInstructionSelector(TargetMachine &TM) {
2885 return new ISel(TM);