1 //===-- PPC32ISelSimple.cpp - A simple instruction selector PowerPC32 -----===//
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 "PPC32TargetMachine.h"
15 #include "llvm/Constants.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Function.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Pass.h"
20 #include "llvm/CodeGen/IntrinsicLowering.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/SSARegMap.h"
25 #include "llvm/Target/MRegisterInfo.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Support/GetElementPtrTypeIterator.h"
28 #include "llvm/Support/InstVisitor.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/ADT/Statistic.h"
35 /// TypeClass - Used by the PowerPC backend to group LLVM types by their basic
36 /// PPC Representation.
39 cByte, cShort, cInt, cFP32, cFP64, cLong
43 /// getClass - Turn a primitive type into a "class" number which is based on the
44 /// size of the type, and whether or not it is floating point.
46 static inline TypeClass getClass(const Type *Ty) {
47 switch (Ty->getTypeID()) {
49 case Type::UByteTyID: return cByte; // Byte operands are class #0
51 case Type::UShortTyID: return cShort; // Short operands are class #1
54 case Type::PointerTyID: return cInt; // Ints and pointers are class #2
56 case Type::FloatTyID: return cFP32; // Single float is #3
57 case Type::DoubleTyID: return cFP64; // Double Point is #4
60 case Type::ULongTyID: return cLong; // Longs are class #5
62 assert(0 && "Invalid type to getClass!");
63 return cByte; // not reached
67 // getClassB - Just like getClass, but treat boolean values as ints.
68 static inline TypeClass getClassB(const Type *Ty) {
69 if (Ty == Type::BoolTy) return cByte;
74 struct PPC32ISel : public FunctionPass, InstVisitor<PPC32ISel> {
75 PPC32TargetMachine &TM;
76 MachineFunction *F; // The function we are compiling into
77 MachineBasicBlock *BB; // The current MBB we are compiling
78 int VarArgsFrameIndex; // FrameIndex for start of varargs area
80 /// CollapsedGepOp - This struct is for recording the intermediate results
81 /// used to calculate the base, index, and offset of a GEP instruction.
82 struct CollapsedGepOp {
83 ConstantSInt *offset; // the current offset into the struct/array
84 Value *index; // the index of the array element
85 ConstantUInt *size; // the size of each array element
86 CollapsedGepOp(ConstantSInt *o, Value *i, ConstantUInt *s) :
87 offset(o), index(i), size(s) {}
90 /// FoldedGEP - This struct is for recording the necessary information to
91 /// emit the GEP in a load or store instruction, used by emitGEPOperation.
96 FoldedGEP() : base(0), index(0), offset(0) {}
97 FoldedGEP(unsigned b, unsigned i, ConstantSInt *o) :
98 base(b), index(i), offset(o) {}
101 /// RlwimiRec - This struct is for recording the arguments to a PowerPC
102 /// rlwimi instruction to be output for a particular Instruction::Or when
103 /// we recognize the pattern for rlwimi, starting with a shift or and.
105 Value *Target, *Insert;
106 unsigned Shift, MB, ME;
107 RlwimiRec() : Target(0), Insert(0), Shift(0), MB(0), ME(0) {}
108 RlwimiRec(Value *tgt, Value *ins, unsigned s, unsigned b, unsigned e) :
109 Target(tgt), Insert(ins), Shift(s), MB(b), ME(e) {}
112 // External functions used in the Module
113 Function *fmodfFn, *fmodFn, *__cmpdi2Fn, *__moddi3Fn, *__divdi3Fn,
114 *__umoddi3Fn, *__udivdi3Fn, *__fixsfdiFn, *__fixdfdiFn, *__fixunssfdiFn,
115 *__fixunsdfdiFn, *__floatdisfFn, *__floatdidfFn, *mallocFn, *freeFn;
117 // Mapping between Values and SSA Regs
118 std::map<Value*, unsigned> RegMap;
120 // MBBMap - Mapping between LLVM BB -> Machine BB
121 std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
123 // AllocaMap - Mapping from fixed sized alloca instructions to the
124 // FrameIndex for the alloca.
125 std::map<AllocaInst*, unsigned> AllocaMap;
127 // GEPMap - Mapping between basic blocks and GEP definitions
128 std::map<GetElementPtrInst*, FoldedGEP> GEPMap;
130 // RlwimiMap - Mapping between BinaryOperand (Or) instructions and info
131 // needed to properly emit a rlwimi instruction in its place.
132 std::map<Instruction *, RlwimiRec> InsertMap;
134 // A rlwimi instruction is the combination of at least three instructions.
135 // Keep a vector of instructions to skip around so that we do not try to
136 // emit instructions that were folded into a rlwimi.
137 std::vector<Instruction *> SkipList;
139 // A Reg to hold the base address used for global loads and stores, and a
140 // flag to set whether or not we need to emit it for this function.
141 unsigned GlobalBaseReg;
142 bool GlobalBaseInitialized;
144 PPC32ISel(TargetMachine &tm):TM(reinterpret_cast<PPC32TargetMachine&>(tm)),
147 bool doInitialization(Module &M) {
148 // Add external functions that we may call
149 Type *i = Type::IntTy;
150 Type *d = Type::DoubleTy;
151 Type *f = Type::FloatTy;
152 Type *l = Type::LongTy;
153 Type *ul = Type::ULongTy;
154 Type *voidPtr = PointerType::get(Type::SByteTy);
155 // float fmodf(float, float);
156 fmodfFn = M.getOrInsertFunction("fmodf", f, f, f, 0);
157 // double fmod(double, double);
158 fmodFn = M.getOrInsertFunction("fmod", d, d, d, 0);
159 // int __cmpdi2(long, long);
160 __cmpdi2Fn = M.getOrInsertFunction("__cmpdi2", i, l, l, 0);
161 // long __moddi3(long, long);
162 __moddi3Fn = M.getOrInsertFunction("__moddi3", l, l, l, 0);
163 // long __divdi3(long, long);
164 __divdi3Fn = M.getOrInsertFunction("__divdi3", l, l, l, 0);
165 // unsigned long __umoddi3(unsigned long, unsigned long);
166 __umoddi3Fn = M.getOrInsertFunction("__umoddi3", ul, ul, ul, 0);
167 // unsigned long __udivdi3(unsigned long, unsigned long);
168 __udivdi3Fn = M.getOrInsertFunction("__udivdi3", ul, ul, ul, 0);
169 // long __fixsfdi(float)
170 __fixsfdiFn = M.getOrInsertFunction("__fixsfdi", l, f, 0);
171 // long __fixdfdi(double)
172 __fixdfdiFn = M.getOrInsertFunction("__fixdfdi", l, d, 0);
173 // unsigned long __fixunssfdi(float)
174 __fixunssfdiFn = M.getOrInsertFunction("__fixunssfdi", ul, f, 0);
175 // unsigned long __fixunsdfdi(double)
176 __fixunsdfdiFn = M.getOrInsertFunction("__fixunsdfdi", ul, d, 0);
177 // float __floatdisf(long)
178 __floatdisfFn = M.getOrInsertFunction("__floatdisf", f, l, 0);
179 // double __floatdidf(long)
180 __floatdidfFn = M.getOrInsertFunction("__floatdidf", d, l, 0);
181 // void* malloc(size_t)
182 mallocFn = M.getOrInsertFunction("malloc", voidPtr, Type::UIntTy, 0);
184 freeFn = M.getOrInsertFunction("free", Type::VoidTy, voidPtr, 0);
188 /// runOnFunction - Top level implementation of instruction selection for
189 /// the entire function.
191 bool runOnFunction(Function &Fn) {
192 // First pass over the function, lower any unknown intrinsic functions
193 // with the IntrinsicLowering class.
194 LowerUnknownIntrinsicFunctionCalls(Fn);
196 F = &MachineFunction::construct(&Fn, TM);
198 // Create all of the machine basic blocks for the function...
199 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
200 F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
204 // Make sure we re-emit a set of the global base reg if necessary
205 GlobalBaseInitialized = false;
207 // Copy incoming arguments off of the stack...
208 LoadArgumentsToVirtualRegs(Fn);
210 // Instruction select everything except PHI nodes
213 // Select the PHI nodes
223 // We always build a machine code representation for the function
227 virtual const char *getPassName() const {
228 return "PowerPC Simple Instruction Selection";
231 /// visitBasicBlock - This method is called when we are visiting a new basic
232 /// block. This simply creates a new MachineBasicBlock to emit code into
233 /// and adds it to the current MachineFunction. Subsequent visit* for
234 /// instructions will be invoked for all instructions in the basic block.
236 void visitBasicBlock(BasicBlock &LLVM_BB) {
237 BB = MBBMap[&LLVM_BB];
240 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
241 /// function, lowering any calls to unknown intrinsic functions into the
242 /// equivalent LLVM code.
244 void LowerUnknownIntrinsicFunctionCalls(Function &F);
246 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function
247 /// from the stack into virtual registers.
249 void LoadArgumentsToVirtualRegs(Function &F);
251 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
252 /// because we have to generate our sources into the source basic blocks,
253 /// not the current one.
255 void SelectPHINodes();
257 // Visitation methods for various instructions. These methods simply emit
258 // fixed PowerPC code for each instruction.
260 // Control flow operators.
261 void visitReturnInst(ReturnInst &RI);
262 void visitBranchInst(BranchInst &BI);
263 void visitUnreachableInst(UnreachableInst &UI) {}
269 ValueRecord(unsigned R, const Type *T) : Val(0), Reg(R), Ty(T) {}
270 ValueRecord(Value *V) : Val(V), Reg(0), Ty(V->getType()) {}
273 void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
274 const std::vector<ValueRecord> &Args, bool isVarArg);
275 void visitCallInst(CallInst &I);
276 void visitIntrinsicCall(Intrinsic::ID ID, CallInst &I);
278 // Arithmetic operators
279 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
280 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
281 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
282 void visitMul(BinaryOperator &B);
284 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
285 void visitRem(BinaryOperator &B) { visitDivRem(B); }
286 void visitDivRem(BinaryOperator &B);
289 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
290 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
291 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
293 // Comparison operators...
294 void visitSetCondInst(SetCondInst &I);
295 unsigned EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
296 MachineBasicBlock *MBB,
297 MachineBasicBlock::iterator MBBI);
298 void visitSelectInst(SelectInst &SI);
301 // Memory Instructions
302 void visitLoadInst(LoadInst &I);
303 void visitStoreInst(StoreInst &I);
304 void visitGetElementPtrInst(GetElementPtrInst &I);
305 void visitAllocaInst(AllocaInst &I);
306 void visitMallocInst(MallocInst &I);
307 void visitFreeInst(FreeInst &I);
310 void visitShiftInst(ShiftInst &I);
311 void visitPHINode(PHINode &I) {} // PHI nodes handled by second pass
312 void visitCastInst(CastInst &I);
313 void visitVANextInst(VANextInst &I);
314 void visitVAArgInst(VAArgInst &I);
316 void visitInstruction(Instruction &I) {
317 std::cerr << "Cannot instruction select: " << I;
321 unsigned ExtendOrClear(MachineBasicBlock *MBB,
322 MachineBasicBlock::iterator IP,
325 /// promote32 - Make a value 32-bits wide, and put it somewhere.
327 void promote32(unsigned targetReg, const ValueRecord &VR);
329 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
330 /// constant expression GEP support.
332 void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
333 GetElementPtrInst *GEPI, bool foldGEP);
335 /// emitCastOperation - Common code shared between visitCastInst and
336 /// constant expression cast support.
338 void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator IP,
339 Value *Src, const Type *DestTy, unsigned TargetReg);
342 /// emitBitfieldInsert - return true if we were able to fold the sequence of
343 /// instructions into a bitfield insert (rlwimi).
344 bool emitBitfieldInsert(User *OpUser, unsigned DestReg);
346 /// emitBitfieldExtract - return true if we were able to fold the sequence
347 /// of instructions into a bitfield extract (rlwinm).
348 bool emitBitfieldExtract(MachineBasicBlock *MBB,
349 MachineBasicBlock::iterator IP,
350 User *OpUser, unsigned DestReg);
352 /// emitBinaryConstOperation - Used by several functions to emit simple
353 /// arithmetic and logical operations with constants on a register rather
356 void emitBinaryConstOperation(MachineBasicBlock *MBB,
357 MachineBasicBlock::iterator IP,
358 unsigned Op0Reg, ConstantInt *Op1,
359 unsigned Opcode, unsigned DestReg);
361 /// emitSimpleBinaryOperation - Implement simple binary operators for
362 /// integral types. OperatorClass is one of: 0 for Add, 1 for Sub,
363 /// 2 for And, 3 for Or, 4 for Xor.
365 void emitSimpleBinaryOperation(MachineBasicBlock *BB,
366 MachineBasicBlock::iterator IP,
367 BinaryOperator *BO, Value *Op0, Value *Op1,
368 unsigned OperatorClass, unsigned TargetReg);
370 /// emitBinaryFPOperation - This method handles emission of floating point
371 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
372 void emitBinaryFPOperation(MachineBasicBlock *BB,
373 MachineBasicBlock::iterator IP,
374 Value *Op0, Value *Op1,
375 unsigned OperatorClass, unsigned TargetReg);
377 void emitMultiply(MachineBasicBlock *BB, MachineBasicBlock::iterator IP,
378 Value *Op0, Value *Op1, unsigned TargetReg);
380 void doMultiply(MachineBasicBlock *MBB,
381 MachineBasicBlock::iterator IP,
382 unsigned DestReg, Value *Op0, Value *Op1);
384 /// doMultiplyConst - This method will multiply the value in Op0Reg by the
385 /// value of the ContantInt *CI
386 void doMultiplyConst(MachineBasicBlock *MBB,
387 MachineBasicBlock::iterator IP,
388 unsigned DestReg, Value *Op0, ConstantInt *CI);
390 void emitDivRemOperation(MachineBasicBlock *BB,
391 MachineBasicBlock::iterator IP,
392 Value *Op0, Value *Op1, bool isDiv,
395 /// emitSetCCOperation - Common code shared between visitSetCondInst and
396 /// constant expression support.
398 void emitSetCCOperation(MachineBasicBlock *BB,
399 MachineBasicBlock::iterator IP,
400 Value *Op0, Value *Op1, unsigned Opcode,
403 /// emitShiftOperation - Common code shared between visitShiftInst and
404 /// constant expression support.
406 void emitShiftOperation(MachineBasicBlock *MBB,
407 MachineBasicBlock::iterator IP,
408 Value *Op, Value *ShiftAmount, bool isLeftShift,
409 const Type *ResultTy, ShiftInst *SI,
412 /// emitSelectOperation - Common code shared between visitSelectInst and the
413 /// constant expression support.
415 void emitSelectOperation(MachineBasicBlock *MBB,
416 MachineBasicBlock::iterator IP,
417 Value *Cond, Value *TrueVal, Value *FalseVal,
420 /// getGlobalBaseReg - Output the instructions required to put the
421 /// base address to use for accessing globals into a register. Returns the
422 /// register containing the base address.
424 unsigned getGlobalBaseReg(MachineBasicBlock *MBB,
425 MachineBasicBlock::iterator IP);
427 /// copyConstantToRegister - Output the instructions required to put the
428 /// specified constant into the specified register.
430 void copyConstantToRegister(MachineBasicBlock *MBB,
431 MachineBasicBlock::iterator MBBI,
432 Constant *C, unsigned Reg);
434 void emitUCOM(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
435 unsigned LHS, unsigned RHS);
437 /// makeAnotherReg - This method returns the next register number we haven't
440 /// Long values are handled somewhat specially. They are always allocated
441 /// as pairs of 32 bit integer values. The register number returned is the
442 /// high 32 bits of the long value, and the regNum+1 is the low 32 bits.
444 unsigned makeAnotherReg(const Type *Ty) {
445 assert(dynamic_cast<const PPC32RegisterInfo*>(TM.getRegisterInfo()) &&
446 "Current target doesn't have PPC reg info??");
447 const PPC32RegisterInfo *PPCRI =
448 static_cast<const PPC32RegisterInfo*>(TM.getRegisterInfo());
449 if (Ty == Type::LongTy || Ty == Type::ULongTy) {
450 const TargetRegisterClass *RC = PPCRI->getRegClassForType(Type::IntTy);
451 // Create the upper part
452 F->getSSARegMap()->createVirtualRegister(RC);
453 // Create the lower part.
454 return F->getSSARegMap()->createVirtualRegister(RC)-1;
457 // Add the mapping of regnumber => reg class to MachineFunction
458 const TargetRegisterClass *RC = PPCRI->getRegClassForType(Ty);
459 return F->getSSARegMap()->createVirtualRegister(RC);
462 /// getReg - This method turns an LLVM value into a register number.
464 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
465 unsigned getReg(Value *V) {
466 // Just append to the end of the current bb.
467 MachineBasicBlock::iterator It = BB->end();
468 return getReg(V, BB, It);
470 unsigned getReg(Value *V, MachineBasicBlock *MBB,
471 MachineBasicBlock::iterator IPt);
473 /// canUseAsImmediateForOpcode - This method returns whether a ConstantInt
474 /// is okay to use as an immediate argument to a certain binary operation
475 bool canUseAsImmediateForOpcode(ConstantInt *CI, unsigned Opcode,
478 /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
479 /// that is to be statically allocated with the initial stack frame
481 unsigned getFixedSizedAllocaFI(AllocaInst *AI);
485 /// dyn_castFixedAlloca - If the specified value is a fixed size alloca
486 /// instruction in the entry block, return it. Otherwise, return a null
488 static AllocaInst *dyn_castFixedAlloca(Value *V) {
489 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
490 BasicBlock *BB = AI->getParent();
491 if (isa<ConstantUInt>(AI->getArraySize()) && BB ==&BB->getParent()->front())
497 /// getReg - This method turns an LLVM value into a register number.
499 unsigned PPC32ISel::getReg(Value *V, MachineBasicBlock *MBB,
500 MachineBasicBlock::iterator IPt) {
501 if (Constant *C = dyn_cast<Constant>(V)) {
502 unsigned Reg = makeAnotherReg(V->getType());
503 copyConstantToRegister(MBB, IPt, C, Reg);
505 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
506 // Do not emit noop casts at all, unless it's a double -> float cast.
507 if (getClassB(CI->getType()) == getClassB(CI->getOperand(0)->getType()))
508 return getReg(CI->getOperand(0), MBB, IPt);
509 } else if (AllocaInst *AI = dyn_castFixedAlloca(V)) {
510 unsigned Reg = makeAnotherReg(V->getType());
511 unsigned FI = getFixedSizedAllocaFI(AI);
512 addFrameReference(BuildMI(*MBB, IPt, PPC::ADDI, 2, Reg), FI, 0, false);
516 unsigned &Reg = RegMap[V];
518 Reg = makeAnotherReg(V->getType());
525 /// canUseAsImmediateForOpcode - This method returns whether a ConstantInt
526 /// is okay to use as an immediate argument to a certain binary operator.
527 /// The shifted argument determines if the immediate is suitable to be used with
528 /// the PowerPC instructions such as addis which concatenate 16 bits of the
529 /// immediate with 16 bits of zeroes.
531 bool PPC32ISel::canUseAsImmediateForOpcode(ConstantInt *CI, unsigned Opcode,
536 // For shifted immediates, any value with the low halfword cleared may be used
538 if (((int32_t)CI->getRawValue() & 0x0000FFFF) == 0)
544 // Treat subfic like addi for the purposes of constant validation
545 if (Opcode == 5) Opcode = 0;
547 // addi, subfic, compare, and non-indexed load take SIMM
548 bool cond1 = (Opcode < 2)
549 && ((int32_t)CI->getRawValue() <= 32767)
550 && ((int32_t)CI->getRawValue() >= -32768);
552 // ANDIo, ORI, and XORI take unsigned values
553 bool cond2 = (Opcode >= 2)
554 && (Op1Cs = dyn_cast<ConstantSInt>(CI))
555 && (Op1Cs->getValue() >= 0)
556 && (Op1Cs->getValue() <= 65535);
558 // ANDIo, ORI, and XORI take UIMMs, so they can be larger
559 bool cond3 = (Opcode >= 2)
560 && (Op1Cu = dyn_cast<ConstantUInt>(CI))
561 && (Op1Cu->getValue() <= 65535);
563 if (cond1 || cond2 || cond3)
569 /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
570 /// that is to be statically allocated with the initial stack frame
572 unsigned PPC32ISel::getFixedSizedAllocaFI(AllocaInst *AI) {
573 // Already computed this?
574 std::map<AllocaInst*, unsigned>::iterator I = AllocaMap.lower_bound(AI);
575 if (I != AllocaMap.end() && I->first == AI) return I->second;
577 const Type *Ty = AI->getAllocatedType();
578 ConstantUInt *CUI = cast<ConstantUInt>(AI->getArraySize());
579 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
580 TySize *= CUI->getValue(); // Get total allocated size...
581 unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
583 // Create a new stack object using the frame manager...
584 int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
585 AllocaMap.insert(I, std::make_pair(AI, FrameIdx));
590 /// getGlobalBaseReg - Output the instructions required to put the
591 /// base address to use for accessing globals into a register.
593 unsigned PPC32ISel::getGlobalBaseReg(MachineBasicBlock *MBB,
594 MachineBasicBlock::iterator IP) {
595 if (!GlobalBaseInitialized) {
596 // Insert the set of GlobalBaseReg into the first MBB of the function
597 MachineBasicBlock &FirstMBB = F->front();
598 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
599 GlobalBaseReg = makeAnotherReg(Type::IntTy);
600 BuildMI(FirstMBB, MBBI, PPC::MovePCtoLR, 0, PPC::LR);
601 BuildMI(FirstMBB, MBBI, PPC::MFLR, 1, GlobalBaseReg).addReg(PPC::LR);
602 GlobalBaseInitialized = true;
604 return GlobalBaseReg;
607 /// copyConstantToRegister - Output the instructions required to put the
608 /// specified constant into the specified register.
610 void PPC32ISel::copyConstantToRegister(MachineBasicBlock *MBB,
611 MachineBasicBlock::iterator IP,
612 Constant *C, unsigned R) {
613 if (isa<UndefValue>(C)) {
614 BuildMI(*MBB, IP, PPC::IMPLICIT_DEF, 0, R);
617 if (C->getType()->isIntegral()) {
618 unsigned Class = getClassB(C->getType());
620 if (Class == cLong) {
621 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(C)) {
622 uint64_t uval = CUI->getValue();
623 unsigned hiUVal = uval >> 32;
624 unsigned loUVal = uval;
625 ConstantUInt *CUHi = ConstantUInt::get(Type::UIntTy, hiUVal);
626 ConstantUInt *CULo = ConstantUInt::get(Type::UIntTy, loUVal);
627 copyConstantToRegister(MBB, IP, CUHi, R);
628 copyConstantToRegister(MBB, IP, CULo, R+1);
630 } else if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(C)) {
631 int64_t sval = CSI->getValue();
632 int hiSVal = sval >> 32;
634 ConstantSInt *CSHi = ConstantSInt::get(Type::IntTy, hiSVal);
635 ConstantSInt *CSLo = ConstantSInt::get(Type::IntTy, loSVal);
636 copyConstantToRegister(MBB, IP, CSHi, R);
637 copyConstantToRegister(MBB, IP, CSLo, R+1);
640 std::cerr << "Unhandled long constant type!\n";
645 assert(Class <= cInt && "Type not handled yet!");
648 if (C->getType() == Type::BoolTy) {
649 BuildMI(*MBB, IP, PPC::LI, 1, R).addSImm(C == ConstantBool::True);
654 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(C)) {
655 unsigned uval = CUI->getValue();
657 BuildMI(*MBB, IP, PPC::LI, 1, R).addSImm(uval);
659 unsigned Temp = makeAnotherReg(Type::IntTy);
660 BuildMI(*MBB, IP, PPC::LIS, 1, Temp).addSImm(uval >> 16);
661 BuildMI(*MBB, IP, PPC::ORI, 2, R).addReg(Temp).addImm(uval & 0xFFFF);
664 } else if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(C)) {
665 int sval = CSI->getValue();
666 if (sval < 32768 && sval >= -32768) {
667 BuildMI(*MBB, IP, PPC::LI, 1, R).addSImm(sval);
669 unsigned Temp = makeAnotherReg(Type::IntTy);
670 BuildMI(*MBB, IP, PPC::LIS, 1, Temp).addSImm(sval >> 16);
671 BuildMI(*MBB, IP, PPC::ORI, 2, R).addReg(Temp).addImm(sval & 0xFFFF);
675 std::cerr << "Unhandled integer constant!\n";
677 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
678 // We need to spill the constant to memory...
679 MachineConstantPool *CP = F->getConstantPool();
680 unsigned CPI = CP->getConstantPoolIndex(CFP);
681 const Type *Ty = CFP->getType();
683 assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
685 // Load addr of constant to reg; constant is located at base + distance
686 unsigned GlobalBase = makeAnotherReg(Type::IntTy);
687 unsigned Reg1 = makeAnotherReg(Type::IntTy);
688 unsigned Opcode = (Ty == Type::FloatTy) ? PPC::LFS : PPC::LFD;
689 // Move value at base + distance into return reg
690 BuildMI(*MBB, IP, PPC::LOADHiAddr, 2, Reg1)
691 .addReg(getGlobalBaseReg(MBB, IP)).addConstantPoolIndex(CPI);
692 BuildMI(*MBB, IP, Opcode, 2, R).addConstantPoolIndex(CPI).addReg(Reg1);
693 } else if (isa<ConstantPointerNull>(C)) {
694 // Copy zero (null pointer) to the register.
695 BuildMI(*MBB, IP, PPC::LI, 1, R).addSImm(0);
696 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
697 // GV is located at base + distance
699 unsigned GlobalBase = makeAnotherReg(Type::IntTy);
700 unsigned TmpReg = makeAnotherReg(GV->getType());
702 // Move value at base + distance into return reg
703 BuildMI(*MBB, IP, PPC::LOADHiAddr, 2, TmpReg)
704 .addReg(getGlobalBaseReg(MBB, IP)).addGlobalAddress(GV);
706 if (GV->hasWeakLinkage() || GV->isExternal()) {
707 BuildMI(*MBB, IP, PPC::LWZ, 2, R).addGlobalAddress(GV).addReg(TmpReg);
709 BuildMI(*MBB, IP, PPC::LA, 2, R).addReg(TmpReg).addGlobalAddress(GV);
712 // Add the GV to the list of things whose addresses have been taken.
713 TM.AddressTaken.insert(GV);
715 std::cerr << "Offending constant: " << *C << "\n";
716 assert(0 && "Type not handled yet!");
720 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
721 /// the stack into virtual registers.
722 void PPC32ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
723 unsigned ArgOffset = 24;
724 unsigned GPR_remaining = 8;
725 unsigned FPR_remaining = 13;
726 unsigned GPR_idx = 0, FPR_idx = 0;
727 static const unsigned GPR[] = {
728 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
729 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
731 static const unsigned FPR[] = {
732 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
733 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
736 MachineFrameInfo *MFI = F->getFrameInfo();
738 for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
739 bool ArgLive = !I->use_empty();
740 unsigned Reg = ArgLive ? getReg(*I) : 0;
741 int FI; // Frame object index
743 switch (getClassB(I->getType())) {
746 FI = MFI->CreateFixedObject(4, ArgOffset);
747 if (GPR_remaining > 0) {
748 BuildMI(BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx]);
749 BuildMI(BB, PPC::OR, 2, Reg).addReg(GPR[GPR_idx])
750 .addReg(GPR[GPR_idx]);
752 addFrameReference(BuildMI(BB, PPC::LBZ, 2, Reg), FI);
758 FI = MFI->CreateFixedObject(4, ArgOffset);
759 if (GPR_remaining > 0) {
760 BuildMI(BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx]);
761 BuildMI(BB, PPC::OR, 2, Reg).addReg(GPR[GPR_idx])
762 .addReg(GPR[GPR_idx]);
764 addFrameReference(BuildMI(BB, PPC::LHZ, 2, Reg), FI);
770 FI = MFI->CreateFixedObject(4, ArgOffset);
771 if (GPR_remaining > 0) {
772 BuildMI(BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx]);
773 BuildMI(BB, PPC::OR, 2, Reg).addReg(GPR[GPR_idx])
774 .addReg(GPR[GPR_idx]);
776 addFrameReference(BuildMI(BB, PPC::LWZ, 2, Reg), FI);
782 FI = MFI->CreateFixedObject(8, ArgOffset);
783 if (GPR_remaining > 1) {
784 BuildMI(BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx]);
785 BuildMI(BB, PPC::IMPLICIT_DEF, 0, GPR[GPR_idx+1]);
786 BuildMI(BB, PPC::OR, 2, Reg).addReg(GPR[GPR_idx])
787 .addReg(GPR[GPR_idx]);
788 BuildMI(BB, PPC::OR, 2, Reg+1).addReg(GPR[GPR_idx+1])
789 .addReg(GPR[GPR_idx+1]);
791 addFrameReference(BuildMI(BB, PPC::LWZ, 2, Reg), FI);
792 addFrameReference(BuildMI(BB, PPC::LWZ, 2, Reg+1), FI, 4);
795 // longs require 4 additional bytes and use 2 GPRs
797 if (GPR_remaining > 1) {
804 FI = MFI->CreateFixedObject(4, ArgOffset);
806 if (FPR_remaining > 0) {
807 BuildMI(BB, PPC::IMPLICIT_DEF, 0, FPR[FPR_idx]);
808 BuildMI(BB, PPC::FMR, 1, Reg).addReg(FPR[FPR_idx]);
812 addFrameReference(BuildMI(BB, PPC::LFS, 2, Reg), FI);
818 FI = MFI->CreateFixedObject(8, ArgOffset);
820 if (FPR_remaining > 0) {
821 BuildMI(BB, PPC::IMPLICIT_DEF, 0, FPR[FPR_idx]);
822 BuildMI(BB, PPC::FMR, 1, Reg).addReg(FPR[FPR_idx]);
826 addFrameReference(BuildMI(BB, PPC::LFD, 2, Reg), FI);
830 // doubles require 4 additional bytes and use 2 GPRs of param space
832 if (GPR_remaining > 0) {
838 assert(0 && "Unhandled argument type!");
840 ArgOffset += 4; // Each argument takes at least 4 bytes on the stack...
841 if (GPR_remaining > 0) {
842 GPR_remaining--; // uses up 2 GPRs
847 // If the function takes variable number of arguments, add a frame offset for
848 // the start of the first vararg value... this is used to expand
850 if (Fn.getFunctionType()->isVarArg())
851 VarArgsFrameIndex = MFI->CreateFixedObject(4, ArgOffset);
855 /// SelectPHINodes - Insert machine code to generate phis. This is tricky
856 /// because we have to generate our sources into the source basic blocks, not
859 void PPC32ISel::SelectPHINodes() {
860 const TargetInstrInfo &TII = *TM.getInstrInfo();
861 const Function &LF = *F->getFunction(); // The LLVM function...
862 for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
863 const BasicBlock *BB = I;
864 MachineBasicBlock &MBB = *MBBMap[I];
866 // Loop over all of the PHI nodes in the LLVM basic block...
867 MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
868 for (BasicBlock::const_iterator I = BB->begin();
869 PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
871 // Create a new machine instr PHI node, and insert it.
872 unsigned PHIReg = getReg(*PN);
873 MachineInstr *PhiMI = BuildMI(MBB, PHIInsertPoint,
874 PPC::PHI, PN->getNumOperands(), PHIReg);
876 MachineInstr *LongPhiMI = 0;
877 if (PN->getType() == Type::LongTy || PN->getType() == Type::ULongTy)
878 LongPhiMI = BuildMI(MBB, PHIInsertPoint,
879 PPC::PHI, PN->getNumOperands(), PHIReg+1);
881 // PHIValues - Map of blocks to incoming virtual registers. We use this
882 // so that we only initialize one incoming value for a particular block,
883 // even if the block has multiple entries in the PHI node.
885 std::map<MachineBasicBlock*, unsigned> PHIValues;
887 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
888 MachineBasicBlock *PredMBB = 0;
889 for (MachineBasicBlock::pred_iterator PI = MBB.pred_begin (),
890 PE = MBB.pred_end (); PI != PE; ++PI)
891 if (PN->getIncomingBlock(i) == (*PI)->getBasicBlock()) {
895 assert (PredMBB && "Couldn't find incoming machine-cfg edge for phi");
898 std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
899 PHIValues.lower_bound(PredMBB);
901 if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
902 // We already inserted an initialization of the register for this
903 // predecessor. Recycle it.
904 ValReg = EntryIt->second;
906 // Get the incoming value into a virtual register.
908 Value *Val = PN->getIncomingValue(i);
910 // If this is a constant or GlobalValue, we may have to insert code
911 // into the basic block to compute it into a virtual register.
912 if ((isa<Constant>(Val) && !isa<ConstantExpr>(Val)) ||
913 isa<GlobalValue>(Val)) {
914 // Simple constants get emitted at the end of the basic block,
915 // before any terminator instructions. We "know" that the code to
916 // move a constant into a register will never clobber any flags.
917 ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
919 // Because we don't want to clobber any values which might be in
920 // physical registers with the computation of this constant (which
921 // might be arbitrarily complex if it is a constant expression),
922 // just insert the computation at the top of the basic block.
923 MachineBasicBlock::iterator PI = PredMBB->begin();
925 // Skip over any PHI nodes though!
926 while (PI != PredMBB->end() && PI->getOpcode() == PPC::PHI)
929 ValReg = getReg(Val, PredMBB, PI);
932 // Remember that we inserted a value for this PHI for this predecessor
933 PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
936 PhiMI->addRegOperand(ValReg);
937 PhiMI->addMachineBasicBlockOperand(PredMBB);
939 LongPhiMI->addRegOperand(ValReg+1);
940 LongPhiMI->addMachineBasicBlockOperand(PredMBB);
944 // Now that we emitted all of the incoming values for the PHI node, make
945 // sure to reposition the InsertPoint after the PHI that we just added.
946 // This is needed because we might have inserted a constant into this
947 // block, right after the PHI's which is before the old insert point!
948 PHIInsertPoint = LongPhiMI ? LongPhiMI : PhiMI;
955 // canFoldSetCCIntoBranchOrSelect - Return the setcc instruction if we can fold
956 // it into the conditional branch or select instruction which is the only user
957 // of the cc instruction. This is the case if the conditional branch is the
958 // only user of the setcc, and if the setcc is in the same basic block as the
959 // conditional branch.
961 static SetCondInst *canFoldSetCCIntoBranchOrSelect(Value *V) {
962 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
963 if (SCI->hasOneUse()) {
964 Instruction *User = cast<Instruction>(SCI->use_back());
965 if ((isa<BranchInst>(User) || isa<SelectInst>(User)) &&
966 SCI->getParent() == User->getParent())
972 // canFoldGEPIntoLoadOrStore - Return the GEP instruction if we can fold it into
973 // the load or store instruction that is the only user of the GEP.
975 static GetElementPtrInst *canFoldGEPIntoLoadOrStore(Value *V) {
976 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
977 bool AllUsesAreMem = true;
978 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
980 Instruction *User = cast<Instruction>(*I);
982 // If the GEP is the target of a store, but not the source, then we are ok
984 if (isa<StoreInst>(User) &&
985 GEPI->getParent() == User->getParent() &&
986 User->getOperand(0) != GEPI &&
987 User->getOperand(1) == GEPI)
990 // If the GEP is the source of a load, then we're always ok to fold it
991 if (isa<LoadInst>(User) &&
992 GEPI->getParent() == User->getParent() &&
993 User->getOperand(0) == GEPI)
996 // if we got to this point, than the instruction was not a load or store
997 // that we are capable of folding the GEP into.
998 AllUsesAreMem = false;
1008 // Return a fixed numbering for setcc instructions which does not depend on the
1009 // order of the opcodes.
1011 static unsigned getSetCCNumber(unsigned Opcode) {
1013 default: assert(0 && "Unknown setcc instruction!");
1014 case Instruction::SetEQ: return 0;
1015 case Instruction::SetNE: return 1;
1016 case Instruction::SetLT: return 2;
1017 case Instruction::SetGE: return 3;
1018 case Instruction::SetGT: return 4;
1019 case Instruction::SetLE: return 5;
1023 static unsigned getPPCOpcodeForSetCCNumber(unsigned Opcode) {
1025 default: assert(0 && "Unknown setcc instruction!");
1026 case Instruction::SetEQ: return PPC::BEQ;
1027 case Instruction::SetNE: return PPC::BNE;
1028 case Instruction::SetLT: return PPC::BLT;
1029 case Instruction::SetGE: return PPC::BGE;
1030 case Instruction::SetGT: return PPC::BGT;
1031 case Instruction::SetLE: return PPC::BLE;
1035 /// emitUCOM - emits an unordered FP compare.
1036 void PPC32ISel::emitUCOM(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
1037 unsigned LHS, unsigned RHS) {
1038 BuildMI(*MBB, IP, PPC::FCMPU, 2, PPC::CR0).addReg(LHS).addReg(RHS);
1041 unsigned PPC32ISel::ExtendOrClear(MachineBasicBlock *MBB,
1042 MachineBasicBlock::iterator IP,
1044 const Type *CompTy = Op0->getType();
1045 unsigned Reg = getReg(Op0, MBB, IP);
1046 unsigned Class = getClassB(CompTy);
1048 // Since we know that boolean values will be either zero or one, we don't
1049 // have to extend or clear them.
1050 if (CompTy == Type::BoolTy)
1053 // Before we do a comparison or SetCC, we have to make sure that we truncate
1054 // the source registers appropriately.
1055 if (Class == cByte) {
1056 unsigned TmpReg = makeAnotherReg(CompTy);
1057 if (CompTy->isSigned())
1058 BuildMI(*MBB, IP, PPC::EXTSB, 1, TmpReg).addReg(Reg);
1060 BuildMI(*MBB, IP, PPC::RLWINM, 4, TmpReg).addReg(Reg).addImm(0)
1061 .addImm(24).addImm(31);
1063 } else if (Class == cShort) {
1064 unsigned TmpReg = makeAnotherReg(CompTy);
1065 if (CompTy->isSigned())
1066 BuildMI(*MBB, IP, PPC::EXTSH, 1, TmpReg).addReg(Reg);
1068 BuildMI(*MBB, IP, PPC::RLWINM, 4, TmpReg).addReg(Reg).addImm(0)
1069 .addImm(16).addImm(31);
1075 /// EmitComparison - emits a comparison of the two operands, returning the
1076 /// extended setcc code to use. The result is in CR0.
1078 unsigned PPC32ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
1079 MachineBasicBlock *MBB,
1080 MachineBasicBlock::iterator IP) {
1081 // The arguments are already supposed to be of the same type.
1082 const Type *CompTy = Op0->getType();
1083 unsigned Class = getClassB(CompTy);
1084 unsigned Op0r = ExtendOrClear(MBB, IP, Op0);
1086 // Use crand for lt, gt and crandc for le, ge
1087 unsigned CROpcode = (OpNum == 2 || OpNum == 4) ? PPC::CRAND : PPC::CRANDC;
1088 // ? cr1[lt] : cr1[gt]
1089 unsigned CR1field = (OpNum == 2 || OpNum == 3) ? 4 : 5;
1090 // ? cr0[lt] : cr0[gt]
1091 unsigned CR0field = (OpNum == 2 || OpNum == 5) ? 0 : 1;
1092 unsigned Opcode = CompTy->isSigned() ? PPC::CMPW : PPC::CMPLW;
1093 unsigned OpcodeImm = CompTy->isSigned() ? PPC::CMPWI : PPC::CMPLWI;
1095 // Special case handling of: cmp R, i
1096 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1097 if (Class == cByte || Class == cShort || Class == cInt) {
1098 unsigned Op1v = CI->getRawValue() & 0xFFFF;
1099 unsigned OpClass = (CompTy->isSigned()) ? 0 : 2;
1101 // Treat compare like ADDI for the purposes of immediate suitability
1102 if (canUseAsImmediateForOpcode(CI, OpClass, false)) {
1103 BuildMI(*MBB, IP, OpcodeImm, 2, PPC::CR0).addReg(Op0r).addSImm(Op1v);
1105 unsigned Op1r = getReg(Op1, MBB, IP);
1106 BuildMI(*MBB, IP, Opcode, 2, PPC::CR0).addReg(Op0r).addReg(Op1r);
1110 assert(Class == cLong && "Unknown integer class!");
1111 unsigned LowCst = CI->getRawValue();
1112 unsigned HiCst = CI->getRawValue() >> 32;
1113 if (OpNum < 2) { // seteq, setne
1114 unsigned LoLow = makeAnotherReg(Type::IntTy);
1115 unsigned LoTmp = makeAnotherReg(Type::IntTy);
1116 unsigned HiLow = makeAnotherReg(Type::IntTy);
1117 unsigned HiTmp = makeAnotherReg(Type::IntTy);
1118 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
1120 BuildMI(*MBB, IP, PPC::XORI, 2, LoLow).addReg(Op0r+1)
1121 .addImm(LowCst & 0xFFFF);
1122 BuildMI(*MBB, IP, PPC::XORIS, 2, LoTmp).addReg(LoLow)
1123 .addImm(LowCst >> 16);
1124 BuildMI(*MBB, IP, PPC::XORI, 2, HiLow).addReg(Op0r)
1125 .addImm(HiCst & 0xFFFF);
1126 BuildMI(*MBB, IP, PPC::XORIS, 2, HiTmp).addReg(HiLow)
1127 .addImm(HiCst >> 16);
1128 BuildMI(*MBB, IP, PPC::ORo, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
1131 unsigned ConstReg = makeAnotherReg(CompTy);
1132 copyConstantToRegister(MBB, IP, CI, ConstReg);
1134 // cr0 = r3 ccOpcode r5 or (r3 == r5 AND r4 ccOpcode r6)
1135 BuildMI(*MBB, IP, Opcode, 2, PPC::CR0).addReg(Op0r)
1137 BuildMI(*MBB, IP, Opcode, 2, PPC::CR1).addReg(Op0r+1)
1138 .addReg(ConstReg+1);
1139 BuildMI(*MBB, IP, PPC::CRAND, 3).addImm(2).addImm(2).addImm(CR1field);
1140 BuildMI(*MBB, IP, PPC::CROR, 3).addImm(CR0field).addImm(CR0field)
1147 unsigned Op1r = getReg(Op1, MBB, IP);
1150 default: assert(0 && "Unknown type class!");
1154 BuildMI(*MBB, IP, Opcode, 2, PPC::CR0).addReg(Op0r).addReg(Op1r);
1159 emitUCOM(MBB, IP, Op0r, Op1r);
1163 if (OpNum < 2) { // seteq, setne
1164 unsigned LoTmp = makeAnotherReg(Type::IntTy);
1165 unsigned HiTmp = makeAnotherReg(Type::IntTy);
1166 unsigned FinalTmp = makeAnotherReg(Type::IntTy);
1167 BuildMI(*MBB, IP, PPC::XOR, 2, HiTmp).addReg(Op0r).addReg(Op1r);
1168 BuildMI(*MBB, IP, PPC::XOR, 2, LoTmp).addReg(Op0r+1).addReg(Op1r+1);
1169 BuildMI(*MBB, IP, PPC::ORo, 2, FinalTmp).addReg(LoTmp).addReg(HiTmp);
1170 break; // Allow the sete or setne to be generated from flags set by OR
1172 unsigned TmpReg1 = makeAnotherReg(Type::IntTy);
1173 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
1175 // cr0 = r3 ccOpcode r5 or (r3 == r5 AND r4 ccOpcode r6)
1176 BuildMI(*MBB, IP, Opcode, 2, PPC::CR0).addReg(Op0r).addReg(Op1r);
1177 BuildMI(*MBB, IP, Opcode, 2, PPC::CR1).addReg(Op0r+1).addReg(Op1r+1);
1178 BuildMI(*MBB, IP, PPC::CRAND, 3).addImm(2).addImm(2).addImm(CR1field);
1179 BuildMI(*MBB, IP, PPC::CROR, 3).addImm(CR0field).addImm(CR0field)
1187 /// visitSetCondInst - emit code to calculate the condition via
1188 /// EmitComparison(), and possibly store a 0 or 1 to a register as a result
1190 void PPC32ISel::visitSetCondInst(SetCondInst &I) {
1191 if (canFoldSetCCIntoBranchOrSelect(&I))
1194 MachineBasicBlock::iterator MI = BB->end();
1195 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1196 const Type *Ty = Op0->getType();
1197 unsigned Class = getClassB(Ty);
1198 unsigned Opcode = I.getOpcode();
1199 unsigned OpNum = getSetCCNumber(Opcode);
1200 unsigned DestReg = getReg(I);
1202 // If the comparison type is byte, short, or int, then we can emit a
1203 // branchless version of the SetCC that puts 0 (false) or 1 (true) in the
1204 // destination register.
1205 if (Class <= cInt) {
1206 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
1208 if (CI && CI->getRawValue() == 0) {
1209 unsigned Op0Reg = ExtendOrClear(BB, MI, Op0);
1211 // comparisons against constant zero and negative one often have shorter
1212 // and/or faster sequences than the set-and-branch general case, handled
1216 unsigned TempReg = makeAnotherReg(Type::IntTy);
1217 BuildMI(*BB, MI, PPC::CNTLZW, 1, TempReg).addReg(Op0Reg);
1218 BuildMI(*BB, MI, PPC::RLWINM, 4, DestReg).addReg(TempReg).addImm(27)
1219 .addImm(5).addImm(31);
1223 unsigned TempReg = makeAnotherReg(Type::IntTy);
1224 BuildMI(*BB, MI, PPC::ADDIC, 2, TempReg).addReg(Op0Reg).addSImm(-1);
1225 BuildMI(*BB, MI, PPC::SUBFE, 2, DestReg).addReg(TempReg).addReg(Op0Reg);
1228 case 2: { // lt0, always false if unsigned
1230 BuildMI(*BB, MI, PPC::RLWINM, 4, DestReg).addReg(Op0Reg).addImm(1)
1231 .addImm(31).addImm(31);
1233 BuildMI(*BB, MI, PPC::LI, 1, DestReg).addSImm(0);
1236 case 3: { // ge0, always true if unsigned
1237 if (Ty->isSigned()) {
1238 unsigned TempReg = makeAnotherReg(Type::IntTy);
1239 BuildMI(*BB, MI, PPC::RLWINM, 4, TempReg).addReg(Op0Reg).addImm(1)
1240 .addImm(31).addImm(31);
1241 BuildMI(*BB, MI, PPC::XORI, 2, DestReg).addReg(TempReg).addImm(1);
1243 BuildMI(*BB, MI, PPC::LI, 1, DestReg).addSImm(1);
1247 case 4: { // gt0, equivalent to ne0 if unsigned
1248 unsigned Temp1 = makeAnotherReg(Type::IntTy);
1249 unsigned Temp2 = makeAnotherReg(Type::IntTy);
1250 if (Ty->isSigned()) {
1251 BuildMI(*BB, MI, PPC::NEG, 2, Temp1).addReg(Op0Reg);
1252 BuildMI(*BB, MI, PPC::ANDC, 2, Temp2).addReg(Temp1).addReg(Op0Reg);
1253 BuildMI(*BB, MI, PPC::RLWINM, 4, DestReg).addReg(Temp2).addImm(1)
1254 .addImm(31).addImm(31);
1256 BuildMI(*BB, MI, PPC::ADDIC, 2, Temp1).addReg(Op0Reg).addSImm(-1);
1257 BuildMI(*BB, MI, PPC::SUBFE, 2, DestReg).addReg(Temp1).addReg(Op0Reg);
1261 case 5: { // le0, equivalent to eq0 if unsigned
1262 unsigned Temp1 = makeAnotherReg(Type::IntTy);
1263 unsigned Temp2 = makeAnotherReg(Type::IntTy);
1264 if (Ty->isSigned()) {
1265 BuildMI(*BB, MI, PPC::NEG, 2, Temp1).addReg(Op0Reg);
1266 BuildMI(*BB, MI, PPC::ORC, 2, Temp2).addReg(Op0Reg).addReg(Temp1);
1267 BuildMI(*BB, MI, PPC::RLWINM, 4, DestReg).addReg(Temp2).addImm(1)
1268 .addImm(31).addImm(31);
1270 BuildMI(*BB, MI, PPC::CNTLZW, 1, Temp1).addReg(Op0Reg);
1271 BuildMI(*BB, MI, PPC::RLWINM, 4, DestReg).addReg(Temp1).addImm(27)
1272 .addImm(5).addImm(31);
1280 unsigned PPCOpcode = getPPCOpcodeForSetCCNumber(Opcode);
1282 // Create an iterator with which to insert the MBB for copying the false value
1283 // and the MBB to hold the PHI instruction for this SetCC.
1284 MachineBasicBlock *thisMBB = BB;
1285 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1286 ilist<MachineBasicBlock>::iterator It = BB;
1291 // cmpTY cr0, r1, r2
1292 // %TrueValue = li 1
1294 EmitComparison(Opcode, Op0, Op1, BB, BB->end());
1295 unsigned TrueValue = makeAnotherReg(I.getType());
1296 BuildMI(BB, PPC::LI, 1, TrueValue).addSImm(1);
1297 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
1298 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
1299 BuildMI(BB, PPCOpcode, 2).addReg(PPC::CR0).addMBB(sinkMBB);
1300 F->getBasicBlockList().insert(It, copy0MBB);
1301 F->getBasicBlockList().insert(It, sinkMBB);
1302 // Update machine-CFG edges
1303 BB->addSuccessor(copy0MBB);
1304 BB->addSuccessor(sinkMBB);
1307 // %FalseValue = li 0
1310 unsigned FalseValue = makeAnotherReg(I.getType());
1311 BuildMI(BB, PPC::LI, 1, FalseValue).addSImm(0);
1312 // Update machine-CFG edges
1313 BB->addSuccessor(sinkMBB);
1316 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1319 BuildMI(BB, PPC::PHI, 4, DestReg).addReg(FalseValue)
1320 .addMBB(copy0MBB).addReg(TrueValue).addMBB(thisMBB);
1323 void PPC32ISel::visitSelectInst(SelectInst &SI) {
1324 unsigned DestReg = getReg(SI);
1325 MachineBasicBlock::iterator MII = BB->end();
1326 emitSelectOperation(BB, MII, SI.getCondition(), SI.getTrueValue(),
1327 SI.getFalseValue(), DestReg);
1330 /// emitSelect - Common code shared between visitSelectInst and the constant
1331 /// expression support.
1332 void PPC32ISel::emitSelectOperation(MachineBasicBlock *MBB,
1333 MachineBasicBlock::iterator IP,
1334 Value *Cond, Value *TrueVal,
1335 Value *FalseVal, unsigned DestReg) {
1336 unsigned SelectClass = getClassB(TrueVal->getType());
1339 // See if we can fold the setcc into the select instruction, or if we have
1340 // to get the register of the Cond value
1341 if (SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(Cond)) {
1342 // We successfully folded the setcc into the select instruction.
1343 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1344 if (OpNum >= 2 && OpNum <= 5) {
1345 unsigned SetCondClass = getClassB(SCI->getOperand(0)->getType());
1346 if ((SetCondClass == cFP32 || SetCondClass == cFP64) &&
1347 (SelectClass == cFP32 || SelectClass == cFP64)) {
1348 unsigned CondReg = getReg(SCI->getOperand(0), MBB, IP);
1349 unsigned TrueReg = getReg(TrueVal, MBB, IP);
1350 unsigned FalseReg = getReg(FalseVal, MBB, IP);
1351 // if the comparison of the floating point value used to for the select
1352 // is against 0, then we can emit an fsel without subtraction.
1353 ConstantFP *Op1C = dyn_cast<ConstantFP>(SCI->getOperand(1));
1354 if (Op1C && (Op1C->isExactlyValue(-0.0) || Op1C->isExactlyValue(0.0))) {
1357 BuildMI(*MBB, IP, PPC::FSEL, 3, DestReg).addReg(CondReg)
1358 .addReg(FalseReg).addReg(TrueReg);
1360 case 3: // GE == !LT
1361 BuildMI(*MBB, IP, PPC::FSEL, 3, DestReg).addReg(CondReg)
1362 .addReg(TrueReg).addReg(FalseReg);
1365 unsigned NegatedReg = makeAnotherReg(SCI->getOperand(0)->getType());
1366 BuildMI(*MBB, IP, PPC::FNEG, 1, NegatedReg).addReg(CondReg);
1367 BuildMI(*MBB, IP, PPC::FSEL, 3, DestReg).addReg(NegatedReg)
1368 .addReg(FalseReg).addReg(TrueReg);
1371 case 5: { // LE == !GT
1372 unsigned NegatedReg = makeAnotherReg(SCI->getOperand(0)->getType());
1373 BuildMI(*MBB, IP, PPC::FNEG, 1, NegatedReg).addReg(CondReg);
1374 BuildMI(*MBB, IP, PPC::FSEL, 3, DestReg).addReg(NegatedReg)
1375 .addReg(TrueReg).addReg(FalseReg);
1379 assert(0 && "Invalid SetCC opcode to fsel");
1384 unsigned OtherCondReg = getReg(SCI->getOperand(1), MBB, IP);
1385 unsigned SelectReg = makeAnotherReg(SCI->getOperand(0)->getType());
1388 BuildMI(*MBB, IP, PPC::FSUB, 2, SelectReg).addReg(CondReg)
1389 .addReg(OtherCondReg);
1390 BuildMI(*MBB, IP, PPC::FSEL, 3, DestReg).addReg(SelectReg)
1391 .addReg(FalseReg).addReg(TrueReg);
1393 case 3: // GE == !LT
1394 BuildMI(*MBB, IP, PPC::FSUB, 2, SelectReg).addReg(CondReg)
1395 .addReg(OtherCondReg);
1396 BuildMI(*MBB, IP, PPC::FSEL, 3, DestReg).addReg(SelectReg)
1397 .addReg(TrueReg).addReg(FalseReg);
1400 BuildMI(*MBB, IP, PPC::FSUB, 2, SelectReg).addReg(OtherCondReg)
1402 BuildMI(*MBB, IP, PPC::FSEL, 3, DestReg).addReg(SelectReg)
1403 .addReg(FalseReg).addReg(TrueReg);
1405 case 5: // LE == !GT
1406 BuildMI(*MBB, IP, PPC::FSUB, 2, SelectReg).addReg(OtherCondReg)
1408 BuildMI(*MBB, IP, PPC::FSEL, 3, DestReg).addReg(SelectReg)
1409 .addReg(TrueReg).addReg(FalseReg);
1412 assert(0 && "Invalid SetCC opcode to fsel");
1420 OpNum = EmitComparison(OpNum, SCI->getOperand(0),SCI->getOperand(1),MBB,IP);
1421 Opcode = getPPCOpcodeForSetCCNumber(SCI->getOpcode());
1423 unsigned CondReg = getReg(Cond, MBB, IP);
1424 BuildMI(*MBB, IP, PPC::CMPWI, 2, PPC::CR0).addReg(CondReg).addSImm(0);
1425 Opcode = getPPCOpcodeForSetCCNumber(Instruction::SetNE);
1428 MachineBasicBlock *thisMBB = BB;
1429 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1430 ilist<MachineBasicBlock>::iterator It = BB;
1435 // cmpTY cr0, r1, r2
1437 // fallthrough --> copy0MBB
1438 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
1439 MachineBasicBlock *copy1MBB = new MachineBasicBlock(LLVM_BB);
1440 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
1441 BuildMI(BB, Opcode, 2).addReg(PPC::CR0).addMBB(copy1MBB);
1442 F->getBasicBlockList().insert(It, copy0MBB);
1443 F->getBasicBlockList().insert(It, copy1MBB);
1444 F->getBasicBlockList().insert(It, sinkMBB);
1445 // Update machine-CFG edges
1446 BB->addSuccessor(copy0MBB);
1447 BB->addSuccessor(copy1MBB);
1450 // %FalseValue = ...
1453 unsigned FalseValue = getReg(FalseVal, BB, BB->begin());
1454 BuildMI(BB, PPC::B, 1).addMBB(sinkMBB);
1455 // Update machine-CFG edges
1456 BB->addSuccessor(sinkMBB);
1462 unsigned TrueValue = getReg(TrueVal, BB, BB->begin());
1463 // Update machine-CFG edges
1464 BB->addSuccessor(sinkMBB);
1467 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1470 BuildMI(BB, PPC::PHI, 4, DestReg).addReg(FalseValue)
1471 .addMBB(copy0MBB).addReg(TrueValue).addMBB(copy1MBB);
1473 // For a register pair representing a long value, define the second reg
1474 // FIXME: Can this really be correct for selecting longs?
1475 if (getClassB(TrueVal->getType()) == cLong)
1476 BuildMI(BB, PPC::LI, 1, DestReg+1).addImm(0);
1482 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
1483 /// operand, in the specified target register.
1485 void PPC32ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
1486 bool isUnsigned = VR.Ty->isUnsigned() || VR.Ty == Type::BoolTy;
1488 Value *Val = VR.Val;
1489 const Type *Ty = VR.Ty;
1491 if (Constant *C = dyn_cast<Constant>(Val)) {
1492 Val = ConstantExpr::getCast(C, Type::IntTy);
1493 if (isa<ConstantExpr>(Val)) // Could not fold
1496 Ty = Type::IntTy; // Folded!
1499 // If this is a simple constant, just emit a load directly to avoid the copy
1500 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
1501 copyConstantToRegister(BB, BB->end(), CI, targetReg);
1506 // Make sure we have the register number for this value...
1507 unsigned Reg = Val ? getReg(Val) : VR.Reg;
1508 switch (getClassB(Ty)) {
1510 // Extend value into target register (8->32)
1511 if (Ty == Type::BoolTy)
1512 BuildMI(BB, PPC::OR, 2, targetReg).addReg(Reg).addReg(Reg);
1513 else if (isUnsigned)
1514 BuildMI(BB, PPC::RLWINM, 4, targetReg).addReg(Reg).addZImm(0)
1515 .addZImm(24).addZImm(31);
1517 BuildMI(BB, PPC::EXTSB, 1, targetReg).addReg(Reg);
1520 // Extend value into target register (16->32)
1522 BuildMI(BB, PPC::RLWINM, 4, targetReg).addReg(Reg).addZImm(0)
1523 .addZImm(16).addZImm(31);
1525 BuildMI(BB, PPC::EXTSH, 1, targetReg).addReg(Reg);
1528 // Move value into target register (32->32)
1529 BuildMI(BB, PPC::OR, 2, targetReg).addReg(Reg).addReg(Reg);
1532 assert(0 && "Unpromotable operand class in promote32");
1536 /// visitReturnInst - implemented with BLR
1538 void PPC32ISel::visitReturnInst(ReturnInst &I) {
1539 // Only do the processing if this is a non-void return
1540 if (I.getNumOperands() > 0) {
1541 Value *RetVal = I.getOperand(0);
1542 switch (getClassB(RetVal->getType())) {
1543 case cByte: // integral return values: extend or move into r3 and return
1546 promote32(PPC::R3, ValueRecord(RetVal));
1549 case cFP64: { // Floats & Doubles: Return in f1
1550 unsigned RetReg = getReg(RetVal);
1551 BuildMI(BB, PPC::FMR, 1, PPC::F1).addReg(RetReg);
1555 unsigned RetReg = getReg(RetVal);
1556 BuildMI(BB, PPC::OR, 2, PPC::R3).addReg(RetReg).addReg(RetReg);
1557 BuildMI(BB, PPC::OR, 2, PPC::R4).addReg(RetReg+1).addReg(RetReg+1);
1561 visitInstruction(I);
1564 BuildMI(BB, PPC::BLR, 1).addImm(0);
1567 // getBlockAfter - Return the basic block which occurs lexically after the
1569 static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
1570 Function::iterator I = BB; ++I; // Get iterator to next block
1571 return I != BB->getParent()->end() ? &*I : 0;
1574 /// visitBranchInst - Handle conditional and unconditional branches here. Note
1575 /// that since code layout is frozen at this point, that if we are trying to
1576 /// jump to a block that is the immediate successor of the current block, we can
1577 /// just make a fall-through (but we don't currently).
1579 void PPC32ISel::visitBranchInst(BranchInst &BI) {
1580 // Update machine-CFG edges
1581 BB->addSuccessor(MBBMap[BI.getSuccessor(0)]);
1582 if (BI.isConditional())
1583 BB->addSuccessor(MBBMap[BI.getSuccessor(1)]);
1585 BasicBlock *NextBB = getBlockAfter(BI.getParent()); // BB after current one
1587 if (!BI.isConditional()) { // Unconditional branch?
1588 if (BI.getSuccessor(0) != NextBB)
1589 BuildMI(BB, PPC::B, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1593 // See if we can fold the setcc into the branch itself...
1594 SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(BI.getCondition());
1596 // Nope, cannot fold setcc into this branch. Emit a branch on a condition
1597 // computed some other way...
1598 unsigned condReg = getReg(BI.getCondition());
1599 BuildMI(BB, PPC::CMPLI, 3, PPC::CR0).addImm(0).addReg(condReg)
1601 if (BI.getSuccessor(1) == NextBB) {
1602 if (BI.getSuccessor(0) != NextBB)
1603 BuildMI(BB, PPC::COND_BRANCH, 3).addReg(PPC::CR0).addImm(PPC::BNE)
1604 .addMBB(MBBMap[BI.getSuccessor(0)])
1605 .addMBB(MBBMap[BI.getSuccessor(1)]);
1607 BuildMI(BB, PPC::COND_BRANCH, 3).addReg(PPC::CR0).addImm(PPC::BEQ)
1608 .addMBB(MBBMap[BI.getSuccessor(1)])
1609 .addMBB(MBBMap[BI.getSuccessor(0)]);
1610 if (BI.getSuccessor(0) != NextBB)
1611 BuildMI(BB, PPC::B, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
1616 unsigned OpNum = getSetCCNumber(SCI->getOpcode());
1617 unsigned Opcode = getPPCOpcodeForSetCCNumber(SCI->getOpcode());
1618 MachineBasicBlock::iterator MII = BB->end();
1619 OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), BB,MII);
1621 if (BI.getSuccessor(0) != NextBB) {
1622 BuildMI(BB, PPC::COND_BRANCH, 3).addReg(PPC::CR0).addImm(Opcode)
1623 .addMBB(MBBMap[BI.getSuccessor(0)])
1624 .addMBB(MBBMap[BI.getSuccessor(1)]);
1625 if (BI.getSuccessor(1) != NextBB)
1626 BuildMI(BB, PPC::B, 1).addMBB(MBBMap[BI.getSuccessor(1)]);
1628 // Change to the inverse condition...
1629 if (BI.getSuccessor(1) != NextBB) {
1630 Opcode = PPC32InstrInfo::invertPPCBranchOpcode(Opcode);
1631 BuildMI(BB, PPC::COND_BRANCH, 3).addReg(PPC::CR0).addImm(Opcode)
1632 .addMBB(MBBMap[BI.getSuccessor(1)])
1633 .addMBB(MBBMap[BI.getSuccessor(0)]);
1638 /// doCall - This emits an abstract call instruction, setting up the arguments
1639 /// and the return value as appropriate. For the actual function call itself,
1640 /// it inserts the specified CallMI instruction into the stream.
1642 /// FIXME: See Documentation at the following URL for "correct" behavior
1643 /// <http://developer.apple.com/documentation/DeveloperTools/Conceptual/MachORuntime/2rt_powerpc_abi/chapter_9_section_5.html>
1644 void PPC32ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
1645 const std::vector<ValueRecord> &Args, bool isVarArg) {
1646 // Count how many bytes are to be pushed on the stack, including the linkage
1647 // area, and parameter passing area.
1648 unsigned NumBytes = 24;
1649 unsigned ArgOffset = 24;
1651 if (!Args.empty()) {
1652 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1653 switch (getClassB(Args[i].Ty)) {
1654 case cByte: case cShort: case cInt:
1655 NumBytes += 4; break;
1657 NumBytes += 8; break;
1659 NumBytes += 4; break;
1661 NumBytes += 8; break;
1663 default: assert(0 && "Unknown class!");
1666 // Just to be safe, we'll always reserve the full 24 bytes of linkage area
1667 // plus 32 bytes of argument space in case any called code gets funky on us.
1668 if (NumBytes < 56) NumBytes = 56;
1670 // Adjust the stack pointer for the new arguments...
1671 // These functions are automatically eliminated by the prolog/epilog pass
1672 BuildMI(BB, PPC::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
1674 // Arguments go on the stack in reverse order, as specified by the ABI.
1675 // Offset to the paramater area on the stack is 24.
1676 int GPR_remaining = 8, FPR_remaining = 13;
1677 unsigned GPR_idx = 0, FPR_idx = 0;
1678 static const unsigned GPR[] = {
1679 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1680 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1682 static const unsigned FPR[] = {
1683 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6,
1684 PPC::F7, PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12,
1688 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1690 switch (getClassB(Args[i].Ty)) {
1693 // Promote arg to 32 bits wide into a temporary register...
1694 ArgReg = makeAnotherReg(Type::UIntTy);
1695 promote32(ArgReg, Args[i]);
1698 if (GPR_remaining > 0) {
1699 BuildMI(BB, PPC::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1701 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1703 if (GPR_remaining <= 0 || isVarArg) {
1704 BuildMI(BB, PPC::STW, 3).addReg(ArgReg).addSImm(ArgOffset)
1709 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1712 if (GPR_remaining > 0) {
1713 BuildMI(BB, PPC::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1715 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1717 if (GPR_remaining <= 0 || isVarArg) {
1718 BuildMI(BB, PPC::STW, 3).addReg(ArgReg).addSImm(ArgOffset)
1723 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1725 // Reg or stack? Note that PPC calling conventions state that long args
1726 // are passed rN = hi, rN+1 = lo, opposite of LLVM.
1727 if (GPR_remaining > 1) {
1728 BuildMI(BB, PPC::OR, 2, GPR[GPR_idx]).addReg(ArgReg)
1730 BuildMI(BB, PPC::OR, 2, GPR[GPR_idx+1]).addReg(ArgReg+1)
1732 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1733 CallMI->addRegOperand(GPR[GPR_idx+1], MachineOperand::Use);
1735 if (GPR_remaining <= 1 || isVarArg) {
1736 BuildMI(BB, PPC::STW, 3).addReg(ArgReg).addSImm(ArgOffset)
1738 BuildMI(BB, PPC::STW, 3).addReg(ArgReg+1).addSImm(ArgOffset+4)
1742 ArgOffset += 4; // 8 byte entry, not 4.
1743 GPR_remaining -= 1; // uses up 2 GPRs
1747 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1749 if (FPR_remaining > 0) {
1750 BuildMI(BB, PPC::FMR, 1, FPR[FPR_idx]).addReg(ArgReg);
1751 CallMI->addRegOperand(FPR[FPR_idx], MachineOperand::Use);
1755 // If this is a vararg function, and there are GPRs left, also
1756 // pass the float in an int. Otherwise, put it on the stack.
1758 BuildMI(BB, PPC::STFS, 3).addReg(ArgReg).addSImm(ArgOffset)
1760 if (GPR_remaining > 0) {
1761 BuildMI(BB, PPC::LWZ, 2, GPR[GPR_idx])
1762 .addSImm(ArgOffset).addReg(PPC::R1);
1763 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1767 BuildMI(BB, PPC::STFS, 3).addReg(ArgReg).addSImm(ArgOffset)
1772 ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
1774 if (FPR_remaining > 0) {
1775 BuildMI(BB, PPC::FMR, 1, FPR[FPR_idx]).addReg(ArgReg);
1776 CallMI->addRegOperand(FPR[FPR_idx], MachineOperand::Use);
1779 // For vararg functions, must pass doubles via int regs as well
1781 BuildMI(BB, PPC::STFD, 3).addReg(ArgReg).addSImm(ArgOffset)
1784 // Doubles can be split across reg + stack for varargs
1785 if (GPR_remaining > 0) {
1786 BuildMI(BB, PPC::LWZ, 2, GPR[GPR_idx]).addSImm(ArgOffset)
1788 CallMI->addRegOperand(GPR[GPR_idx], MachineOperand::Use);
1790 if (GPR_remaining > 1) {
1791 BuildMI(BB, PPC::LWZ, 2, GPR[GPR_idx+1])
1792 .addSImm(ArgOffset+4).addReg(PPC::R1);
1793 CallMI->addRegOperand(GPR[GPR_idx+1], MachineOperand::Use);
1797 BuildMI(BB, PPC::STFD, 3).addReg(ArgReg).addSImm(ArgOffset)
1800 // Doubles use 8 bytes, and 2 GPRs worth of param space
1806 default: assert(0 && "Unknown class!");
1813 BuildMI(BB, PPC::ADJCALLSTACKDOWN, 1).addImm(NumBytes);
1816 BuildMI(BB, PPC::IMPLICIT_DEF, 0, PPC::LR);
1817 BB->push_back(CallMI);
1819 // These functions are automatically eliminated by the prolog/epilog pass
1820 BuildMI(BB, PPC::ADJCALLSTACKUP, 1).addImm(NumBytes);
1822 // If there is a return value, scavenge the result from the location the call
1825 if (Ret.Ty != Type::VoidTy) {
1826 unsigned DestClass = getClassB(Ret.Ty);
1827 switch (DestClass) {
1831 // Integral results are in r3
1832 BuildMI(BB, PPC::OR, 2, Ret.Reg).addReg(PPC::R3).addReg(PPC::R3);
1834 case cFP32: // Floating-point return values live in f1
1836 BuildMI(BB, PPC::FMR, 1, Ret.Reg).addReg(PPC::F1);
1838 case cLong: // Long values are in r3:r4
1839 BuildMI(BB, PPC::OR, 2, Ret.Reg).addReg(PPC::R3).addReg(PPC::R3);
1840 BuildMI(BB, PPC::OR, 2, Ret.Reg+1).addReg(PPC::R4).addReg(PPC::R4);
1842 default: assert(0 && "Unknown class!");
1848 /// visitCallInst - Push args on stack and do a procedure call instruction.
1849 void PPC32ISel::visitCallInst(CallInst &CI) {
1850 MachineInstr *TheCall;
1851 Function *F = CI.getCalledFunction();
1853 // Is it an intrinsic function call?
1854 if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1855 visitIntrinsicCall(ID, CI); // Special intrinsics are not handled here
1858 // Emit a CALL instruction with PC-relative displacement.
1859 TheCall = BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(F, true);
1860 // Add it to the set of functions called to be used by the Printer
1861 TM.CalledFunctions.insert(F);
1862 } else { // Emit an indirect call through the CTR
1863 unsigned Reg = getReg(CI.getCalledValue());
1864 BuildMI(BB, PPC::OR, 2, PPC::R12).addReg(Reg).addReg(Reg);
1865 BuildMI(BB, PPC::MTCTR, 1).addReg(PPC::R12);
1866 TheCall = BuildMI(PPC::CALLindirect, 2).addZImm(20).addZImm(0)
1870 std::vector<ValueRecord> Args;
1871 for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
1872 Args.push_back(ValueRecord(CI.getOperand(i)));
1874 unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
1875 bool isVarArg = F ? F->getFunctionType()->isVarArg() : true;
1876 doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args, isVarArg);
1880 /// dyncastIsNan - Return the operand of an isnan operation if this is an isnan.
1882 static Value *dyncastIsNan(Value *V) {
1883 if (CallInst *CI = dyn_cast<CallInst>(V))
1884 if (Function *F = CI->getCalledFunction())
1885 if (F->getIntrinsicID() == Intrinsic::isunordered)
1886 return CI->getOperand(1);
1890 /// isOnlyUsedByUnorderedComparisons - Return true if this value is only used by
1891 /// or's whos operands are all calls to the isnan predicate.
1892 static bool isOnlyUsedByUnorderedComparisons(Value *V) {
1893 assert(dyncastIsNan(V) && "The value isn't an isnan call!");
1895 // Check all uses, which will be or's of isnans if this predicate is true.
1896 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1897 Instruction *I = cast<Instruction>(*UI);
1898 if (I->getOpcode() != Instruction::Or) return false;
1899 if (I->getOperand(0) != V && !dyncastIsNan(I->getOperand(0))) return false;
1900 if (I->getOperand(1) != V && !dyncastIsNan(I->getOperand(1))) return false;
1906 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
1907 /// function, lowering any calls to unknown intrinsic functions into the
1908 /// equivalent LLVM code.
1910 void PPC32ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
1911 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1912 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1913 if (CallInst *CI = dyn_cast<CallInst>(I++))
1914 if (Function *F = CI->getCalledFunction())
1915 switch (F->getIntrinsicID()) {
1916 case Intrinsic::not_intrinsic:
1917 case Intrinsic::vastart:
1918 case Intrinsic::vacopy:
1919 case Intrinsic::vaend:
1920 case Intrinsic::returnaddress:
1921 case Intrinsic::frameaddress:
1922 // FIXME: should lower these ourselves
1923 // case Intrinsic::isunordered:
1924 // case Intrinsic::memcpy: -> doCall(). system memcpy almost
1925 // guaranteed to be faster than anything we generate ourselves
1926 // We directly implement these intrinsics
1928 case Intrinsic::readio: {
1929 // On PPC, memory operations are in-order. Lower this intrinsic
1930 // into a volatile load.
1931 Instruction *Before = CI->getPrev();
1932 LoadInst * LI = new LoadInst(CI->getOperand(1), "", true, CI);
1933 CI->replaceAllUsesWith(LI);
1934 BB->getInstList().erase(CI);
1937 case Intrinsic::writeio: {
1938 // On PPC, memory operations are in-order. Lower this intrinsic
1939 // into a volatile store.
1940 Instruction *Before = CI->getPrev();
1941 StoreInst *SI = new StoreInst(CI->getOperand(1),
1942 CI->getOperand(2), true, CI);
1943 CI->replaceAllUsesWith(SI);
1944 BB->getInstList().erase(CI);
1948 // All other intrinsic calls we must lower.
1949 Instruction *Before = CI->getPrev();
1950 TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
1951 if (Before) { // Move iterator to instruction after call
1959 void PPC32ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
1960 unsigned TmpReg1, TmpReg2, TmpReg3;
1962 case Intrinsic::vastart:
1963 // Get the address of the first vararg value...
1964 TmpReg1 = getReg(CI);
1965 addFrameReference(BuildMI(BB, PPC::ADDI, 2, TmpReg1), VarArgsFrameIndex,
1969 case Intrinsic::vacopy:
1970 TmpReg1 = getReg(CI);
1971 TmpReg2 = getReg(CI.getOperand(1));
1972 BuildMI(BB, PPC::OR, 2, TmpReg1).addReg(TmpReg2).addReg(TmpReg2);
1974 case Intrinsic::vaend: return;
1976 case Intrinsic::returnaddress:
1977 TmpReg1 = getReg(CI);
1978 if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1979 MachineFrameInfo *MFI = F->getFrameInfo();
1980 unsigned NumBytes = MFI->getStackSize();
1982 BuildMI(BB, PPC::LWZ, 2, TmpReg1).addSImm(NumBytes+8)
1985 // Values other than zero are not implemented yet.
1986 BuildMI(BB, PPC::LI, 1, TmpReg1).addSImm(0);
1990 case Intrinsic::frameaddress:
1991 TmpReg1 = getReg(CI);
1992 if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
1993 BuildMI(BB, PPC::OR, 2, TmpReg1).addReg(PPC::R1).addReg(PPC::R1);
1995 // Values other than zero are not implemented yet.
1996 BuildMI(BB, PPC::LI, 1, TmpReg1).addSImm(0);
2001 // This may be useful for supporting isunordered
2002 case Intrinsic::isnan:
2003 // If this is only used by 'isunordered' style comparisons, don't emit it.
2004 if (isOnlyUsedByUnorderedComparisons(&CI)) return;
2005 TmpReg1 = getReg(CI.getOperand(1));
2006 emitUCOM(BB, BB->end(), TmpReg1, TmpReg1);
2007 TmpReg2 = makeAnotherReg(Type::IntTy);
2008 BuildMI(BB, PPC::MFCR, TmpReg2);
2009 TmpReg3 = getReg(CI);
2010 BuildMI(BB, PPC::RLWINM, 4, TmpReg3).addReg(TmpReg2).addImm(4).addImm(31).addImm(31);
2014 default: assert(0 && "Error: unknown intrinsics should have been lowered!");
2018 /// visitSimpleBinary - Implement simple binary operators for integral types...
2019 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
2022 void PPC32ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
2023 if (std::find(SkipList.begin(), SkipList.end(), &B) != SkipList.end())
2026 unsigned DestReg = getReg(B);
2027 MachineBasicBlock::iterator MI = BB->end();
2028 RlwimiRec RR = InsertMap[&B];
2029 if (RR.Target != 0) {
2030 unsigned TargetReg = getReg(RR.Target, BB, MI);
2031 unsigned InsertReg = getReg(RR.Insert, BB, MI);
2032 BuildMI(*BB, MI, PPC::RLWIMI, 5, DestReg).addReg(TargetReg)
2033 .addReg(InsertReg).addImm(RR.Shift).addImm(RR.MB).addImm(RR.ME);
2037 unsigned Class = getClassB(B.getType());
2038 Value *Op0 = B.getOperand(0), *Op1 = B.getOperand(1);
2039 emitSimpleBinaryOperation(BB, MI, &B, Op0, Op1, OperatorClass, DestReg);
2042 /// emitBinaryFPOperation - This method handles emission of floating point
2043 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
2044 void PPC32ISel::emitBinaryFPOperation(MachineBasicBlock *BB,
2045 MachineBasicBlock::iterator IP,
2046 Value *Op0, Value *Op1,
2047 unsigned OperatorClass, unsigned DestReg){
2049 static const unsigned OpcodeTab[][4] = {
2050 { PPC::FADDS, PPC::FSUBS, PPC::FMULS, PPC::FDIVS }, // Float
2051 { PPC::FADD, PPC::FSUB, PPC::FMUL, PPC::FDIV }, // Double
2054 // Special case: R1 = op <const fp>, R2
2055 if (ConstantFP *Op0C = dyn_cast<ConstantFP>(Op0))
2056 if (Op0C->isExactlyValue(-0.0) && OperatorClass == 1) {
2058 unsigned op1Reg = getReg(Op1, BB, IP);
2059 BuildMI(*BB, IP, PPC::FNEG, 1, DestReg).addReg(op1Reg);
2063 unsigned Opcode = OpcodeTab[Op0->getType() == Type::DoubleTy][OperatorClass];
2064 unsigned Op0r = getReg(Op0, BB, IP);
2065 unsigned Op1r = getReg(Op1, BB, IP);
2066 BuildMI(*BB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
2069 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N. It
2070 // returns zero when the input is not exactly a power of two.
2071 static unsigned ExactLog2(unsigned Val) {
2072 if (Val == 0 || (Val & (Val-1))) return 0;
2081 // isRunOfOnes - returns true if Val consists of one contiguous run of 1's with
2082 // any number of 0's on either side. the 1's are allowed to wrap from LSB to
2083 // MSB. so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2084 // not, since all 1's are not contiguous.
2085 static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
2090 // look for first set bit
2092 for (; i < 32; i++) {
2093 if ((Val & (1 << (31 - i))) != 0) {
2100 // look for last set bit
2101 for (; i < 32; i++) {
2102 if ((Val & (1 << (31 - i))) == 0)
2107 // look for next set bit
2108 for (; i < 32; i++) {
2109 if ((Val & (1 << (31 - i))) != 0)
2113 // if we exhausted all the bits, we found a match at this point for 0*1*0*
2117 // since we just encountered more 1's, if it doesn't wrap around to the
2118 // most significant bit of the word, then we did not find a match to 1*0*1* so
2123 // look for last set bit
2124 for (MB = i; i < 32; i++) {
2125 if ((Val & (1 << (31 - i))) == 0)
2129 // if we exhausted all the bits, then we found a match for 1*0*1*, otherwise,
2130 // the value is not a run of ones.
2136 /// isInsertAndHalf - Helper function for emitBitfieldInsert. Returns true if
2137 /// OpUser has one use, is used by an or instruction, and is itself an and whose
2138 /// second operand is a constant int. Optionally, set OrI to the Or instruction
2139 /// that is the sole user of OpUser, and Op1User to the other operand of the Or
2141 static bool isInsertAndHalf(User *OpUser, Instruction **Op1User,
2142 Instruction **OrI, unsigned &Mask) {
2143 // If this instruction doesn't have one use, then return false.
2144 if (!OpUser->hasOneUse())
2148 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(OpUser))
2149 if (BO->getOpcode() == Instruction::And) {
2150 Value *AndUse = *(OpUser->use_begin());
2151 if (BinaryOperator *Or = dyn_cast<BinaryOperator>(AndUse)) {
2152 if (Or->getOpcode() == Instruction::Or) {
2153 if (ConstantInt *CI = dyn_cast<ConstantInt>(OpUser->getOperand(1))) {
2156 if (Or->getOperand(0) == OpUser)
2157 *Op1User = dyn_cast<Instruction>(Or->getOperand(1));
2159 *Op1User = dyn_cast<Instruction>(Or->getOperand(0));
2161 Mask &= CI->getRawValue();
2170 /// isInsertShiftHalf - Helper function for emitBitfieldInsert. Returns true if
2171 /// OpUser has one use, is used by an or instruction, and is itself a shift
2172 /// instruction that is either used directly by the or instruction, or is used
2173 /// by an and instruction whose second operand is a constant int, and which is
2174 /// used by the or instruction.
2175 static bool isInsertShiftHalf(User *OpUser, Instruction **Op1User,
2176 Instruction **OrI, Instruction **OptAndI,
2177 unsigned &Shift, unsigned &Mask) {
2178 // If this instruction doesn't have one use, then return false.
2179 if (!OpUser->hasOneUse())
2183 if (ShiftInst *SI = dyn_cast<ShiftInst>(OpUser)) {
2184 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2185 Shift = CI->getRawValue();
2186 if (SI->getOpcode() == Instruction::Shl)
2188 else if (!SI->getOperand(0)->getType()->isSigned()) {
2193 // Now check to see if the shift instruction is used by an or.
2194 Value *ShiftUse = *(OpUser->use_begin());
2195 Value *OptAndICopy = 0;
2196 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ShiftUse)) {
2197 if (BO->getOpcode() == Instruction::And && BO->hasOneUse()) {
2198 if (ConstantInt *ACI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2199 if (OptAndI) *OptAndI = BO;
2201 Mask &= ACI->getRawValue();
2202 BO = dyn_cast<BinaryOperator>(*(BO->use_begin()));
2205 if (BO && BO->getOpcode() == Instruction::Or) {
2208 if (BO->getOperand(0) == OpUser || BO->getOperand(0) == OptAndICopy)
2209 *Op1User = dyn_cast<Instruction>(BO->getOperand(1));
2211 *Op1User = dyn_cast<Instruction>(BO->getOperand(0));
2221 /// emitBitfieldInsert - turn a shift used only by an and with immediate into
2222 /// the rotate left word immediate then mask insert (rlwimi) instruction.
2223 /// Patterns matched:
2224 /// 1. or shl, and 5. or (shl-and), and 9. or and, and
2225 /// 2. or and, shl 6. or and, (shl-and)
2226 /// 3. or shr, and 7. or (shr-and), and
2227 /// 4. or and, shr 8. or and, (shr-and)
2228 bool PPC32ISel::emitBitfieldInsert(User *OpUser, unsigned DestReg) {
2229 // Instructions to skip if we match any of the patterns
2230 Instruction *Op0User, *Op1User = 0, *OptAndI = 0, *OrI = 0;
2231 unsigned TgtMask, InsMask, Amount = 0;
2232 bool matched = false;
2234 // We require OpUser to be an instruction to continue
2235 Op0User = dyn_cast<Instruction>(OpUser);
2239 // Look for cases 2, 4, 6, 8, and 9
2240 if (isInsertAndHalf(Op0User, &Op1User, &OrI, TgtMask))
2242 if (isInsertAndHalf(Op1User, 0, 0, InsMask))
2244 else if (isInsertShiftHalf(Op1User, 0, 0, &OptAndI, Amount, InsMask))
2247 // Look for cases 1, 3, 5, and 7. Force the shift argument to be the one
2248 // inserted into the target, since rlwimi can only rotate the value inserted,
2249 // not the value being inserted into.
2250 if (matched == false)
2251 if (isInsertShiftHalf(Op0User, &Op1User, &OrI, &OptAndI, Amount, InsMask))
2252 if (Op1User && isInsertAndHalf(Op1User, 0, 0, TgtMask)) {
2253 std::swap(Op0User, Op1User);
2257 // We didn't succeed in matching one of the patterns, so return false
2258 if (matched == false)
2261 // If the masks xor to -1, and the insert mask is a run of ones, then we have
2262 // succeeded in matching one of the cases for generating rlwimi. Update the
2263 // skip lists and users of the Instruction::Or.
2265 if (((TgtMask ^ InsMask) == 0xFFFFFFFF) && isRunOfOnes(InsMask, MB, ME)) {
2266 SkipList.push_back(Op0User);
2267 SkipList.push_back(Op1User);
2268 SkipList.push_back(OptAndI);
2269 InsertMap[OrI] = RlwimiRec(Op0User->getOperand(0), Op1User->getOperand(0),
2276 /// emitBitfieldExtract - turn a shift used only by an and with immediate into the
2277 /// rotate left word immediate then and with mask (rlwinm) instruction.
2278 bool PPC32ISel::emitBitfieldExtract(MachineBasicBlock *MBB,
2279 MachineBasicBlock::iterator IP,
2280 User *OpUser, unsigned DestReg) {
2283 // Instructions to skip if we match any of the patterns
2284 Instruction *Op0User, *Op1User = 0;
2285 unsigned ShiftMask, AndMask, Amount = 0;
2286 bool matched = false;
2288 // We require OpUser to be an instruction to continue
2289 Op0User = dyn_cast<Instruction>(OpUser);
2293 if (isExtractShiftHalf)
2294 if (isExtractAndHalf)
2297 if (matched == false && isExtractAndHalf)
2298 if (isExtractShiftHalf)
2301 if (matched == false)
2304 if (isRunOfOnes(Imm, MB, ME)) {
2305 unsigned SrcReg = getReg(Op, MBB, IP);
2306 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg).addImm(Rotate)
2307 .addImm(MB).addImm(ME);
2308 Op1User->replaceAllUsesWith(Op0User);
2309 SkipList.push_back(BO);
2315 /// emitBinaryConstOperation - Implement simple binary operators for integral
2316 /// types with a constant operand. Opcode is one of: 0 for Add, 1 for Sub,
2317 /// 2 for And, 3 for Or, 4 for Xor, and 5 for Subtract-From.
2319 void PPC32ISel::emitBinaryConstOperation(MachineBasicBlock *MBB,
2320 MachineBasicBlock::iterator IP,
2321 unsigned Op0Reg, ConstantInt *Op1,
2322 unsigned Opcode, unsigned DestReg) {
2323 static const unsigned OpTab[] = {
2324 PPC::ADD, PPC::SUB, PPC::AND, PPC::OR, PPC::XOR, PPC::SUBF
2326 static const unsigned ImmOpTab[2][6] = {
2327 { PPC::ADDI, PPC::ADDI, PPC::ANDIo, PPC::ORI, PPC::XORI, PPC::SUBFIC },
2328 { PPC::ADDIS, PPC::ADDIS, PPC::ANDISo, PPC::ORIS, PPC::XORIS, PPC::SUBFIC }
2331 // Handle subtract now by inverting the constant value
2332 ConstantInt *CI = Op1;
2334 ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op1);
2335 CI = ConstantSInt::get(Op1->getType(), -CSI->getValue());
2338 // xor X, -1 -> not X
2340 ConstantInt *CI = dyn_cast<ConstantSInt>(Op1);
2341 if (CI && CI->isAllOnesValue()) {
2342 BuildMI(*MBB, IP, PPC::NOR, 2, DestReg).addReg(Op0Reg).addReg(Op0Reg);
2347 if (Opcode == 2 && !CI->isNullValue()) {
2348 unsigned MB, ME, mask = CI->getRawValue();
2349 if (isRunOfOnes(mask, MB, ME)) {
2350 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(Op0Reg).addImm(0)
2351 .addImm(MB).addImm(ME);
2356 // PowerPC 16 bit signed immediates are sign extended before use by the
2357 // instruction. Therefore, we can only split up an add of a reg with a 32 bit
2358 // immediate into addis and addi if the sign bit of the low 16 bits is cleared
2359 // so that for register A, const imm X, we don't end up with
2360 // A + XXXX0000 + FFFFXXXX.
2361 bool WontSignExtend = (0 == (Op1->getRawValue() & 0x8000));
2363 // For Add, Sub, and SubF the instruction takes a signed immediate. For And,
2364 // Or, and Xor, the instruction takes an unsigned immediate. There is no
2365 // shifted immediate form of SubF so disallow its opcode for those constants.
2366 if (canUseAsImmediateForOpcode(CI, Opcode, false)) {
2367 if (Opcode < 2 || Opcode == 5)
2368 BuildMI(*MBB, IP, ImmOpTab[0][Opcode], 2, DestReg).addReg(Op0Reg)
2369 .addSImm(Op1->getRawValue());
2371 BuildMI(*MBB, IP, ImmOpTab[0][Opcode], 2, DestReg).addReg(Op0Reg)
2372 .addZImm(Op1->getRawValue());
2373 } else if (canUseAsImmediateForOpcode(CI, Opcode, true) && (Opcode < 5)) {
2375 BuildMI(*MBB, IP, ImmOpTab[1][Opcode], 2, DestReg).addReg(Op0Reg)
2376 .addSImm(Op1->getRawValue() >> 16);
2378 BuildMI(*MBB, IP, ImmOpTab[1][Opcode], 2, DestReg).addReg(Op0Reg)
2379 .addZImm(Op1->getRawValue() >> 16);
2380 } else if ((Opcode < 2 && WontSignExtend) || Opcode == 3 || Opcode == 4) {
2381 unsigned TmpReg = makeAnotherReg(Op1->getType());
2383 BuildMI(*MBB, IP, ImmOpTab[1][Opcode], 2, TmpReg).addReg(Op0Reg)
2384 .addSImm(Op1->getRawValue() >> 16);
2385 BuildMI(*MBB, IP, ImmOpTab[0][Opcode], 2, DestReg).addReg(TmpReg)
2386 .addSImm(Op1->getRawValue());
2388 BuildMI(*MBB, IP, ImmOpTab[1][Opcode], 2, TmpReg).addReg(Op0Reg)
2389 .addZImm(Op1->getRawValue() >> 16);
2390 BuildMI(*MBB, IP, ImmOpTab[0][Opcode], 2, DestReg).addReg(TmpReg)
2391 .addZImm(Op1->getRawValue());
2394 unsigned Op1Reg = getReg(Op1, MBB, IP);
2395 BuildMI(*MBB, IP, OpTab[Opcode], 2, DestReg).addReg(Op0Reg).addReg(Op1Reg);
2399 /// emitSimpleBinaryOperation - Implement simple binary operators for integral
2400 /// types... OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for
2403 void PPC32ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
2404 MachineBasicBlock::iterator IP,
2406 Value *Op0, Value *Op1,
2407 unsigned OperatorClass,
2409 // Arithmetic and Bitwise operators
2410 static const unsigned OpcodeTab[] = {
2411 PPC::ADD, PPC::SUB, PPC::AND, PPC::OR, PPC::XOR
2413 static const unsigned LongOpTab[2][5] = {
2414 { PPC::ADDC, PPC::SUBC, PPC::AND, PPC::OR, PPC::XOR },
2415 { PPC::ADDE, PPC::SUBFE, PPC::AND, PPC::OR, PPC::XOR }
2418 unsigned Class = getClassB(Op0->getType());
2420 if (Class == cFP32 || Class == cFP64) {
2421 assert(OperatorClass < 2 && "No logical ops for FP!");
2422 emitBinaryFPOperation(MBB, IP, Op0, Op1, OperatorClass, DestReg);
2426 if (Op0->getType() == Type::BoolTy) {
2427 if (OperatorClass == 3)
2428 // If this is an or of two isnan's, emit an FP comparison directly instead
2429 // of or'ing two isnan's together.
2430 if (Value *LHS = dyncastIsNan(Op0))
2431 if (Value *RHS = dyncastIsNan(Op1)) {
2432 unsigned Op0Reg = getReg(RHS, MBB, IP), Op1Reg = getReg(LHS, MBB, IP);
2433 unsigned TmpReg = makeAnotherReg(Type::IntTy);
2434 emitUCOM(MBB, IP, Op0Reg, Op1Reg);
2435 BuildMI(*MBB, IP, PPC::MFCR, TmpReg);
2436 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(TmpReg).addImm(4)
2437 .addImm(31).addImm(31);
2442 // Special case: op <const int>, Reg
2443 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0))
2444 if (Class != cLong) {
2445 unsigned Opcode = (OperatorClass == 1) ? 5 : OperatorClass;
2446 unsigned Op1r = getReg(Op1, MBB, IP);
2447 emitBinaryConstOperation(MBB, IP, Op1r, CI, Opcode, DestReg);
2450 // Special case: op Reg, <const int>
2451 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
2452 if (Class != cLong) {
2453 if (emitBitfieldInsert(BO, DestReg))
2456 unsigned Op0r = getReg(Op0, MBB, IP);
2457 emitBinaryConstOperation(MBB, IP, Op0r, CI, OperatorClass, DestReg);
2461 // We couldn't generate an immediate variant of the op, load both halves into
2462 // registers and emit the appropriate opcode.
2463 unsigned Op0r = getReg(Op0, MBB, IP);
2464 unsigned Op1r = getReg(Op1, MBB, IP);
2466 if (Class != cLong) {
2467 unsigned Opcode = OpcodeTab[OperatorClass];
2468 BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
2470 BuildMI(*MBB, IP, LongOpTab[0][OperatorClass], 2, DestReg+1).addReg(Op0r+1)
2472 BuildMI(*MBB, IP, LongOpTab[1][OperatorClass], 2, DestReg).addReg(Op0r)
2478 /// doMultiply - Emit appropriate instructions to multiply together the
2479 /// Values Op0 and Op1, and put the result in DestReg.
2481 void PPC32ISel::doMultiply(MachineBasicBlock *MBB,
2482 MachineBasicBlock::iterator IP,
2483 unsigned DestReg, Value *Op0, Value *Op1) {
2484 unsigned Class0 = getClass(Op0->getType());
2485 unsigned Class1 = getClass(Op1->getType());
2487 unsigned Op0r = getReg(Op0, MBB, IP);
2488 unsigned Op1r = getReg(Op1, MBB, IP);
2491 if (Class0 == cLong && Class1 == cLong) {
2492 unsigned Tmp1 = makeAnotherReg(Type::IntTy);
2493 unsigned Tmp2 = makeAnotherReg(Type::IntTy);
2494 unsigned Tmp3 = makeAnotherReg(Type::IntTy);
2495 unsigned Tmp4 = makeAnotherReg(Type::IntTy);
2496 BuildMI(*MBB, IP, PPC::MULHWU, 2, Tmp1).addReg(Op0r+1).addReg(Op1r+1);
2497 BuildMI(*MBB, IP, PPC::MULLW, 2, DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
2498 BuildMI(*MBB, IP, PPC::MULLW, 2, Tmp2).addReg(Op0r+1).addReg(Op1r);
2499 BuildMI(*MBB, IP, PPC::ADD, 2, Tmp3).addReg(Tmp1).addReg(Tmp2);
2500 BuildMI(*MBB, IP, PPC::MULLW, 2, Tmp4).addReg(Op0r).addReg(Op1r+1);
2501 BuildMI(*MBB, IP, PPC::ADD, 2, DestReg).addReg(Tmp3).addReg(Tmp4);
2505 // 64 x 32 or less, promote 32 to 64 and do a 64 x 64
2506 if (Class0 == cLong && Class1 <= cInt) {
2507 unsigned Tmp0 = makeAnotherReg(Type::IntTy);
2508 unsigned Tmp1 = makeAnotherReg(Type::IntTy);
2509 unsigned Tmp2 = makeAnotherReg(Type::IntTy);
2510 unsigned Tmp3 = makeAnotherReg(Type::IntTy);
2511 unsigned Tmp4 = makeAnotherReg(Type::IntTy);
2512 if (Op1->getType()->isSigned())
2513 BuildMI(*MBB, IP, PPC::SRAWI, 2, Tmp0).addReg(Op1r).addImm(31);
2515 BuildMI(*MBB, IP, PPC::LI, 2, Tmp0).addSImm(0);
2516 BuildMI(*MBB, IP, PPC::MULHWU, 2, Tmp1).addReg(Op0r+1).addReg(Op1r);
2517 BuildMI(*MBB, IP, PPC::MULLW, 2, DestReg+1).addReg(Op0r+1).addReg(Op1r);
2518 BuildMI(*MBB, IP, PPC::MULLW, 2, Tmp2).addReg(Op0r+1).addReg(Tmp0);
2519 BuildMI(*MBB, IP, PPC::ADD, 2, Tmp3).addReg(Tmp1).addReg(Tmp2);
2520 BuildMI(*MBB, IP, PPC::MULLW, 2, Tmp4).addReg(Op0r).addReg(Op1r);
2521 BuildMI(*MBB, IP, PPC::ADD, 2, DestReg).addReg(Tmp3).addReg(Tmp4);
2526 if (Class0 <= cInt && Class1 <= cInt) {
2527 BuildMI(*MBB, IP, PPC::MULLW, 2, DestReg).addReg(Op0r).addReg(Op1r);
2531 assert(0 && "doMultiply cannot operate on unknown type!");
2534 /// doMultiplyConst - This method will multiply the value in Op0 by the
2535 /// value of the ContantInt *CI
2536 void PPC32ISel::doMultiplyConst(MachineBasicBlock *MBB,
2537 MachineBasicBlock::iterator IP,
2538 unsigned DestReg, Value *Op0, ConstantInt *CI) {
2539 unsigned Class = getClass(Op0->getType());
2542 if (CI->isNullValue()) {
2543 BuildMI(*MBB, IP, PPC::LI, 1, DestReg).addSImm(0);
2545 BuildMI(*MBB, IP, PPC::LI, 1, DestReg+1).addSImm(0);
2549 // Mul op0, 1 ==> op0
2550 if (CI->equalsInt(1)) {
2551 unsigned Op0r = getReg(Op0, MBB, IP);
2552 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(Op0r).addReg(Op0r);
2554 BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(Op0r+1).addReg(Op0r+1);
2558 // If the element size is exactly a power of 2, use a shift to get it.
2559 if (unsigned Shift = ExactLog2(CI->getRawValue())) {
2560 ConstantUInt *ShiftCI = ConstantUInt::get(Type::UByteTy, Shift);
2561 emitShiftOperation(MBB, IP, Op0, ShiftCI, true, Op0->getType(), 0, DestReg);
2565 // If 32 bits or less and immediate is in right range, emit mul by immediate
2566 if (Class == cByte || Class == cShort || Class == cInt) {
2567 if (canUseAsImmediateForOpcode(CI, 0, false)) {
2568 unsigned Op0r = getReg(Op0, MBB, IP);
2569 unsigned imm = CI->getRawValue() & 0xFFFF;
2570 BuildMI(*MBB, IP, PPC::MULLI, 2, DestReg).addReg(Op0r).addSImm(imm);
2575 doMultiply(MBB, IP, DestReg, Op0, CI);
2578 void PPC32ISel::visitMul(BinaryOperator &I) {
2579 unsigned ResultReg = getReg(I);
2581 Value *Op0 = I.getOperand(0);
2582 Value *Op1 = I.getOperand(1);
2584 MachineBasicBlock::iterator IP = BB->end();
2585 emitMultiply(BB, IP, Op0, Op1, ResultReg);
2588 void PPC32ISel::emitMultiply(MachineBasicBlock *MBB,
2589 MachineBasicBlock::iterator IP,
2590 Value *Op0, Value *Op1, unsigned DestReg) {
2591 TypeClass Class = getClass(Op0->getType());
2598 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2599 doMultiplyConst(MBB, IP, DestReg, Op0, CI);
2601 doMultiply(MBB, IP, DestReg, Op0, Op1);
2606 emitBinaryFPOperation(MBB, IP, Op0, Op1, 2, DestReg);
2613 /// visitDivRem - Handle division and remainder instructions... these
2614 /// instruction both require the same instructions to be generated, they just
2615 /// select the result from a different register. Note that both of these
2616 /// instructions work differently for signed and unsigned operands.
2618 void PPC32ISel::visitDivRem(BinaryOperator &I) {
2619 unsigned ResultReg = getReg(I);
2620 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2622 MachineBasicBlock::iterator IP = BB->end();
2623 emitDivRemOperation(BB, IP, Op0, Op1, I.getOpcode() == Instruction::Div,
2627 void PPC32ISel::emitDivRemOperation(MachineBasicBlock *MBB,
2628 MachineBasicBlock::iterator IP,
2629 Value *Op0, Value *Op1, bool isDiv,
2630 unsigned ResultReg) {
2631 const Type *Ty = Op0->getType();
2632 unsigned Class = getClass(Ty);
2636 // Floating point divide...
2637 emitBinaryFPOperation(MBB, IP, Op0, Op1, 3, ResultReg);
2640 // Floating point remainder via fmodf(float x, float y);
2641 unsigned Op0Reg = getReg(Op0, MBB, IP);
2642 unsigned Op1Reg = getReg(Op1, MBB, IP);
2643 MachineInstr *TheCall =
2644 BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(fmodfFn, true);
2645 std::vector<ValueRecord> Args;
2646 Args.push_back(ValueRecord(Op0Reg, Type::FloatTy));
2647 Args.push_back(ValueRecord(Op1Reg, Type::FloatTy));
2648 doCall(ValueRecord(ResultReg, Type::FloatTy), TheCall, Args, false);
2649 TM.CalledFunctions.insert(fmodfFn);
2654 // Floating point divide...
2655 emitBinaryFPOperation(MBB, IP, Op0, Op1, 3, ResultReg);
2658 // Floating point remainder via fmod(double x, double y);
2659 unsigned Op0Reg = getReg(Op0, MBB, IP);
2660 unsigned Op1Reg = getReg(Op1, MBB, IP);
2661 MachineInstr *TheCall =
2662 BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(fmodFn, true);
2663 std::vector<ValueRecord> Args;
2664 Args.push_back(ValueRecord(Op0Reg, Type::DoubleTy));
2665 Args.push_back(ValueRecord(Op1Reg, Type::DoubleTy));
2666 doCall(ValueRecord(ResultReg, Type::DoubleTy), TheCall, Args, false);
2667 TM.CalledFunctions.insert(fmodFn);
2671 static Function* const Funcs[] =
2672 { __moddi3Fn, __divdi3Fn, __umoddi3Fn, __udivdi3Fn };
2673 unsigned Op0Reg = getReg(Op0, MBB, IP);
2674 unsigned Op1Reg = getReg(Op1, MBB, IP);
2675 unsigned NameIdx = Ty->isUnsigned()*2 + isDiv;
2676 MachineInstr *TheCall =
2677 BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(Funcs[NameIdx], true);
2679 std::vector<ValueRecord> Args;
2680 Args.push_back(ValueRecord(Op0Reg, Type::LongTy));
2681 Args.push_back(ValueRecord(Op1Reg, Type::LongTy));
2682 doCall(ValueRecord(ResultReg, Type::LongTy), TheCall, Args, false);
2683 TM.CalledFunctions.insert(Funcs[NameIdx]);
2686 case cByte: case cShort: case cInt:
2687 break; // Small integrals, handled below...
2688 default: assert(0 && "Unknown class!");
2691 // Special case signed division by power of 2.
2693 if (ConstantSInt *CI = dyn_cast<ConstantSInt>(Op1)) {
2694 assert(Class != cLong && "This doesn't handle 64-bit divides!");
2695 int V = CI->getValue();
2697 if (V == 1) { // X /s 1 => X
2698 unsigned Op0Reg = getReg(Op0, MBB, IP);
2699 BuildMI(*MBB, IP, PPC::OR, 2, ResultReg).addReg(Op0Reg).addReg(Op0Reg);
2703 if (V == -1) { // X /s -1 => -X
2704 unsigned Op0Reg = getReg(Op0, MBB, IP);
2705 BuildMI(*MBB, IP, PPC::NEG, 1, ResultReg).addReg(Op0Reg);
2709 unsigned log2V = ExactLog2(V);
2710 if (log2V != 0 && Ty->isSigned()) {
2711 unsigned Op0Reg = getReg(Op0, MBB, IP);
2712 unsigned TmpReg = makeAnotherReg(Op0->getType());
2714 BuildMI(*MBB, IP, PPC::SRAWI, 2, TmpReg).addReg(Op0Reg).addImm(log2V);
2715 BuildMI(*MBB, IP, PPC::ADDZE, 1, ResultReg).addReg(TmpReg);
2720 unsigned Op0Reg = getReg(Op0, MBB, IP);
2723 unsigned Op1Reg = getReg(Op1, MBB, IP);
2724 unsigned Opcode = Ty->isSigned() ? PPC::DIVW : PPC::DIVWU;
2725 BuildMI(*MBB, IP, Opcode, 2, ResultReg).addReg(Op0Reg).addReg(Op1Reg);
2726 } else { // Remainder
2727 // FIXME: don't load the CI part of a CI divide twice
2728 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
2729 unsigned TmpReg1 = makeAnotherReg(Op0->getType());
2730 unsigned TmpReg2 = makeAnotherReg(Op0->getType());
2731 emitDivRemOperation(MBB, IP, Op0, Op1, true, TmpReg1);
2732 if (CI && canUseAsImmediateForOpcode(CI, 0, false)) {
2733 BuildMI(*MBB, IP, PPC::MULLI, 2, TmpReg2).addReg(TmpReg1)
2734 .addSImm(CI->getRawValue());
2736 unsigned Op1Reg = getReg(Op1, MBB, IP);
2737 BuildMI(*MBB, IP, PPC::MULLW, 2, TmpReg2).addReg(TmpReg1).addReg(Op1Reg);
2739 BuildMI(*MBB, IP, PPC::SUBF, 2, ResultReg).addReg(TmpReg2).addReg(Op0Reg);
2744 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
2745 /// for constant immediate shift values, and for constant immediate
2746 /// shift values equal to 1. Even the general case is sort of special,
2747 /// because the shift amount has to be in CL, not just any old register.
2749 void PPC32ISel::visitShiftInst(ShiftInst &I) {
2750 if (std::find(SkipList.begin(), SkipList.end(), &I) != SkipList.end())
2753 MachineBasicBlock::iterator IP = BB->end();
2754 emitShiftOperation(BB, IP, I.getOperand(0), I.getOperand(1),
2755 I.getOpcode() == Instruction::Shl, I.getType(),
2759 /// emitShiftOperation - Common code shared between visitShiftInst and
2760 /// constant expression support.
2762 void PPC32ISel::emitShiftOperation(MachineBasicBlock *MBB,
2763 MachineBasicBlock::iterator IP,
2764 Value *Op, Value *ShiftAmount,
2765 bool isLeftShift, const Type *ResultTy,
2766 ShiftInst *SI, unsigned DestReg) {
2767 bool isSigned = ResultTy->isSigned ();
2768 unsigned Class = getClass (ResultTy);
2770 // Longs, as usual, are handled specially...
2771 if (Class == cLong) {
2772 unsigned SrcReg = getReg (Op, MBB, IP);
2773 // If we have a constant shift, we can generate much more efficient code
2774 // than for a variable shift by using the rlwimi instruction.
2775 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2776 unsigned Amount = CUI->getValue();
2778 unsigned TempReg = makeAnotherReg(ResultTy);
2780 BuildMI(*MBB, IP, PPC::RLWINM, 4, TempReg).addReg(SrcReg)
2781 .addImm(Amount).addImm(0).addImm(31-Amount);
2782 BuildMI(*MBB, IP, PPC::RLWIMI, 5, DestReg).addReg(TempReg)
2783 .addReg(SrcReg+1).addImm(Amount).addImm(32-Amount).addImm(31);
2784 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg+1).addReg(SrcReg+1)
2785 .addImm(Amount).addImm(0).addImm(31-Amount);
2787 BuildMI(*MBB, IP, PPC::RLWINM, 4, TempReg).addReg(SrcReg+1)
2788 .addImm(32-Amount).addImm(Amount).addImm(31);
2789 BuildMI(*MBB, IP, PPC::RLWIMI, 5, DestReg+1).addReg(TempReg)
2790 .addReg(SrcReg).addImm(32-Amount).addImm(0).addImm(Amount-1);
2791 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
2792 .addImm(32-Amount).addImm(Amount).addImm(31);
2794 } else { // Shifting more than 32 bits
2798 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg+1)
2799 .addImm(Amount).addImm(0).addImm(31-Amount);
2801 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg+1)
2804 BuildMI(*MBB, IP, PPC::LI, 1, DestReg+1).addSImm(0);
2808 BuildMI(*MBB, IP, PPC::SRAWI, 2, DestReg+1).addReg(SrcReg)
2811 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg+1).addReg(SrcReg)
2812 .addImm(32-Amount).addImm(Amount).addImm(31);
2814 BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(SrcReg)
2817 BuildMI(*MBB, IP,PPC::LI, 1, DestReg).addSImm(0);
2821 unsigned TmpReg1 = makeAnotherReg(Type::IntTy);
2822 unsigned TmpReg2 = makeAnotherReg(Type::IntTy);
2823 unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
2824 unsigned TmpReg4 = makeAnotherReg(Type::IntTy);
2825 unsigned TmpReg5 = makeAnotherReg(Type::IntTy);
2826 unsigned TmpReg6 = makeAnotherReg(Type::IntTy);
2827 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
2830 BuildMI(*MBB, IP, PPC::SUBFIC, 2, TmpReg1).addReg(ShiftAmountReg)
2832 BuildMI(*MBB, IP, PPC::SLW, 2, TmpReg2).addReg(SrcReg)
2833 .addReg(ShiftAmountReg);
2834 BuildMI(*MBB, IP, PPC::SRW, 2, TmpReg3).addReg(SrcReg+1)
2836 BuildMI(*MBB, IP, PPC::OR, 2,TmpReg4).addReg(TmpReg2).addReg(TmpReg3);
2837 BuildMI(*MBB, IP, PPC::ADDI, 2, TmpReg5).addReg(ShiftAmountReg)
2839 BuildMI(*MBB, IP, PPC::SLW, 2, TmpReg6).addReg(SrcReg+1)
2841 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(TmpReg4)
2843 BuildMI(*MBB, IP, PPC::SLW, 2, DestReg+1).addReg(SrcReg+1)
2844 .addReg(ShiftAmountReg);
2846 if (isSigned) { // shift right algebraic
2847 MachineBasicBlock *TmpMBB =new MachineBasicBlock(BB->getBasicBlock());
2848 MachineBasicBlock *PhiMBB =new MachineBasicBlock(BB->getBasicBlock());
2849 MachineBasicBlock *OldMBB = BB;
2850 ilist<MachineBasicBlock>::iterator It = BB; ++It;
2851 F->getBasicBlockList().insert(It, TmpMBB);
2852 F->getBasicBlockList().insert(It, PhiMBB);
2853 BB->addSuccessor(TmpMBB);
2854 BB->addSuccessor(PhiMBB);
2856 BuildMI(*MBB, IP, PPC::SUBFIC, 2, TmpReg1).addReg(ShiftAmountReg)
2858 BuildMI(*MBB, IP, PPC::SRW, 2, TmpReg2).addReg(SrcReg+1)
2859 .addReg(ShiftAmountReg);
2860 BuildMI(*MBB, IP, PPC::SLW, 2, TmpReg3).addReg(SrcReg)
2862 BuildMI(*MBB, IP, PPC::OR, 2, TmpReg4).addReg(TmpReg2)
2864 BuildMI(*MBB, IP, PPC::ADDICo, 2, TmpReg5).addReg(ShiftAmountReg)
2866 BuildMI(*MBB, IP, PPC::SRAW, 2, TmpReg6).addReg(SrcReg)
2868 BuildMI(*MBB, IP, PPC::SRAW, 2, DestReg).addReg(SrcReg)
2869 .addReg(ShiftAmountReg);
2870 BuildMI(*MBB, IP, PPC::BLE, 2).addReg(PPC::CR0).addMBB(PhiMBB);
2873 // Select correct least significant half if the shift amount > 32
2875 unsigned OrReg = makeAnotherReg(Type::IntTy);
2876 BuildMI(BB, PPC::OR, 2, OrReg).addReg(TmpReg6).addImm(TmpReg6);
2877 TmpMBB->addSuccessor(PhiMBB);
2880 BuildMI(BB, PPC::PHI, 4, DestReg+1).addReg(TmpReg4).addMBB(OldMBB)
2881 .addReg(OrReg).addMBB(TmpMBB);
2882 } else { // shift right logical
2883 BuildMI(*MBB, IP, PPC::SUBFIC, 2, TmpReg1).addReg(ShiftAmountReg)
2885 BuildMI(*MBB, IP, PPC::SRW, 2, TmpReg2).addReg(SrcReg+1)
2886 .addReg(ShiftAmountReg);
2887 BuildMI(*MBB, IP, PPC::SLW, 2, TmpReg3).addReg(SrcReg)
2889 BuildMI(*MBB, IP, PPC::OR, 2, TmpReg4).addReg(TmpReg2)
2891 BuildMI(*MBB, IP, PPC::ADDI, 2, TmpReg5).addReg(ShiftAmountReg)
2893 BuildMI(*MBB, IP, PPC::SRW, 2, TmpReg6).addReg(SrcReg)
2895 BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(TmpReg4)
2897 BuildMI(*MBB, IP, PPC::SRW, 2, DestReg).addReg(SrcReg)
2898 .addReg(ShiftAmountReg);
2905 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
2906 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
2907 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
2908 unsigned Amount = CUI->getValue();
2910 // If this is a shift with one use, and that use is an And instruction,
2911 // then attempt to emit a bitfield operation.
2912 if (SI && emitBitfieldInsert(SI, DestReg))
2915 unsigned SrcReg = getReg (Op, MBB, IP);
2917 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
2918 .addImm(Amount).addImm(0).addImm(31-Amount);
2921 BuildMI(*MBB, IP, PPC::SRAWI,2,DestReg).addReg(SrcReg).addImm(Amount);
2923 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
2924 .addImm(32-Amount).addImm(Amount).addImm(31);
2927 } else { // The shift amount is non-constant.
2928 unsigned SrcReg = getReg (Op, MBB, IP);
2929 unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
2932 BuildMI(*MBB, IP, PPC::SLW, 2, DestReg).addReg(SrcReg)
2933 .addReg(ShiftAmountReg);
2935 BuildMI(*MBB, IP, isSigned ? PPC::SRAW : PPC::SRW, 2, DestReg)
2936 .addReg(SrcReg).addReg(ShiftAmountReg);
2941 /// LoadNeedsSignExtend - On PowerPC, there is no load byte with sign extend.
2942 /// Therefore, if this is a byte load and the destination type is signed, we
2943 /// would normally need to also emit a sign extend instruction after the load.
2944 /// However, store instructions don't care whether a signed type was sign
2945 /// extended across a whole register. Also, a SetCC instruction will emit its
2946 /// own sign extension to force the value into the appropriate range, so we
2947 /// need not emit it here. Ideally, this kind of thing wouldn't be necessary
2948 /// once LLVM's type system is improved.
2949 static bool LoadNeedsSignExtend(LoadInst &LI) {
2950 if (cByte == getClassB(LI.getType()) && LI.getType()->isSigned()) {
2951 bool AllUsesAreStoresOrSetCC = true;
2952 for (Value::use_iterator I = LI.use_begin(), E = LI.use_end(); I != E; ++I){
2953 if (isa<SetCondInst>(*I))
2955 if (StoreInst *SI = dyn_cast<StoreInst>(*I))
2956 if (cByte == getClassB(SI->getOperand(0)->getType()))
2958 AllUsesAreStoresOrSetCC = false;
2961 if (!AllUsesAreStoresOrSetCC)
2967 /// visitLoadInst - Implement LLVM load instructions. Pretty straightforward
2968 /// mapping of LLVM classes to PPC load instructions, with the exception of
2969 /// signed byte loads, which need a sign extension following them.
2971 void PPC32ISel::visitLoadInst(LoadInst &I) {
2972 // Immediate opcodes, for reg+imm addressing
2973 static const unsigned ImmOpcodes[] = {
2974 PPC::LBZ, PPC::LHZ, PPC::LWZ,
2975 PPC::LFS, PPC::LFD, PPC::LWZ
2977 // Indexed opcodes, for reg+reg addressing
2978 static const unsigned IdxOpcodes[] = {
2979 PPC::LBZX, PPC::LHZX, PPC::LWZX,
2980 PPC::LFSX, PPC::LFDX, PPC::LWZX
2983 unsigned Class = getClassB(I.getType());
2984 unsigned ImmOpcode = ImmOpcodes[Class];
2985 unsigned IdxOpcode = IdxOpcodes[Class];
2986 unsigned DestReg = getReg(I);
2987 Value *SourceAddr = I.getOperand(0);
2989 if (Class == cShort && I.getType()->isSigned()) ImmOpcode = PPC::LHA;
2990 if (Class == cShort && I.getType()->isSigned()) IdxOpcode = PPC::LHAX;
2992 // If this is a fixed size alloca, emit a load directly from the stack slot
2993 // corresponding to it.
2994 if (AllocaInst *AI = dyn_castFixedAlloca(SourceAddr)) {
2995 unsigned FI = getFixedSizedAllocaFI(AI);
2996 if (Class == cLong) {
2997 addFrameReference(BuildMI(BB, ImmOpcode, 2, DestReg), FI);
2998 addFrameReference(BuildMI(BB, ImmOpcode, 2, DestReg+1), FI, 4);
2999 } else if (LoadNeedsSignExtend(I)) {
3000 unsigned TmpReg = makeAnotherReg(I.getType());
3001 addFrameReference(BuildMI(BB, ImmOpcode, 2, TmpReg), FI);
3002 BuildMI(BB, PPC::EXTSB, 1, DestReg).addReg(TmpReg);
3004 addFrameReference(BuildMI(BB, ImmOpcode, 2, DestReg), FI);
3009 // If the offset fits in 16 bits, we can emit a reg+imm load, otherwise, we
3010 // use the index from the FoldedGEP struct and use reg+reg addressing.
3011 if (GetElementPtrInst *GEPI = canFoldGEPIntoLoadOrStore(SourceAddr)) {
3013 // Generate the code for the GEP and get the components of the folded GEP
3014 emitGEPOperation(BB, BB->end(), GEPI, true);
3015 unsigned baseReg = GEPMap[GEPI].base;
3016 unsigned indexReg = GEPMap[GEPI].index;
3017 ConstantSInt *offset = GEPMap[GEPI].offset;
3019 if (Class != cLong) {
3020 unsigned TmpReg = LoadNeedsSignExtend(I) ? makeAnotherReg(I.getType())
3023 BuildMI(BB, ImmOpcode, 2, TmpReg).addSImm(offset->getValue())
3026 BuildMI(BB, IdxOpcode, 2, TmpReg).addReg(indexReg).addReg(baseReg);
3027 if (LoadNeedsSignExtend(I))
3028 BuildMI(BB, PPC::EXTSB, 1, DestReg).addReg(TmpReg);
3030 indexReg = (indexReg != 0) ? indexReg : getReg(offset);
3031 unsigned indexPlus4 = makeAnotherReg(Type::IntTy);
3032 BuildMI(BB, PPC::ADDI, 2, indexPlus4).addReg(indexReg).addSImm(4);
3033 BuildMI(BB, IdxOpcode, 2, DestReg).addReg(indexReg).addReg(baseReg);
3034 BuildMI(BB, IdxOpcode, 2, DestReg+1).addReg(indexPlus4).addReg(baseReg);
3039 // The fallback case, where the load was from a source that could not be
3040 // folded into the load instruction.
3041 unsigned SrcAddrReg = getReg(SourceAddr);
3043 if (Class == cLong) {
3044 BuildMI(BB, ImmOpcode, 2, DestReg).addSImm(0).addReg(SrcAddrReg);
3045 BuildMI(BB, ImmOpcode, 2, DestReg+1).addSImm(4).addReg(SrcAddrReg);
3046 } else if (LoadNeedsSignExtend(I)) {
3047 unsigned TmpReg = makeAnotherReg(I.getType());
3048 BuildMI(BB, ImmOpcode, 2, TmpReg).addSImm(0).addReg(SrcAddrReg);
3049 BuildMI(BB, PPC::EXTSB, 1, DestReg).addReg(TmpReg);
3051 BuildMI(BB, ImmOpcode, 2, DestReg).addSImm(0).addReg(SrcAddrReg);
3055 /// visitStoreInst - Implement LLVM store instructions
3057 void PPC32ISel::visitStoreInst(StoreInst &I) {
3058 // Immediate opcodes, for reg+imm addressing
3059 static const unsigned ImmOpcodes[] = {
3060 PPC::STB, PPC::STH, PPC::STW,
3061 PPC::STFS, PPC::STFD, PPC::STW
3063 // Indexed opcodes, for reg+reg addressing
3064 static const unsigned IdxOpcodes[] = {
3065 PPC::STBX, PPC::STHX, PPC::STWX,
3066 PPC::STFSX, PPC::STFDX, PPC::STWX
3069 Value *SourceAddr = I.getOperand(1);
3070 const Type *ValTy = I.getOperand(0)->getType();
3071 unsigned Class = getClassB(ValTy);
3072 unsigned ImmOpcode = ImmOpcodes[Class];
3073 unsigned IdxOpcode = IdxOpcodes[Class];
3074 unsigned ValReg = getReg(I.getOperand(0));
3076 // If this is a fixed size alloca, emit a store directly to the stack slot
3077 // corresponding to it.
3078 if (AllocaInst *AI = dyn_castFixedAlloca(SourceAddr)) {
3079 unsigned FI = getFixedSizedAllocaFI(AI);
3080 addFrameReference(BuildMI(BB, ImmOpcode, 3).addReg(ValReg), FI);
3082 addFrameReference(BuildMI(BB, ImmOpcode, 3).addReg(ValReg+1), FI, 4);
3086 // If the offset fits in 16 bits, we can emit a reg+imm store, otherwise, we
3087 // use the index from the FoldedGEP struct and use reg+reg addressing.
3088 if (GetElementPtrInst *GEPI = canFoldGEPIntoLoadOrStore(SourceAddr)) {
3089 // Generate the code for the GEP and get the components of the folded GEP
3090 emitGEPOperation(BB, BB->end(), GEPI, true);
3091 unsigned baseReg = GEPMap[GEPI].base;
3092 unsigned indexReg = GEPMap[GEPI].index;
3093 ConstantSInt *offset = GEPMap[GEPI].offset;
3095 if (Class != cLong) {
3097 BuildMI(BB, ImmOpcode, 3).addReg(ValReg).addSImm(offset->getValue())
3100 BuildMI(BB, IdxOpcode, 3).addReg(ValReg).addReg(indexReg)
3103 indexReg = (indexReg != 0) ? indexReg : getReg(offset);
3104 unsigned indexPlus4 = makeAnotherReg(Type::IntTy);
3105 BuildMI(BB, PPC::ADDI, 2, indexPlus4).addReg(indexReg).addSImm(4);
3106 BuildMI(BB, IdxOpcode, 3).addReg(ValReg).addReg(indexReg).addReg(baseReg);
3107 BuildMI(BB, IdxOpcode, 3).addReg(ValReg+1).addReg(indexPlus4)
3113 // If the store address wasn't the only use of a GEP, we fall back to the
3114 // standard path: store the ValReg at the value in AddressReg.
3115 unsigned AddressReg = getReg(I.getOperand(1));
3116 if (Class == cLong) {
3117 BuildMI(BB, ImmOpcode, 3).addReg(ValReg).addSImm(0).addReg(AddressReg);
3118 BuildMI(BB, ImmOpcode, 3).addReg(ValReg+1).addSImm(4).addReg(AddressReg);
3121 BuildMI(BB, ImmOpcode, 3).addReg(ValReg).addSImm(0).addReg(AddressReg);
3125 /// visitCastInst - Here we have various kinds of copying with or without sign
3126 /// extension going on.
3128 void PPC32ISel::visitCastInst(CastInst &CI) {
3129 Value *Op = CI.getOperand(0);
3131 unsigned SrcClass = getClassB(Op->getType());
3132 unsigned DestClass = getClassB(CI.getType());
3134 // Noop casts are not emitted: getReg will return the source operand as the
3135 // register to use for any uses of the noop cast.
3136 if (DestClass == SrcClass) return;
3138 // If this is a cast from a 32-bit integer to a Long type, and the only uses
3139 // of the cast are GEP instructions, then the cast does not need to be
3140 // generated explicitly, it will be folded into the GEP.
3141 if (DestClass == cLong && SrcClass == cInt) {
3142 bool AllUsesAreGEPs = true;
3143 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
3144 if (!isa<GetElementPtrInst>(*I)) {
3145 AllUsesAreGEPs = false;
3148 if (AllUsesAreGEPs) return;
3151 unsigned DestReg = getReg(CI);
3152 MachineBasicBlock::iterator MI = BB->end();
3154 // If this is a cast from an integer type to a ubyte, with one use where the
3155 // use is the shift amount argument of a shift instruction, just emit a move
3156 // instead (since the shift instruction will only look at the low 5 bits
3157 // regardless of how it is sign extended)
3158 if (CI.getType() == Type::UByteTy && SrcClass <= cInt && CI.hasOneUse()) {
3159 ShiftInst *SI = dyn_cast<ShiftInst>(*(CI.use_begin()));
3160 if (SI && (SI->getOperand(1) == &CI)) {
3161 unsigned SrcReg = getReg(Op, BB, MI);
3162 BuildMI(*BB, MI, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
3167 // If this is a cast from an byte, short, or int to an integer type of equal
3168 // or lesser width, and all uses of the cast are store instructions then dont
3169 // emit them, as the store instruction will implicitly not store the zero or
3170 // sign extended bytes.
3171 if (SrcClass <= cInt && SrcClass >= DestClass) {
3172 bool AllUsesAreStores = true;
3173 for (Value::use_iterator I = CI.use_begin(), E = CI.use_end(); I != E; ++I)
3174 if (!isa<StoreInst>(*I)) {
3175 AllUsesAreStores = false;
3178 // Turn this cast directly into a move instruction, which the register
3179 // allocator will deal with.
3180 if (AllUsesAreStores) {
3181 unsigned SrcReg = getReg(Op, BB, MI);
3182 BuildMI(*BB, MI, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
3186 emitCastOperation(BB, MI, Op, CI.getType(), DestReg);
3189 /// emitCastOperation - Common code shared between visitCastInst and constant
3190 /// expression cast support.
3192 void PPC32ISel::emitCastOperation(MachineBasicBlock *MBB,
3193 MachineBasicBlock::iterator IP,
3194 Value *Src, const Type *DestTy,
3196 const Type *SrcTy = Src->getType();
3197 unsigned SrcClass = getClassB(SrcTy);
3198 unsigned DestClass = getClassB(DestTy);
3199 unsigned SrcReg = getReg(Src, MBB, IP);
3201 // Implement casts from bool to integer types as a move operation
3202 if (SrcTy == Type::BoolTy) {
3203 switch (DestClass) {
3207 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
3210 BuildMI(*MBB, IP, PPC::LI, 1, DestReg).addImm(0);
3211 BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(SrcReg).addReg(SrcReg);
3218 // Implement casts to bool by using compare on the operand followed by set if
3219 // not zero on the result.
3220 if (DestTy == Type::BoolTy) {
3225 unsigned TmpReg = makeAnotherReg(Type::IntTy);
3226 BuildMI(*MBB, IP, PPC::ADDIC, 2, TmpReg).addReg(SrcReg).addSImm(-1);
3227 BuildMI(*MBB, IP, PPC::SUBFE, 2, DestReg).addReg(TmpReg).addReg(SrcReg);
3231 unsigned TmpReg = makeAnotherReg(Type::IntTy);
3232 unsigned SrcReg2 = makeAnotherReg(Type::IntTy);
3233 BuildMI(*MBB, IP, PPC::OR, 2, SrcReg2).addReg(SrcReg).addReg(SrcReg+1);
3234 BuildMI(*MBB, IP, PPC::ADDIC, 2, TmpReg).addReg(SrcReg2).addSImm(-1);
3235 BuildMI(*MBB, IP, PPC::SUBFE, 2, DestReg).addReg(TmpReg)
3241 unsigned TmpReg = makeAnotherReg(Type::IntTy);
3242 unsigned ConstZero = getReg(ConstantFP::get(Type::DoubleTy, 0.0), BB, IP);
3243 BuildMI(*MBB, IP, PPC::FCMPU, PPC::CR7).addReg(SrcReg).addReg(ConstZero);
3244 BuildMI(*MBB, IP, PPC::MFCR, TmpReg);
3245 BuildMI(*MBB, IP, PPC::RLWINM, DestReg).addReg(TmpReg).addImm(31)
3246 .addImm(31).addImm(31);
3251 // Handle cast of Float -> Double
3252 if (SrcClass == cFP32 && DestClass == cFP64) {
3253 BuildMI(*MBB, IP, PPC::FMR, 1, DestReg).addReg(SrcReg);
3257 // Handle cast of Double -> Float
3258 if (SrcClass == cFP64 && DestClass == cFP32) {
3259 BuildMI(*MBB, IP, PPC::FRSP, 1, DestReg).addReg(SrcReg);
3263 // Handle casts from integer to floating point now...
3264 if (DestClass == cFP32 || DestClass == cFP64) {
3266 // Emit a library call for long to float conversion
3267 if (SrcClass == cLong) {
3268 Function *floatFn = (DestClass == cFP32) ? __floatdisfFn : __floatdidfFn;
3269 if (SrcTy->isSigned()) {
3270 std::vector<ValueRecord> Args;
3271 Args.push_back(ValueRecord(SrcReg, SrcTy));
3272 MachineInstr *TheCall =
3273 BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(floatFn, true);
3274 doCall(ValueRecord(DestReg, DestTy), TheCall, Args, false);
3275 TM.CalledFunctions.insert(floatFn);
3277 std::vector<ValueRecord> CmpArgs, ClrArgs, SetArgs;
3278 unsigned ZeroLong = getReg(ConstantUInt::get(SrcTy, 0));
3279 unsigned CondReg = makeAnotherReg(Type::IntTy);
3281 // Update machine-CFG edges
3282 MachineBasicBlock *ClrMBB = new MachineBasicBlock(BB->getBasicBlock());
3283 MachineBasicBlock *SetMBB = new MachineBasicBlock(BB->getBasicBlock());
3284 MachineBasicBlock *PhiMBB = new MachineBasicBlock(BB->getBasicBlock());
3285 MachineBasicBlock *OldMBB = BB;
3286 ilist<MachineBasicBlock>::iterator It = BB; ++It;
3287 F->getBasicBlockList().insert(It, ClrMBB);
3288 F->getBasicBlockList().insert(It, SetMBB);
3289 F->getBasicBlockList().insert(It, PhiMBB);
3290 BB->addSuccessor(ClrMBB);
3291 BB->addSuccessor(SetMBB);
3293 CmpArgs.push_back(ValueRecord(SrcReg, SrcTy));
3294 CmpArgs.push_back(ValueRecord(ZeroLong, SrcTy));
3295 MachineInstr *TheCall =
3296 BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(__cmpdi2Fn, true);
3297 doCall(ValueRecord(CondReg, Type::IntTy), TheCall, CmpArgs, false);
3298 TM.CalledFunctions.insert(__cmpdi2Fn);
3299 BuildMI(*MBB, IP, PPC::CMPWI, 2, PPC::CR0).addReg(CondReg).addSImm(0);
3300 BuildMI(*MBB, IP, PPC::BLE, 2).addReg(PPC::CR0).addMBB(SetMBB);
3304 unsigned ClrReg = makeAnotherReg(DestTy);
3305 ClrArgs.push_back(ValueRecord(SrcReg, SrcTy));
3306 TheCall = BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(floatFn, true);
3307 doCall(ValueRecord(ClrReg, DestTy), TheCall, ClrArgs, false);
3308 TM.CalledFunctions.insert(floatFn);
3309 BuildMI(BB, PPC::B, 1).addMBB(PhiMBB);
3310 BB->addSuccessor(PhiMBB);
3314 unsigned SetReg = makeAnotherReg(DestTy);
3315 unsigned CallReg = makeAnotherReg(DestTy);
3316 unsigned ShiftedReg = makeAnotherReg(SrcTy);
3317 ConstantSInt *Const1 = ConstantSInt::get(Type::IntTy, 1);
3318 emitShiftOperation(BB, BB->end(), Src, Const1, false, SrcTy, 0,
3320 SetArgs.push_back(ValueRecord(ShiftedReg, SrcTy));
3321 TheCall = BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(floatFn, true);
3322 doCall(ValueRecord(CallReg, DestTy), TheCall, SetArgs, false);
3323 TM.CalledFunctions.insert(floatFn);
3324 unsigned SetOpcode = (DestClass == cFP32) ? PPC::FADDS : PPC::FADD;
3325 BuildMI(BB, SetOpcode, 2, SetReg).addReg(CallReg).addReg(CallReg);
3326 BB->addSuccessor(PhiMBB);
3330 BuildMI(BB, PPC::PHI, 4, DestReg).addReg(ClrReg).addMBB(ClrMBB)
3331 .addReg(SetReg).addMBB(SetMBB);
3336 // Make sure we're dealing with a full 32 bits
3337 if (SrcClass < cInt) {
3338 unsigned TmpReg = makeAnotherReg(Type::IntTy);
3339 promote32(TmpReg, ValueRecord(SrcReg, SrcTy));
3343 // Spill the integer to memory and reload it from there.
3344 // Also spill room for a special conversion constant
3346 F->getFrameInfo()->CreateStackObject(Type::DoubleTy, TM.getTargetData());
3348 MachineConstantPool *CP = F->getConstantPool();
3349 unsigned constantHi = makeAnotherReg(Type::IntTy);
3350 unsigned TempF = makeAnotherReg(Type::DoubleTy);
3352 if (!SrcTy->isSigned()) {
3353 ConstantFP *CFP = ConstantFP::get(Type::DoubleTy, 0x1.000000p52);
3354 unsigned ConstF = getReg(CFP, BB, IP);
3355 BuildMI(*MBB, IP, PPC::LIS, 1, constantHi).addSImm(0x4330);
3356 addFrameReference(BuildMI(*MBB, IP, PPC::STW, 3).addReg(constantHi),
3358 addFrameReference(BuildMI(*MBB, IP, PPC::STW, 3).addReg(SrcReg),
3360 addFrameReference(BuildMI(*MBB, IP, PPC::LFD, 2, TempF), ValueFrameIdx);
3361 BuildMI(*MBB, IP, PPC::FSUB, 2, DestReg).addReg(TempF).addReg(ConstF);
3363 ConstantFP *CFP = ConstantFP::get(Type::DoubleTy, 0x1.000008p52);
3364 unsigned ConstF = getReg(CFP, BB, IP);
3365 unsigned TempLo = makeAnotherReg(Type::IntTy);
3366 BuildMI(*MBB, IP, PPC::LIS, 1, constantHi).addSImm(0x4330);
3367 addFrameReference(BuildMI(*MBB, IP, PPC::STW, 3).addReg(constantHi),
3369 BuildMI(*MBB, IP, PPC::XORIS, 2, TempLo).addReg(SrcReg).addImm(0x8000);
3370 addFrameReference(BuildMI(*MBB, IP, PPC::STW, 3).addReg(TempLo),
3372 addFrameReference(BuildMI(*MBB, IP, PPC::LFD, 2, TempF), ValueFrameIdx);
3373 BuildMI(*MBB, IP, PPC::FSUB, 2, DestReg).addReg(TempF).addReg(ConstF);
3378 // Handle casts from floating point to integer now...
3379 if (SrcClass == cFP32 || SrcClass == cFP64) {
3380 static Function* const Funcs[] =
3381 { __fixsfdiFn, __fixdfdiFn, __fixunssfdiFn, __fixunsdfdiFn };
3382 // emit library call
3383 if (DestClass == cLong) {
3384 bool isDouble = SrcClass == cFP64;
3385 unsigned nameIndex = 2 * DestTy->isSigned() + isDouble;
3386 std::vector<ValueRecord> Args;
3387 Args.push_back(ValueRecord(SrcReg, SrcTy));
3388 Function *floatFn = Funcs[nameIndex];
3389 MachineInstr *TheCall =
3390 BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(floatFn, true);
3391 doCall(ValueRecord(DestReg, DestTy), TheCall, Args, false);
3392 TM.CalledFunctions.insert(floatFn);
3397 F->getFrameInfo()->CreateStackObject(Type::DoubleTy, TM.getTargetData());
3399 if (DestTy->isSigned()) {
3400 unsigned TempReg = makeAnotherReg(Type::DoubleTy);
3402 // Convert to integer in the FP reg and store it to a stack slot
3403 BuildMI(*MBB, IP, PPC::FCTIWZ, 1, TempReg).addReg(SrcReg);
3404 addFrameReference(BuildMI(*MBB, IP, PPC::STFD, 3)
3405 .addReg(TempReg), ValueFrameIdx);
3407 // There is no load signed byte opcode, so we must emit a sign extend for
3408 // that particular size. Make sure to source the new integer from the
3410 if (DestClass == cByte) {
3411 unsigned TempReg2 = makeAnotherReg(DestTy);
3412 addFrameReference(BuildMI(*MBB, IP, PPC::LBZ, 2, TempReg2),
3414 BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(TempReg2);
3416 int offset = (DestClass == cShort) ? 6 : 4;
3417 unsigned LoadOp = (DestClass == cShort) ? PPC::LHA : PPC::LWZ;
3418 addFrameReference(BuildMI(*MBB, IP, LoadOp, 2, DestReg),
3419 ValueFrameIdx, offset);
3422 unsigned Zero = getReg(ConstantFP::get(Type::DoubleTy, 0.0f));
3423 double maxInt = (1LL << 32) - 1;
3424 unsigned MaxInt = getReg(ConstantFP::get(Type::DoubleTy, maxInt));
3425 double border = 1LL << 31;
3426 unsigned Border = getReg(ConstantFP::get(Type::DoubleTy, border));
3427 unsigned UseZero = makeAnotherReg(Type::DoubleTy);
3428 unsigned UseMaxInt = makeAnotherReg(Type::DoubleTy);
3429 unsigned UseChoice = makeAnotherReg(Type::DoubleTy);
3430 unsigned TmpReg = makeAnotherReg(Type::DoubleTy);
3431 unsigned TmpReg2 = makeAnotherReg(Type::DoubleTy);
3432 unsigned ConvReg = makeAnotherReg(Type::DoubleTy);
3433 unsigned IntTmp = makeAnotherReg(Type::IntTy);
3434 unsigned XorReg = makeAnotherReg(Type::IntTy);
3436 F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
3437 // Update machine-CFG edges
3438 MachineBasicBlock *XorMBB = new MachineBasicBlock(BB->getBasicBlock());
3439 MachineBasicBlock *PhiMBB = new MachineBasicBlock(BB->getBasicBlock());
3440 MachineBasicBlock *OldMBB = BB;
3441 ilist<MachineBasicBlock>::iterator It = BB; ++It;
3442 F->getBasicBlockList().insert(It, XorMBB);
3443 F->getBasicBlockList().insert(It, PhiMBB);
3444 BB->addSuccessor(XorMBB);
3445 BB->addSuccessor(PhiMBB);
3447 // Convert from floating point to unsigned 32-bit value
3448 // Use 0 if incoming value is < 0.0
3449 BuildMI(*MBB, IP, PPC::FSEL, 3, UseZero).addReg(SrcReg).addReg(SrcReg)
3451 // Use 2**32 - 1 if incoming value is >= 2**32
3452 BuildMI(*MBB, IP, PPC::FSUB, 2, UseMaxInt).addReg(MaxInt).addReg(SrcReg);
3453 BuildMI(*MBB, IP, PPC::FSEL, 3, UseChoice).addReg(UseMaxInt)
3454 .addReg(UseZero).addReg(MaxInt);
3456 BuildMI(*MBB, IP, PPC::FSUB, 2, TmpReg).addReg(UseChoice).addReg(Border);
3457 // Use difference if >= 2**31
3458 BuildMI(*MBB, IP, PPC::FCMPU, 2, PPC::CR0).addReg(UseChoice)
3460 BuildMI(*MBB, IP, PPC::FSEL, 3, TmpReg2).addReg(TmpReg).addReg(TmpReg)
3462 // Convert to integer
3463 BuildMI(*MBB, IP, PPC::FCTIWZ, 1, ConvReg).addReg(TmpReg2);
3464 addFrameReference(BuildMI(*MBB, IP, PPC::STFD, 3).addReg(ConvReg),
3466 if (DestClass == cByte) {
3467 addFrameReference(BuildMI(*MBB, IP, PPC::LBZ, 2, DestReg),
3469 } else if (DestClass == cShort) {
3470 addFrameReference(BuildMI(*MBB, IP, PPC::LHZ, 2, DestReg),
3472 } if (DestClass == cInt) {
3473 addFrameReference(BuildMI(*MBB, IP, PPC::LWZ, 2, IntTmp),
3475 BuildMI(*MBB, IP, PPC::BLT, 2).addReg(PPC::CR0).addMBB(PhiMBB);
3476 BuildMI(*MBB, IP, PPC::B, 1).addMBB(XorMBB);
3479 // add 2**31 if input was >= 2**31
3481 BuildMI(BB, PPC::XORIS, 2, XorReg).addReg(IntTmp).addImm(0x8000);
3482 XorMBB->addSuccessor(PhiMBB);
3485 // DestReg = phi [ IntTmp, OldMBB ], [ XorReg, XorMBB ]
3487 BuildMI(BB, PPC::PHI, 4, DestReg).addReg(IntTmp).addMBB(OldMBB)
3488 .addReg(XorReg).addMBB(XorMBB);
3494 // Check our invariants
3495 assert((SrcClass <= cInt || SrcClass == cLong) &&
3496 "Unhandled source class for cast operation!");
3497 assert((DestClass <= cInt || DestClass == cLong) &&
3498 "Unhandled destination class for cast operation!");
3500 bool sourceUnsigned = SrcTy->isUnsigned() || SrcTy == Type::BoolTy;
3501 bool destUnsigned = DestTy->isUnsigned();
3503 // Unsigned -> Unsigned, clear if larger,
3504 if (sourceUnsigned && destUnsigned) {
3505 // handle long dest class now to keep switch clean
3506 if (DestClass == cLong) {
3507 BuildMI(*MBB, IP, PPC::LI, 1, DestReg).addSImm(0);
3508 BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(SrcReg)
3513 // handle u{ byte, short, int } x u{ byte, short, int }
3514 unsigned clearBits = (SrcClass == cByte || DestClass == cByte) ? 24 : 16;
3518 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
3519 .addImm(0).addImm(clearBits).addImm(31);
3525 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
3526 .addImm(0).addImm(clearBits).addImm(31);
3533 if (!sourceUnsigned && !destUnsigned) {
3534 // handle long dest class now to keep switch clean
3535 if (DestClass == cLong) {
3536 BuildMI(*MBB, IP, PPC::SRAWI, 2, DestReg).addReg(SrcReg).addImm(31);
3537 BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(SrcReg)
3542 // handle { byte, short, int } x { byte, short, int }
3545 BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
3548 if (DestClass == cByte)
3549 BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
3551 BuildMI(*MBB, IP, PPC::EXTSH, 1, DestReg).addReg(SrcReg);
3557 if (DestClass == cByte)
3558 BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
3559 else if (DestClass == cShort)
3560 BuildMI(*MBB, IP, PPC::EXTSH, 1, DestReg).addReg(SrcReg);
3562 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
3568 // Unsigned -> Signed
3569 if (sourceUnsigned && !destUnsigned) {
3570 // handle long dest class now to keep switch clean
3571 if (DestClass == cLong) {
3572 BuildMI(*MBB, IP, PPC::LI, 1, DestReg).addSImm(0);
3573 BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(SrcReg)
3578 // handle u{ byte, short, int } -> { byte, short, int }
3581 // uByte 255 -> signed short/int == 255
3582 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg).addImm(0)
3583 .addImm(24).addImm(31);
3586 if (DestClass == cByte)
3587 BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
3589 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg).addImm(0)
3590 .addImm(16).addImm(31);
3596 if (DestClass == cByte)
3597 BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
3598 else if (DestClass == cShort)
3599 BuildMI(*MBB, IP, PPC::EXTSH, 1, DestReg).addReg(SrcReg);
3601 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
3607 // Signed -> Unsigned
3608 if (!sourceUnsigned && destUnsigned) {
3609 // handle long dest class now to keep switch clean
3610 if (DestClass == cLong) {
3611 BuildMI(*MBB, IP, PPC::SRAWI, 2, DestReg).addReg(SrcReg).addImm(31);
3612 BuildMI(*MBB, IP, PPC::OR, 2, DestReg+1).addReg(SrcReg)
3617 // handle { byte, short, int } -> u{ byte, short, int }
3618 unsigned clearBits = (DestClass == cByte) ? 24 : 16;
3621 BuildMI(*MBB, IP, PPC::EXTSB, 1, DestReg).addReg(SrcReg);
3624 if (DestClass == cByte)
3625 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
3626 .addImm(0).addImm(clearBits).addImm(31);
3628 BuildMI(*MBB, IP, PPC::EXTSH, 1, DestReg).addReg(SrcReg);
3634 if (DestClass == cInt)
3635 BuildMI(*MBB, IP, PPC::OR, 2, DestReg).addReg(SrcReg).addReg(SrcReg);
3637 BuildMI(*MBB, IP, PPC::RLWINM, 4, DestReg).addReg(SrcReg)
3638 .addImm(0).addImm(clearBits).addImm(31);
3644 // Anything we haven't handled already, we can't (yet) handle at all.
3645 std::cerr << "Unhandled cast from " << SrcTy->getDescription()
3646 << "to " << DestTy->getDescription() << '\n';
3650 /// visitVANextInst - Implement the va_next instruction...
3652 void PPC32ISel::visitVANextInst(VANextInst &I) {
3653 unsigned VAList = getReg(I.getOperand(0));
3654 unsigned DestReg = getReg(I);
3657 switch (I.getArgType()->getTypeID()) {
3660 assert(0 && "Error: bad type for va_next instruction!");
3662 case Type::PointerTyID:
3663 case Type::UIntTyID:
3667 case Type::ULongTyID:
3668 case Type::LongTyID:
3669 case Type::DoubleTyID:
3674 // Increment the VAList pointer...
3675 BuildMI(BB, PPC::ADDI, 2, DestReg).addReg(VAList).addSImm(Size);
3678 void PPC32ISel::visitVAArgInst(VAArgInst &I) {
3679 unsigned VAList = getReg(I.getOperand(0));
3680 unsigned DestReg = getReg(I);
3682 switch (I.getType()->getTypeID()) {
3685 assert(0 && "Error: bad type for va_next instruction!");
3687 case Type::PointerTyID:
3688 case Type::UIntTyID:
3690 BuildMI(BB, PPC::LWZ, 2, DestReg).addSImm(0).addReg(VAList);
3692 case Type::ULongTyID:
3693 case Type::LongTyID:
3694 BuildMI(BB, PPC::LWZ, 2, DestReg).addSImm(0).addReg(VAList);
3695 BuildMI(BB, PPC::LWZ, 2, DestReg+1).addSImm(4).addReg(VAList);
3697 case Type::FloatTyID:
3698 BuildMI(BB, PPC::LFS, 2, DestReg).addSImm(0).addReg(VAList);
3700 case Type::DoubleTyID:
3701 BuildMI(BB, PPC::LFD, 2, DestReg).addSImm(0).addReg(VAList);
3706 /// visitGetElementPtrInst - instruction-select GEP instructions
3708 void PPC32ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
3709 if (canFoldGEPIntoLoadOrStore(&I))
3712 emitGEPOperation(BB, BB->end(), &I, false);
3715 /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
3716 /// constant expression GEP support.
3718 void PPC32ISel::emitGEPOperation(MachineBasicBlock *MBB,
3719 MachineBasicBlock::iterator IP,
3720 GetElementPtrInst *GEPI, bool GEPIsFolded) {
3721 // If we've already emitted this particular GEP, just return to avoid
3722 // multiple definitions of the base register.
3723 if (GEPIsFolded && (GEPMap[GEPI].base != 0))
3726 Value *Src = GEPI->getOperand(0);
3727 User::op_iterator IdxBegin = GEPI->op_begin()+1;
3728 User::op_iterator IdxEnd = GEPI->op_end();
3729 const TargetData &TD = TM.getTargetData();
3730 const Type *Ty = Src->getType();
3731 int64_t constValue = 0;
3733 // Record the operations to emit the GEP in a vector so that we can emit them
3734 // after having analyzed the entire instruction.
3735 std::vector<CollapsedGepOp> ops;
3737 // GEPs have zero or more indices; we must perform a struct access
3738 // or array access for each one.
3739 for (GetElementPtrInst::op_iterator oi = IdxBegin, oe = IdxEnd; oi != oe;
3742 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
3743 // It's a struct access. idx is the index into the structure,
3744 // which names the field. Use the TargetData structure to
3745 // pick out what the layout of the structure is in memory.
3746 // Use the (constant) structure index's value to find the
3747 // right byte offset from the StructLayout class's list of
3748 // structure member offsets.
3749 unsigned fieldIndex = cast<ConstantUInt>(idx)->getValue();
3751 // StructType member offsets are always constant values. Add it to the
3753 constValue += TD.getStructLayout(StTy)->MemberOffsets[fieldIndex];
3755 // The next type is the member of the structure selected by the index.
3756 Ty = StTy->getElementType (fieldIndex);
3757 } else if (const SequentialType *SqTy = dyn_cast<SequentialType>(Ty)) {
3758 // Many GEP instructions use a [cast (int/uint) to LongTy] as their
3759 // operand. Handle this case directly now...
3760 if (CastInst *CI = dyn_cast<CastInst>(idx))
3761 if (CI->getOperand(0)->getType() == Type::IntTy ||
3762 CI->getOperand(0)->getType() == Type::UIntTy)
3763 idx = CI->getOperand(0);
3765 // It's an array or pointer access: [ArraySize x ElementType].
3766 // We want to add basePtrReg to (idxReg * sizeof ElementType). First, we
3767 // must find the size of the pointed-to type (Not coincidentally, the next
3768 // type is the type of the elements in the array).
3769 Ty = SqTy->getElementType();
3770 unsigned elementSize = TD.getTypeSize(Ty);
3772 if (ConstantInt *C = dyn_cast<ConstantInt>(idx)) {
3773 if (ConstantSInt *CS = dyn_cast<ConstantSInt>(C))
3774 constValue += CS->getValue() * elementSize;
3775 else if (ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
3776 constValue += CU->getValue() * elementSize;
3778 assert(0 && "Invalid ConstantInt GEP index type!");
3780 // Push current gep state to this point as an add and multiply
3781 ops.push_back(CollapsedGepOp(
3782 ConstantSInt::get(Type::IntTy, constValue),
3783 idx, ConstantUInt::get(Type::UIntTy, elementSize)));
3789 // Emit instructions for all the collapsed ops
3790 unsigned indexReg = 0;
3791 for(std::vector<CollapsedGepOp>::iterator cgo_i = ops.begin(),
3792 cgo_e = ops.end(); cgo_i != cgo_e; ++cgo_i) {
3793 CollapsedGepOp& cgo = *cgo_i;
3795 // Avoid emitting known move instructions here for the register allocator
3796 // to deal with later. val * 1 == val. val + 0 == val.
3798 if (cgo.size->getValue() == 1) {
3799 TmpReg1 = getReg(cgo.index, MBB, IP);
3801 TmpReg1 = makeAnotherReg(Type::IntTy);
3802 doMultiplyConst(MBB, IP, TmpReg1, cgo.index, cgo.size);
3806 if (cgo.offset->isNullValue()) {
3809 TmpReg2 = makeAnotherReg(Type::IntTy);
3810 emitBinaryConstOperation(MBB, IP, TmpReg1, cgo.offset, 0, TmpReg2);
3816 unsigned TmpReg3 = makeAnotherReg(Type::IntTy);
3817 BuildMI(*MBB, IP, PPC::ADD, 2, TmpReg3).addReg(indexReg).addReg(TmpReg2);
3822 // We now have a base register, an index register, and possibly a constant
3823 // remainder. If the GEP is going to be folded, we try to generate the
3824 // optimal addressing mode.
3825 ConstantSInt *remainder = ConstantSInt::get(Type::IntTy, constValue);
3827 // If we are emitting this during a fold, copy the current base register to
3828 // the target, and save the current constant offset so the folding load or
3829 // store can try and use it as an immediate.
3831 if (indexReg == 0) {
3832 if (!canUseAsImmediateForOpcode(remainder, 0, false)) {
3833 indexReg = getReg(remainder, MBB, IP);
3836 } else if (!remainder->isNullValue()) {
3837 unsigned TmpReg = makeAnotherReg(Type::IntTy);
3838 emitBinaryConstOperation(MBB, IP, indexReg, remainder, 0, TmpReg);
3842 unsigned basePtrReg = getReg(Src, MBB, IP);
3843 GEPMap[GEPI] = FoldedGEP(basePtrReg, indexReg, remainder);
3847 // We're not folding, so collapse the base, index, and any remainder into the
3848 // destination register.
3849 unsigned TargetReg = getReg(GEPI, MBB, IP);
3850 unsigned basePtrReg = getReg(Src, MBB, IP);
3852 if ((indexReg == 0) && remainder->isNullValue()) {
3853 BuildMI(*MBB, IP, PPC::OR, 2, TargetReg).addReg(basePtrReg)
3854 .addReg(basePtrReg);
3857 if (!remainder->isNullValue()) {
3858 unsigned TmpReg = (indexReg == 0) ? TargetReg : makeAnotherReg(Type::IntTy);
3859 emitBinaryConstOperation(MBB, IP, basePtrReg, remainder, 0, TmpReg);
3860 basePtrReg = TmpReg;
3863 BuildMI(*MBB, IP, PPC::ADD, 2, TargetReg).addReg(indexReg)
3864 .addReg(basePtrReg);
3867 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
3868 /// frame manager, otherwise do it the hard way.
3870 void PPC32ISel::visitAllocaInst(AllocaInst &I) {
3871 // If this is a fixed size alloca in the entry block for the function, we
3872 // statically stack allocate the space, so we don't need to do anything here.
3874 if (dyn_castFixedAlloca(&I)) return;
3876 // Find the data size of the alloca inst's getAllocatedType.
3877 const Type *Ty = I.getAllocatedType();
3878 unsigned TySize = TM.getTargetData().getTypeSize(Ty);
3880 // Create a register to hold the temporary result of multiplying the type size
3881 // constant by the variable amount.
3882 unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
3884 // TotalSizeReg = mul <numelements>, <TypeSize>
3885 MachineBasicBlock::iterator MBBI = BB->end();
3886 ConstantUInt *CUI = ConstantUInt::get(Type::UIntTy, TySize);
3887 doMultiplyConst(BB, MBBI, TotalSizeReg, I.getArraySize(), CUI);
3889 // AddedSize = add <TotalSizeReg>, 15
3890 unsigned AddedSizeReg = makeAnotherReg(Type::UIntTy);
3891 BuildMI(BB, PPC::ADDI, 2, AddedSizeReg).addReg(TotalSizeReg).addSImm(15);
3893 // AlignedSize = and <AddedSize>, ~15
3894 unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
3895 BuildMI(BB, PPC::RLWINM, 4, AlignedSize).addReg(AddedSizeReg).addImm(0)
3896 .addImm(0).addImm(27);
3898 // Subtract size from stack pointer, thereby allocating some space.
3899 BuildMI(BB, PPC::SUB, 2, PPC::R1).addReg(PPC::R1).addReg(AlignedSize);
3901 // Put a pointer to the space into the result register, by copying
3902 // the stack pointer.
3903 BuildMI(BB, PPC::OR, 2, getReg(I)).addReg(PPC::R1).addReg(PPC::R1);
3905 // Inform the Frame Information that we have just allocated a variable-sized
3907 F->getFrameInfo()->CreateVariableSizedObject();
3910 /// visitMallocInst - Malloc instructions are code generated into direct calls
3911 /// to the library malloc.
3913 void PPC32ISel::visitMallocInst(MallocInst &I) {
3914 unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
3917 if (ConstantUInt *C = dyn_cast<ConstantUInt>(I.getOperand(0))) {
3918 Arg = getReg(ConstantUInt::get(Type::UIntTy, C->getValue() * AllocSize));
3920 Arg = makeAnotherReg(Type::UIntTy);
3921 MachineBasicBlock::iterator MBBI = BB->end();
3922 ConstantUInt *CUI = ConstantUInt::get(Type::UIntTy, AllocSize);
3923 doMultiplyConst(BB, MBBI, Arg, I.getOperand(0), CUI);
3926 std::vector<ValueRecord> Args;
3927 Args.push_back(ValueRecord(Arg, Type::UIntTy));
3928 MachineInstr *TheCall =
3929 BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(mallocFn, true);
3930 doCall(ValueRecord(getReg(I), I.getType()), TheCall, Args, false);
3931 TM.CalledFunctions.insert(mallocFn);
3934 /// visitFreeInst - Free instructions are code gen'd to call the free libc
3937 void PPC32ISel::visitFreeInst(FreeInst &I) {
3938 std::vector<ValueRecord> Args;
3939 Args.push_back(ValueRecord(I.getOperand(0)));
3940 MachineInstr *TheCall =
3941 BuildMI(PPC::CALLpcrel, 1).addGlobalAddress(freeFn, true);
3942 doCall(ValueRecord(0, Type::VoidTy), TheCall, Args, false);
3943 TM.CalledFunctions.insert(freeFn);
3946 /// createPPC32ISelSimple - This pass converts an LLVM function into a machine
3947 /// code representation is a very simple peep-hole fashion.
3949 FunctionPass *llvm::createPPC32ISelSimple(TargetMachine &TM) {
3950 return new PPC32ISel(TM);