1 //===-- InstSelectSimple.cpp - A simple instruction selector for PowerPC --===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #define DEBUG_TYPE "isel"
12 #include "PowerPCInstrBuilder.h"
13 #include "PowerPCInstrInfo.h"
14 #include "llvm/Constants.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/Function.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Pass.h"
19 #include "llvm/CodeGen/IntrinsicLowering.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/SSARegMap.h"
24 #include "llvm/Target/MRegisterInfo.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Support/GetElementPtrTypeIterator.h"
27 #include "llvm/Support/InstVisitor.h"
28 #include "Support/Debug.h"
33 /// TypeClass - Used by the PowerPC backend to group LLVM types by their basic
34 /// PPC Representation.
37 cByte, cShort, cInt, cFP, cLong
41 /// getClass - Turn a primitive type into a "class" number which is based on the
42 /// size of the type, and whether or not it is floating point.
44 static inline TypeClass getClass(const Type *Ty) {
45 switch (Ty->getTypeID()) {
47 case Type::UByteTyID: return cByte; // Byte operands are class #0
49 case Type::UShortTyID: return cShort; // Short operands are class #1
52 case Type::PointerTyID: return cInt; // Ints and pointers are class #2
55 case Type::DoubleTyID: return cFP; // Floating Point is #3
58 case Type::ULongTyID: return cLong; // Longs are class #4
60 assert(0 && "Invalid type to getClass!");
61 return cByte; // not reached
65 // getClassB - Just like getClass, but treat boolean values as ints.
66 static inline TypeClass getClassB(const Type *Ty) {
67 if (Ty == Type::BoolTy) return cInt;
72 struct ISel : public FunctionPass, InstVisitor<ISel> {
74 MachineFunction *F; // The function we are compiling into
75 MachineBasicBlock *BB; // The current MBB we are compiling
76 int VarArgsFrameIndex; // FrameIndex for start of varargs area
77 int ReturnAddressIndex; // FrameIndex for the return address
79 std::map<Value*, unsigned> RegMap; // Mapping between Values and SSA Regs
81 // External functions used in the Module
82 Function *fmodFn, *__moddi3Fn, *__divdi3Fn, *__umoddi3Fn, *__udivdi3Fn,
83 *__fixdfdiFn, *__floatdisfFn, *__floatdidfFn, *mallocFn, *freeFn;
85 // MBBMap - Mapping between LLVM BB -> Machine BB
86 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
88 // AllocaMap - Mapping from fixed sized alloca instructions to the
89 // FrameIndex for the alloca.
90 std::map<AllocaInst*, unsigned> AllocaMap;
92 ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
94 bool doInitialization(Module &M) {
95 // Add external functions that we may call
96 Type *d = Type::DoubleTy;
97 Type *f = Type::FloatTy;
98 Type *l = Type::LongTy;
99 Type *ul = Type::ULongTy;
100 Type *voidPtr = PointerType::get(Type::SByteTy);
101 // double fmod(double, double);
102 fmodFn = M.getOrInsertFunction("fmod", d, d, d, 0);
103 // long __moddi3(long, long);
104 __moddi3Fn = M.getOrInsertFunction("__moddi3", l, l, l, 0);
105 // long __divdi3(long, long);
106 __divdi3Fn = M.getOrInsertFunction("__divdi3", l, l, l, 0);
107 // unsigned long __umoddi3(unsigned long, unsigned long);
108 __umoddi3Fn = M.getOrInsertFunction("__umoddi3", ul, ul, ul, 0);
109 // unsigned long __udivdi3(unsigned long, unsigned long);
110 __udivdi3Fn = M.getOrInsertFunction("__udivdi3", ul, ul, ul, 0);
111 // long __fixdfdi(double)
112 __fixdfdiFn = M.getOrInsertFunction("__fixdfdi", l, d, 0);
113 // float __floatdisf(long)
114 __floatdisfFn = M.getOrInsertFunction("__floatdisf", f, l, 0);
115 // double __floatdidf(long)
116 __floatdidfFn = M.getOrInsertFunction("__floatdidf", d, l, 0);
117 // void* malloc(size_t)
118 mallocFn = M.getOrInsertFunction("malloc", voidPtr, Type::UIntTy, 0);
120 freeFn = M.getOrInsertFunction("free", Type::VoidTy, voidPtr, 0);
124 /// runOnFunction - Top level implementation of instruction selection for
125 /// the entire function.
127 bool runOnFunction(Function &Fn) {
128 // First pass over the function, lower any unknown intrinsic functions
129 // with the IntrinsicLowering class.
130 LowerUnknownIntrinsicFunctionCalls(Fn);
132 F = &MachineFunction::construct(&Fn, TM);
134 // Create all of the machine basic blocks for the function...
135 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
136 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
140 // Set up a frame object for the return address. This is used by the
141 // llvm.returnaddress & llvm.frameaddress intrinisics.
142 ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
144 // Copy incoming arguments off of the stack...
145 LoadArgumentsToVirtualRegs(Fn);
147 // Instruction select everything except PHI nodes
150 // Select the PHI nodes
157 // We always build a machine code representation for the function
161 virtual const char *getPassName() const {
162 return "PowerPC Simple Instruction Selection";
165 /// visitBasicBlock - This method is called when we are visiting a new basic
166 /// block. This simply creates a new MachineBasicBlock to emit code into
167 /// and adds it to the current MachineFunction. Subsequent visit* for
168 /// instructions will be invoked for all instructions in the basic block.
170 void visitBasicBlock(BasicBlock &LLVM_BB) {
171 BB = MBBMap[&LLVM_BB];
174 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
175 /// function, lowering any calls to unknown intrinsic functions into the
176 /// equivalent LLVM code.
178 void LowerUnknownIntrinsicFunctionCalls(Function &F);
180 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
181 /// from the stack into virtual registers.
183 void LoadArgumentsToVirtualRegs(Function &F);
185 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
186 /// because we have to generate our sources into the source basic blocks,
187 /// not the current one.
189 void SelectPHINodes();
191 // Visitation methods for various instructions. These methods simply emit
192 // fixed PowerPC code for each instruction.
194 // Control flow operators
195 void visitReturnInst(ReturnInst &RI);
196 void visitBranchInst(BranchInst &BI);
202 ValueRecord(unsigned R, const Type *T) : Val(0), Reg(R), Ty(T) {}
203 ValueRecord(Value *V) : Val(V), Reg(0), Ty(V->getType()) {}
205 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
206 const std::vector<ValueRecord> &Args, bool isVarArg);
207 void visitCallInst(CallInst &I);
208 void visitIntrinsicCall(Intrinsic::ID ID, CallInst &I);
210 // Arithmetic operators
211 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
212 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
213 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
214 void visitMul(BinaryOperator &B);
216 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
217 void visitRem(BinaryOperator &B) { visitDivRem(B); }
218 void visitDivRem(BinaryOperator &B);
221 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
222 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
223 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
225 // Comparison operators...
226 void visitSetCondInst(SetCondInst &I);
227 unsigned EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
228 MachineBasicBlock *MBB,
229 MachineBasicBlock::iterator MBBI);
230 void visitSelectInst(SelectInst &SI);
233 // Memory Instructions
234 void visitLoadInst(LoadInst &I);
235 void visitStoreInst(StoreInst &I);
236 void visitGetElementPtrInst(GetElementPtrInst &I);
237 void visitAllocaInst(AllocaInst &I);
238 void visitMallocInst(MallocInst &I);
239 void visitFreeInst(FreeInst &I);
242 void visitShiftInst(ShiftInst &I);
243 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
244 void visitCastInst(CastInst &I);
245 void visitVANextInst(VANextInst &I);
246 void visitVAArgInst(VAArgInst &I);
248 void visitInstruction(Instruction &I) {
249 std::cerr << "Cannot instruction select: " << I;
253 /// promote32 - Make a value 32-bits wide, and put it somewhere.
255 void promote32(unsigned targetReg, const ValueRecord &VR);
257 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
258 /// constant expression GEP support.
260 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
261 Value *Src, User::op_iterator IdxBegin,
262 User::op_iterator IdxEnd, unsigned TargetReg);
264 /// emitCastOperation - Common code shared between visitCastInst and
265 /// constant expression cast support.
267 void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
268 Value *Src, const Type *DestTy, unsigned TargetReg);
270 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
271 /// and constant expression support.
273 void emitSimpleBinaryOperation(MachineBasicBlock *BB,
274 MachineBasicBlock::iterator IP,
275 Value *Op0, Value *Op1,
276 unsigned OperatorClass, unsigned TargetReg);
278 /// emitBinaryFPOperation - This method handles emission of floating point
279 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
280 void emitBinaryFPOperation(MachineBasicBlock *BB,
281 MachineBasicBlock::iterator IP,
282 Value *Op0, Value *Op1,
283 unsigned OperatorClass, unsigned TargetReg);
285 void emitMultiply(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
286 Value *Op0, Value *Op1, unsigned TargetReg);
288 void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
289 unsigned DestReg, const Type *DestTy,
290 unsigned Op0Reg, unsigned Op1Reg);
291 void doMultiplyConst(MachineBasicBlock *MBB,
292 MachineBasicBlock::iterator MBBI,
293 unsigned DestReg, const Type *DestTy,
294 unsigned Op0Reg, unsigned Op1Val);
296 void emitDivRemOperation(MachineBasicBlock *BB,
297 MachineBasicBlock::iterator IP,
298 Value *Op0, Value *Op1, bool isDiv,
301 /// emitSetCCOperation - Common code shared between visitSetCondInst and
302 /// constant expression support.
304 void emitSetCCOperation(MachineBasicBlock *BB,
305 MachineBasicBlock::iterator IP,
306 Value *Op0, Value *Op1, unsigned Opcode,
309 /// emitShiftOperation - Common code shared between visitShiftInst and
310 /// constant expression support.
312 void emitShiftOperation(MachineBasicBlock *MBB,
313 MachineBasicBlock::iterator IP,
314 Value *Op, Value *ShiftAmount, bool isLeftShift,
315 const Type *ResultTy, unsigned DestReg);
317 /// emitSelectOperation - Common code shared between visitSelectInst and the
318 /// constant expression support.
319 void emitSelectOperation(MachineBasicBlock *MBB,
320 MachineBasicBlock::iterator IP,
321 Value *Cond, Value *TrueVal, Value *FalseVal,
324 /// copyConstantToRegister - Output the instructions required to put the
325 /// specified constant into the specified register.
327 void copyConstantToRegister(MachineBasicBlock *MBB,
328 MachineBasicBlock::iterator MBBI,
329 Constant *C, unsigned Reg);
331 void emitUCOM(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
332 unsigned LHS, unsigned RHS);
334 /// makeAnotherReg - This method returns the next register number we haven't
337 /// Long values are handled somewhat specially. They are always allocated
338 /// as pairs of 32 bit integer values. The register number returned is the
339 /// lower 32 bits of the long value, and the regNum+1 is the upper 32 bits
340 /// of the long value.
342 unsigned makeAnotherReg(const Type *Ty) {
343 assert(dynamic_cast<const PowerPCRegisterInfo*>(TM.getRegisterInfo()) &&
344 "Current target doesn't have PPC reg info??");
345 const PowerPCRegisterInfo *MRI =
346 static_cast<const PowerPCRegisterInfo*>(TM.getRegisterInfo());
347 if (Ty == Type::LongTy || Ty == Type::ULongTy) {
348 const TargetRegisterClass *RC = MRI->getRegClassForType(Type::IntTy);
349 // Create the lower part
350 F->getSSARegMap()->createVirtualRegister(RC);
351 // Create the upper part.
352 return F->getSSARegMap()->createVirtualRegister(RC)-1;
355 // Add the mapping of regnumber => reg class to MachineFunction
356 const TargetRegisterClass *RC = MRI->getRegClassForType(Ty);
357 return F->getSSARegMap()->createVirtualRegister(RC);
360 /// getReg - This method turns an LLVM value into a register number.
362 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
363 unsigned getReg(Value *V) {
364 // Just append to the end of the current bb.
365 MachineBasicBlock::iterator It = BB->end();
366 return getReg(V, BB, It);
368 unsigned getReg(Value *V, MachineBasicBlock *MBB,
369 MachineBasicBlock::iterator IPt);
371 /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
372 /// that is to be statically allocated with the initial stack frame
374 unsigned getFixedSizedAllocaFI(AllocaInst *AI);
378 /// dyn_castFixedAlloca - If the specified value is a fixed size alloca
379 /// instruction in the entry block, return it. Otherwise, return a null
381 static AllocaInst *dyn_castFixedAlloca(Value *V) {
382 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
383 BasicBlock *BB = AI->getParent();
384 if (isa<ConstantUInt>(AI->getArraySize()) && BB ==&BB->getParent()->front())
390 /// getReg - This method turns an LLVM value into a register number.
392 unsigned ISel::getReg(Value *V, MachineBasicBlock *MBB,
393 MachineBasicBlock::iterator IPt) {
394 // If this operand is a constant, emit the code to copy the constant into
395 // the register here...
397 if (Constant *C = dyn_cast<Constant>(V)) {
398 unsigned Reg = makeAnotherReg(V->getType());
399 copyConstantToRegister(MBB, IPt, C, Reg);
401 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
402 // GV is located at PC + distance
403 unsigned CurPC = makeAnotherReg(Type::IntTy);
404 unsigned Reg1 = makeAnotherReg(V->getType());
405 unsigned Reg2 = makeAnotherReg(V->getType());
406 // Move PC to destination reg
407 BuildMI(*MBB, IPt, PPC32::MovePCtoLR, 0, CurPC);
408 // Move value at PC + distance into return reg
409 BuildMI(*MBB, IPt, PPC32::LOADHiAddr, 2, Reg1).addReg(CurPC)
410 .addGlobalAddress(GV);
411 BuildMI(*MBB, IPt, PPC32::LOADLoAddr, 2, Reg2).addReg(Reg1)
412 .addGlobalAddress(GV);
414 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
415 // Do not emit noop casts at all.
416 if (getClassB(CI->getType()) == getClassB(CI->getOperand(0)->getType()))
417 return getReg(CI->getOperand(0), MBB, IPt);
418 } else if (AllocaInst *AI = dyn_castFixedAlloca(V)) {
419 unsigned Reg = makeAnotherReg(V->getType());
420 unsigned FI = getFixedSizedAllocaFI(AI);
421 addFrameReference(BuildMI(*MBB, IPt, PPC32::ADDI, 2, Reg), FI, 0, false);
425 unsigned &Reg = RegMap[V];
427 Reg = makeAnotherReg(V->getType());
434 /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
435 /// that is to be statically allocated with the initial stack frame
437 unsigned ISel::getFixedSizedAllocaFI(AllocaInst *AI) {
438 // Already computed this?
439 std::map<AllocaInst*, unsigned>::iterator I = AllocaMap.lower_bound(AI);
440 if (I != AllocaMap.end() && I->first == AI) return I->second;
442 const Type *Ty = AI->getAllocatedType();
443 ConstantUInt *CUI = cast<ConstantUInt>(AI->getArraySize());
444 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
445 TySize *= CUI->getValue(); // Get total allocated size...
446 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
448 // Create a new stack object using the frame manager...
449 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
450 AllocaMap.insert(I, std::make_pair(AI, FrameIdx));
455 /// copyConstantToRegister - Output the instructions required to put the
456 /// specified constant into the specified register.
458 void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
459 MachineBasicBlock::iterator IP,
460 Constant *C, unsigned R) {
461 if (C->getType()->isIntegral()) {
462 unsigned Class = getClassB(C->getType());
464 if (Class == cLong) {
465 // Copy the value into the register pair.
466 uint64_t Val = cast<ConstantInt>(C)->getRawValue();
467 unsigned hiTmp = makeAnotherReg(Type::IntTy);
468 unsigned loTmp = makeAnotherReg(Type::IntTy);
469 BuildMI(*MBB, IP, PPC32::ADDIS, 2, loTmp).addReg(PPC32::R0)
471 BuildMI(*MBB, IP, PPC32::ORI, 2, R).addReg(loTmp)
472 .addImm((Val >> 32) & 0xFFFF);
473 BuildMI(*MBB, IP, PPC32::ADDIS, 2, hiTmp).addReg(PPC32::R0)
474 .addImm((Val >> 16) & 0xFFFF);
475 BuildMI(*MBB, IP, PPC32::ORI, 2, R+1).addReg(hiTmp).addImm(Val & 0xFFFF);
479 assert(Class <= cInt && "Type not handled yet!");
481 if (C->getType() == Type::BoolTy) {
482 BuildMI(*MBB, IP, PPC32::ADDI, 2, R).addReg(PPC32::R0)
483 .addImm(C == ConstantBool::True);
484 } else if (Class == cByte || Class == cShort) {
485 ConstantInt *CI = cast<ConstantInt>(C);
486 BuildMI(*MBB, IP, PPC32::ADDI, 2, R).addReg(PPC32::R0)
487 .addImm(CI->getRawValue());
489 ConstantInt *CI = cast<ConstantInt>(C);
490 int TheVal = CI->getRawValue() & 0xFFFFFFFF;
491 if (TheVal < 32768 && TheVal >= -32768) {
492 BuildMI(*MBB, IP, PPC32::ADDI, 2, R).addReg(PPC32::R0)
493 .addImm(CI->getRawValue());
495 unsigned TmpReg = makeAnotherReg(Type::IntTy);
496 BuildMI(*MBB, IP, PPC32::ADDIS, 2, TmpReg).addReg(PPC32::R0)
497 .addImm(CI->getRawValue() >> 16);
498 BuildMI(*MBB, IP, PPC32::ORI, 2, R).addReg(TmpReg)
499 .addImm(CI->getRawValue() & 0xFFFF);
502 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
503 // We need to spill the constant to memory...
504 MachineConstantPool *CP = F->getConstantPool();
505 unsigned CPI = CP->getConstantPoolIndex(CFP);
506 const Type *Ty = CFP->getType();
508 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
510 // Load addr of constant to reg; constant is located at PC + distance
511 unsigned CurPC = makeAnotherReg(Type::IntTy);
512 unsigned Reg1 = makeAnotherReg(Type::IntTy);
513 unsigned Reg2 = makeAnotherReg(Type::IntTy);
514 // Move PC to destination reg
515 BuildMI(*MBB, IP, PPC32::MovePCtoLR, 0, CurPC);
516 // Move value at PC + distance into return reg
517 BuildMI(*MBB, IP, PPC32::LOADHiAddr, 2, Reg1).addReg(CurPC)
518 .addConstantPoolIndex(CPI);
519 BuildMI(*MBB, IP, PPC32::LOADLoAddr, 2, Reg2).addReg(Reg1)
520 .addConstantPoolIndex(CPI);
522 unsigned LoadOpcode = (Ty == Type::FloatTy) ? PPC32::LFS : PPC32::LFD;
523 BuildMI(*MBB, IP, LoadOpcode, 2, R).addImm(0).addReg(Reg2);
524 } else if (isa<ConstantPointerNull>(C)) {
525 // Copy zero (null pointer) to the register.
526 BuildMI(*MBB, IP, PPC32::ADDI, 2, R).addReg(PPC32::R0).addImm(0);
527 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
528 BuildMI(*MBB, IP, PPC32::ADDIS, 2, R).addReg(PPC32::R0)
529 .addGlobalAddress(CPR->getValue());
530 BuildMI(*MBB, IP, PPC32::ORI, 2, R).addReg(PPC32::R0)
531 .addGlobalAddress(CPR->getValue());
533 std::cerr << "Offending constant: " << C << "\n";
534 assert(0 && "Type not handled yet!");
538 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
539 /// the stack into virtual registers.
541 /// FIXME: When we can calculate which args are coming in via registers
542 /// source them from there instead.
543 void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
544 unsigned ArgOffset = 0; // Frame mechanisms handle retaddr slot
545 unsigned GPR_remaining = 8;
546 unsigned FPR_remaining = 13;
547 unsigned GPR_idx = 0, FPR_idx = 0;
548 static const unsigned GPR[] = {
549 PPC32::R3, PPC32::R4, PPC32::R5, PPC32::R6,
550 PPC32::R7, PPC32::R8, PPC32::R9, PPC32::R10,
552 static const unsigned FPR[] = {
553 PPC32::F1, PPC32::F2, PPC32::F3, PPC32::F4, PPC32::F5, PPC32::F6, PPC32::F7,
554 PPC32::F8, PPC32::F9, PPC32::F10, PPC32::F11, PPC32::F12, PPC32::F13
557 MachineFrameInfo *MFI = F->getFrameInfo();
559 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
560 bool ArgLive = !I->use_empty();
561 unsigned Reg = ArgLive ? getReg(*I) : 0;
562 int FI; // Frame object index
564 switch (getClassB(I->getType())) {
567 FI = MFI->CreateFixedObject(1, ArgOffset);
568 if (GPR_remaining > 0) {
569 BuildMI(BB, PPC32::OR, 2, Reg).addReg(GPR[GPR_idx])
570 .addReg(GPR[GPR_idx]);
572 addFrameReference(BuildMI(BB, PPC32::LBZ, 2, Reg), FI);
578 FI = MFI->CreateFixedObject(2, ArgOffset);
579 if (GPR_remaining > 0) {
580 BuildMI(BB, PPC32::OR, 2, Reg).addReg(GPR[GPR_idx])
581 .addReg(GPR[GPR_idx]);
583 addFrameReference(BuildMI(BB, PPC32::LHZ, 2, Reg), FI);
589 FI = MFI->CreateFixedObject(4, ArgOffset);
590 if (GPR_remaining > 0) {
591 BuildMI(BB, PPC32::OR, 2, Reg).addReg(GPR[GPR_idx])
592 .addReg(GPR[GPR_idx]);
594 addFrameReference(BuildMI(BB, PPC32::LWZ, 2, Reg), FI);
600 FI = MFI->CreateFixedObject(8, ArgOffset);
601 if (GPR_remaining > 1) {
602 BuildMI(BB, PPC32::OR, 2, Reg).addReg(GPR[GPR_idx])
603 .addReg(GPR[GPR_idx]);
604 BuildMI(BB, PPC32::OR, 2, Reg+1).addReg(GPR[GPR_idx+1])
605 .addReg(GPR[GPR_idx+1]);
607 addFrameReference(BuildMI(BB, PPC32::LWZ, 2, Reg), FI);
608 addFrameReference(BuildMI(BB, PPC32::LWZ, 2, Reg+1), FI, 4);
611 ArgOffset += 4; // longs require 4 additional bytes
612 if (GPR_remaining > 1) {
613 GPR_remaining--; // uses up 2 GPRs
620 if (I->getType() == Type::FloatTy) {
622 FI = MFI->CreateFixedObject(4, ArgOffset);
625 FI = MFI->CreateFixedObject(8, ArgOffset);
627 if (FPR_remaining > 0) {
628 BuildMI(BB, PPC32::FMR, 1, Reg).addReg(FPR[FPR_idx]);
632 addFrameReference(BuildMI(BB, Opcode, 2, Reg), FI);
635 if (I->getType() == Type::DoubleTy) {
636 ArgOffset += 4; // doubles require 4 additional bytes
637 if (GPR_remaining > 0) {
638 GPR_remaining--; // uses up 2 GPRs
644 assert(0 && "Unhandled argument type!");
646 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
647 if (GPR_remaining > 0) {
648 GPR_remaining--; // uses up 2 GPRs
653 // If the function takes variable number of arguments, add a frame offset for
654 // the start of the first vararg value... this is used to expand
656 if (Fn.getFunctionType()->isVarArg())
657 VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
661 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
662 /// because we have to generate our sources into the source basic blocks, not
665 void ISel::SelectPHINodes() {
666 const TargetInstrInfo &TII = *TM.getInstrInfo();
667 const Function &LF = *F->getFunction(); // The LLVM function...
668 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
669 const BasicBlock *BB = I;
670 MachineBasicBlock &MBB = *MBBMap[I];
672 // Loop over all of the PHI nodes in the LLVM basic block...
673 MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
674 for (BasicBlock::const_iterator I = BB->begin();
675 PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
677 // Create a new machine instr PHI node, and insert it.
678 unsigned PHIReg = getReg(*PN);
679 MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
680 PPC32::PHI, PN->getNumOperands(), PHIReg);
682 MachineInstr *LongPhiMI = 0;
683 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
684 LongPhiMI = BuildMI(MBB, PHIInsertPoint,
685 PPC32::PHI, PN->getNumOperands(), PHIReg+1);
687 // PHIValues - Map of blocks to incoming virtual registers. We use this
688 // so that we only initialize one incoming value for a particular block,
689 // even if the block has multiple entries in the PHI node.
691 std::map<MachineBasicBlock*, unsigned> PHIValues;
693 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
694 MachineBasicBlock *PredMBB = 0;
695 for (MachineBasicBlock::pred_iterator PI = MBB.pred_begin (),
696 PE = MBB.pred_end (); PI != PE; ++PI)
697 if (PN->getIncomingBlock(i) == (*PI)->getBasicBlock()) {
701 assert (PredMBB && "Couldn't find incoming machine-cfg edge for phi");
704 std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
705 PHIValues.lower_bound(PredMBB);
707 if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
708 // We already inserted an initialization of the register for this
709 // predecessor. Recycle it.
710 ValReg = EntryIt->second;
713 // Get the incoming value into a virtual register.
715 Value *Val = PN->getIncomingValue(i);
717 // If this is a constant or GlobalValue, we may have to insert code
718 // into the basic block to compute it into a virtual register.
719 if ((isa<Constant>(Val) && !isa<ConstantExpr>(Val)) ||
720 isa<GlobalValue>(Val)) {
721 // Simple constants get emitted at the end of the basic block,
722 // before any terminator instructions. We "know" that the code to
723 // move a constant into a register will never clobber any flags.
724 ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
726 // Because we don't want to clobber any values which might be in
727 // physical registers with the computation of this constant (which
728 // might be arbitrarily complex if it is a constant expression),
729 // just insert the computation at the top of the basic block.
730 MachineBasicBlock::iterator PI = PredMBB->begin();
732 // Skip over any PHI nodes though!
733 while (PI != PredMBB->end() && PI->getOpcode() == PPC32::PHI)
736 ValReg = getReg(Val, PredMBB, PI);
739 // Remember that we inserted a value for this PHI for this predecessor
740 PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
743 PhiMI->addRegOperand(ValReg);
744 PhiMI->addMachineBasicBlockOperand(PredMBB);
746 LongPhiMI->addRegOperand(ValReg+1);
747 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
751 // Now that we emitted all of the incoming values for the PHI node, make
752 // sure to reposition the InsertPoint after the PHI that we just added.
753 // This is needed because we might have inserted a constant into this
754 // block, right after the PHI's which is before the old insert point!
755 PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
762 // canFoldSetCCIntoBranchOrSelect - Return the setcc instruction if we can fold
763 // it into the conditional branch or select instruction which is the only user
764 // of the cc instruction. This is the case if the conditional branch is the
765 // only user of the setcc, and if the setcc is in the same basic block as the
766 // conditional branch. We also don't handle long arguments below, so we reject
767 // them here as well.
769 static SetCondInst *canFoldSetCCIntoBranchOrSelect(Value *V) {
770 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
771 if (SCI->hasOneUse()) {
772 Instruction *User = cast<Instruction>(SCI->use_back());
773 if ((isa<BranchInst>(User) || isa<SelectInst>(User)) &&
774 SCI->getParent() == User->getParent() &&
775 (getClassB(SCI->getOperand(0)->getType()) != cLong ||
776 SCI->getOpcode() == Instruction::SetEQ ||
777 SCI->getOpcode() == Instruction::SetNE))
783 // Return a fixed numbering for setcc instructions which does not depend on the
784 // order of the opcodes.
786 static unsigned getSetCCNumber(unsigned Opcode) {
788 default: assert(0 && "Unknown setcc instruction!");
789 case Instruction::SetEQ: return 0;
790 case Instruction::SetNE: return 1;
791 case Instruction::SetLT: return 2;
792 case Instruction::SetGE: return 3;
793 case Instruction::SetGT: return 4;
794 case Instruction::SetLE: return 5;
798 static unsigned getPPCOpcodeForSetCCNumber(unsigned Opcode) {
800 default: assert(0 && "Unknown setcc instruction!");
801 case Instruction::SetEQ: return PPC32::BEQ;
802 case Instruction::SetNE: return PPC32::BNE;
803 case Instruction::SetLT: return PPC32::BLT;
804 case Instruction::SetGE: return PPC32::BGE;
805 case Instruction::SetGT: return PPC32::BGT;
806 case Instruction::SetLE: return PPC32::BLE;
810 static unsigned invertPPCBranchOpcode(unsigned Opcode) {
812 default: assert(0 && "Unknown PPC32 branch opcode!");
813 case PPC32::BEQ: return PPC32::BNE;
814 case PPC32::BNE: return PPC32::BEQ;
815 case PPC32::BLT: return PPC32::BGE;
816 case PPC32::BGE: return PPC32::BLT;
817 case PPC32::BGT: return PPC32::BLE;
818 case PPC32::BLE: return PPC32::BGT;
822 /// emitUCOM - emits an unordered FP compare.
823 void ISel::emitUCOM(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
824 unsigned LHS, unsigned RHS) {
825 BuildMI(*MBB, IP, PPC32::FCMPU, 2, PPC32::CR0).addReg(LHS).addReg(RHS);
828 // EmitComparison - This function emits a comparison of the two operands,
829 // returning the extended setcc code to use.
830 unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
831 MachineBasicBlock *MBB,
832 MachineBasicBlock::iterator IP) {
833 // The arguments are already supposed to be of the same type.
834 const Type *CompTy = Op0->getType();
835 unsigned Class = getClassB(CompTy);
836 unsigned Op0r = getReg(Op0, MBB, IP);
838 // Special case handling of: cmp R, i
839 if (isa<ConstantPointerNull>(Op1)) {
840 BuildMI(*MBB, IP, PPC32::CMPI, 2, PPC32::CR0).addReg(Op0r).addImm(0);
841 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
842 if (Class == cByte || Class == cShort || Class == cInt) {
843 unsigned Op1v = CI->getRawValue();
845 // Mask off any upper bits of the constant, if there are any...
846 Op1v &= (1ULL << (8 << Class)) - 1;
848 // Compare immediate or promote to reg?
850 BuildMI(*MBB, IP, CompTy->isSigned() ? PPC32::CMPI : PPC32::CMPLI, 3,
851 PPC32::CR0).addImm(0).addReg(Op0r).addImm(Op1v);
853 unsigned Op1r = getReg(Op1, MBB, IP);
854 BuildMI(*MBB, IP, CompTy->isSigned() ? PPC32::CMP : PPC32::CMPL, 3,
855 PPC32::CR0).addImm(0).addReg(Op0r).addReg(Op1r);
859 assert(Class == cLong && "Unknown integer class!");
860 unsigned LowCst = CI->getRawValue();
861 unsigned HiCst = CI->getRawValue() >> 32;
862 if (OpNum < 2) { // seteq, setne
863 unsigned LoTmp = Op0r;
865 unsigned LoLow = makeAnotherReg(Type::IntTy);
866 unsigned LoTmp = makeAnotherReg(Type::IntTy);
867 BuildMI(*MBB, IP, PPC32::XORI, 2, LoLow).addReg(Op0r).addImm(LowCst);
868 BuildMI(*MBB, IP, PPC32::XORIS, 2, LoTmp).addReg(LoLow)
869 .addImm(LowCst >> 16);
871 unsigned HiTmp = Op0r+1;
873 unsigned HiLow = makeAnotherReg(Type::IntTy);
874 unsigned HiTmp = makeAnotherReg(Type::IntTy);
875 BuildMI(*MBB, IP, PPC32::XORI, 2, HiLow).addReg(Op0r+1).addImm(HiCst);
876 BuildMI(*MBB, IP, PPC32::XORIS, 2, HiTmp).addReg(HiLow)
877 .addImm(HiCst >> 16);
879 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
880 BuildMI(*MBB, IP, PPC32::ORo, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
881 //BuildMI(*MBB, IP, PPC32::CMPLI, 2, PPC32::CR0).addReg(FinalTmp).addImm(0);
884 // FIXME: Not Yet Implemented
885 std::cerr << "EmitComparison unimplemented: Opnum >= 2\n";
892 unsigned Op1r = getReg(Op1, MBB, IP);
894 default: assert(0 && "Unknown type class!");
898 BuildMI(*MBB, IP, CompTy->isSigned() ? PPC32::CMP : PPC32::CMPL, 2,
899 PPC32::CR0).addReg(Op0r).addReg(Op1r);
903 emitUCOM(MBB, IP, Op0r, Op1r);
907 if (OpNum < 2) { // seteq, setne
908 unsigned LoTmp = makeAnotherReg(Type::IntTy);
909 unsigned HiTmp = makeAnotherReg(Type::IntTy);
910 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
911 BuildMI(*MBB, IP, PPC32::XOR, 2, LoTmp).addReg(Op0r).addReg(Op1r);
912 BuildMI(*MBB, IP, PPC32::XOR, 2, HiTmp).addReg(Op0r+1).addReg(Op1r+1);
913 BuildMI(*MBB, IP, PPC32::ORo, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
914 //BuildMI(*MBB, IP, PPC32::CMPLI, 2, PPC32::CR0).addReg(FinalTmp).addImm(0);
915 break; // Allow the sete or setne to be generated from flags set by OR
917 // FIXME: Not Yet Implemented
918 std::cerr << "EmitComparison (cLong) unimplemented: Opnum >= 2\n";
926 /// visitSetCondInst - emit code to calculate the condition via
927 /// EmitComparison(), and possibly store a 0 or 1 to a register as a result
929 void ISel::visitSetCondInst(SetCondInst &I) {
930 if (canFoldSetCCIntoBranchOrSelect(&I))
933 unsigned Op0Reg = getReg(I.getOperand(0));
934 unsigned Op1Reg = getReg(I.getOperand(1));
935 unsigned DestReg = getReg(I);
936 unsigned OpNum = I.getOpcode();
937 const Type *Ty = I.getOperand (0)->getType();
939 EmitComparison(OpNum, I.getOperand(0), I.getOperand(1), BB, BB->end());
941 unsigned Opcode = getPPCOpcodeForSetCCNumber(OpNum);
942 MachineBasicBlock *thisMBB = BB;
943 const BasicBlock *LLVM_BB = BB->getBasicBlock();
950 // FIXME: we wouldn't need copy0MBB (we could fold it into thisMBB)
951 // if we could insert other, non-terminator instructions after the
952 // bCC. But MBB->getFirstTerminator() can't understand this.
953 MachineBasicBlock *copy1MBB = new MachineBasicBlock(LLVM_BB);
954 F->getBasicBlockList().push_back(copy1MBB);
955 BuildMI(BB, Opcode, 2).addReg(PPC32::CR0).addMBB(copy1MBB);
956 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
957 F->getBasicBlockList().push_back(copy0MBB);
958 BuildMI(BB, PPC32::B, 1).addMBB(copy0MBB);
959 // Update machine-CFG edges
960 BB->addSuccessor(copy1MBB);
961 BB->addSuccessor(copy0MBB);
964 // %FalseValue = li 0
967 unsigned FalseValue = makeAnotherReg(I.getType());
968 BuildMI(BB, PPC32::LI, 1, FalseValue).addZImm(0);
969 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
970 F->getBasicBlockList().push_back(sinkMBB);
971 BuildMI(BB, PPC32::B, 1).addMBB(sinkMBB);
972 // Update machine-CFG edges
973 BB->addSuccessor(sinkMBB);
975 DEBUG(std::cerr << "thisMBB is at " << (void*)thisMBB << "\n");
976 DEBUG(std::cerr << "copy1MBB is at " << (void*)copy1MBB << "\n");
977 DEBUG(std::cerr << "copy0MBB is at " << (void*)copy0MBB << "\n");
978 DEBUG(std::cerr << "sinkMBB is at " << (void*)sinkMBB << "\n");
984 unsigned TrueValue = makeAnotherReg (I.getType ());
985 BuildMI(BB, PPC32::LI, 1, TrueValue).addZImm(1);
986 BuildMI(BB, PPC32::B, 1).addMBB(sinkMBB);
987 // Update machine-CFG edges
988 BB->addSuccessor(sinkMBB);
991 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, copy1MBB ]
994 BuildMI(BB, PPC32::PHI, 4, DestReg).addReg(FalseValue)
995 .addMBB(copy0MBB).addReg(TrueValue).addMBB(copy1MBB);
998 void ISel::visitSelectInst(SelectInst &SI) {
999 unsigned DestReg = getReg(SI);
1000 MachineBasicBlock::iterator MII = BB->end();
1001 emitSelectOperation(BB, MII, SI.getCondition(), SI.getTrueValue(),
1002 SI.getFalseValue(), DestReg);
1005 /// emitSelect - Common code shared between visitSelectInst and the constant
1006 /// expression support.
1007 /// FIXME: this is most likely broken in one or more ways. Namely, PowerPC has
1008 /// no select instruction. FSEL only works for comparisons against zero.
1009 void ISel::emitSelectOperation(MachineBasicBlock *MBB,
1010 MachineBasicBlock::iterator IP,
1011 Value *Cond, Value *TrueVal, Value *FalseVal,
1013 unsigned SelectClass = getClassB(TrueVal->getType());
1015 unsigned TrueReg = getReg(TrueVal, MBB, IP);
1016 unsigned FalseReg = getReg(FalseVal, MBB, IP);
1018 if (TrueReg == FalseReg) {
1019 if (SelectClass == cFP) {
1020 BuildMI(*MBB, IP, PPC32::FMR, 1, DestReg).addReg(TrueReg);
1022 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(TrueReg).addReg(TrueReg);
1025 if (SelectClass == cLong)
1026 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg+1).addReg(TrueReg+1)
1031 unsigned CondReg = getReg(Cond, MBB, IP);
1032 unsigned numZeros = makeAnotherReg(Type::IntTy);
1033 unsigned falseHi = makeAnotherReg(Type::IntTy);
1034 unsigned falseAll = makeAnotherReg(Type::IntTy);
1035 unsigned trueAll = makeAnotherReg(Type::IntTy);
1036 unsigned Temp1 = makeAnotherReg(Type::IntTy);
1037 unsigned Temp2 = makeAnotherReg(Type::IntTy);
1039 BuildMI(*MBB, IP, PPC32::CNTLZW, 1, numZeros).addReg(CondReg);
1040 BuildMI(*MBB, IP, PPC32::RLWINM, 4, falseHi).addReg(numZeros).addImm(26)
1041 .addImm(0).addImm(0);
1042 BuildMI(*MBB, IP, PPC32::SRAWI, 2, falseAll).addReg(falseHi).addImm(31);
1043 BuildMI(*MBB, IP, PPC32::NOR, 2, trueAll).addReg(falseAll).addReg(falseAll);
1044 BuildMI(*MBB, IP, PPC32::AND, 2, Temp1).addReg(TrueReg).addReg(trueAll);
1045 BuildMI(*MBB, IP, PPC32::AND, 2, Temp2).addReg(FalseReg).addReg(falseAll);
1046 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(Temp1).addReg(Temp2);
1048 if (SelectClass == cLong) {
1049 unsigned Temp3 = makeAnotherReg(Type::IntTy);
1050 unsigned Temp4 = makeAnotherReg(Type::IntTy);
1051 BuildMI(*MBB, IP, PPC32::AND, 2, Temp3).addReg(TrueReg+1).addReg(trueAll);
1052 BuildMI(*MBB, IP, PPC32::AND, 2, Temp4).addReg(FalseReg+1).addReg(falseAll);
1053 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg+1).addReg(Temp3).addReg(Temp4);
1061 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
1062 /// operand, in the specified target register.
1064 void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
1065 bool isUnsigned = VR.Ty->isUnsigned() || VR.Ty == Type::BoolTy;
1067 Value *Val = VR.Val;
1068 const Type *Ty = VR.Ty;
1070 if (Constant *C = dyn_cast<Constant>(Val)) {
1071 Val = ConstantExpr::getCast(C, Type::IntTy);
1075 // If this is a simple constant, just emit a load directly to avoid the copy
1076 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
1077 int TheVal = CI->getRawValue() & 0xFFFFFFFF;
1079 if (TheVal < 32768 && TheVal >= -32768) {
1080 BuildMI(BB, PPC32::ADDI, 2, targetReg).addReg(PPC32::R0).addImm(TheVal);
1082 unsigned TmpReg = makeAnotherReg(Type::IntTy);
1083 BuildMI(BB, PPC32::ADDIS, 2, TmpReg).addReg(PPC32::R0)
1084 .addImm(TheVal >> 16);
1085 BuildMI(BB, PPC32::ORI, 2, targetReg).addReg(TmpReg)
1086 .addImm(TheVal & 0xFFFF);
1092 // Make sure we have the register number for this value...
1093 unsigned Reg = Val ? getReg(Val) : VR.Reg;
1095 switch (getClassB(Ty)) {
1097 // Extend value into target register (8->32)
1099 BuildMI(BB, PPC32::RLWINM, 4, targetReg).addReg(Reg).addZImm(0)
1100 .addZImm(24).addZImm(31);
1102 BuildMI(BB, PPC32::EXTSB, 1, targetReg).addReg(Reg);
1105 // Extend value into target register (16->32)
1107 BuildMI(BB, PPC32::RLWINM, 4, targetReg).addReg(Reg).addZImm(0)
1108 .addZImm(16).addZImm(31);
1110 BuildMI(BB, PPC32::EXTSH, 1, targetReg).addReg(Reg);
1113 // Move value into target register (32->32)
1114 BuildMI(BB, PPC32::OR, 2, targetReg).addReg(Reg).addReg(Reg);
1117 assert(0 && "Unpromotable operand class in promote32");
1121 /// visitReturnInst - implemented with BLR
1123 void ISel::visitReturnInst(ReturnInst &I) {
1124 // Only do the processing if this is a non-void return
1125 if (I.getNumOperands() > 0) {
1126 Value *RetVal = I.getOperand(0);
1127 switch (getClassB(RetVal->getType())) {
1128 case cByte: // integral return values: extend or move into r3 and return
1131 promote32(PPC32::R3, ValueRecord(RetVal));
1133 case cFP: { // Floats & Doubles: Return in f1
1134 unsigned RetReg = getReg(RetVal);
1135 BuildMI(BB, PPC32::FMR, 1, PPC32::F1).addReg(RetReg);
1139 unsigned RetReg = getReg(RetVal);
1140 BuildMI(BB, PPC32::OR, 2, PPC32::R3).addReg(RetReg).addReg(RetReg);
1141 BuildMI(BB, PPC32::OR, 2, PPC32::R4).addReg(RetReg+1).addReg(RetReg+1);
1145 visitInstruction(I);
1148 BuildMI(BB, PPC32::BLR, 1).addImm(0);
1151 // getBlockAfter - Return the basic block which occurs lexically after the
1153 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1154 Function::iterator I = BB; ++I; // Get iterator to next block
1155 return I != BB->getParent()->end() ? &*I : 0;
1158 /// visitBranchInst - Handle conditional and unconditional branches here. Note
1159 /// that since code layout is frozen at this point, that if we are trying to
1160 /// jump to a block that is the immediate successor of the current block, we can
1161 /// just make a fall-through (but we don't currently).
1163 void ISel::visitBranchInst(BranchInst &BI) {
1164 // Update machine-CFG edges
1165 BB->addSuccessor (MBBMap[BI.getSuccessor(0)]);
1166 if (BI.isConditional())
1167 BB->addSuccessor (MBBMap[BI.getSuccessor(1)]);
1169 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
1171 if (!BI.isConditional()) { // Unconditional branch?
1172 if (BI.getSuccessor(0) != NextBB)
1173 BuildMI(BB, PPC32::B, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1177 // See if we can fold the setcc into the branch itself...
1178 SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(BI.getCondition());
1180 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
1181 // computed some other way...
1182 unsigned condReg = getReg(BI.getCondition());
1183 BuildMI(BB, PPC32::CMPLI, 3, PPC32::CR1).addImm(0).addReg(condReg)
1185 if (BI.getSuccessor(1) == NextBB) {
1186 if (BI.getSuccessor(0) != NextBB)
1187 BuildMI(BB, PPC32::BNE, 2).addReg(PPC32::CR1)
1188 .addMBB(MBBMap[BI.getSuccessor(0)]);
1190 BuildMI(BB, PPC32::BNE, 2).addReg(PPC32::CR1)
1191 .addMBB(MBBMap[BI.getSuccessor(1)]);
1193 if (BI.getSuccessor(0) != NextBB)
1194 BuildMI(BB, PPC32::B, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1199 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1200 unsigned Opcode = getPPCOpcodeForSetCCNumber(SCI->getOpcode());
1201 MachineBasicBlock::iterator MII = BB->end();
1202 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
1204 if (BI.getSuccessor(0) != NextBB) {
1205 BuildMI(BB, Opcode, 2).addReg(PPC32::CR0)
1206 .addMBB(MBBMap[BI.getSuccessor(0)]);
1207 if (BI.getSuccessor(1) != NextBB)
1208 BuildMI(BB, PPC32::B, 1).addMBB(MBBMap[BI.getSuccessor(1)]);
1210 // Change to the inverse condition...
1211 if (BI.getSuccessor(1) != NextBB) {
1212 Opcode = invertPPCBranchOpcode(Opcode);
1213 BuildMI(BB, Opcode, 2).addReg(PPC32::CR0)
1214 .addMBB(MBBMap[BI.getSuccessor(1)]);
1219 static Constant* minUConstantForValue(uint64_t val) {
1221 return ConstantBool::get(val);
1222 else if (ConstantUInt::isValueValidForType(Type::UShortTy, val))
1223 return ConstantUInt::get(Type::UShortTy, val);
1224 else if (ConstantUInt::isValueValidForType(Type::UIntTy, val))
1225 return ConstantUInt::get(Type::UIntTy, val);
1226 else if (ConstantUInt::isValueValidForType(Type::ULongTy, val))
1227 return ConstantUInt::get(Type::ULongTy, val);
1229 std::cerr << "Value: " << val << " not accepted for any integral type!\n";
1233 /// doCall - This emits an abstract call instruction, setting up the arguments
1234 /// and the return value as appropriate. For the actual function call itself,
1235 /// it inserts the specified CallMI instruction into the stream.
1237 /// FIXME: See Documentation at the following URL for "correct" behavior
1238 /// <http://developer.apple.com/documentation/DeveloperTools/Conceptual/MachORuntime/2rt_powerpc_abi/chapter_9_section_5.html>
1239 void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
1240 const std::vector<ValueRecord> &Args, bool isVarArg) {
1241 // Count how many bytes are to be pushed on the stack...
1242 unsigned NumBytes = 0;
1244 if (!Args.empty()) {
1245 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1246 switch (getClassB(Args[i].Ty)) {
1247 case cByte: case cShort: case cInt:
1248 NumBytes += 4; break;
1250 NumBytes += 8; break;
1252 NumBytes += Args[i].Ty == Type::FloatTy ? 4 : 8;
1254 default: assert(0 && "Unknown class!");
1257 // Adjust the stack pointer for the new arguments...
1258 BuildMI(BB, PPC32::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
1260 // Arguments go on the stack in reverse order, as specified by the ABI.
1261 unsigned ArgOffset = 0;
1262 int GPR_remaining = 8, FPR_remaining = 13;
1263 unsigned GPR_idx = 0, FPR_idx = 0;
1264 static const unsigned GPR[] = {
1265 PPC32::R3, PPC32::R4, PPC32::R5, PPC32::R6,
1266 PPC32::R7, PPC32::R8, PPC32::R9, PPC32::R10,
1268 static const unsigned FPR[] = {
1269 PPC32::F1, PPC32::F2, PPC32::F3, PPC32::F4, PPC32::F5, PPC32::F6,
1270 PPC32::F7, PPC32::F8, PPC32::F9, PPC32::F10, PPC32::F11, PPC32::F12,
1274 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1276 switch (getClassB(Args[i].Ty)) {
1279 // Promote arg to 32 bits wide into a temporary register...
1280 ArgReg = makeAnotherReg(Type::UIntTy);
1281 promote32(ArgReg, Args[i]);
1284 if (GPR_remaining > 0) {
1285 BuildMI(BB, PPC32::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1288 BuildMI(BB, PPC32::STW, 3).addReg(ArgReg).addImm(ArgOffset)
1293 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1296 if (GPR_remaining > 0) {
1297 BuildMI(BB, PPC32::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1300 BuildMI(BB, PPC32::STW, 3).addReg(ArgReg).addImm(ArgOffset)
1305 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1308 if (GPR_remaining > 1) {
1309 BuildMI(BB, PPC32::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1311 BuildMI(BB, PPC32::OR, 2, GPR[GPR_idx + 1]).addReg(ArgReg+1)
1314 BuildMI(BB, PPC32::STW, 3).addReg(ArgReg).addImm(ArgOffset)
1316 BuildMI(BB, PPC32::STW, 3).addReg(ArgReg+1).addImm(ArgOffset+4)
1320 ArgOffset += 4; // 8 byte entry, not 4.
1321 GPR_remaining -= 1; // uses up 2 GPRs
1325 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1326 if (Args[i].Ty == Type::FloatTy) {
1327 assert(!isVarArg && "Cannot pass floats to vararg functions!");
1329 if (FPR_remaining > 0) {
1330 BuildMI(BB, PPC32::FMR, 1, FPR[FPR_idx]).addReg(ArgReg);
1334 BuildMI(BB, PPC32::STFS, 3).addReg(ArgReg).addImm(ArgOffset)
1338 assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
1340 if (FPR_remaining > 0) {
1341 BuildMI(BB, PPC32::FMR, 1, FPR[FPR_idx]).addReg(ArgReg);
1344 // For vararg functions, must pass doubles via int regs as well
1346 Value *Val = Args[i].Val;
1347 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Val)) {
1355 U.FVal = CFP->getValue();
1356 if (GPR_remaining > 0) {
1357 Constant *hi32 = minUConstantForValue(U.UVal.hi32);
1358 copyConstantToRegister(BB, BB->end(), hi32, GPR[GPR_idx]);
1360 if (GPR_remaining > 1) {
1361 Constant *lo32 = minUConstantForValue(U.UVal.lo32);
1362 copyConstantToRegister(BB, BB->end(), lo32, GPR[GPR_idx+1]);
1365 // Since this is not a constant, we must load it into int regs
1367 BuildMI(BB, PPC32::STFD, 3).addReg(ArgReg).addImm(ArgOffset)
1369 if (GPR_remaining > 0)
1370 BuildMI(BB, PPC32::LWZ, 2, GPR[GPR_idx]).addImm(ArgOffset)
1372 if (GPR_remaining > 1)
1373 BuildMI(BB, PPC32::LWZ, 2, GPR[GPR_idx+1])
1374 .addImm(ArgOffset+4).addReg(PPC32::R1);
1378 BuildMI(BB, PPC32::STFD, 3).addReg(ArgReg).addImm(ArgOffset)
1382 ArgOffset += 4; // 8 byte entry, not 4.
1383 GPR_remaining--; // uses up 2 GPRs
1388 default: assert(0 && "Unknown class!");
1395 BuildMI(BB, PPC32::ADJCALLSTACKDOWN, 1).addImm(0);
1398 BB->push_back(CallMI);
1399 BuildMI(BB, PPC32::ADJCALLSTACKUP, 1).addImm(NumBytes);
1401 // If there is a return value, scavenge the result from the location the call
1404 if (Ret.Ty != Type::VoidTy) {
1405 unsigned DestClass = getClassB(Ret.Ty);
1406 switch (DestClass) {
1410 // Integral results are in r3
1411 BuildMI(BB, PPC32::OR, 2, Ret.Reg).addReg(PPC32::R3).addReg(PPC32::R3);
1413 case cFP: // Floating-point return values live in f1
1414 BuildMI(BB, PPC32::FMR, 1, Ret.Reg).addReg(PPC32::F1);
1416 case cLong: // Long values are in r3:r4
1417 BuildMI(BB, PPC32::OR, 2, Ret.Reg).addReg(PPC32::R3).addReg(PPC32::R3);
1418 BuildMI(BB, PPC32::OR, 2, Ret.Reg+1).addReg(PPC32::R4).addReg(PPC32::R4);
1420 default: assert(0 && "Unknown class!");
1426 /// visitCallInst - Push args on stack and do a procedure call instruction.
1427 void ISel::visitCallInst(CallInst &CI) {
1428 MachineInstr *TheCall;
1429 Function *F = CI.getCalledFunction();
1431 // Is it an intrinsic function call?
1432 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1433 visitIntrinsicCall(ID, CI); // Special intrinsics are not handled here
1437 // Emit a CALL instruction with PC-relative displacement.
1438 TheCall = BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(F, true);
1439 } else { // Emit an indirect call through the CTR
1440 unsigned Reg = getReg(CI.getCalledValue());
1441 BuildMI(PPC32::MTSPR, 2).addZImm(9).addReg(Reg);
1442 TheCall = BuildMI(PPC32::CALLindirect, 1).addZImm(20).addZImm(0);
1445 std::vector<ValueRecord> Args;
1446 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
1447 Args.push_back(ValueRecord(CI.getOperand(i)));
1449 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1450 bool isVarArg = F ? F->getFunctionType()->isVarArg() : true;
1451 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args, isVarArg);
1455 /// dyncastIsNan - Return the operand of an isnan operation if this is an isnan.
1457 static Value *dyncastIsNan(Value *V) {
1458 if (CallInst *CI = dyn_cast<CallInst>(V))
1459 if (Function *F = CI->getCalledFunction())
1460 if (F->getIntrinsicID() == Intrinsic::isunordered)
1461 return CI->getOperand(1);
1465 /// isOnlyUsedByUnorderedComparisons - Return true if this value is only used by
1466 /// or's whos operands are all calls to the isnan predicate.
1467 static bool isOnlyUsedByUnorderedComparisons(Value *V) {
1468 assert(dyncastIsNan(V) && "The value isn't an isnan call!");
1470 // Check all uses, which will be or's of isnans if this predicate is true.
1471 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1472 Instruction *I = cast<Instruction>(*UI);
1473 if (I->getOpcode() != Instruction::Or) return false;
1474 if (I->getOperand(0) != V && !dyncastIsNan(I->getOperand(0))) return false;
1475 if (I->getOperand(1) != V && !dyncastIsNan(I->getOperand(1))) return false;
1481 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1482 /// function, lowering any calls to unknown intrinsic functions into the
1483 /// equivalent LLVM code.
1485 void ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1486 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1487 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1488 if (CallInst *CI = dyn_cast<CallInst>(I++))
1489 if (Function *F = CI->getCalledFunction())
1490 switch (F->getIntrinsicID()) {
1491 case Intrinsic::not_intrinsic:
1492 case Intrinsic::vastart:
1493 case Intrinsic::vacopy:
1494 case Intrinsic::vaend:
1495 case Intrinsic::returnaddress:
1496 case Intrinsic::frameaddress:
1497 // FIXME: should lower this ourselves
1498 // case Intrinsic::isunordered:
1499 // We directly implement these intrinsics
1501 case Intrinsic::readio: {
1502 // On PPC, memory operations are in-order. Lower this intrinsic
1503 // into a volatile load.
1504 Instruction *Before = CI->getPrev();
1505 LoadInst * LI = new LoadInst(CI->getOperand(1), "", true, CI);
1506 CI->replaceAllUsesWith(LI);
1507 BB->getInstList().erase(CI);
1510 case Intrinsic::writeio: {
1511 // On PPC, memory operations are in-order. Lower this intrinsic
1512 // into a volatile store.
1513 Instruction *Before = CI->getPrev();
1514 StoreInst *LI = new StoreInst(CI->getOperand(1),
1515 CI->getOperand(2), true, CI);
1516 CI->replaceAllUsesWith(LI);
1517 BB->getInstList().erase(CI);
1521 // All other intrinsic calls we must lower.
1522 Instruction *Before = CI->getPrev();
1523 TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
1524 if (Before) { // Move iterator to instruction after call
1532 void ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
1533 unsigned TmpReg1, TmpReg2, TmpReg3;
1535 case Intrinsic::vastart:
1536 // Get the address of the first vararg value...
1537 TmpReg1 = getReg(CI);
1538 addFrameReference(BuildMI(BB, PPC32::ADDI, 2, TmpReg1), VarArgsFrameIndex);
1541 case Intrinsic::vacopy:
1542 TmpReg1 = getReg(CI);
1543 TmpReg2 = getReg(CI.getOperand(1));
1544 BuildMI(BB, PPC32::OR, 2, TmpReg1).addReg(TmpReg2).addReg(TmpReg2);
1546 case Intrinsic::vaend: return;
1548 case Intrinsic::returnaddress:
1549 case Intrinsic::frameaddress:
1550 TmpReg1 = getReg(CI);
1551 if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1552 if (ID == Intrinsic::returnaddress) {
1553 // Just load the return address
1554 addFrameReference(BuildMI(BB, PPC32::LWZ, 2, TmpReg1),
1555 ReturnAddressIndex);
1557 addFrameReference(BuildMI(BB, PPC32::ADDI, 2, TmpReg1),
1558 ReturnAddressIndex, -4, false);
1561 // Values other than zero are not implemented yet.
1562 BuildMI(BB, PPC32::ADDI, 2, TmpReg1).addReg(PPC32::R0).addImm(0);
1567 // This may be useful for supporting isunordered
1568 case Intrinsic::isnan:
1569 // If this is only used by 'isunordered' style comparisons, don't emit it.
1570 if (isOnlyUsedByUnorderedComparisons(&CI)) return;
1571 TmpReg1 = getReg(CI.getOperand(1));
1572 emitUCOM(BB, BB->end(), TmpReg1, TmpReg1);
1573 TmpReg2 = makeAnotherReg(Type::IntTy);
1574 BuildMI(BB, PPC32::MFCR, TmpReg2);
1575 TmpReg3 = getReg(CI);
1576 BuildMI(BB, PPC32::RLWINM, 4, TmpReg3).addReg(TmpReg2).addImm(4).addImm(31).addImm(31);
1580 default: assert(0 && "Error: unknown intrinsics should have been lowered!");
1584 /// visitSimpleBinary - Implement simple binary operators for integral types...
1585 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
1588 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
1589 unsigned DestReg = getReg(B);
1590 MachineBasicBlock::iterator MI = BB->end();
1591 Value *Op0 = B.getOperand(0), *Op1 = B.getOperand(1);
1592 unsigned Class = getClassB(B.getType());
1594 emitSimpleBinaryOperation(BB, MI, Op0, Op1, OperatorClass, DestReg);
1597 /// emitBinaryFPOperation - This method handles emission of floating point
1598 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
1599 void ISel::emitBinaryFPOperation(MachineBasicBlock *BB,
1600 MachineBasicBlock::iterator IP,
1601 Value *Op0, Value *Op1,
1602 unsigned OperatorClass, unsigned DestReg) {
1604 // Special case: op Reg, <const fp>
1605 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1606 // Create a constant pool entry for this constant.
1607 MachineConstantPool *CP = F->getConstantPool();
1608 unsigned CPI = CP->getConstantPoolIndex(Op1C);
1609 const Type *Ty = Op1->getType();
1611 static const unsigned OpcodeTab[][4] = {
1612 { PPC32::FADDS, PPC32::FSUBS, PPC32::FMULS, PPC32::FDIVS }, // Float
1613 { PPC32::FADD, PPC32::FSUB, PPC32::FMUL, PPC32::FDIV }, // Double
1616 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1617 unsigned TempReg = makeAnotherReg(Ty);
1618 unsigned LoadOpcode = (Ty == Type::FloatTy) ? PPC32::LFS : PPC32::LFD;
1619 addConstantPoolReference(BuildMI(*BB, IP, LoadOpcode, 2, TempReg), CPI);
1621 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
1622 unsigned Op0r = getReg(Op0, BB, IP);
1623 BuildMI(*BB, IP, Opcode, DestReg).addReg(Op0r).addReg(TempReg);
1627 // Special case: R1 = op <const fp>, R2
1628 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op0))
1629 if (CFP->isExactlyValue(-0.0) && OperatorClass == 1) {
1631 unsigned op1Reg = getReg(Op1, BB, IP);
1632 BuildMI(*BB, IP, PPC32::FNEG, 1, DestReg).addReg(op1Reg);
1635 // R1 = op CST, R2 --> R1 = opr R2, CST
1637 // Create a constant pool entry for this constant.
1638 MachineConstantPool *CP = F->getConstantPool();
1639 unsigned CPI = CP->getConstantPoolIndex(CFP);
1640 const Type *Ty = CFP->getType();
1642 static const unsigned OpcodeTab[][4] = {
1643 { PPC32::FADDS, PPC32::FSUBS, PPC32::FMULS, PPC32::FDIVS }, // Float
1644 { PPC32::FADD, PPC32::FSUB, PPC32::FMUL, PPC32::FDIV }, // Double
1647 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
1648 unsigned TempReg = makeAnotherReg(Ty);
1649 unsigned LoadOpcode = (Ty == Type::FloatTy) ? PPC32::LFS : PPC32::LFD;
1650 addConstantPoolReference(BuildMI(*BB, IP, LoadOpcode, 2, TempReg), CPI);
1652 unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
1653 unsigned Op1r = getReg(Op1, BB, IP);
1654 BuildMI(*BB, IP, Opcode, DestReg).addReg(TempReg).addReg(Op1r);
1659 static const unsigned OpcodeTab[] = {
1660 PPC32::FADD, PPC32::FSUB, PPC32::FMUL, PPC32::FDIV
1663 unsigned Opcode = OpcodeTab[OperatorClass];
1664 unsigned Op0r = getReg(Op0, BB, IP);
1665 unsigned Op1r = getReg(Op1, BB, IP);
1666 BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1669 /// emitSimpleBinaryOperation - Implement simple binary operators for integral
1670 /// types... OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
1673 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
1674 /// and constant expression support.
1676 void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
1677 MachineBasicBlock::iterator IP,
1678 Value *Op0, Value *Op1,
1679 unsigned OperatorClass, unsigned DestReg) {
1680 unsigned Class = getClassB(Op0->getType());
1682 // Arithmetic and Bitwise operators
1683 static const unsigned OpcodeTab[] = {
1684 PPC32::ADD, PPC32::SUB, PPC32::AND, PPC32::OR, PPC32::XOR
1686 // Otherwise, code generate the full operation with a constant.
1687 static const unsigned BottomTab[] = {
1688 PPC32::ADDC, PPC32::SUBC, PPC32::AND, PPC32::OR, PPC32::XOR
1690 static const unsigned TopTab[] = {
1691 PPC32::ADDE, PPC32::SUBFE, PPC32::AND, PPC32::OR, PPC32::XOR
1695 assert(OperatorClass < 2 && "No logical ops for FP!");
1696 emitBinaryFPOperation(MBB, IP, Op0, Op1, OperatorClass, DestReg);
1700 if (Op0->getType() == Type::BoolTy) {
1701 if (OperatorClass == 3)
1702 // If this is an or of two isnan's, emit an FP comparison directly instead
1703 // of or'ing two isnan's together.
1704 if (Value *LHS = dyncastIsNan(Op0))
1705 if (Value *RHS = dyncastIsNan(Op1)) {
1706 unsigned Op0Reg = getReg(RHS, MBB, IP), Op1Reg = getReg(LHS, MBB, IP);
1707 unsigned TmpReg = makeAnotherReg(Type::IntTy);
1708 emitUCOM(MBB, IP, Op0Reg, Op1Reg);
1709 BuildMI(*MBB, IP, PPC32::MFCR, TmpReg);
1710 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(TmpReg).addImm(4)
1711 .addImm(31).addImm(31);
1716 // sub 0, X -> neg X
1717 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0))
1718 if (OperatorClass == 1 && CI->isNullValue()) {
1719 unsigned op1Reg = getReg(Op1, MBB, IP);
1720 BuildMI(*MBB, IP, PPC32::NEG, 1, DestReg).addReg(op1Reg);
1722 if (Class == cLong) {
1723 unsigned zeroes = makeAnotherReg(Type::IntTy);
1724 unsigned overflow = makeAnotherReg(Type::IntTy);
1725 unsigned T = makeAnotherReg(Type::IntTy);
1726 BuildMI(*MBB, IP, PPC32::CNTLZW, 1, zeroes).addReg(op1Reg);
1727 BuildMI(*MBB, IP, PPC32::RLWINM, 4, overflow).addReg(zeroes).addImm(27)
1728 .addImm(5).addImm(31);
1729 BuildMI(*MBB, IP, PPC32::ADD, 2, T).addReg(op1Reg+1).addReg(overflow);
1730 BuildMI(*MBB, IP, PPC32::NEG, 1, DestReg+1).addReg(T);
1735 // Special case: op Reg, <const int>
1736 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1737 unsigned Op0r = getReg(Op0, MBB, IP);
1739 // xor X, -1 -> not X
1740 if (OperatorClass == 4 && Op1C->isAllOnesValue()) {
1741 BuildMI(*MBB, IP, PPC32::NOR, 2, DestReg).addReg(Op0r).addReg(Op0r);
1742 if (Class == cLong) // Invert the top part too
1743 BuildMI(*MBB, IP, PPC32::NOR, 2, DestReg+1).addReg(Op0r+1)
1748 unsigned Opcode = OpcodeTab[OperatorClass];
1749 unsigned Op1r = getReg(Op1, MBB, IP);
1751 if (Class != cLong) {
1752 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1756 // If the constant is zero in the low 32-bits, just copy the low part
1757 // across and apply the normal 32-bit operation to the high parts. There
1758 // will be no carry or borrow into the top.
1759 if (cast<ConstantInt>(Op1C)->getRawValue() == 0) {
1760 if (OperatorClass != 2) // All but and...
1761 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(Op0r).addReg(Op0r);
1763 BuildMI(*MBB, IP, PPC32::ADDI, 2, DestReg).addReg(PPC32::R0).addImm(0);
1764 BuildMI(*MBB, IP, Opcode, 2, DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
1768 // If this is a long value and the high or low bits have a special
1769 // property, emit some special cases.
1770 unsigned Op1h = cast<ConstantInt>(Op1C)->getRawValue() >> 32LL;
1772 // If this is a logical operation and the top 32-bits are zero, just
1773 // operate on the lower 32.
1774 if (Op1h == 0 && OperatorClass > 1) {
1775 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1776 if (OperatorClass != 2) // All but and
1777 BuildMI(*MBB, IP, PPC32::OR, 2,DestReg+1).addReg(Op0r+1).addReg(Op0r+1);
1779 BuildMI(*MBB, IP, PPC32::ADDI, 2,DestReg+1).addReg(PPC32::R0).addImm(0);
1783 // TODO: We could handle lots of other special cases here, such as AND'ing
1784 // with 0xFFFFFFFF00000000 -> noop, etc.
1786 BuildMI(*MBB, IP, BottomTab[OperatorClass], 2, DestReg).addReg(Op0r)
1788 BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg+1).addReg(Op0r+1)
1793 unsigned Op0r = getReg(Op0, MBB, IP);
1794 unsigned Op1r = getReg(Op1, MBB, IP);
1796 if (Class != cLong) {
1797 unsigned Opcode = OpcodeTab[OperatorClass];
1798 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
1800 BuildMI(*MBB, IP, BottomTab[OperatorClass], 2, DestReg).addReg(Op0r)
1802 BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg+1).addReg(Op0r+1)
1808 /// doMultiply - Emit appropriate instructions to multiply together the
1809 /// registers op0Reg and op1Reg, and put the result in DestReg. The type of the
1810 /// result should be given as DestTy.
1812 void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
1813 unsigned DestReg, const Type *DestTy,
1814 unsigned op0Reg, unsigned op1Reg) {
1815 unsigned Class = getClass(DestTy);
1818 BuildMI(*MBB, MBBI, PPC32::MULHW, 2, DestReg+1).addReg(op0Reg+1)
1823 BuildMI(*MBB, MBBI, PPC32::MULLW, 2, DestReg).addReg(op0Reg).addReg(op1Reg);
1826 assert(0 && "doMultiply cannot operate on unknown type!");
1830 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
1831 // returns zero when the input is not exactly a power of two.
1832 static unsigned ExactLog2(unsigned Val) {
1833 if (Val == 0 || (Val & (Val-1))) return 0;
1843 /// doMultiplyConst - This function is specialized to efficiently codegen an 8,
1844 /// 16, or 32-bit integer multiply by a constant.
1846 void ISel::doMultiplyConst(MachineBasicBlock *MBB,
1847 MachineBasicBlock::iterator IP,
1848 unsigned DestReg, const Type *DestTy,
1849 unsigned op0Reg, unsigned ConstRHS) {
1850 unsigned Class = getClass(DestTy);
1851 // Handle special cases here.
1854 BuildMI(*MBB, IP, PPC32::ADDI, 2, DestReg).addReg(PPC32::R0).addImm(0);
1857 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(op0Reg).addReg(op0Reg);
1860 BuildMI(*MBB, IP, PPC32::ADD, 2,DestReg).addReg(op0Reg).addReg(op0Reg);
1864 // If the element size is exactly a power of 2, use a shift to get it.
1865 if (unsigned Shift = ExactLog2(ConstRHS)) {
1867 default: assert(0 && "Unknown class for this function!");
1871 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(op0Reg)
1872 .addImm(Shift-1).addImm(0).addImm(31-Shift-1);
1877 // Most general case, emit a normal multiply...
1878 unsigned TmpReg1 = makeAnotherReg(Type::IntTy);
1879 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
1880 BuildMI(*MBB, IP, PPC32::ADDIS, 2, TmpReg1).addReg(PPC32::R0)
1881 .addImm(ConstRHS >> 16);
1882 BuildMI(*MBB, IP, PPC32::ORI, 2, TmpReg2).addReg(TmpReg1).addImm(ConstRHS);
1884 // Emit a MUL to multiply the register holding the index by
1885 // elementSize, putting the result in OffsetReg.
1886 doMultiply(MBB, IP, DestReg, DestTy, op0Reg, TmpReg2);
1889 void ISel::visitMul(BinaryOperator &I) {
1890 unsigned ResultReg = getReg(I);
1892 Value *Op0 = I.getOperand(0);
1893 Value *Op1 = I.getOperand(1);
1895 MachineBasicBlock::iterator IP = BB->end();
1896 emitMultiply(BB, IP, Op0, Op1, ResultReg);
1899 void ISel::emitMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
1900 Value *Op0, Value *Op1, unsigned DestReg) {
1901 MachineBasicBlock &BB = *MBB;
1902 TypeClass Class = getClass(Op0->getType());
1904 // Simple scalar multiply?
1905 unsigned Op0Reg = getReg(Op0, &BB, IP);
1910 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1911 unsigned Val = (unsigned)CI->getRawValue(); // Isn't a 64-bit constant
1912 doMultiplyConst(&BB, IP, DestReg, Op0->getType(), Op0Reg, Val);
1914 unsigned Op1Reg = getReg(Op1, &BB, IP);
1915 doMultiply(&BB, IP, DestReg, Op1->getType(), Op0Reg, Op1Reg);
1919 emitBinaryFPOperation(MBB, IP, Op0, Op1, 2, DestReg);
1925 // Long value. We have to do things the hard way...
1926 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1927 unsigned CLow = CI->getRawValue();
1928 unsigned CHi = CI->getRawValue() >> 32;
1931 // If the low part of the constant is all zeros, things are simple.
1932 BuildMI(BB, IP, PPC32::ADDI, 2, DestReg).addReg(PPC32::R0).addImm(0);
1933 doMultiplyConst(&BB, IP, DestReg+1, Type::UIntTy, Op0Reg, CHi);
1937 // Multiply the two low parts
1938 unsigned OverflowReg = 0;
1940 BuildMI(BB, IP, PPC32::OR, 2, DestReg).addReg(Op0Reg).addReg(Op0Reg);
1942 unsigned TmpRegL = makeAnotherReg(Type::UIntTy);
1943 unsigned Op1RegL = makeAnotherReg(Type::UIntTy);
1944 OverflowReg = makeAnotherReg(Type::UIntTy);
1945 BuildMI(BB, IP, PPC32::ADDIS, 2, TmpRegL).addReg(PPC32::R0)
1946 .addImm(CLow >> 16);
1947 BuildMI(BB, IP, PPC32::ORI, 2, Op1RegL).addReg(TmpRegL).addImm(CLow);
1948 BuildMI(BB, IP, PPC32::MULLW, 2, DestReg).addReg(Op0Reg).addReg(Op1RegL);
1949 BuildMI(BB, IP, PPC32::MULHW, 2, OverflowReg).addReg(Op0Reg)
1953 unsigned AHBLReg = makeAnotherReg(Type::UIntTy);
1954 doMultiplyConst(&BB, IP, AHBLReg, Type::UIntTy, Op0Reg+1, CLow);
1956 unsigned AHBLplusOverflowReg;
1958 AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
1959 BuildMI(BB, IP, PPC32::ADD, 2,
1960 AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
1962 AHBLplusOverflowReg = AHBLReg;
1966 BuildMI(BB, IP, PPC32::OR, 2, DestReg+1).addReg(AHBLplusOverflowReg)
1967 .addReg(AHBLplusOverflowReg);
1969 unsigned ALBHReg = makeAnotherReg(Type::UIntTy);
1970 doMultiplyConst(&BB, IP, ALBHReg, Type::UIntTy, Op0Reg, CHi);
1972 BuildMI(BB, IP, PPC32::ADD, 2,
1973 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
1978 // General 64x64 multiply
1980 unsigned Op1Reg = getReg(Op1, &BB, IP);
1982 // Multiply the two low parts...
1983 BuildMI(BB, IP, PPC32::MULLW, 2, DestReg).addReg(Op0Reg).addReg(Op1Reg);
1985 unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
1986 BuildMI(BB, IP, PPC32::MULHW, 2, OverflowReg).addReg(Op0Reg).addReg(Op1Reg);
1988 unsigned AHBLReg = makeAnotherReg(Type::UIntTy);
1989 BuildMI(BB, IP, PPC32::MULLW, 2, AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
1991 unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
1992 BuildMI(BB, IP, PPC32::ADD, 2, AHBLplusOverflowReg).addReg(AHBLReg)
1993 .addReg(OverflowReg);
1995 unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
1996 BuildMI(BB, IP, PPC32::MULLW, 2, ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
1998 BuildMI(BB, IP, PPC32::ADD, 2,
1999 DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
2003 /// visitDivRem - Handle division and remainder instructions... these
2004 /// instruction both require the same instructions to be generated, they just
2005 /// select the result from a different register. Note that both of these
2006 /// instructions work differently for signed and unsigned operands.
2008 void ISel::visitDivRem(BinaryOperator &I) {
2009 unsigned ResultReg = getReg(I);
2010 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2012 MachineBasicBlock::iterator IP = BB->end();
2013 emitDivRemOperation(BB, IP, Op0, Op1, I.getOpcode() == Instruction::Div,
2017 void ISel::emitDivRemOperation(MachineBasicBlock *BB,
2018 MachineBasicBlock::iterator IP,
2019 Value *Op0, Value *Op1, bool isDiv,
2020 unsigned ResultReg) {
2021 const Type *Ty = Op0->getType();
2022 unsigned Class = getClass(Ty);
2024 case cFP: // Floating point divide
2026 emitBinaryFPOperation(BB, IP, Op0, Op1, 3, ResultReg);
2028 } else { // Floating point remainder...
2029 unsigned Op0Reg = getReg(Op0, BB, IP);
2030 unsigned Op1Reg = getReg(Op1, BB, IP);
2031 MachineInstr *TheCall =
2032 BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(fmodFn, true);
2033 std::vector<ValueRecord> Args;
2034 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
2035 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
2036 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args, false);
2040 static Function* const Funcs[] =
2041 { __moddi3Fn, __divdi3Fn, __umoddi3Fn, __udivdi3Fn };
2042 unsigned Op0Reg = getReg(Op0, BB, IP);
2043 unsigned Op1Reg = getReg(Op1, BB, IP);
2044 unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
2045 MachineInstr *TheCall =
2046 BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(Funcs[NameIdx], true);
2048 std::vector<ValueRecord> Args;
2049 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
2050 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
2051 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args, false);
2054 case cByte: case cShort: case cInt:
2055 break; // Small integrals, handled below...
2056 default: assert(0 && "Unknown class!");
2059 // Special case signed division by power of 2.
2061 if (ConstantSInt *CI = dyn_cast<ConstantSInt>(Op1)) {
2062 assert(Class != cLong && "This doesn't handle 64-bit divides!");
2063 int V = CI->getValue();
2065 if (V == 1) { // X /s 1 => X
2066 unsigned Op0Reg = getReg(Op0, BB, IP);
2067 BuildMI(*BB, IP, PPC32::OR, 2, ResultReg).addReg(Op0Reg).addReg(Op0Reg);
2071 if (V == -1) { // X /s -1 => -X
2072 unsigned Op0Reg = getReg(Op0, BB, IP);
2073 BuildMI(*BB, IP, PPC32::NEG, 1, ResultReg).addReg(Op0Reg);
2078 if (V < 0) { // Not a positive power of 2?
2080 isNeg = true; // Maybe it's a negative power of 2.
2082 if (unsigned Log = ExactLog2(V)) {
2084 unsigned Op0Reg = getReg(Op0, BB, IP);
2085 unsigned TmpReg = makeAnotherReg(Op0->getType());
2087 BuildMI(*BB, IP, PPC32::SRAWI,2, TmpReg).addReg(Op0Reg).addImm(Log-1);
2089 BuildMI(*BB, IP, PPC32::OR, 2, TmpReg).addReg(Op0Reg).addReg(Op0Reg);
2091 unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2092 BuildMI(*BB, IP, PPC32::RLWINM, 4, TmpReg2).addReg(TmpReg).addImm(Log)
2093 .addImm(32-Log).addImm(31);
2095 unsigned TmpReg3 = makeAnotherReg(Op0->getType());
2096 BuildMI(*BB, IP, PPC32::ADD, 2, TmpReg3).addReg(Op0Reg).addReg(TmpReg2);
2098 unsigned TmpReg4 = isNeg ? makeAnotherReg(Op0->getType()) : ResultReg;
2099 BuildMI(*BB, IP, PPC32::SRAWI, 2, TmpReg4).addReg(Op0Reg).addImm(Log);
2102 BuildMI(*BB, IP, PPC32::NEG, 1, ResultReg).addReg(TmpReg4);
2107 unsigned Op0Reg = getReg(Op0, BB, IP);
2108 unsigned Op1Reg = getReg(Op1, BB, IP);
2111 if (Ty->isSigned()) {
2112 BuildMI(*BB, IP, PPC32::DIVW, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
2114 BuildMI(*BB, IP,PPC32::DIVWU, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
2116 } else { // Remainder
2117 unsigned TmpReg1 = makeAnotherReg(Op0->getType());
2118 unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2120 if (Ty->isSigned()) {
2121 BuildMI(*BB, IP, PPC32::DIVW, 2, TmpReg1).addReg(Op0Reg).addReg(Op1Reg);
2123 BuildMI(*BB, IP, PPC32::DIVWU, 2, TmpReg1).addReg(Op0Reg).addReg(Op1Reg);
2125 BuildMI(*BB, IP, PPC32::MULLW, 2, TmpReg2).addReg(TmpReg1).addReg(Op1Reg);
2126 BuildMI(*BB, IP, PPC32::SUBF, 2, ResultReg).addReg(TmpReg2).addReg(Op0Reg);
2131 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
2132 /// for constant immediate shift values, and for constant immediate
2133 /// shift values equal to 1. Even the general case is sort of special,
2134 /// because the shift amount has to be in CL, not just any old register.
2136 void ISel::visitShiftInst(ShiftInst &I) {
2137 MachineBasicBlock::iterator IP = BB->end ();
2138 emitShiftOperation(BB, IP, I.getOperand (0), I.getOperand (1),
2139 I.getOpcode () == Instruction::Shl, I.getType (),
2143 /// emitShiftOperation - Common code shared between visitShiftInst and
2144 /// constant expression support.
2146 void ISel::emitShiftOperation(MachineBasicBlock *MBB,
2147 MachineBasicBlock::iterator IP,
2148 Value *Op, Value *ShiftAmount, bool isLeftShift,
2149 const Type *ResultTy, unsigned DestReg) {
2150 unsigned SrcReg = getReg (Op, MBB, IP);
2151 bool isSigned = ResultTy->isSigned ();
2152 unsigned Class = getClass (ResultTy);
2154 // Longs, as usual, are handled specially...
2155 if (Class == cLong) {
2156 // If we have a constant shift, we can generate much more efficient code
2157 // than otherwise...
2159 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2160 unsigned Amount = CUI->getValue();
2163 // FIXME: RLWIMI is a use-and-def of DestReg+1, but that violates SSA
2164 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg+1).addReg(SrcReg+1)
2165 .addImm(Amount).addImm(0).addImm(31-Amount);
2166 BuildMI(*MBB, IP, PPC32::RLWIMI, 5).addReg(DestReg+1).addReg(SrcReg)
2167 .addImm(Amount).addImm(32-Amount).addImm(31);
2168 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg)
2169 .addImm(Amount).addImm(0).addImm(31-Amount);
2171 // FIXME: RLWIMI is a use-and-def of DestReg, but that violates SSA
2172 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg)
2173 .addImm(32-Amount).addImm(Amount).addImm(31);
2174 BuildMI(*MBB, IP, PPC32::RLWIMI, 5).addReg(DestReg).addReg(SrcReg+1)
2175 .addImm(32-Amount).addImm(0).addImm(Amount-1);
2176 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg+1).addReg(SrcReg+1)
2177 .addImm(32-Amount).addImm(Amount).addImm(31);
2179 } else { // Shifting more than 32 bits
2183 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg+1).addReg(SrcReg)
2184 .addImm(Amount).addImm(0).addImm(31-Amount);
2186 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg+1).addReg(SrcReg)
2189 BuildMI(*MBB, IP, PPC32::ADDI, 2,DestReg).addReg(PPC32::R0).addImm(0);
2193 BuildMI(*MBB, IP, PPC32::SRAWI, 2, DestReg).addReg(SrcReg+1)
2196 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg+1)
2197 .addImm(32-Amount).addImm(Amount).addImm(31);
2199 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg+1)
2202 BuildMI(*MBB, IP,PPC32::ADDI,2,DestReg+1).addReg(PPC32::R0).addImm(0);
2206 unsigned TmpReg1 = makeAnotherReg(Type::IntTy);
2207 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
2208 unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
2209 unsigned TmpReg4 = makeAnotherReg(Type::IntTy);
2210 unsigned TmpReg5 = makeAnotherReg(Type::IntTy);
2211 unsigned TmpReg6 = makeAnotherReg(Type::IntTy);
2212 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
2215 BuildMI(*MBB, IP, PPC32::SUBFIC, 2, TmpReg1).addReg(ShiftAmountReg)
2217 BuildMI(*MBB, IP, PPC32::SLW, 2, TmpReg2).addReg(SrcReg+1)
2218 .addReg(ShiftAmountReg);
2219 BuildMI(*MBB, IP, PPC32::SRW, 2,TmpReg3).addReg(SrcReg).addReg(TmpReg1);
2220 BuildMI(*MBB, IP, PPC32::OR, 2,TmpReg4).addReg(TmpReg2).addReg(TmpReg3);
2221 BuildMI(*MBB, IP, PPC32::ADDI, 2, TmpReg5).addReg(ShiftAmountReg)
2223 BuildMI(*MBB, IP, PPC32::SLW, 2,TmpReg6).addReg(SrcReg).addReg(TmpReg5);
2224 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg+1).addReg(TmpReg4)
2226 BuildMI(*MBB, IP, PPC32::SLW, 2, DestReg).addReg(SrcReg)
2227 .addReg(ShiftAmountReg);
2230 // FIXME: Unimplemented
2231 // Page C-3 of the PowerPC 32bit Programming Environments Manual
2232 std::cerr << "Unimplemented: signed right shift\n";
2235 BuildMI(*MBB, IP, PPC32::SUBFIC, 2, TmpReg1).addReg(ShiftAmountReg)
2237 BuildMI(*MBB, IP, PPC32::SRW, 2, TmpReg2).addReg(SrcReg)
2238 .addReg(ShiftAmountReg);
2239 BuildMI(*MBB, IP, PPC32::SLW, 2, TmpReg3).addReg(SrcReg+1)
2241 BuildMI(*MBB, IP, PPC32::OR, 2, TmpReg4).addReg(TmpReg2)
2243 BuildMI(*MBB, IP, PPC32::ADDI, 2, TmpReg5).addReg(ShiftAmountReg)
2245 BuildMI(*MBB, IP, PPC32::SRW, 2, TmpReg6).addReg(SrcReg+1)
2247 BuildMI(*MBB, IP, PPC32::OR, 2, DestReg).addReg(TmpReg4)
2249 BuildMI(*MBB, IP, PPC32::SRW, 2, DestReg+1).addReg(SrcReg+1)
2250 .addReg(ShiftAmountReg);
2257 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2258 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
2259 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
2260 unsigned Amount = CUI->getValue();
2263 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg)
2264 .addImm(Amount).addImm(0).addImm(31-Amount);
2267 BuildMI(*MBB, IP, PPC32::SRAWI,2,DestReg).addReg(SrcReg).addImm(Amount);
2269 BuildMI(*MBB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg)
2270 .addImm(32-Amount).addImm(Amount).addImm(31);
2273 } else { // The shift amount is non-constant.
2274 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
2277 BuildMI(*MBB, IP, PPC32::SLW, 2, DestReg).addReg(SrcReg)
2278 .addReg(ShiftAmountReg);
2280 BuildMI(*MBB, IP, isSigned ? PPC32::SRAW : PPC32::SRW, 2, DestReg)
2281 .addReg(SrcReg).addReg(ShiftAmountReg);
2287 /// visitLoadInst - Implement LLVM load instructions
2289 void ISel::visitLoadInst(LoadInst &I) {
2290 static const unsigned Opcodes[] = {
2291 PPC32::LBZ, PPC32::LHZ, PPC32::LWZ, PPC32::LFS
2293 unsigned Class = getClassB(I.getType());
2294 unsigned Opcode = Opcodes[Class];
2295 if (I.getType() == Type::DoubleTy) Opcode = PPC32::LFD;
2297 unsigned DestReg = getReg(I);
2299 if (AllocaInst *AI = dyn_castFixedAlloca(I.getOperand(0))) {
2300 unsigned FI = getFixedSizedAllocaFI(AI);
2301 if (Class == cLong) {
2302 addFrameReference(BuildMI(BB, PPC32::LWZ, 2, DestReg), FI);
2303 addFrameReference(BuildMI(BB, PPC32::LWZ, 2, DestReg+1), FI, 4);
2305 addFrameReference(BuildMI(BB, Opcode, 2, DestReg), FI);
2308 unsigned SrcAddrReg = getReg(I.getOperand(0));
2310 if (Class == cLong) {
2311 BuildMI(BB, PPC32::LWZ, 2, DestReg).addImm(0).addReg(SrcAddrReg);
2312 BuildMI(BB, PPC32::LWZ, 2, DestReg+1).addImm(4).addReg(SrcAddrReg);
2314 BuildMI(BB, Opcode, 2, DestReg).addImm(0).addReg(SrcAddrReg);
2319 /// visitStoreInst - Implement LLVM store instructions
2321 void ISel::visitStoreInst(StoreInst &I) {
2322 unsigned ValReg = getReg(I.getOperand(0));
2323 unsigned AddressReg = getReg(I.getOperand(1));
2325 const Type *ValTy = I.getOperand(0)->getType();
2326 unsigned Class = getClassB(ValTy);
2328 if (Class == cLong) {
2329 BuildMI(BB, PPC32::STW, 3).addReg(ValReg).addImm(0).addReg(AddressReg);
2330 BuildMI(BB, PPC32::STW, 3).addReg(ValReg+1).addImm(4).addReg(AddressReg);
2334 static const unsigned Opcodes[] = {
2335 PPC32::STB, PPC32::STH, PPC32::STW, PPC32::STFS
2337 unsigned Opcode = Opcodes[Class];
2338 if (ValTy == Type::DoubleTy) Opcode = PPC32::STFD;
2339 BuildMI(BB, Opcode, 3).addReg(ValReg).addImm(0).addReg(AddressReg);
2343 /// visitCastInst - Here we have various kinds of copying with or without sign
2344 /// extension going on.
2346 void ISel::visitCastInst(CastInst &CI) {
2347 Value *Op = CI.getOperand(0);
2349 unsigned SrcClass = getClassB(Op->getType());
2350 unsigned DestClass = getClassB(CI.getType());
2351 // Noop casts are not emitted: getReg will return the source operand as the
2352 // register to use for any uses of the noop cast.
2353 if (DestClass == SrcClass)
2356 // If this is a cast from a 32-bit integer to a Long type, and the only uses
2357 // of the case are GEP instructions, then the cast does not need to be
2358 // generated explicitly, it will be folded into the GEP.
2359 if (DestClass == cLong && SrcClass == cInt) {
2360 bool AllUsesAreGEPs = true;
2361 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
2362 if (!isa<GetElementPtrInst>(*I)) {
2363 AllUsesAreGEPs = false;
2367 // No need to codegen this cast if all users are getelementptr instrs...
2368 if (AllUsesAreGEPs) return;
2371 unsigned DestReg = getReg(CI);
2372 MachineBasicBlock::iterator MI = BB->end();
2373 emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
2376 /// emitCastOperation - Common code shared between visitCastInst and constant
2377 /// expression cast support.
2379 void ISel::emitCastOperation(MachineBasicBlock *BB,
2380 MachineBasicBlock::iterator IP,
2381 Value *Src, const Type *DestTy,
2383 const Type *SrcTy = Src->getType();
2384 unsigned SrcClass = getClassB(SrcTy);
2385 unsigned DestClass = getClassB(DestTy);
2386 unsigned SrcReg = getReg(Src, BB, IP);
2388 // Implement casts to bool by using compare on the operand followed by set if
2389 // not zero on the result.
2390 if (DestTy == Type::BoolTy) {
2395 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2396 BuildMI(*BB, IP, PPC32::ADDIC, 2, TmpReg).addReg(SrcReg).addImm(-1);
2397 BuildMI(*BB, IP, PPC32::SUBFE, 2, DestReg).addReg(TmpReg).addReg(SrcReg);
2401 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2402 unsigned SrcReg2 = makeAnotherReg(Type::IntTy);
2403 BuildMI(*BB, IP, PPC32::OR, 2, SrcReg2).addReg(SrcReg).addReg(SrcReg+1);
2404 BuildMI(*BB, IP, PPC32::ADDIC, 2, TmpReg).addReg(SrcReg2).addImm(-1);
2405 BuildMI(*BB, IP, PPC32::SUBFE, 2, DestReg).addReg(TmpReg).addReg(SrcReg2);
2419 std::cerr << "Cast fp-to-bool not implemented!";
2425 // Implement casts between values of the same type class (as determined by
2426 // getClass) by using a register-to-register move.
2427 if (SrcClass == DestClass) {
2428 if (SrcClass <= cInt) {
2429 BuildMI(*BB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2430 } else if (SrcClass == cFP && SrcTy == DestTy) {
2431 BuildMI(*BB, IP, PPC32::FMR, 1, DestReg).addReg(SrcReg);
2432 } else if (SrcClass == cFP) {
2433 if (SrcTy == Type::FloatTy) { // float -> double
2434 assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
2435 BuildMI(*BB, IP, PPC32::FMR, 1, DestReg).addReg(SrcReg);
2436 } else { // double -> float
2437 assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
2438 "Unknown cFP member!");
2439 BuildMI(*BB, IP, PPC32::FRSP, 1, DestReg).addReg(SrcReg);
2441 } else if (SrcClass == cLong) {
2442 BuildMI(*BB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2443 BuildMI(*BB, IP, PPC32::OR, 2, DestReg+1).addReg(SrcReg+1)
2446 assert(0 && "Cannot handle this type of cast instruction!");
2452 // Handle cast of SMALLER int to LARGER int using a move with sign extension
2453 // or zero extension, depending on whether the source type was signed.
2454 if (SrcClass <= cInt && (DestClass <= cInt || DestClass == cLong) &&
2455 SrcClass < DestClass) {
2456 bool isLong = DestClass == cLong;
2457 if (isLong) DestClass = cInt;
2459 bool isUnsigned = SrcTy->isUnsigned() || SrcTy == Type::BoolTy;
2460 if (SrcClass < cInt) {
2462 unsigned shift = (SrcClass == cByte) ? 24 : 16;
2463 BuildMI(*BB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg).addZImm(0)
2464 .addImm(shift).addImm(31);
2466 BuildMI(*BB, IP, (SrcClass == cByte) ? PPC32::EXTSB : PPC32::EXTSH,
2467 1, DestReg).addReg(SrcReg);
2470 BuildMI(*BB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2473 if (isLong) { // Handle upper 32 bits as appropriate...
2474 if (isUnsigned) // Zero out top bits...
2475 BuildMI(*BB, IP, PPC32::ADDI, 2, DestReg+1).addReg(PPC32::R0).addImm(0);
2476 else // Sign extend bottom half...
2477 BuildMI(*BB, IP, PPC32::SRAWI, 2, DestReg+1).addReg(DestReg).addImm(31);
2482 // Special case long -> int ...
2483 if (SrcClass == cLong && DestClass == cInt) {
2484 BuildMI(*BB, IP, PPC32::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
2488 // Handle cast of LARGER int to SMALLER int with a clear or sign extend
2489 if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
2490 && SrcClass > DestClass) {
2491 bool isUnsigned = SrcTy->isUnsigned() || SrcTy == Type::BoolTy;
2493 unsigned shift = (SrcClass == cByte) ? 24 : 16;
2494 BuildMI(*BB, IP, PPC32::RLWINM, 4, DestReg).addReg(SrcReg).addZImm(0)
2495 .addImm(shift).addImm(31);
2497 BuildMI(*BB, IP, (SrcClass == cByte) ? PPC32::EXTSB : PPC32::EXTSH, 1,
2498 DestReg).addReg(SrcReg);
2503 // Handle casts from integer to floating point now...
2504 if (DestClass == cFP) {
2506 // Emit a library call for long to float conversion
2507 if (SrcClass == cLong) {
2508 std::vector<ValueRecord> Args;
2509 Args.push_back(ValueRecord(SrcReg, SrcTy));
2510 Function *floatFn = (SrcTy==Type::FloatTy) ? __floatdisfFn : __floatdidfFn;
2511 MachineInstr *TheCall =
2512 BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(floatFn, true);
2513 doCall(ValueRecord(DestReg, DestTy), TheCall, Args, false);
2517 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2518 switch (SrcTy->getTypeID()) {
2519 case Type::BoolTyID:
2520 case Type::SByteTyID:
2521 BuildMI(*BB, IP, PPC32::EXTSB, 1, TmpReg).addReg(SrcReg);
2523 case Type::UByteTyID:
2524 BuildMI(*BB, IP, PPC32::RLWINM, 4, TmpReg).addReg(SrcReg).addZImm(0)
2525 .addImm(24).addImm(31);
2527 case Type::ShortTyID:
2528 BuildMI(*BB, IP, PPC32::EXTSB, 1, TmpReg).addReg(SrcReg);
2530 case Type::UShortTyID:
2531 BuildMI(*BB, IP, PPC32::RLWINM, 4, TmpReg).addReg(SrcReg).addZImm(0)
2532 .addImm(16).addImm(31);
2535 BuildMI(*BB, IP, PPC32::OR, 2, TmpReg).addReg(SrcReg).addReg(SrcReg);
2537 case Type::UIntTyID:
2538 BuildMI(*BB, IP, PPC32::OR, 2, TmpReg).addReg(SrcReg).addReg(SrcReg);
2540 default: // No promotion needed...
2546 // Spill the integer to memory and reload it from there.
2547 // Also spill room for a special conversion constant
2548 int ConstantFrameIndex =
2549 F->getFrameInfo()->CreateStackObject(Type::DoubleTy, TM.getTargetData());
2551 F->getFrameInfo()->CreateStackObject(Type::DoubleTy, TM.getTargetData());
2553 unsigned constantHi = makeAnotherReg(Type::IntTy);
2554 unsigned constantLo = makeAnotherReg(Type::IntTy);
2555 unsigned ConstF = makeAnotherReg(Type::DoubleTy);
2556 unsigned TempF = makeAnotherReg(Type::DoubleTy);
2558 if (!SrcTy->isSigned()) {
2559 BuildMI(*BB, IP, PPC32::ADDIS, 2, constantHi).addReg(PPC32::R0)
2561 BuildMI(*BB, IP, PPC32::ADDI, 2, constantLo).addReg(PPC32::R0).addImm(0);
2562 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantHi),
2563 ConstantFrameIndex);
2564 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantLo),
2565 ConstantFrameIndex, 4);
2566 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantHi),
2568 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(SrcReg),
2570 addFrameReference(BuildMI(*BB, IP, PPC32::LFD, 2, ConstF),
2571 ConstantFrameIndex);
2572 addFrameReference(BuildMI(*BB, IP, PPC32::LFD, 2, TempF), ValueFrameIdx);
2573 BuildMI(*BB, IP, PPC32::FSUB, 2, DestReg).addReg(TempF).addReg(ConstF);
2575 unsigned TempLo = makeAnotherReg(Type::IntTy);
2576 BuildMI(*BB, IP, PPC32::ADDIS, 2, constantHi).addReg(PPC32::R0)
2578 BuildMI(*BB, IP, PPC32::ADDIS, 2, constantLo).addReg(PPC32::R0)
2580 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantHi),
2581 ConstantFrameIndex);
2582 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantLo),
2583 ConstantFrameIndex, 4);
2584 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(constantHi),
2586 BuildMI(*BB, IP, PPC32::XORIS, 2, TempLo).addReg(SrcReg).addImm(0x8000);
2587 addFrameReference(BuildMI(*BB, IP, PPC32::STW, 3).addReg(TempLo),
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);
2597 // Handle casts from floating point to integer now...
2598 if (SrcClass == cFP) {
2600 // emit library call
2601 if (DestClass == cLong) {
2602 std::vector<ValueRecord> Args;
2603 Args.push_back(ValueRecord(SrcReg, SrcTy));
2604 MachineInstr *TheCall =
2605 BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(__fixdfdiFn, true);
2606 doCall(ValueRecord(DestReg, DestTy), TheCall, Args, false);
2611 F->getFrameInfo()->CreateStackObject(Type::DoubleTy, TM.getTargetData());
2613 // load into 32 bit value, and then truncate as necessary
2614 // FIXME: This is wrong for unsigned dest types
2615 //if (DestTy->isSigned()) {
2616 unsigned TempReg = makeAnotherReg(Type::DoubleTy);
2617 BuildMI(*BB, IP, PPC32::FCTIWZ, 1, TempReg).addReg(SrcReg);
2618 addFrameReference(BuildMI(*BB, IP, PPC32::STFD, 3)
2619 .addReg(TempReg), ValueFrameIdx);
2620 addFrameReference(BuildMI(*BB, IP, PPC32::LWZ, 2, DestReg),
2625 // FIXME: Truncate return value
2629 // Anything we haven't handled already, we can't (yet) handle at all.
2630 assert(0 && "Unhandled cast instruction!");
2634 /// visitVANextInst - Implement the va_next instruction...
2636 void ISel::visitVANextInst(VANextInst &I) {
2637 unsigned VAList = getReg(I.getOperand(0));
2638 unsigned DestReg = getReg(I);
2641 switch (I.getArgType()->getTypeID()) {
2644 assert(0 && "Error: bad type for va_next instruction!");
2646 case Type::PointerTyID:
2647 case Type::UIntTyID:
2651 case Type::ULongTyID:
2652 case Type::LongTyID:
2653 case Type::DoubleTyID:
2658 // Increment the VAList pointer...
2659 BuildMI(BB, PPC32::ADDI, 2, DestReg).addReg(VAList).addImm(Size);
2662 void ISel::visitVAArgInst(VAArgInst &I) {
2663 unsigned VAList = getReg(I.getOperand(0));
2664 unsigned DestReg = getReg(I);
2666 switch (I.getType()->getTypeID()) {
2669 assert(0 && "Error: bad type for va_next instruction!");
2671 case Type::PointerTyID:
2672 case Type::UIntTyID:
2674 BuildMI(BB, PPC32::LWZ, 2, DestReg).addImm(0).addReg(VAList);
2676 case Type::ULongTyID:
2677 case Type::LongTyID:
2678 BuildMI(BB, PPC32::LWZ, 2, DestReg).addImm(0).addReg(VAList);
2679 BuildMI(BB, PPC32::LWZ, 2, DestReg+1).addImm(4).addReg(VAList);
2681 case Type::DoubleTyID:
2682 BuildMI(BB, PPC32::LFD, 2, DestReg).addImm(0).addReg(VAList);
2687 /// visitGetElementPtrInst - instruction-select GEP instructions
2689 void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
2690 unsigned outputReg = getReg(I);
2691 emitGEPOperation(BB, BB->end(), I.getOperand(0), I.op_begin()+1, I.op_end(),
2695 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
2696 MachineBasicBlock::iterator IP,
2697 Value *Src, User::op_iterator IdxBegin,
2698 User::op_iterator IdxEnd, unsigned TargetReg) {
2699 const TargetData &TD = TM.getTargetData();
2700 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
2701 Src = CPR->getValue();
2703 std::vector<Value*> GEPOps;
2704 GEPOps.resize(IdxEnd-IdxBegin+1);
2706 std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
2708 std::vector<const Type*> GEPTypes;
2709 GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
2710 gep_type_end(Src->getType(), IdxBegin, IdxEnd));
2712 // Keep emitting instructions until we consume the entire GEP instruction.
2713 while (!GEPOps.empty()) {
2714 if (GEPTypes.empty()) {
2715 // Load the base pointer into a register.
2716 unsigned Reg = getReg(Src, MBB, IP);
2717 BuildMI(*MBB, IP, PPC32::OR, 2, TargetReg).addReg(Reg).addReg(Reg);
2718 break; // we are now done
2720 if (const StructType *StTy = dyn_cast<StructType>(GEPTypes.back())) {
2721 // It's a struct access. CUI is the index into the structure,
2722 // which names the field. This index must have unsigned type.
2723 const ConstantUInt *CUI = cast<ConstantUInt>(GEPOps.back());
2725 // Use the TargetData structure to pick out what the layout of the
2726 // structure is in memory. Since the structure index must be constant, we
2727 // can get its value and use it to find the right byte offset from the
2728 // StructLayout class's list of structure member offsets.
2729 unsigned Disp = TD.getStructLayout(StTy)->MemberOffsets[CUI->getValue()];
2730 GEPOps.pop_back(); // Consume a GEP operand
2731 GEPTypes.pop_back();
2732 unsigned Reg = makeAnotherReg(Type::UIntTy);
2733 unsigned DispReg = makeAnotherReg(Type::UIntTy);
2734 BuildMI(*MBB, IP, PPC32::LI, 2, DispReg).addImm(Disp);
2735 BuildMI(*MBB, IP, PPC32::ADD, 2, TargetReg).addReg(Reg).addReg(DispReg);
2736 --IP; // Insert the next instruction before this one.
2737 TargetReg = Reg; // Codegen the rest of the GEP into this
2739 // It's an array or pointer access: [ArraySize x ElementType].
2740 const SequentialType *SqTy = cast<SequentialType>(GEPTypes.back());
2741 Value *idx = GEPOps.back();
2742 GEPOps.pop_back(); // Consume a GEP operand
2743 GEPTypes.pop_back();
2745 // Many GEP instructions use a [cast (int/uint) to LongTy] as their
2746 // operand. Handle this case directly now...
2747 if (CastInst *CI = dyn_cast<CastInst>(idx))
2748 if (CI->getOperand(0)->getType() == Type::IntTy ||
2749 CI->getOperand(0)->getType() == Type::UIntTy)
2750 idx = CI->getOperand(0);
2752 // We want to add BaseReg to(idxReg * sizeof ElementType). First, we
2753 // must find the size of the pointed-to type (Not coincidentally, the next
2754 // type is the type of the elements in the array).
2755 const Type *ElTy = SqTy->getElementType();
2756 unsigned elementSize = TD.getTypeSize(ElTy);
2758 if (idx == Constant::getNullValue(idx->getType())) {
2759 // GEP with idx 0 is a no-op
2760 } else if (elementSize == 1) {
2761 // If the element size is 1, we don't have to multiply, just add
2762 unsigned idxReg = getReg(idx, MBB, IP);
2763 unsigned Reg = makeAnotherReg(Type::UIntTy);
2764 BuildMI(*MBB, IP, PPC32::ADD, 2,TargetReg).addReg(Reg).addReg(idxReg);
2765 --IP; // Insert the next instruction before this one.
2766 TargetReg = Reg; // Codegen the rest of the GEP into this
2768 unsigned idxReg = getReg(idx, MBB, IP);
2769 unsigned OffsetReg = makeAnotherReg(Type::UIntTy);
2771 // Make sure we can back the iterator up to point to the first
2772 // instruction emitted.
2773 MachineBasicBlock::iterator BeforeIt = IP;
2774 if (IP == MBB->begin())
2775 BeforeIt = MBB->end();
2778 doMultiplyConst(MBB, IP, OffsetReg, Type::IntTy, idxReg, elementSize);
2780 // Emit an ADD to add OffsetReg to the basePtr.
2781 unsigned Reg = makeAnotherReg(Type::UIntTy);
2782 BuildMI(*MBB, IP, PPC32::ADD, 2, TargetReg).addReg(Reg).addReg(OffsetReg);
2784 // Step to the first instruction of the multiply.
2785 if (BeforeIt == MBB->end())
2790 TargetReg = Reg; // Codegen the rest of the GEP into this
2796 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
2797 /// frame manager, otherwise do it the hard way.
2799 void ISel::visitAllocaInst(AllocaInst &I) {
2800 // If this is a fixed size alloca in the entry block for the function, we
2801 // statically stack allocate the space, so we don't need to do anything here.
2803 if (dyn_castFixedAlloca(&I)) return;
2805 // Find the data size of the alloca inst's getAllocatedType.
2806 const Type *Ty = I.getAllocatedType();
2807 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
2809 // Create a register to hold the temporary result of multiplying the type size
2810 // constant by the variable amount.
2811 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
2812 unsigned SrcReg1 = getReg(I.getArraySize());
2814 // TotalSizeReg = mul <numelements>, <TypeSize>
2815 MachineBasicBlock::iterator MBBI = BB->end();
2816 doMultiplyConst(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, TySize);
2818 // AddedSize = add <TotalSizeReg>, 15
2819 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
2820 BuildMI(BB, PPC32::ADD, 2, AddedSizeReg).addReg(TotalSizeReg).addImm(15);
2822 // AlignedSize = and <AddedSize>, ~15
2823 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
2824 BuildMI(BB, PPC32::RLWNM, 4, AlignedSize).addReg(AddedSizeReg).addImm(0)
2825 .addImm(0).addImm(27);
2827 // Subtract size from stack pointer, thereby allocating some space.
2828 BuildMI(BB, PPC32::SUB, 2, PPC32::R1).addReg(PPC32::R1).addReg(AlignedSize);
2830 // Put a pointer to the space into the result register, by copying
2831 // the stack pointer.
2832 BuildMI(BB, PPC32::OR, 2, getReg(I)).addReg(PPC32::R1).addReg(PPC32::R1);
2834 // Inform the Frame Information that we have just allocated a variable-sized
2836 F->getFrameInfo()->CreateVariableSizedObject();
2839 /// visitMallocInst - Malloc instructions are code generated into direct calls
2840 /// to the library malloc.
2842 void ISel::visitMallocInst(MallocInst &I) {
2843 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
2846 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
2847 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
2849 Arg = makeAnotherReg(Type::UIntTy);
2850 unsigned Op0Reg = getReg(I.getOperand(0));
2851 MachineBasicBlock::iterator MBBI = BB->end();
2852 doMultiplyConst(BB, MBBI, Arg, Type::UIntTy, Op0Reg, AllocSize);
2855 std::vector<ValueRecord> Args;
2856 Args.push_back(ValueRecord(Arg, Type::UIntTy));
2857 MachineInstr *TheCall =
2858 BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(mallocFn, true);
2859 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args, false);
2863 /// visitFreeInst - Free instructions are code gen'd to call the free libc
2866 void ISel::visitFreeInst(FreeInst &I) {
2867 std::vector<ValueRecord> Args;
2868 Args.push_back(ValueRecord(I.getOperand(0)));
2869 MachineInstr *TheCall =
2870 BuildMI(PPC32::CALLpcrel, 1).addGlobalAddress(freeFn, true);
2871 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args, false);
2874 /// createPPC32SimpleInstructionSelector - This pass converts an LLVM function
2875 /// into a machine code representation is a very simple peep-hole fashion. The
2876 /// generated code sucks but the implementation is nice and simple.
2878 FunctionPass *llvm::createPPCSimpleInstructionSelector(TargetMachine &TM) {
2879 return new ISel(TM);