1 //***************************************************************************
3 // InstrSelectionSupport.h
6 // Target-independent instruction selection code.
7 // See SparcInstrSelection.cpp for usage.
10 // 10/10/01 - Vikram Adve - Created
11 //**************************************************************************/
13 #include "llvm/CodeGen/InstrSelectionSupport.h"
14 #include "llvm/CodeGen/InstrSelection.h"
15 #include "llvm/CodeGen/MachineInstr.h"
16 #include "llvm/CodeGen/MachineInstrAnnot.h"
17 #include "llvm/CodeGen/MachineCodeForInstruction.h"
18 #include "llvm/CodeGen/MachineCodeForMethod.h"
19 #include "llvm/CodeGen/InstrForest.h"
20 #include "llvm/Target/TargetMachine.h"
21 #include "llvm/Target/MachineRegInfo.h"
22 #include "llvm/Constants.h"
23 #include "llvm/Function.h"
24 #include "llvm/BasicBlock.h"
25 #include "llvm/Type.h"
26 #include "llvm/iMemory.h"
29 //*************************** Local Functions ******************************/
32 // Generate code to load the constant into a TmpInstruction (virtual reg) and
33 // returns the virtual register.
35 static TmpInstruction*
36 InsertCodeToLoadConstant(Function *F,
39 vector<MachineInstr*>& loadConstVec,
40 TargetMachine& target)
42 // Create a tmp virtual register to hold the constant.
43 TmpInstruction* tmpReg = new TmpInstruction(opValue);
44 MachineCodeForInstruction &mcfi = MachineCodeForInstruction::get(vmInstr);
47 target.getInstrInfo().CreateCodeToLoadConst(target, F, opValue, tmpReg,
50 // Record the mapping from the tmp VM instruction to machine instruction.
51 // Do this for all machine instructions that were not mapped to any
52 // other temp values created by
53 // tmpReg->addMachineInstruction(loadConstVec.back());
59 //---------------------------------------------------------------------------
60 // Function GetConstantValueAsUnsignedInt
61 // Function GetConstantValueAsSignedInt
63 // Convenience functions to get the value of an integral constant, for an
64 // appropriate integer or non-integer type that can be held in a signed
65 // or unsigned integer respectively. The type of the argument must be
67 // Signed or unsigned integer
71 // isValidConstant is set to true if a valid constant was found.
72 //---------------------------------------------------------------------------
75 GetConstantValueAsUnsignedInt(const Value *V,
76 bool &isValidConstant)
78 isValidConstant = true;
81 if (V->getType() == Type::BoolTy)
82 return (int64_t) cast<ConstantBool>(V)->getValue();
83 else if (V->getType()->isIntegral())
84 return (V->getType()->isUnsigned()
85 ? cast<ConstantUInt>(V)->getValue()
86 : (uint64_t) cast<ConstantSInt>(V)->getValue());
88 isValidConstant = false;
93 GetConstantValueAsSignedInt(const Value *V,
94 bool &isValidConstant)
96 uint64_t C = GetConstantValueAsUnsignedInt(V, isValidConstant);
97 if (isValidConstant) {
98 if (V->getType()->isSigned() || C < INT64_MAX) // 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 = cast<MemAccessInst>(ptrChild->getValue());
138 MemAccessInst::op_iterator OI, firstIdx = getElemInst->idx_begin();
139 MemAccessInst::op_iterator lastIdx = getElemInst->idx_end();
140 bool allConstantOffsets = true;
142 // Check that all offsets are constant for this instruction
143 for (OI = firstIdx; allConstantOffsets && OI != lastIdx; ++OI)
144 allConstantOffsets = isa<ConstantInt>(*OI);
146 if (allConstantOffsets)
147 { // Get pointer value out of ptrChild.
148 ptrVal = getElemInst->getPointerOperand();
150 // Check for a leading [0] index, if any. It will be discarded later.
151 ConstantUInt* CV = dyn_cast<ConstantUInt>((Value*) *firstIdx);
152 hasLeadingZero = bool(CV && CV->getValue() == 0);
154 // Insert its index vector at the start, skipping any leading [0]
155 chainIdxVec.insert(chainIdxVec.begin(),
156 firstIdx + hasLeadingZero, lastIdx);
158 // Mark the folded node so no code is generated for it.
159 ((InstructionNode*) ptrChild)->markFoldedIntoParent();
161 else // cannot fold this getElementPtr instr. or any further ones
164 ptrChild = ptrChild->leftChild();
167 // If the first getElementPtr instruction had a leading [0], add it back.
168 // Note that this instruction is the *last* one successfully folded above.
169 if (ptrVal && hasLeadingZero)
170 chainIdxVec.insert(chainIdxVec.begin(), ConstantUInt::get(Type::UIntTy,0));
176 //------------------------------------------------------------------------
177 // Function Set2OperandsFromInstr
178 // Function Set3OperandsFromInstr
180 // For the common case of 2- and 3-operand arithmetic/logical instructions,
181 // set the m/c instr. operands directly from the VM instruction's operands.
182 // Check whether the first or second operand is 0 and can use a dedicated "0"
184 // Check whether the second operand should use an immediate field or register.
185 // (First and third operands are never immediates for such instructions.)
188 // canDiscardResult: Specifies that the result operand can be discarded
189 // by using the dedicated "0"
191 // op1position, op2position and resultPosition: Specify in which position
192 // in the machine instruction the 3 operands (arg1, arg2
193 // and result) should go.
195 //------------------------------------------------------------------------
198 Set2OperandsFromInstr(MachineInstr* minstr,
199 InstructionNode* vmInstrNode,
200 const TargetMachine& target,
201 bool canDiscardResult,
205 Set3OperandsFromInstr(minstr, vmInstrNode, target,
206 canDiscardResult, op1Position,
207 /*op2Position*/ -1, resultPosition);
212 Set3OperandsFromInstr(MachineInstr* minstr,
213 InstructionNode* vmInstrNode,
214 const TargetMachine& target,
215 bool canDiscardResult,
220 assert(op1Position >= 0);
221 assert(resultPosition >= 0);
224 minstr->SetMachineOperandVal(op1Position, MachineOperand::MO_VirtualRegister,
225 vmInstrNode->leftChild()->getValue());
227 // operand 2 (if any)
228 if (op2Position >= 0)
229 minstr->SetMachineOperandVal(op2Position, MachineOperand::MO_VirtualRegister,
230 vmInstrNode->rightChild()->getValue());
232 // result operand: if it can be discarded, use a dead register if one exists
233 if (canDiscardResult && target.getRegInfo().getZeroRegNum() >= 0)
234 minstr->SetMachineOperandReg(resultPosition,
235 target.getRegInfo().getZeroRegNum());
237 minstr->SetMachineOperandVal(resultPosition,
238 MachineOperand::MO_VirtualRegister, vmInstrNode->getValue());
242 MachineOperand::MachineOperandType
243 ChooseRegOrImmed(Value* val,
244 MachineOpCode opCode,
245 const TargetMachine& target,
247 unsigned int& getMachineRegNum,
248 int64_t& getImmedValue)
250 MachineOperand::MachineOperandType opType =
251 MachineOperand::MO_VirtualRegister;
252 getMachineRegNum = 0;
255 // Check for the common case first: argument is not constant
257 Constant *CPV = dyn_cast<Constant>(val);
258 if (!CPV) return opType;
260 if (ConstantBool *CPB = dyn_cast<ConstantBool>(CPV))
262 if (!CPB->getValue() && target.getRegInfo().getZeroRegNum() >= 0)
264 getMachineRegNum = target.getRegInfo().getZeroRegNum();
265 return MachineOperand::MO_MachineRegister;
269 return MachineOperand::MO_SignExtendedImmed;
272 // Otherwise it needs to be an integer or a NULL pointer
273 if (! CPV->getType()->isIntegral() &&
274 ! (isa<PointerType>(CPV->getType()) &&
278 // Now get the constant value and check if it fits in the IMMED field.
279 // Take advantage of the fact that the max unsigned value will rarely
280 // fit into any IMMED field and ignore that case (i.e., cast smaller
281 // unsigned constants to signed).
284 if (isa<PointerType>(CPV->getType()))
288 else if (CPV->getType()->isSigned())
290 intValue = cast<ConstantSInt>(CPV)->getValue();
294 uint64_t V = cast<ConstantUInt>(CPV)->getValue();
295 if (V >= INT64_MAX) return opType;
296 intValue = (int64_t)V;
299 if (intValue == 0 && target.getRegInfo().getZeroRegNum() >= 0)
301 opType = MachineOperand::MO_MachineRegister;
302 getMachineRegNum = target.getRegInfo().getZeroRegNum();
304 else if (canUseImmed &&
305 target.getInstrInfo().constantFitsInImmedField(opCode, intValue))
307 opType = CPV->getType()->isSigned()
308 ? MachineOperand::MO_SignExtendedImmed
309 : MachineOperand::MO_UnextendedImmed;
310 getImmedValue = intValue;
317 //---------------------------------------------------------------------------
318 // Function: FixConstantOperandsForInstr
321 // Special handling for constant operands of a machine instruction
322 // -- if the constant is 0, use the hardwired 0 register, if any;
323 // -- if the constant fits in the IMMEDIATE field, use that field;
324 // -- else create instructions to put the constant into a register, either
325 // directly or by loading explicitly from the constant pool.
327 // In the first 2 cases, the operand of `minstr' is modified in place.
328 // Returns a vector of machine instructions generated for operands that
329 // fall under case 3; these must be inserted before `minstr'.
330 //---------------------------------------------------------------------------
332 vector<MachineInstr*>
333 FixConstantOperandsForInstr(Instruction* vmInstr,
334 MachineInstr* minstr,
335 TargetMachine& target)
337 vector<MachineInstr*> loadConstVec;
339 const MachineInstrDescriptor& instrDesc =
340 target.getInstrInfo().getDescriptor(minstr->getOpCode());
342 Function *F = vmInstr->getParent()->getParent();
344 for (unsigned op=0; op < minstr->getNumOperands(); op++)
346 const MachineOperand& mop = minstr->getOperand(op);
348 // skip the result position (for efficiency below) and any other
349 // positions already marked as not a virtual register
350 if (instrDesc.resultPos == (int) op ||
351 mop.getOperandType() != MachineOperand::MO_VirtualRegister ||
352 mop.getVRegValue() == NULL)
357 Value* opValue = mop.getVRegValue();
358 bool constantThatMustBeLoaded = false;
360 if (Constant *opConst = dyn_cast<Constant>(opValue))
362 unsigned int machineRegNum;
364 MachineOperand::MachineOperandType opType =
365 ChooseRegOrImmed(opValue, minstr->getOpCode(), target,
366 (target.getInstrInfo().getImmedConstantPos(minstr->getOpCode()) == (int) op),
367 machineRegNum, immedValue);
369 if (opType == MachineOperand::MO_MachineRegister)
370 minstr->SetMachineOperandReg(op, machineRegNum);
371 else if (opType == MachineOperand::MO_VirtualRegister)
372 constantThatMustBeLoaded = true; // load is generated below
374 minstr->SetMachineOperandConst(op, opType, immedValue);
377 if (constantThatMustBeLoaded || isa<GlobalValue>(opValue))
378 { // opValue is a constant that must be explicitly loaded into a reg.
379 TmpInstruction* tmpReg = InsertCodeToLoadConstant(F, opValue,vmInstr,
382 minstr->SetMachineOperandVal(op, MachineOperand::MO_VirtualRegister,
388 // Also, check for implicit operands used by the machine instruction
389 // (no need to check those defined since they cannot be constants).
391 // -- arguments to a Call
392 // -- return value of a Return
393 // Any such operand that is a constant value needs to be fixed also.
394 // The current instructions with implicit refs (viz., Call and Return)
395 // have no immediate fields, so the constant always needs to be loaded
398 bool isCall = target.getInstrInfo().isCall(minstr->getOpCode());
399 unsigned lastCallArgNum = 0; // unused if not a call
400 CallArgsDescriptor* argDesc = NULL; // unused if not a call
402 argDesc = CallArgsDescriptor::get(minstr);
404 for (unsigned i=0, N=minstr->getNumImplicitRefs(); i < N; ++i)
405 if (isa<Constant>(minstr->getImplicitRef(i)) ||
406 isa<GlobalValue>(minstr->getImplicitRef(i)))
408 Value* oldVal = minstr->getImplicitRef(i);
409 TmpInstruction* tmpReg =
410 InsertCodeToLoadConstant(F, oldVal, vmInstr, loadConstVec, target);
411 minstr->setImplicitRef(i, tmpReg);
414 { // find and replace the argument in the CallArgsDescriptor
415 unsigned i=lastCallArgNum;
416 while (argDesc->getArgInfo(i).getArgVal() != oldVal)
418 assert(i < argDesc->getNumArgs() &&
419 "Constant operands to a call *must* be in the arg list");
421 argDesc->getArgInfo(i).replaceArgVal(tmpReg);