2 //***************************************************************************
4 // InstrSelectionSupport.h
7 // Target-independent instruction selection code.
8 // See SparcInstrSelection.cpp for usage.
11 // 10/10/01 - Vikram Adve - Created
12 //**************************************************************************/
14 #include "llvm/CodeGen/InstrSelectionSupport.h"
15 #include "llvm/CodeGen/InstrSelection.h"
16 #include "llvm/CodeGen/MachineInstr.h"
17 #include "llvm/CodeGen/MachineInstrAnnot.h"
18 #include "llvm/CodeGen/MachineCodeForInstruction.h"
19 #include "llvm/CodeGen/MachineCodeForMethod.h"
20 #include "llvm/CodeGen/InstrForest.h"
21 #include "llvm/Target/TargetMachine.h"
22 #include "llvm/Target/MachineRegInfo.h"
23 #include "llvm/Constants.h"
24 #include "llvm/Function.h"
25 #include "llvm/BasicBlock.h"
26 #include "llvm/Type.h"
27 #include "llvm/iMemory.h"
30 //*************************** Local Functions ******************************/
33 // Generate code to load the constant into a TmpInstruction (virtual reg) and
34 // returns the virtual register.
36 static TmpInstruction*
37 InsertCodeToLoadConstant(Function *F,
40 vector<MachineInstr*>& loadConstVec,
41 TargetMachine& target)
43 vector<TmpInstruction*> tempVec;
45 // Create a tmp virtual register to hold the constant.
46 TmpInstruction* tmpReg = new TmpInstruction(opValue);
47 MachineCodeForInstruction &mcfi = MachineCodeForInstruction::get(vmInstr);
50 target.getInstrInfo().CreateCodeToLoadConst(target, F, opValue, tmpReg,
53 // Record the mapping from the tmp VM instruction to machine instruction.
54 // Do this for all machine instructions that were not mapped to any
55 // other temp values created by
56 // tmpReg->addMachineInstruction(loadConstVec.back());
62 //---------------------------------------------------------------------------
63 // Function GetConstantValueAsSignedInt
65 // Convenience function to get the value of an integer constant, for an
66 // appropriate integer or non-integer type that can be held in an integer.
67 // The type of the argument must be the following:
68 // Signed or unsigned integer
72 // isValidConstant is set to true if a valid constant was found.
73 //---------------------------------------------------------------------------
76 GetConstantValueAsSignedInt(const Value *V,
77 bool &isValidConstant)
79 if (!isa<Constant>(V))
81 isValidConstant = false;
85 isValidConstant = true;
87 if (V->getType() == Type::BoolTy)
88 return (int64_t) cast<ConstantBool>(V)->getValue();
90 if (V->getType()->isIntegral())
92 if (V->getType()->isSigned())
93 return cast<ConstantSInt>(V)->getValue();
95 assert(V->getType()->isUnsigned());
96 uint64_t Val = cast<ConstantUInt>(V)->getValue();
97 if (Val < INT64_MAX) // then safe to cast to signed
101 isValidConstant = false;
106 //---------------------------------------------------------------------------
107 // Function: FoldGetElemChain
110 // Fold a chain of GetElementPtr instructions containing only
111 // constant offsets into an equivalent (Pointer, IndexVector) pair.
112 // Returns the pointer Value, and stores the resulting IndexVector
113 // in argument chainIdxVec.
114 //---------------------------------------------------------------------------
117 FoldGetElemChain(const InstructionNode* getElemInstrNode,
118 vector<Value*>& chainIdxVec)
120 MemAccessInst* getElemInst = (MemAccessInst*)
121 getElemInstrNode->getInstruction();
123 // Return NULL if we don't fold any instructions in.
124 Value* ptrVal = NULL;
126 // Remember if the last instruction had a leading [0] index.
127 bool hasLeadingZero = false;
129 // Now chase the chain of getElementInstr instructions, if any.
130 // Check for any non-constant indices and stop there.
132 const InstrTreeNode* ptrChild = getElemInstrNode;
133 while (ptrChild->getOpLabel() == Instruction::GetElementPtr ||
134 ptrChild->getOpLabel() == GetElemPtrIdx)
136 // Child is a GetElemPtr instruction
137 getElemInst = (MemAccessInst*)
138 ((InstructionNode*) ptrChild)->getInstruction();
139 const vector<Value*>& idxVec = getElemInst->copyIndices();
140 bool allConstantOffsets = true;
142 // Check for a leading [0] index, if any. It will be discarded later.
143 ConstantUInt* CV = dyn_cast<ConstantUInt>(idxVec[0]);
144 hasLeadingZero = bool(CV && CV->getType() == Type::UIntTy &&
145 (CV->getValue() == 0));
147 // Check that all offsets are constant for this instruction
148 for (unsigned int i=0; i < idxVec.size(); i++)
149 if (! isa<ConstantUInt>(idxVec[i]))
151 allConstantOffsets = false;
155 if (allConstantOffsets)
156 { // Get pointer value out of ptrChild.
157 ptrVal = getElemInst->getPointerOperand();
159 // Insert its index vector at the start.
160 chainIdxVec.insert(chainIdxVec.begin(),
161 idxVec.begin() + (hasLeadingZero? 1:0),
164 // Mark the folded node so no code is generated for it.
165 ((InstructionNode*) ptrChild)->markFoldedIntoParent();
167 else // cannot fold this getElementPtr instr. or any further ones
170 ptrChild = ptrChild->leftChild();
173 // If the first getElementPtr instruction had a leading [0], add it back.
174 // Note that this instruction is the *last* one handled above.
176 chainIdxVec.insert(chainIdxVec.begin(), ConstantUInt::get(Type::UIntTy,0));
182 //------------------------------------------------------------------------
183 // Function Set2OperandsFromInstr
184 // Function Set3OperandsFromInstr
186 // For the common case of 2- and 3-operand arithmetic/logical instructions,
187 // set the m/c instr. operands directly from the VM instruction's operands.
188 // Check whether the first or second operand is 0 and can use a dedicated "0"
190 // Check whether the second operand should use an immediate field or register.
191 // (First and third operands are never immediates for such instructions.)
194 // canDiscardResult: Specifies that the result operand can be discarded
195 // by using the dedicated "0"
197 // op1position, op2position and resultPosition: Specify in which position
198 // in the machine instruction the 3 operands (arg1, arg2
199 // and result) should go.
201 //------------------------------------------------------------------------
204 Set2OperandsFromInstr(MachineInstr* minstr,
205 InstructionNode* vmInstrNode,
206 const TargetMachine& target,
207 bool canDiscardResult,
211 Set3OperandsFromInstr(minstr, vmInstrNode, target,
212 canDiscardResult, op1Position,
213 /*op2Position*/ -1, resultPosition);
218 Set3OperandsFromInstr(MachineInstr* minstr,
219 InstructionNode* vmInstrNode,
220 const TargetMachine& target,
221 bool canDiscardResult,
226 assert(op1Position >= 0);
227 assert(resultPosition >= 0);
230 minstr->SetMachineOperandVal(op1Position, MachineOperand::MO_VirtualRegister,
231 vmInstrNode->leftChild()->getValue());
233 // operand 2 (if any)
234 if (op2Position >= 0)
235 minstr->SetMachineOperandVal(op2Position, MachineOperand::MO_VirtualRegister,
236 vmInstrNode->rightChild()->getValue());
238 // result operand: if it can be discarded, use a dead register if one exists
239 if (canDiscardResult && target.getRegInfo().getZeroRegNum() >= 0)
240 minstr->SetMachineOperandReg(resultPosition,
241 target.getRegInfo().getZeroRegNum());
243 minstr->SetMachineOperandVal(resultPosition,
244 MachineOperand::MO_VirtualRegister, vmInstrNode->getValue());
248 MachineOperand::MachineOperandType
249 ChooseRegOrImmed(Value* val,
250 MachineOpCode opCode,
251 const TargetMachine& target,
253 unsigned int& getMachineRegNum,
254 int64_t& getImmedValue)
256 MachineOperand::MachineOperandType opType =
257 MachineOperand::MO_VirtualRegister;
258 getMachineRegNum = 0;
261 // Check for the common case first: argument is not constant
263 Constant *CPV = dyn_cast<Constant>(val);
264 if (!CPV) return opType;
266 if (ConstantBool *CPB = dyn_cast<ConstantBool>(CPV))
268 if (!CPB->getValue() && target.getRegInfo().getZeroRegNum() >= 0)
270 getMachineRegNum = target.getRegInfo().getZeroRegNum();
271 return MachineOperand::MO_MachineRegister;
275 return MachineOperand::MO_SignExtendedImmed;
278 // Otherwise it needs to be an integer or a NULL pointer
279 if (! CPV->getType()->isIntegral() &&
280 ! (isa<PointerType>(CPV->getType()) &&
284 // Now get the constant value and check if it fits in the IMMED field.
285 // Take advantage of the fact that the max unsigned value will rarely
286 // fit into any IMMED field and ignore that case (i.e., cast smaller
287 // unsigned constants to signed).
290 if (isa<PointerType>(CPV->getType()))
294 else if (CPV->getType()->isSigned())
296 intValue = cast<ConstantSInt>(CPV)->getValue();
300 uint64_t V = cast<ConstantUInt>(CPV)->getValue();
301 if (V >= INT64_MAX) return opType;
302 intValue = (int64_t)V;
305 if (intValue == 0 && target.getRegInfo().getZeroRegNum() >= 0)
307 opType = MachineOperand::MO_MachineRegister;
308 getMachineRegNum = target.getRegInfo().getZeroRegNum();
310 else if (canUseImmed &&
311 target.getInstrInfo().constantFitsInImmedField(opCode, intValue))
313 opType = CPV->getType()->isSigned()
314 ? MachineOperand::MO_SignExtendedImmed
315 : MachineOperand::MO_UnextendedImmed;
316 getImmedValue = intValue;
323 //---------------------------------------------------------------------------
324 // Function: FixConstantOperandsForInstr
327 // Special handling for constant operands of a machine instruction
328 // -- if the constant is 0, use the hardwired 0 register, if any;
329 // -- if the constant fits in the IMMEDIATE field, use that field;
330 // -- else create instructions to put the constant into a register, either
331 // directly or by loading explicitly from the constant pool.
333 // In the first 2 cases, the operand of `minstr' is modified in place.
334 // Returns a vector of machine instructions generated for operands that
335 // fall under case 3; these must be inserted before `minstr'.
336 //---------------------------------------------------------------------------
338 vector<MachineInstr*>
339 FixConstantOperandsForInstr(Instruction* vmInstr,
340 MachineInstr* minstr,
341 TargetMachine& target)
343 vector<MachineInstr*> loadConstVec;
345 const MachineInstrDescriptor& instrDesc =
346 target.getInstrInfo().getDescriptor(minstr->getOpCode());
348 Function *F = vmInstr->getParent()->getParent();
350 for (unsigned op=0; op < minstr->getNumOperands(); op++)
352 const MachineOperand& mop = minstr->getOperand(op);
354 // skip the result position (for efficiency below) and any other
355 // positions already marked as not a virtual register
356 if (instrDesc.resultPos == (int) op ||
357 mop.getOperandType() != MachineOperand::MO_VirtualRegister ||
358 mop.getVRegValue() == NULL)
363 Value* opValue = mop.getVRegValue();
364 bool constantThatMustBeLoaded = false;
366 if (Constant *opConst = dyn_cast<Constant>(opValue))
368 unsigned int machineRegNum;
370 MachineOperand::MachineOperandType opType =
371 ChooseRegOrImmed(opValue, minstr->getOpCode(), target,
372 (target.getInstrInfo().getImmedConstantPos(minstr->getOpCode()) == (int) op),
373 machineRegNum, immedValue);
375 if (opType == MachineOperand::MO_MachineRegister)
376 minstr->SetMachineOperandReg(op, machineRegNum);
377 else if (opType == MachineOperand::MO_VirtualRegister)
378 constantThatMustBeLoaded = true; // load is generated below
380 minstr->SetMachineOperandConst(op, opType, immedValue);
383 if (constantThatMustBeLoaded || isa<GlobalValue>(opValue))
384 { // opValue is a constant that must be explicitly loaded into a reg.
385 TmpInstruction* tmpReg = InsertCodeToLoadConstant(F, opValue,vmInstr,
388 minstr->SetMachineOperandVal(op, MachineOperand::MO_VirtualRegister,
394 // Also, check for implicit operands used by the machine instruction
395 // (no need to check those defined since they cannot be constants).
397 // -- arguments to a Call
398 // -- return value of a Return
399 // Any such operand that is a constant value needs to be fixed also.
400 // The current instructions with implicit refs (viz., Call and Return)
401 // have no immediate fields, so the constant always needs to be loaded
404 bool isCall = target.getInstrInfo().isCall(minstr->getOpCode());
405 unsigned lastCallArgNum = 0; // unused if not a call
406 CallArgsDescriptor* argDesc = NULL; // unused if not a call
408 argDesc = CallArgsDescriptor::get(minstr);
410 for (unsigned i=0, N=minstr->getNumImplicitRefs(); i < N; ++i)
411 if (isa<Constant>(minstr->getImplicitRef(i)) ||
412 isa<GlobalValue>(minstr->getImplicitRef(i)))
414 Value* oldVal = minstr->getImplicitRef(i);
415 TmpInstruction* tmpReg =
416 InsertCodeToLoadConstant(F, oldVal, vmInstr, loadConstVec, target);
417 minstr->setImplicitRef(i, tmpReg);
420 { // find and replace the argument in the CallArgsDescriptor
421 unsigned i=lastCallArgNum;
422 while (argDesc->getArgInfo(i).getArgVal() != oldVal)
424 assert(i < argDesc->getNumArgs() &&
425 "Constant operands to a call *must* be in the arg list");
427 argDesc->getArgInfo(i).replaceArgVal(tmpReg);