blob: bc725865c2ec86a3483fcc202f61672bc3a0cf47 [file] [log] [blame]
Justin Holewinskiae556d32012-05-04 20:18:50 +00001//===-- NVPTXAsmPrinter.cpp - NVPTX LLVM assembly writer ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains a printer that converts from our internal representation
11// of machine-dependent LLVM code to NVPTX assembly language.
12//
13//===----------------------------------------------------------------------===//
14
Bill Wendlinge38859d2012-06-28 00:05:13 +000015#include "NVPTXAsmPrinter.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000016#include "InstPrinter/NVPTXInstPrinter.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "MCTargetDesc/NVPTXMCAsmInfo.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000018#include "NVPTX.h"
19#include "NVPTXInstrInfo.h"
Justin Holewinskia2a63d22013-08-06 14:13:27 +000020#include "NVPTXMCExpr.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "NVPTXRegisterInfo.h"
22#include "NVPTXTargetMachine.h"
23#include "NVPTXUtilities.h"
24#include "cl_common_defines.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000025#include "llvm/ADT/StringExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/Analysis/ConstantFolding.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000027#include "llvm/CodeGen/Analysis.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000028#include "llvm/CodeGen/MachineFrameInfo.h"
29#include "llvm/CodeGen/MachineModuleInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/CodeGen/MachineRegisterInfo.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000031#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/DerivedTypes.h"
33#include "llvm/IR/Function.h"
34#include "llvm/IR/GlobalVariable.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000035#include "llvm/IR/Mangler.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#include "llvm/IR/Module.h"
37#include "llvm/IR/Operator.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000038#include "llvm/MC/MCStreamer.h"
39#include "llvm/MC/MCSymbol.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000040#include "llvm/Support/CommandLine.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000041#include "llvm/Support/ErrorHandling.h"
42#include "llvm/Support/FormattedStream.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000043#include "llvm/Support/Path.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000044#include "llvm/Support/TargetRegistry.h"
45#include "llvm/Support/TimeValue.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000046#include "llvm/Target/TargetLoweringObjectFile.h"
Bill Wendlinge38859d2012-06-28 00:05:13 +000047#include <sstream>
Justin Holewinskiae556d32012-05-04 20:18:50 +000048using namespace llvm;
49
Justin Holewinskiae556d32012-05-04 20:18:50 +000050#define DEPOTNAME "__local_depot"
51
52static cl::opt<bool>
Nadav Rotem7f27e0b2013-10-18 23:38:13 +000053EmitLineNumbers("nvptx-emit-line-numbers", cl::Hidden,
Justin Holewinskiae556d32012-05-04 20:18:50 +000054 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
55 cl::init(true));
56
Benjamin Kramer7ad41002013-10-27 11:31:46 +000057static cl::opt<bool>
Nadav Rotem7f27e0b2013-10-18 23:38:13 +000058InterleaveSrc("nvptx-emit-src", cl::ZeroOrMore, cl::Hidden,
Justin Holewinski0497ab12013-03-30 14:29:21 +000059 cl::desc("NVPTX Specific: Emit source line in ptx file"),
Benjamin Kramer7ad41002013-10-27 11:31:46 +000060 cl::init(false));
Justin Holewinskiae556d32012-05-04 20:18:50 +000061
Justin Holewinski2c5ac702012-11-16 21:03:51 +000062namespace {
63/// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
64/// depends.
Justin Holewinski01f89f02013-05-20 12:13:32 +000065void DiscoverDependentGlobals(const Value *V,
66 DenseSet<const GlobalVariable *> &Globals) {
67 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
Justin Holewinski2c5ac702012-11-16 21:03:51 +000068 Globals.insert(GV);
69 else {
Justin Holewinski01f89f02013-05-20 12:13:32 +000070 if (const User *U = dyn_cast<User>(V)) {
Justin Holewinski2c5ac702012-11-16 21:03:51 +000071 for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
72 DiscoverDependentGlobals(U->getOperand(i), Globals);
73 }
74 }
75 }
76}
Justin Holewinskiae556d32012-05-04 20:18:50 +000077
Justin Holewinski2c5ac702012-11-16 21:03:51 +000078/// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
79/// instances to be emitted, but only after any dependents have been added
80/// first.
Justin Holewinski0497ab12013-03-30 14:29:21 +000081void VisitGlobalVariableForEmission(
Justin Holewinski01f89f02013-05-20 12:13:32 +000082 const GlobalVariable *GV, SmallVectorImpl<const GlobalVariable *> &Order,
83 DenseSet<const GlobalVariable *> &Visited,
84 DenseSet<const GlobalVariable *> &Visiting) {
Justin Holewinski2c5ac702012-11-16 21:03:51 +000085 // Have we already visited this one?
Justin Holewinski0497ab12013-03-30 14:29:21 +000086 if (Visited.count(GV))
87 return;
Justin Holewinski2c5ac702012-11-16 21:03:51 +000088
89 // Do we have a circular dependency?
90 if (Visiting.count(GV))
91 report_fatal_error("Circular dependency found in global variable set");
92
93 // Start visiting this global
94 Visiting.insert(GV);
95
96 // Make sure we visit all dependents first
Justin Holewinski01f89f02013-05-20 12:13:32 +000097 DenseSet<const GlobalVariable *> Others;
Justin Holewinski2c5ac702012-11-16 21:03:51 +000098 for (unsigned i = 0, e = GV->getNumOperands(); i != e; ++i)
99 DiscoverDependentGlobals(GV->getOperand(i), Others);
Justin Holewinski0497ab12013-03-30 14:29:21 +0000100
Justin Holewinski01f89f02013-05-20 12:13:32 +0000101 for (DenseSet<const GlobalVariable *>::iterator I = Others.begin(),
102 E = Others.end();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000103 I != E; ++I)
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000104 VisitGlobalVariableForEmission(*I, Order, Visited, Visiting);
105
106 // Now we can visit ourself
107 Order.push_back(GV);
108 Visited.insert(GV);
109 Visiting.erase(GV);
110}
111}
Justin Holewinskiae556d32012-05-04 20:18:50 +0000112
113// @TODO: This is a copy from AsmPrinter.cpp. The function is static, so we
114// cannot just link to the existing version.
115/// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
116///
117using namespace nvptx;
118const MCExpr *nvptx::LowerConstant(const Constant *CV, AsmPrinter &AP) {
119 MCContext &Ctx = AP.OutContext;
120
121 if (CV->isNullValue() || isa<UndefValue>(CV))
122 return MCConstantExpr::Create(0, Ctx);
123
124 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
125 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
126
127 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
Rafael Espindola79858aa2013-10-29 17:07:16 +0000128 return MCSymbolRefExpr::Create(AP.getSymbol(GV), Ctx);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000129
130 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
131 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
132
133 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
134 if (CE == 0)
135 llvm_unreachable("Unknown constant value to lower!");
136
Justin Holewinskiae556d32012-05-04 20:18:50 +0000137 switch (CE->getOpcode()) {
138 default:
139 // If the code isn't optimized, there may be outstanding folding
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000140 // opportunities. Attempt to fold the expression using DataLayout as a
Justin Holewinskiae556d32012-05-04 20:18:50 +0000141 // last resort before giving up.
Justin Holewinski0497ab12013-03-30 14:29:21 +0000142 if (Constant *C = ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000143 if (C != CE)
144 return LowerConstant(C, AP);
145
146 // Otherwise report the problem to the user.
147 {
Justin Holewinski0497ab12013-03-30 14:29:21 +0000148 std::string S;
149 raw_string_ostream OS(S);
150 OS << "Unsupported expression in static initializer: ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000151 CE->printAsOperand(OS, /*PrintType=*/ false,
Justin Holewinski0497ab12013-03-30 14:29:21 +0000152 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
153 report_fatal_error(OS.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000154 }
155 case Instruction::GetElementPtr: {
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000156 const DataLayout &TD = *AP.TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000157 // Generate a symbolic expression for the byte address
Nuno Lopesb6ad9822012-12-30 16:25:48 +0000158 APInt OffsetAI(TD.getPointerSizeInBits(), 0);
159 cast<GEPOperator>(CE)->accumulateConstantOffset(TD, OffsetAI);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000160
161 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
Nuno Lopesb6ad9822012-12-30 16:25:48 +0000162 if (!OffsetAI)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000163 return Base;
164
Nuno Lopesb6ad9822012-12-30 16:25:48 +0000165 int64_t Offset = OffsetAI.getSExtValue();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000166 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
167 Ctx);
168 }
169
170 case Instruction::Trunc:
171 // We emit the value and depend on the assembler to truncate the generated
172 // expression properly. This is important for differences between
173 // blockaddress labels. Since the two labels are in the same function, it
174 // is reasonable to treat their delta as a 32-bit value.
Justin Holewinski0497ab12013-03-30 14:29:21 +0000175 // FALL THROUGH.
Justin Holewinskiae556d32012-05-04 20:18:50 +0000176 case Instruction::BitCast:
177 return LowerConstant(CE->getOperand(0), AP);
178
179 case Instruction::IntToPtr: {
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000180 const DataLayout &TD = *AP.TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000181 // Handle casts to pointers by changing them into casts to the appropriate
182 // integer type. This promotes constant folding and simplifies this code.
183 Constant *Op = CE->getOperand(0);
Chandler Carruth7ec50852012-11-01 08:07:29 +0000184 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
Justin Holewinski0497ab12013-03-30 14:29:21 +0000185 false /*ZExt*/);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000186 return LowerConstant(Op, AP);
187 }
188
189 case Instruction::PtrToInt: {
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000190 const DataLayout &TD = *AP.TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000191 // Support only foldable casts to/from pointers that can be eliminated by
192 // changing the pointer to the appropriately sized integer type.
193 Constant *Op = CE->getOperand(0);
194 Type *Ty = CE->getType();
195
196 const MCExpr *OpExpr = LowerConstant(Op, AP);
197
198 // We can emit the pointer value into this slot if the slot is an
199 // integer slot equal to the size of the pointer.
200 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
201 return OpExpr;
202
203 // Otherwise the pointer is smaller than the resultant integer, mask off
204 // the high bits so we are sure to get a proper truncation if the input is
205 // a constant expr.
206 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
Justin Holewinski0497ab12013-03-30 14:29:21 +0000207 const MCExpr *MaskExpr =
208 MCConstantExpr::Create(~0ULL >> (64 - InBits), Ctx);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000209 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
210 }
211
Justin Holewinski0497ab12013-03-30 14:29:21 +0000212 // The MC library also has a right-shift operator, but it isn't consistently
Justin Holewinskiae556d32012-05-04 20:18:50 +0000213 // signed or unsigned between different targets.
214 case Instruction::Add:
215 case Instruction::Sub:
216 case Instruction::Mul:
217 case Instruction::SDiv:
218 case Instruction::SRem:
219 case Instruction::Shl:
220 case Instruction::And:
221 case Instruction::Or:
222 case Instruction::Xor: {
223 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
224 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
225 switch (CE->getOpcode()) {
Justin Holewinski0497ab12013-03-30 14:29:21 +0000226 default:
227 llvm_unreachable("Unknown binary operator constant cast expr");
228 case Instruction::Add:
229 return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
230 case Instruction::Sub:
231 return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
232 case Instruction::Mul:
233 return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
234 case Instruction::SDiv:
235 return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
236 case Instruction::SRem:
237 return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
238 case Instruction::Shl:
239 return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
240 case Instruction::And:
241 return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
242 case Instruction::Or:
243 return MCBinaryExpr::CreateOr(LHS, RHS, Ctx);
244 case Instruction::Xor:
245 return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000246 }
247 }
248 }
249}
250
Justin Holewinski0497ab12013-03-30 14:29:21 +0000251void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000252 if (!EmitLineNumbers)
253 return;
254 if (ignoreLoc(MI))
255 return;
256
257 DebugLoc curLoc = MI.getDebugLoc();
258
259 if (prevDebugLoc.isUnknown() && curLoc.isUnknown())
260 return;
261
262 if (prevDebugLoc == curLoc)
263 return;
264
265 prevDebugLoc = curLoc;
266
267 if (curLoc.isUnknown())
268 return;
269
Justin Holewinskiae556d32012-05-04 20:18:50 +0000270 const MachineFunction *MF = MI.getParent()->getParent();
271 //const TargetMachine &TM = MF->getTarget();
272
273 const LLVMContext &ctx = MF->getFunction()->getContext();
274 DIScope Scope(curLoc.getScope(ctx));
275
Manman Ren983a16c2013-06-28 05:43:10 +0000276 assert((!Scope || Scope.isScope()) &&
277 "Scope of a DebugLoc should be null or a DIScope.");
278 if (!Scope)
279 return;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000280
281 StringRef fileName(Scope.getFilename());
282 StringRef dirName(Scope.getDirectory());
283 SmallString<128> FullPathName = dirName;
284 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
285 sys::path::append(FullPathName, fileName);
286 fileName = FullPathName.str();
287 }
288
289 if (filenameMap.find(fileName.str()) == filenameMap.end())
290 return;
291
Justin Holewinskiae556d32012-05-04 20:18:50 +0000292 // Emit the line from the source file.
Benjamin Kramer7ad41002013-10-27 11:31:46 +0000293 if (InterleaveSrc)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000294 this->emitSrcInText(fileName.str(), curLoc.getLine());
295
296 std::stringstream temp;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000297 temp << "\t.loc " << filenameMap[fileName.str()] << " " << curLoc.getLine()
298 << " " << curLoc.getCol();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000299 OutStreamer.EmitRawText(Twine(temp.str().c_str()));
300}
301
302void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
303 SmallString<128> Str;
304 raw_svector_ostream OS(Str);
305 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
306 emitLineNumberAsDotLoc(*MI);
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000307
308 MCInst Inst;
309 lowerToMCInst(MI, Inst);
David Woodhousee6c13e42014-01-28 23:12:42 +0000310 EmitToStreamer(OutStreamer, Inst);
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000311}
312
313void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
314 OutMI.setOpcode(MI->getOpcode());
315
Justin Holewinski3d49e5c2013-11-15 12:30:04 +0000316 // Special: Do not mangle symbol operand of CALL_PROTOTYPE
317 if (MI->getOpcode() == NVPTX::CALL_PROTOTYPE) {
318 const MachineOperand &MO = MI->getOperand(0);
319 OutMI.addOperand(GetSymbolRef(MO,
320 OutContext.GetOrCreateSymbol(Twine(MO.getSymbolName()))));
321 return;
322 }
323
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000324 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
325 const MachineOperand &MO = MI->getOperand(i);
326
327 MCOperand MCOp;
328 if (lowerOperand(MO, MCOp))
329 OutMI.addOperand(MCOp);
330 }
331}
332
333bool NVPTXAsmPrinter::lowerOperand(const MachineOperand &MO,
334 MCOperand &MCOp) {
335 switch (MO.getType()) {
336 default: llvm_unreachable("unknown operand type");
337 case MachineOperand::MO_Register:
338 MCOp = MCOperand::CreateReg(encodeVirtualRegister(MO.getReg()));
339 break;
340 case MachineOperand::MO_Immediate:
341 MCOp = MCOperand::CreateImm(MO.getImm());
342 break;
343 case MachineOperand::MO_MachineBasicBlock:
344 MCOp = MCOperand::CreateExpr(MCSymbolRefExpr::Create(
345 MO.getMBB()->getSymbol(), OutContext));
346 break;
347 case MachineOperand::MO_ExternalSymbol:
348 MCOp = GetSymbolRef(MO, GetExternalSymbolSymbol(MO.getSymbolName()));
349 break;
350 case MachineOperand::MO_GlobalAddress:
Rafael Espindola79858aa2013-10-29 17:07:16 +0000351 MCOp = GetSymbolRef(MO, getSymbol(MO.getGlobal()));
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000352 break;
353 case MachineOperand::MO_FPImmediate: {
354 const ConstantFP *Cnt = MO.getFPImm();
355 APFloat Val = Cnt->getValueAPF();
356
357 switch (Cnt->getType()->getTypeID()) {
358 default: report_fatal_error("Unsupported FP type"); break;
359 case Type::FloatTyID:
360 MCOp = MCOperand::CreateExpr(
361 NVPTXFloatMCExpr::CreateConstantFPSingle(Val, OutContext));
362 break;
363 case Type::DoubleTyID:
364 MCOp = MCOperand::CreateExpr(
365 NVPTXFloatMCExpr::CreateConstantFPDouble(Val, OutContext));
366 break;
367 }
368 break;
369 }
370 }
371 return true;
372}
373
374unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
Justin Holewinski871ec932013-08-06 14:13:31 +0000375 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
376 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000377
Justin Holewinski871ec932013-08-06 14:13:31 +0000378 DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
379 unsigned RegNum = RegMap[Reg];
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000380
Justin Holewinski871ec932013-08-06 14:13:31 +0000381 // Encode the register class in the upper 4 bits
382 // Must be kept in sync with NVPTXInstPrinter::printRegName
383 unsigned Ret = 0;
384 if (RC == &NVPTX::Int1RegsRegClass) {
385 Ret = (1 << 28);
386 } else if (RC == &NVPTX::Int16RegsRegClass) {
387 Ret = (2 << 28);
388 } else if (RC == &NVPTX::Int32RegsRegClass) {
389 Ret = (3 << 28);
390 } else if (RC == &NVPTX::Int64RegsRegClass) {
391 Ret = (4 << 28);
392 } else if (RC == &NVPTX::Float32RegsRegClass) {
393 Ret = (5 << 28);
394 } else if (RC == &NVPTX::Float64RegsRegClass) {
395 Ret = (6 << 28);
396 } else {
397 report_fatal_error("Bad register class");
398 }
399
400 // Insert the vreg number
401 Ret |= (RegNum & 0x0FFFFFFF);
402 return Ret;
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000403 } else {
Justin Holewinski871ec932013-08-06 14:13:31 +0000404 // Some special-use registers are actually physical registers.
405 // Encode this as the register class ID of 0 and the real register ID.
406 return Reg & 0x0FFFFFFF;
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000407 }
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000408}
409
410MCOperand NVPTXAsmPrinter::GetSymbolRef(const MachineOperand &MO,
411 const MCSymbol *Symbol) {
412 const MCExpr *Expr;
Justin Holewinski8b24e1e2013-08-06 23:06:42 +0000413 Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None,
414 OutContext);
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000415 return MCOperand::CreateExpr(Expr);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000416}
417
Justin Holewinski0497ab12013-03-30 14:29:21 +0000418void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000419 const DataLayout *TD = TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000420 const TargetLowering *TLI = TM.getTargetLowering();
421
422 Type *Ty = F->getReturnType();
423
424 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
425
426 if (Ty->getTypeID() == Type::VoidTyID)
427 return;
428
429 O << " (";
430
431 if (isABI) {
Rafael Espindola08013342013-12-07 19:34:20 +0000432 if (Ty->isFloatingPointTy() || Ty->isIntegerTy()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000433 unsigned size = 0;
434 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
435 size = ITy->getBitWidth();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000436 if (size < 32)
437 size = 32;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000438 } else {
Justin Holewinski0497ab12013-03-30 14:29:21 +0000439 assert(Ty->isFloatingPointTy() && "Floating point type expected here");
Justin Holewinskiae556d32012-05-04 20:18:50 +0000440 size = Ty->getPrimitiveSizeInBits();
441 }
442
443 O << ".param .b" << size << " func_retval0";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000444 } else if (isa<PointerType>(Ty)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000445 O << ".param .b" << TLI->getPointerTy().getSizeInBits()
Justin Holewinski0497ab12013-03-30 14:29:21 +0000446 << " func_retval0";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000447 } else {
Justin Holewinski0497ab12013-03-30 14:29:21 +0000448 if ((Ty->getTypeID() == Type::StructTyID) || isa<VectorType>(Ty)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000449 SmallVector<EVT, 16> vtparts;
450 ComputeValueVTs(*TLI, Ty, vtparts);
451 unsigned totalsz = 0;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000452 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000453 unsigned elems = 1;
454 EVT elemtype = vtparts[i];
455 if (vtparts[i].isVector()) {
456 elems = vtparts[i].getVectorNumElements();
457 elemtype = vtparts[i].getVectorElementType();
458 }
Justin Holewinski0497ab12013-03-30 14:29:21 +0000459 for (unsigned j = 0, je = elems; j != je; ++j) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000460 unsigned sz = elemtype.getSizeInBits();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000461 if (elemtype.isInteger() && (sz < 8))
462 sz = 8;
463 totalsz += sz / 8;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000464 }
465 }
466 unsigned retAlignment = 0;
467 if (!llvm::getAlign(*F, 0, retAlignment))
468 retAlignment = TD->getABITypeAlignment(Ty);
Justin Holewinski0497ab12013-03-30 14:29:21 +0000469 O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
470 << "]";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000471 } else
Justin Holewinski0497ab12013-03-30 14:29:21 +0000472 assert(false && "Unknown return type");
Justin Holewinskiae556d32012-05-04 20:18:50 +0000473 }
474 } else {
475 SmallVector<EVT, 16> vtparts;
476 ComputeValueVTs(*TLI, Ty, vtparts);
477 unsigned idx = 0;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000478 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000479 unsigned elems = 1;
480 EVT elemtype = vtparts[i];
481 if (vtparts[i].isVector()) {
482 elems = vtparts[i].getVectorNumElements();
483 elemtype = vtparts[i].getVectorElementType();
484 }
485
Justin Holewinski0497ab12013-03-30 14:29:21 +0000486 for (unsigned j = 0, je = elems; j != je; ++j) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000487 unsigned sz = elemtype.getSizeInBits();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000488 if (elemtype.isInteger() && (sz < 32))
489 sz = 32;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000490 O << ".reg .b" << sz << " func_retval" << idx;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000491 if (j < je - 1)
492 O << ", ";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000493 ++idx;
494 }
Justin Holewinski0497ab12013-03-30 14:29:21 +0000495 if (i < e - 1)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000496 O << ", ";
497 }
498 }
499 O << ") ";
500 return;
501}
502
503void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
504 raw_ostream &O) {
505 const Function *F = MF.getFunction();
506 printReturnValStr(F, O);
507}
508
509void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
510 SmallString<128> Str;
511 raw_svector_ostream O(Str);
512
Justin Holewinski01f89f02013-05-20 12:13:32 +0000513 if (!GlobalsEmitted) {
514 emitGlobals(*MF->getFunction()->getParent());
515 GlobalsEmitted = true;
516 }
517
Justin Holewinskiae556d32012-05-04 20:18:50 +0000518 // Set up
519 MRI = &MF->getRegInfo();
520 F = MF->getFunction();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000521 emitLinkageDirective(F, O);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000522 if (llvm::isKernelFunction(*F))
523 O << ".entry ";
524 else {
525 O << ".func ";
526 printReturnValStr(*MF, O);
527 }
528
529 O << *CurrentFnSym;
530
531 emitFunctionParamList(*MF, O);
532
533 if (llvm::isKernelFunction(*F))
534 emitKernelFunctionDirectives(*F, O);
535
536 OutStreamer.EmitRawText(O.str());
537
538 prevDebugLoc = DebugLoc();
539}
540
541void NVPTXAsmPrinter::EmitFunctionBodyStart() {
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +0000542 VRegMapping.clear();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000543 OutStreamer.EmitRawText(StringRef("{\n"));
544 setAndEmitFunctionVirtualRegisters(*MF);
545
546 SmallString<128> Str;
547 raw_svector_ostream O(Str);
548 emitDemotedVars(MF->getFunction(), O);
549 OutStreamer.EmitRawText(O.str());
550}
551
552void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
553 OutStreamer.EmitRawText(StringRef("}\n"));
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +0000554 VRegMapping.clear();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000555}
556
Justin Holewinski660597d2013-10-11 12:39:36 +0000557void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
558 unsigned RegNo = MI->getOperand(0).getReg();
559 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
560 if (TRI->isVirtualRegister(RegNo)) {
561 OutStreamer.AddComment(Twine("implicit-def: ") +
562 getVirtualRegisterName(RegNo));
563 } else {
564 OutStreamer.AddComment(Twine("implicit-def: ") +
565 TM.getRegisterInfo()->getName(RegNo));
566 }
567 OutStreamer.AddBlankLine();
568}
569
Justin Holewinski0497ab12013-03-30 14:29:21 +0000570void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
571 raw_ostream &O) const {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000572 // If the NVVM IR has some of reqntid* specified, then output
573 // the reqntid directive, and set the unspecified ones to 1.
574 // If none of reqntid* is specified, don't output reqntid directive.
575 unsigned reqntidx, reqntidy, reqntidz;
576 bool specified = false;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000577 if (llvm::getReqNTIDx(F, reqntidx) == false)
578 reqntidx = 1;
579 else
580 specified = true;
581 if (llvm::getReqNTIDy(F, reqntidy) == false)
582 reqntidy = 1;
583 else
584 specified = true;
585 if (llvm::getReqNTIDz(F, reqntidz) == false)
586 reqntidz = 1;
587 else
588 specified = true;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000589
590 if (specified)
Justin Holewinski0497ab12013-03-30 14:29:21 +0000591 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
592 << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000593
594 // If the NVVM IR has some of maxntid* specified, then output
595 // the maxntid directive, and set the unspecified ones to 1.
596 // If none of maxntid* is specified, don't output maxntid directive.
597 unsigned maxntidx, maxntidy, maxntidz;
598 specified = false;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000599 if (llvm::getMaxNTIDx(F, maxntidx) == false)
600 maxntidx = 1;
601 else
602 specified = true;
603 if (llvm::getMaxNTIDy(F, maxntidy) == false)
604 maxntidy = 1;
605 else
606 specified = true;
607 if (llvm::getMaxNTIDz(F, maxntidz) == false)
608 maxntidz = 1;
609 else
610 specified = true;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000611
612 if (specified)
Justin Holewinski0497ab12013-03-30 14:29:21 +0000613 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
614 << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000615
616 unsigned mincta;
617 if (llvm::getMinCTASm(F, mincta))
618 O << ".minnctapersm " << mincta << "\n";
619}
620
Justin Holewinski660597d2013-10-11 12:39:36 +0000621std::string
622NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
623 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000624
Justin Holewinski660597d2013-10-11 12:39:36 +0000625 std::string Name;
626 raw_string_ostream NameStr(Name);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000627
Justin Holewinski660597d2013-10-11 12:39:36 +0000628 VRegRCMap::const_iterator I = VRegMapping.find(RC);
629 assert(I != VRegMapping.end() && "Bad register class");
630 const DenseMap<unsigned, unsigned> &RegMap = I->second;
631
632 VRegMap::const_iterator VI = RegMap.find(Reg);
633 assert(VI != RegMap.end() && "Bad virtual register");
634 unsigned MappedVR = VI->second;
635
636 NameStr << getNVPTXRegClassStr(RC) << MappedVR;
637
638 NameStr.flush();
639 return Name;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000640}
641
Justin Holewinski660597d2013-10-11 12:39:36 +0000642void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
Justin Holewinski0497ab12013-03-30 14:29:21 +0000643 raw_ostream &O) {
Justin Holewinski660597d2013-10-11 12:39:36 +0000644 O << getVirtualRegisterName(vr);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000645}
646
Justin Holewinski0497ab12013-03-30 14:29:21 +0000647void NVPTXAsmPrinter::printVecModifiedImmediate(
648 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
649 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
650 int Imm = (int) MO.getImm();
651 if (0 == strcmp(Modifier, "vecelem"))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000652 O << "_" << vecelem[Imm];
Justin Holewinski0497ab12013-03-30 14:29:21 +0000653 else if (0 == strcmp(Modifier, "vecv4comm1")) {
654 if ((Imm < 0) || (Imm > 3))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000655 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000656 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
657 if ((Imm < 4) || (Imm > 7))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000658 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000659 } else if (0 == strcmp(Modifier, "vecv4pos")) {
660 if (Imm < 0)
661 Imm = 0;
662 O << "_" << vecelem[Imm % 4];
663 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
664 if ((Imm < 0) || (Imm > 1))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000665 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000666 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
667 if ((Imm < 2) || (Imm > 3))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000668 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000669 } else if (0 == strcmp(Modifier, "vecv2pos")) {
670 if (Imm < 0)
671 Imm = 0;
672 O << "_" << vecelem[Imm % 2];
673 } else
Craig Topperbdf39a42012-05-24 07:02:50 +0000674 llvm_unreachable("Unknown Modifier on immediate operand");
Justin Holewinskiae556d32012-05-04 20:18:50 +0000675}
676
Justin Holewinskidc5e3b62013-06-28 17:58:04 +0000677
678
Justin Holewinski0497ab12013-03-30 14:29:21 +0000679void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000680
Justin Holewinski0497ab12013-03-30 14:29:21 +0000681 emitLinkageDirective(F, O);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000682 if (llvm::isKernelFunction(*F))
683 O << ".entry ";
684 else
685 O << ".func ";
686 printReturnValStr(F, O);
Eli Benderskye78ae052014-03-10 20:05:42 +0000687 O << getSymbolName(F) << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000688 emitFunctionParamList(F, O);
689 O << ";\n";
690}
691
Justin Holewinski0497ab12013-03-30 14:29:21 +0000692static bool usedInGlobalVarDef(const Constant *C) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000693 if (!C)
694 return false;
695
696 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
697 if (GV->getName().str() == "llvm.used")
698 return false;
699 return true;
700 }
701
Chandler Carruthcdf47882014-03-09 03:16:01 +0000702 for (const User *U : C->users())
703 if (const Constant *C = dyn_cast<Constant>(U))
704 if (usedInGlobalVarDef(C))
705 return true;
706
Justin Holewinskiae556d32012-05-04 20:18:50 +0000707 return false;
708}
709
Justin Holewinski0497ab12013-03-30 14:29:21 +0000710static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000711 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
712 if (othergv->getName().str() == "llvm.used")
713 return true;
714 }
715
716 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
717 if (instr->getParent() && instr->getParent()->getParent()) {
718 const Function *curFunc = instr->getParent()->getParent();
719 if (oneFunc && (curFunc != oneFunc))
720 return false;
721 oneFunc = curFunc;
722 return true;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000723 } else
Justin Holewinskiae556d32012-05-04 20:18:50 +0000724 return false;
725 }
726
727 if (const MDNode *md = dyn_cast<MDNode>(U))
728 if (md->hasName() && ((md->getName().str() == "llvm.dbg.gv") ||
Justin Holewinski0497ab12013-03-30 14:29:21 +0000729 (md->getName().str() == "llvm.dbg.sp")))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000730 return true;
731
Chandler Carruthcdf47882014-03-09 03:16:01 +0000732 for (const User *UU : U->users())
733 if (usedInOneFunc(UU, oneFunc) == false)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000734 return false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000735
Justin Holewinskiae556d32012-05-04 20:18:50 +0000736 return true;
737}
738
739/* Find out if a global variable can be demoted to local scope.
740 * Currently, this is valid for CUDA shared variables, which have local
741 * scope and global lifetime. So the conditions to check are :
742 * 1. Is the global variable in shared address space?
743 * 2. Does it have internal linkage?
744 * 3. Is the global variable referenced only in one function?
745 */
746static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
747 if (gv->hasInternalLinkage() == false)
748 return false;
749 const PointerType *Pty = gv->getType();
750 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
751 return false;
752
753 const Function *oneFunc = 0;
754
755 bool flag = usedInOneFunc(gv, oneFunc);
756 if (flag == false)
757 return false;
758 if (!oneFunc)
759 return false;
760 f = oneFunc;
761 return true;
762}
763
764static bool useFuncSeen(const Constant *C,
765 llvm::DenseMap<const Function *, bool> &seenMap) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000766 for (const User *U : C->users()) {
767 if (const Constant *cu = dyn_cast<Constant>(U)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000768 if (useFuncSeen(cu, seenMap))
769 return true;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000770 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000771 const BasicBlock *bb = I->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000772 if (!bb)
773 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000774 const Function *caller = bb->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000775 if (!caller)
776 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000777 if (seenMap.find(caller) != seenMap.end())
778 return true;
779 }
780 }
781 return false;
782}
783
Justin Holewinski01f89f02013-05-20 12:13:32 +0000784void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000785 llvm::DenseMap<const Function *, bool> seenMap;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000786 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000787 const Function *F = FI;
788
789 if (F->isDeclaration()) {
790 if (F->use_empty())
791 continue;
792 if (F->getIntrinsicID())
793 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000794 emitDeclaration(F, O);
795 continue;
796 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000797 for (const User *U : F->users()) {
798 if (const Constant *C = dyn_cast<Constant>(U)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000799 if (usedInGlobalVarDef(C)) {
800 // The use is in the initialization of a global variable
801 // that is a function pointer, so print a declaration
802 // for the original function
Justin Holewinskiae556d32012-05-04 20:18:50 +0000803 emitDeclaration(F, O);
804 break;
805 }
806 // Emit a declaration of this function if the function that
807 // uses this constant expr has already been seen.
808 if (useFuncSeen(C, seenMap)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000809 emitDeclaration(F, O);
810 break;
811 }
812 }
813
Chandler Carruthcdf47882014-03-09 03:16:01 +0000814 if (!isa<Instruction>(U))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000815 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000816 const Instruction *instr = cast<Instruction>(U);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000817 const BasicBlock *bb = instr->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000818 if (!bb)
819 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000820 const Function *caller = bb->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000821 if (!caller)
822 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000823
824 // If a caller has already been seen, then the caller is
825 // appearing in the module before the callee. so print out
826 // a declaration for the callee.
827 if (seenMap.find(caller) != seenMap.end()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000828 emitDeclaration(F, O);
829 break;
830 }
831 }
832 seenMap[F] = true;
833 }
834}
835
836void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
837 DebugInfoFinder DbgFinder;
838 DbgFinder.processModule(M);
839
Justin Holewinski0497ab12013-03-30 14:29:21 +0000840 unsigned i = 1;
Alon Mishnead312152014-03-18 09:41:07 +0000841 for (DICompileUnit DIUnit : DbgFinder.compile_units()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000842 StringRef Filename(DIUnit.getFilename());
843 StringRef Dirname(DIUnit.getDirectory());
844 SmallString<128> FullPathName = Dirname;
845 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
846 sys::path::append(FullPathName, Filename);
847 Filename = FullPathName.str();
848 }
849 if (filenameMap.find(Filename.str()) != filenameMap.end())
850 continue;
851 filenameMap[Filename.str()] = i;
852 OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
853 ++i;
854 }
855
Alon Mishnead312152014-03-18 09:41:07 +0000856 for (DISubprogram SP : DbgFinder.subprograms()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000857 StringRef Filename(SP.getFilename());
858 StringRef Dirname(SP.getDirectory());
859 SmallString<128> FullPathName = Dirname;
860 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
861 sys::path::append(FullPathName, Filename);
862 Filename = FullPathName.str();
863 }
864 if (filenameMap.find(Filename.str()) != filenameMap.end())
865 continue;
866 filenameMap[Filename.str()] = i;
867 ++i;
868 }
869}
870
Justin Holewinski0497ab12013-03-30 14:29:21 +0000871bool NVPTXAsmPrinter::doInitialization(Module &M) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000872
873 SmallString<128> Str1;
874 raw_svector_ostream OS1(Str1);
875
876 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
877 MMI->AnalyzeModule(M);
878
879 // We need to call the parent's one explicitly.
880 //bool Result = AsmPrinter::doInitialization(M);
881
882 // Initialize TargetLoweringObjectFile.
Justin Holewinski0497ab12013-03-30 14:29:21 +0000883 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
884 .Initialize(OutContext, TM);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000885
Rafael Espindola58873562014-01-03 19:21:54 +0000886 Mang = new Mangler(TM.getDataLayout());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000887
888 // Emit header before any dwarf directives are emitted below.
889 emitHeader(M, OS1);
890 OutStreamer.EmitRawText(OS1.str());
891
Justin Holewinskiae556d32012-05-04 20:18:50 +0000892 // Already commented out
893 //bool Result = AsmPrinter::doInitialization(M);
894
Justin Holewinskid2bbdf02013-07-01 13:00:14 +0000895 // Emit module-level inline asm if it exists.
896 if (!M.getModuleInlineAsm().empty()) {
897 OutStreamer.AddComment("Start of file scope inline assembly");
898 OutStreamer.AddBlankLine();
899 OutStreamer.EmitRawText(StringRef(M.getModuleInlineAsm()));
900 OutStreamer.AddBlankLine();
901 OutStreamer.AddComment("End of file scope inline assembly");
902 OutStreamer.AddBlankLine();
903 }
904
Justin Holewinskiae556d32012-05-04 20:18:50 +0000905 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
906 recordAndEmitFilenames(M);
907
Justin Holewinski01f89f02013-05-20 12:13:32 +0000908 GlobalsEmitted = false;
909
910 return false; // success
911}
912
913void NVPTXAsmPrinter::emitGlobals(const Module &M) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000914 SmallString<128> Str2;
915 raw_svector_ostream OS2(Str2);
916
917 emitDeclarations(M, OS2);
918
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000919 // As ptxas does not support forward references of globals, we need to first
920 // sort the list of module-level globals in def-use order. We visit each
921 // global variable in order, and ensure that we emit it *after* its dependent
922 // globals. We use a little extra memory maintaining both a set and a list to
923 // have fast searches while maintaining a strict ordering.
Justin Holewinski01f89f02013-05-20 12:13:32 +0000924 SmallVector<const GlobalVariable *, 8> Globals;
925 DenseSet<const GlobalVariable *> GVVisited;
926 DenseSet<const GlobalVariable *> GVVisiting;
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000927
928 // Visit each global variable, in order
Justin Holewinski01f89f02013-05-20 12:13:32 +0000929 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
930 I != E; ++I)
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000931 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
932
Justin Holewinski0497ab12013-03-30 14:29:21 +0000933 assert(GVVisited.size() == M.getGlobalList().size() &&
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000934 "Missed a global variable");
935 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
936
937 // Print out module-level global variables in proper order
938 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
939 printModuleLevelGV(Globals[i], OS2);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000940
941 OS2 << '\n';
942
943 OutStreamer.EmitRawText(OS2.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000944}
945
Justin Holewinski0497ab12013-03-30 14:29:21 +0000946void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000947 O << "//\n";
948 O << "// Generated by LLVM NVPTX Back-End\n";
949 O << "//\n";
950 O << "\n";
951
Justin Holewinski1812ee92012-11-12 03:16:43 +0000952 unsigned PTXVersion = nvptxSubtarget.getPTXVersion();
953 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000954
955 O << ".target ";
956 O << nvptxSubtarget.getTargetName();
957
958 if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
959 O << ", texmode_independent";
960 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
961 if (!nvptxSubtarget.hasDouble())
962 O << ", map_f64_to_f32";
963 }
964
965 if (MAI->doesSupportDebugInformation())
966 O << ", debug";
967
968 O << "\n";
969
970 O << ".address_size ";
971 if (nvptxSubtarget.is64Bit())
972 O << "64";
973 else
974 O << "32";
975 O << "\n";
976
977 O << "\n";
978}
979
980bool NVPTXAsmPrinter::doFinalization(Module &M) {
Justin Holewinski01f89f02013-05-20 12:13:32 +0000981
982 // If we did not emit any functions, then the global declarations have not
983 // yet been emitted.
984 if (!GlobalsEmitted) {
985 emitGlobals(M);
986 GlobalsEmitted = true;
987 }
988
Justin Holewinskiae556d32012-05-04 20:18:50 +0000989 // XXX Temproarily remove global variables so that doFinalization() will not
990 // emit them again (global variables are emitted at beginning).
991
992 Module::GlobalListType &global_list = M.getGlobalList();
993 int i, n = global_list.size();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000994 GlobalVariable **gv_array = new GlobalVariable *[n];
Justin Holewinskiae556d32012-05-04 20:18:50 +0000995
996 // first, back-up GlobalVariable in gv_array
997 i = 0;
998 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000999 I != E; ++I)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001000 gv_array[i++] = &*I;
1001
1002 // second, empty global_list
1003 while (!global_list.empty())
1004 global_list.remove(global_list.begin());
1005
1006 // call doFinalization
1007 bool ret = AsmPrinter::doFinalization(M);
1008
1009 // now we restore global variables
Justin Holewinski0497ab12013-03-30 14:29:21 +00001010 for (i = 0; i < n; i++)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001011 global_list.insert(global_list.end(), gv_array[i]);
1012
1013 delete[] gv_array;
1014 return ret;
1015
Justin Holewinskiae556d32012-05-04 20:18:50 +00001016 //bool Result = AsmPrinter::doFinalization(M);
1017 // Instead of calling the parents doFinalization, we may
1018 // clone parents doFinalization and customize here.
1019 // Currently, we if NVISA out the EmitGlobals() in
1020 // parent's doFinalization, which is too intrusive.
1021 //
1022 // Same for the doInitialization.
1023 //return Result;
1024}
1025
1026// This function emits appropriate linkage directives for
1027// functions and global variables.
1028//
1029// extern function declaration -> .extern
1030// extern function definition -> .visible
1031// external global variable with init -> .visible
1032// external without init -> .extern
1033// appending -> not allowed, assert.
1034
Justin Holewinski0497ab12013-03-30 14:29:21 +00001035void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
1036 raw_ostream &O) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001037 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1038 if (V->hasExternalLinkage()) {
1039 if (isa<GlobalVariable>(V)) {
1040 const GlobalVariable *GVar = cast<GlobalVariable>(V);
1041 if (GVar) {
1042 if (GVar->hasInitializer())
1043 O << ".visible ";
1044 else
1045 O << ".extern ";
1046 }
1047 } else if (V->isDeclaration())
1048 O << ".extern ";
1049 else
1050 O << ".visible ";
1051 } else if (V->hasAppendingLinkage()) {
1052 std::string msg;
1053 msg.append("Error: ");
1054 msg.append("Symbol ");
1055 if (V->hasName())
1056 msg.append(V->getName().str());
1057 msg.append("has unsupported appending linkage type");
1058 llvm_unreachable(msg.c_str());
1059 }
1060 }
1061}
1062
Justin Holewinski01f89f02013-05-20 12:13:32 +00001063void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1064 raw_ostream &O,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001065 bool processDemoted) {
1066
1067 // Skip meta data
1068 if (GVar->hasSection()) {
1069 if (GVar->getSection() == "llvm.metadata")
1070 return;
1071 }
1072
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001073 const DataLayout *TD = TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001074
1075 // GlobalVariables are always constant pointers themselves.
1076 const PointerType *PTy = GVar->getType();
1077 Type *ETy = PTy->getElementType();
1078
1079 if (GVar->hasExternalLinkage()) {
1080 if (GVar->hasInitializer())
1081 O << ".visible ";
1082 else
1083 O << ".extern ";
1084 }
1085
1086 if (llvm::isTexture(*GVar)) {
1087 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1088 return;
1089 }
1090
1091 if (llvm::isSurface(*GVar)) {
1092 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1093 return;
1094 }
1095
1096 if (GVar->isDeclaration()) {
1097 // (extern) declarations, no definition or initializer
1098 // Currently the only known declaration is for an automatic __local
1099 // (.shared) promoted to global.
1100 emitPTXGlobalVariable(GVar, O);
1101 O << ";\n";
1102 return;
1103 }
1104
1105 if (llvm::isSampler(*GVar)) {
1106 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1107
Justin Holewinski01f89f02013-05-20 12:13:32 +00001108 const Constant *Initializer = NULL;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001109 if (GVar->hasInitializer())
1110 Initializer = GVar->getInitializer();
Justin Holewinski01f89f02013-05-20 12:13:32 +00001111 const ConstantInt *CI = NULL;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001112 if (Initializer)
1113 CI = dyn_cast<ConstantInt>(Initializer);
1114 if (CI) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001115 unsigned sample = CI->getZExtValue();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001116
1117 O << " = { ";
1118
Justin Holewinski0497ab12013-03-30 14:29:21 +00001119 for (int i = 0,
1120 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1121 i < 3; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001122 O << "addr_mode_" << i << " = ";
1123 switch (addr) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001124 case 0:
1125 O << "wrap";
1126 break;
1127 case 1:
1128 O << "clamp_to_border";
1129 break;
1130 case 2:
1131 O << "clamp_to_edge";
1132 break;
1133 case 3:
1134 O << "wrap";
1135 break;
1136 case 4:
1137 O << "mirror";
1138 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001139 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001140 O << ", ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001141 }
1142 O << "filter_mode = ";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001143 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1144 case 0:
1145 O << "nearest";
1146 break;
1147 case 1:
1148 O << "linear";
1149 break;
1150 case 2:
1151 assert(0 && "Anisotropic filtering is not supported");
1152 default:
1153 O << "nearest";
1154 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001155 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001156 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001157 O << ", force_unnormalized_coords = 1";
1158 }
1159 O << " }";
1160 }
1161
1162 O << ";\n";
1163 return;
1164 }
1165
1166 if (GVar->hasPrivateLinkage()) {
1167
1168 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1169 return;
1170
1171 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1172 if (!strncmp(GVar->getName().data(), "filename", 8))
1173 return;
1174 if (GVar->use_empty())
1175 return;
1176 }
1177
1178 const Function *demotedFunc = 0;
1179 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1180 O << "// " << GVar->getName().str() << " has been demoted\n";
1181 if (localDecls.find(demotedFunc) != localDecls.end())
1182 localDecls[demotedFunc].push_back(GVar);
1183 else {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001184 std::vector<const GlobalVariable *> temp;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001185 temp.push_back(GVar);
1186 localDecls[demotedFunc] = temp;
1187 }
1188 return;
1189 }
1190
1191 O << ".";
1192 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1193 if (GVar->getAlignment() == 0)
1194 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1195 else
1196 O << " .align " << GVar->getAlignment();
1197
Rafael Espindola08013342013-12-07 19:34:20 +00001198 if (ETy->isSingleValueType()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001199 O << " .";
Justin Holewinski700b6fa2013-05-20 12:13:28 +00001200 // Special case: ABI requires that we use .u8 for predicates
1201 if (ETy->isIntegerTy(1))
1202 O << "u8";
1203 else
1204 O << getPTXFundamentalTypeStr(ETy, false);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001205 O << " ";
Eli Benderskye78ae052014-03-10 20:05:42 +00001206 O << getSymbolName(GVar);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001207
1208 // Ptx allows variable initilization only for constant and global state
1209 // spaces.
1210 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
Justin Holewinski0497ab12013-03-30 14:29:21 +00001211 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1212 GVar->hasInitializer()) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001213 const Constant *Initializer = GVar->getInitializer();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001214 if (!Initializer->isNullValue()) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001215 O << " = ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001216 printScalarConstant(Initializer, O);
1217 }
1218 }
1219 } else {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001220 unsigned int ElementSize = 0;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001221
1222 // Although PTX has direct support for struct type and array type and
1223 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1224 // targets that support these high level field accesses. Structs, arrays
1225 // and vectors are lowered into arrays of bytes.
1226 switch (ETy->getTypeID()) {
1227 case Type::StructTyID:
1228 case Type::ArrayTyID:
1229 case Type::VectorTyID:
1230 ElementSize = TD->getTypeStoreSize(ETy);
1231 // Ptx allows variable initilization only for constant and
1232 // global state spaces.
1233 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
Justin Holewinski0497ab12013-03-30 14:29:21 +00001234 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1235 GVar->hasInitializer()) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001236 const Constant *Initializer = GVar->getInitializer();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001237 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001238 AggBuffer aggBuffer(ElementSize, O, *this);
1239 bufferAggregateConstant(Initializer, &aggBuffer);
1240 if (aggBuffer.numSymbols) {
1241 if (nvptxSubtarget.is64Bit()) {
Eli Benderskye78ae052014-03-10 20:05:42 +00001242 O << " .u64 " << getSymbolName(GVar) << "[";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001243 O << ElementSize / 8;
1244 } else {
Eli Benderskye78ae052014-03-10 20:05:42 +00001245 O << " .u32 " << getSymbolName(GVar) << "[";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001246 O << ElementSize / 4;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001247 }
1248 O << "]";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001249 } else {
Eli Benderskye78ae052014-03-10 20:05:42 +00001250 O << " .b8 " << getSymbolName(GVar) << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001251 O << ElementSize;
1252 O << "]";
1253 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001254 O << " = {";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001255 aggBuffer.print();
1256 O << "}";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001257 } else {
Eli Benderskye78ae052014-03-10 20:05:42 +00001258 O << " .b8 " << getSymbolName(GVar);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001259 if (ElementSize) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001260 O << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001261 O << ElementSize;
1262 O << "]";
1263 }
1264 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001265 } else {
Eli Benderskye78ae052014-03-10 20:05:42 +00001266 O << " .b8 " << getSymbolName(GVar);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001267 if (ElementSize) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001268 O << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001269 O << ElementSize;
1270 O << "]";
1271 }
1272 }
1273 break;
1274 default:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001275 assert(0 && "type not supported yet");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001276 }
1277
1278 }
1279 O << ";\n";
1280}
1281
1282void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1283 if (localDecls.find(f) == localDecls.end())
1284 return;
1285
Justin Holewinski01f89f02013-05-20 12:13:32 +00001286 std::vector<const GlobalVariable *> &gvars = localDecls[f];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001287
Justin Holewinski0497ab12013-03-30 14:29:21 +00001288 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001289 O << "\t// demoted variable\n\t";
1290 printModuleLevelGV(gvars[i], O, true);
1291 }
1292}
1293
1294void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1295 raw_ostream &O) const {
1296 switch (AddressSpace) {
1297 case llvm::ADDRESS_SPACE_LOCAL:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001298 O << "local";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001299 break;
1300 case llvm::ADDRESS_SPACE_GLOBAL:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001301 O << "global";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001302 break;
1303 case llvm::ADDRESS_SPACE_CONST:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001304 O << "const";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001305 break;
1306 case llvm::ADDRESS_SPACE_SHARED:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001307 O << "shared";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001308 break;
1309 default:
Justin Holewinski36a50992013-02-09 13:34:15 +00001310 report_fatal_error("Bad address space found while emitting PTX");
1311 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001312 }
1313}
1314
Justin Holewinski0497ab12013-03-30 14:29:21 +00001315std::string
1316NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001317 switch (Ty->getTypeID()) {
1318 default:
1319 llvm_unreachable("unexpected type");
1320 break;
1321 case Type::IntegerTyID: {
1322 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1323 if (NumBits == 1)
1324 return "pred";
1325 else if (NumBits <= 64) {
1326 std::string name = "u";
1327 return name + utostr(NumBits);
1328 } else {
1329 llvm_unreachable("Integer too large");
1330 break;
1331 }
1332 break;
1333 }
1334 case Type::FloatTyID:
1335 return "f32";
1336 case Type::DoubleTyID:
1337 return "f64";
1338 case Type::PointerTyID:
1339 if (nvptxSubtarget.is64Bit())
Justin Holewinski0497ab12013-03-30 14:29:21 +00001340 if (useB4PTR)
1341 return "b64";
1342 else
1343 return "u64";
1344 else if (useB4PTR)
1345 return "b32";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001346 else
Justin Holewinski0497ab12013-03-30 14:29:21 +00001347 return "u32";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001348 }
1349 llvm_unreachable("unexpected type");
1350 return NULL;
1351}
1352
Justin Holewinski0497ab12013-03-30 14:29:21 +00001353void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001354 raw_ostream &O) {
1355
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001356 const DataLayout *TD = TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001357
1358 // GlobalVariables are always constant pointers themselves.
1359 const PointerType *PTy = GVar->getType();
1360 Type *ETy = PTy->getElementType();
1361
1362 O << ".";
1363 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1364 if (GVar->getAlignment() == 0)
1365 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1366 else
1367 O << " .align " << GVar->getAlignment();
1368
Rafael Espindola08013342013-12-07 19:34:20 +00001369 if (ETy->isSingleValueType()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001370 O << " .";
1371 O << getPTXFundamentalTypeStr(ETy);
1372 O << " ";
Eli Benderskye78ae052014-03-10 20:05:42 +00001373 O << getSymbolName(GVar);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001374 return;
1375 }
1376
Justin Holewinski0497ab12013-03-30 14:29:21 +00001377 int64_t ElementSize = 0;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001378
1379 // Although PTX has direct support for struct type and array type and LLVM IR
1380 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1381 // support these high level field accesses. Structs and arrays are lowered
1382 // into arrays of bytes.
1383 switch (ETy->getTypeID()) {
1384 case Type::StructTyID:
1385 case Type::ArrayTyID:
1386 case Type::VectorTyID:
1387 ElementSize = TD->getTypeStoreSize(ETy);
Eli Benderskye78ae052014-03-10 20:05:42 +00001388 O << " .b8 " << getSymbolName(GVar) << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001389 if (ElementSize) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001390 O << itostr(ElementSize);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001391 }
1392 O << "]";
1393 break;
1394 default:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001395 assert(0 && "type not supported yet");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001396 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001397 return;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001398}
1399
Justin Holewinski0497ab12013-03-30 14:29:21 +00001400static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
Rafael Espindola08013342013-12-07 19:34:20 +00001401 if (Ty->isSingleValueType())
Justin Holewinskiae556d32012-05-04 20:18:50 +00001402 return TD->getPrefTypeAlignment(Ty);
1403
1404 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1405 if (ATy)
1406 return getOpenCLAlignment(TD, ATy->getElementType());
1407
1408 const VectorType *VTy = dyn_cast<VectorType>(Ty);
1409 if (VTy) {
1410 Type *ETy = VTy->getElementType();
1411 unsigned int numE = VTy->getNumElements();
1412 unsigned int alignE = TD->getPrefTypeAlignment(ETy);
1413 if (numE == 3)
Justin Holewinski0497ab12013-03-30 14:29:21 +00001414 return 4 * alignE;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001415 else
Justin Holewinski0497ab12013-03-30 14:29:21 +00001416 return numE * alignE;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001417 }
1418
1419 const StructType *STy = dyn_cast<StructType>(Ty);
1420 if (STy) {
1421 unsigned int alignStruct = 1;
1422 // Go through each element of the struct and find the
1423 // largest alignment.
Justin Holewinski0497ab12013-03-30 14:29:21 +00001424 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001425 Type *ETy = STy->getElementType(i);
1426 unsigned int align = getOpenCLAlignment(TD, ETy);
1427 if (align > alignStruct)
1428 alignStruct = align;
1429 }
1430 return alignStruct;
1431 }
1432
1433 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1434 if (FTy)
Chandler Carruth5da3f052012-11-01 09:14:31 +00001435 return TD->getPointerPrefAlignment();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001436 return TD->getPrefTypeAlignment(Ty);
1437}
1438
1439void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1440 int paramIndex, raw_ostream &O) {
1441 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1442 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
Eli Benderskye78ae052014-03-10 20:05:42 +00001443 O << getSymbolName(I->getParent()) << "_param_" << paramIndex;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001444 else {
1445 std::string argName = I->getName();
1446 const char *p = argName.c_str();
1447 while (*p) {
1448 if (*p == '.')
1449 O << "_";
1450 else
1451 O << *p;
1452 p++;
1453 }
1454 }
1455}
1456
1457void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1458 Function::const_arg_iterator I, E;
1459 int i = 0;
1460
1461 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1462 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1463 O << *CurrentFnSym << "_param_" << paramIndex;
1464 return;
1465 }
1466
1467 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001468 if (i == paramIndex) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001469 printParamName(I, paramIndex, O);
1470 return;
1471 }
1472 }
1473 llvm_unreachable("paramIndex out of bound");
1474}
1475
Justin Holewinski0497ab12013-03-30 14:29:21 +00001476void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001477 const DataLayout *TD = TM.getDataLayout();
Bill Wendlinge94d8432012-12-07 23:16:57 +00001478 const AttributeSet &PAL = F->getAttributes();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001479 const TargetLowering *TLI = TM.getTargetLowering();
1480 Function::const_arg_iterator I, E;
1481 unsigned paramIndex = 0;
1482 bool first = true;
1483 bool isKernelFunc = llvm::isKernelFunction(*F);
1484 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1485 MVT thePointerTy = TLI->getPointerTy();
1486
1487 O << "(\n";
1488
1489 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
Justin Holewinskie9884092013-03-24 21:17:47 +00001490 Type *Ty = I->getType();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001491
1492 if (!first)
1493 O << ",\n";
1494
1495 first = false;
1496
1497 // Handle image/sampler parameters
1498 if (llvm::isSampler(*I) || llvm::isImage(*I)) {
1499 if (llvm::isImage(*I)) {
1500 std::string sname = I->getName();
1501 if (llvm::isImageWriteOnly(*I))
Eli Benderskye78ae052014-03-10 20:05:42 +00001502 O << "\t.param .surfref " << getSymbolName(F) << "_param_"
Justin Holewinski4c47d872013-05-20 16:42:18 +00001503 << paramIndex;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001504 else // Default image is read_only
Eli Benderskye78ae052014-03-10 20:05:42 +00001505 O << "\t.param .texref " << getSymbolName(F) << "_param_"
Justin Holewinski4c47d872013-05-20 16:42:18 +00001506 << paramIndex;
Justin Holewinski0497ab12013-03-30 14:29:21 +00001507 } else // Should be llvm::isSampler(*I)
Eli Benderskye78ae052014-03-10 20:05:42 +00001508 O << "\t.param .samplerref " << getSymbolName(F) << "_param_"
Justin Holewinski0497ab12013-03-30 14:29:21 +00001509 << paramIndex;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001510 continue;
1511 }
1512
Justin Holewinski0497ab12013-03-30 14:29:21 +00001513 if (PAL.hasAttribute(paramIndex + 1, Attribute::ByVal) == false) {
Gautam Chakrabarti2c283402014-01-28 18:35:29 +00001514 if (Ty->isAggregateType() || Ty->isVectorTy()) {
1515 // Just print .param .align <a> .b8 .param[size];
Justin Holewinskie9884092013-03-24 21:17:47 +00001516 // <a> = PAL.getparamalignment
1517 // size = typeallocsize of element type
Justin Holewinski0497ab12013-03-30 14:29:21 +00001518 unsigned align = PAL.getParamAlignment(paramIndex + 1);
Justin Holewinskie9884092013-03-24 21:17:47 +00001519 if (align == 0)
1520 align = TD->getABITypeAlignment(Ty);
1521
1522 unsigned sz = TD->getTypeAllocSize(Ty);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001523 O << "\t.param .align " << align << " .b8 ";
Justin Holewinskie9884092013-03-24 21:17:47 +00001524 printParamName(I, paramIndex, O);
1525 O << "[" << sz << "]";
1526
1527 continue;
1528 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001529 // Just a scalar
1530 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1531 if (isKernelFunc) {
1532 if (PTy) {
1533 // Special handling for pointer arguments to kernel
1534 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1535
1536 if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
1537 Type *ETy = PTy->getElementType();
1538 int addrSpace = PTy->getAddressSpace();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001539 switch (addrSpace) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001540 default:
1541 O << ".ptr ";
1542 break;
Justin Holewinskib96d1392013-06-10 13:29:47 +00001543 case llvm::ADDRESS_SPACE_CONST:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001544 O << ".ptr .const ";
1545 break;
1546 case llvm::ADDRESS_SPACE_SHARED:
1547 O << ".ptr .shared ";
1548 break;
1549 case llvm::ADDRESS_SPACE_GLOBAL:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001550 O << ".ptr .global ";
1551 break;
1552 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001553 O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001554 }
1555 printParamName(I, paramIndex, O);
1556 continue;
1557 }
1558
1559 // non-pointer scalar to kernel func
Justin Holewinski700b6fa2013-05-20 12:13:28 +00001560 O << "\t.param .";
1561 // Special case: predicate operands become .u8 types
1562 if (Ty->isIntegerTy(1))
1563 O << "u8";
1564 else
1565 O << getPTXFundamentalTypeStr(Ty);
1566 O << " ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001567 printParamName(I, paramIndex, O);
1568 continue;
1569 }
1570 // Non-kernel function, just print .param .b<size> for ABI
Alp Tokerf907b892013-12-05 05:44:44 +00001571 // and .reg .b<size> for non-ABI
Justin Holewinskiae556d32012-05-04 20:18:50 +00001572 unsigned sz = 0;
1573 if (isa<IntegerType>(Ty)) {
1574 sz = cast<IntegerType>(Ty)->getBitWidth();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001575 if (sz < 32)
1576 sz = 32;
1577 } else if (isa<PointerType>(Ty))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001578 sz = thePointerTy.getSizeInBits();
1579 else
1580 sz = Ty->getPrimitiveSizeInBits();
1581 if (isABI)
1582 O << "\t.param .b" << sz << " ";
1583 else
1584 O << "\t.reg .b" << sz << " ";
1585 printParamName(I, paramIndex, O);
1586 continue;
1587 }
1588
1589 // param has byVal attribute. So should be a pointer
1590 const PointerType *PTy = dyn_cast<PointerType>(Ty);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001591 assert(PTy && "Param with byval attribute should be a pointer type");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001592 Type *ETy = PTy->getElementType();
1593
1594 if (isABI || isKernelFunc) {
Gautam Chakrabarti2c283402014-01-28 18:35:29 +00001595 // Just print .param .align <a> .b8 .param[size];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001596 // <a> = PAL.getparamalignment
1597 // size = typeallocsize of element type
Justin Holewinski0497ab12013-03-30 14:29:21 +00001598 unsigned align = PAL.getParamAlignment(paramIndex + 1);
Justin Holewinski2dc9d072012-11-09 23:50:24 +00001599 if (align == 0)
1600 align = TD->getABITypeAlignment(ETy);
1601
Justin Holewinskiae556d32012-05-04 20:18:50 +00001602 unsigned sz = TD->getTypeAllocSize(ETy);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001603 O << "\t.param .align " << align << " .b8 ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001604 printParamName(I, paramIndex, O);
1605 O << "[" << sz << "]";
1606 continue;
1607 } else {
1608 // Split the ETy into constituent parts and
1609 // print .param .b<size> <name> for each part.
1610 // Further, if a part is vector, print the above for
1611 // each vector element.
1612 SmallVector<EVT, 16> vtparts;
1613 ComputeValueVTs(*TLI, ETy, vtparts);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001614 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001615 unsigned elems = 1;
1616 EVT elemtype = vtparts[i];
1617 if (vtparts[i].isVector()) {
1618 elems = vtparts[i].getVectorNumElements();
1619 elemtype = vtparts[i].getVectorElementType();
1620 }
1621
Justin Holewinski0497ab12013-03-30 14:29:21 +00001622 for (unsigned j = 0, je = elems; j != je; ++j) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001623 unsigned sz = elemtype.getSizeInBits();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001624 if (elemtype.isInteger() && (sz < 32))
1625 sz = 32;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001626 O << "\t.reg .b" << sz << " ";
1627 printParamName(I, paramIndex, O);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001628 if (j < je - 1)
1629 O << ",\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001630 ++paramIndex;
1631 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001632 if (i < e - 1)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001633 O << ",\n";
1634 }
1635 --paramIndex;
1636 continue;
1637 }
1638 }
1639
1640 O << "\n)\n";
1641}
1642
1643void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1644 raw_ostream &O) {
1645 const Function *F = MF.getFunction();
1646 emitFunctionParamList(F, O);
1647}
1648
Justin Holewinski0497ab12013-03-30 14:29:21 +00001649void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1650 const MachineFunction &MF) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001651 SmallString<128> Str;
1652 raw_svector_ostream O(Str);
1653
1654 // Map the global virtual register number to a register class specific
1655 // virtual register number starting from 1 with that class.
1656 const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
1657 //unsigned numRegClasses = TRI->getNumRegClasses();
1658
1659 // Emit the Fake Stack Object
1660 const MachineFrameInfo *MFI = MF.getFrameInfo();
1661 int NumBytes = (int) MFI->getStackSize();
1662 if (NumBytes) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001663 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1664 << getFunctionNumber() << "[" << NumBytes << "];\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001665 if (nvptxSubtarget.is64Bit()) {
1666 O << "\t.reg .b64 \t%SP;\n";
1667 O << "\t.reg .b64 \t%SPL;\n";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001668 } else {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001669 O << "\t.reg .b32 \t%SP;\n";
1670 O << "\t.reg .b32 \t%SPL;\n";
1671 }
1672 }
1673
1674 // Go through all virtual registers to establish the mapping between the
1675 // global virtual
1676 // register number and the per class virtual register number.
1677 // We use the per class virtual register number in the ptx output.
1678 unsigned int numVRs = MRI->getNumVirtRegs();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001679 for (unsigned i = 0; i < numVRs; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001680 unsigned int vr = TRI->index2VirtReg(i);
1681 const TargetRegisterClass *RC = MRI->getRegClass(vr);
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001682 DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001683 int n = regmap.size();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001684 regmap.insert(std::make_pair(vr, n + 1));
Justin Holewinskiae556d32012-05-04 20:18:50 +00001685 }
1686
1687 // Emit register declarations
1688 // @TODO: Extract out the real register usage
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001689 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1690 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1691 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1692 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1693 // O << "\t.reg .s64 %rl<" << NVPTXNumRegisters << ">;\n";
1694 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1695 // O << "\t.reg .f64 %fl<" << NVPTXNumRegisters << ">;\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001696
1697 // Emit declaration of the virtual registers or 'physical' registers for
1698 // each register class
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001699 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1700 const TargetRegisterClass *RC = TRI->getRegClass(i);
1701 DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
1702 std::string rcname = getNVPTXRegClassName(RC);
1703 std::string rcStr = getNVPTXRegClassStr(RC);
1704 int n = regmap.size();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001705
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001706 // Only declare those registers that may be used.
1707 if (n) {
1708 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1709 << ">;\n";
1710 }
1711 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001712
1713 OutStreamer.EmitRawText(O.str());
1714}
1715
Justin Holewinskiae556d32012-05-04 20:18:50 +00001716void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001717 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
Justin Holewinskiae556d32012-05-04 20:18:50 +00001718 bool ignored;
1719 unsigned int numHex;
1720 const char *lead;
1721
Justin Holewinski0497ab12013-03-30 14:29:21 +00001722 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001723 numHex = 8;
1724 lead = "0f";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001725 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001726 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1727 numHex = 16;
1728 lead = "0d";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001729 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001730 } else
1731 llvm_unreachable("unsupported fp type");
1732
1733 APInt API = APF.bitcastToAPInt();
1734 std::string hexstr(utohexstr(API.getZExtValue()));
1735 O << lead;
1736 if (hexstr.length() < numHex)
1737 O << std::string(numHex - hexstr.length(), '0');
1738 O << utohexstr(API.getZExtValue());
1739}
1740
Justin Holewinski01f89f02013-05-20 12:13:32 +00001741void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1742 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001743 O << CI->getValue();
1744 return;
1745 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001746 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001747 printFPConstant(CFP, O);
1748 return;
1749 }
1750 if (isa<ConstantPointerNull>(CPV)) {
1751 O << "0";
1752 return;
1753 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001754 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
Eli Benderskye78ae052014-03-10 20:05:42 +00001755 O << getSymbolName(GVar);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001756 return;
1757 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001758 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1759 const Value *v = Cexpr->stripPointerCasts();
1760 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
Eli Benderskye78ae052014-03-10 20:05:42 +00001761 O << getSymbolName(GVar);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001762 return;
1763 } else {
1764 O << *LowerConstant(CPV, *this);
1765 return;
1766 }
1767 }
1768 llvm_unreachable("Not scalar type found in printScalarConstant()");
1769}
1770
Justin Holewinski01f89f02013-05-20 12:13:32 +00001771void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001772 AggBuffer *aggBuffer) {
1773
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001774 const DataLayout *TD = TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001775
1776 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1777 int s = TD->getTypeAllocSize(CPV->getType());
Justin Holewinski0497ab12013-03-30 14:29:21 +00001778 if (s < Bytes)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001779 s = Bytes;
1780 aggBuffer->addZeros(s);
1781 return;
1782 }
1783
1784 unsigned char *ptr;
1785 switch (CPV->getType()->getTypeID()) {
1786
1787 case Type::IntegerTyID: {
1788 const Type *ETy = CPV->getType();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001789 if (ETy == Type::getInt8Ty(CPV->getContext())) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001790 unsigned char c =
1791 (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1792 ptr = &c;
1793 aggBuffer->addBytes(ptr, 1, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001794 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1795 short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1796 ptr = (unsigned char *)&int16;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001797 aggBuffer->addBytes(ptr, 2, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001798 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001799 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001800 int int32 = (int)(constInt->getZExtValue());
1801 ptr = (unsigned char *)&int32;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001802 aggBuffer->addBytes(ptr, 4, Bytes);
1803 break;
Justin Holewinski01f89f02013-05-20 12:13:32 +00001804 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1805 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
Justin Holewinski0497ab12013-03-30 14:29:21 +00001806 ConstantFoldConstantExpression(Cexpr, TD))) {
1807 int int32 = (int)(constInt->getZExtValue());
1808 ptr = (unsigned char *)&int32;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001809 aggBuffer->addBytes(ptr, 4, Bytes);
1810 break;
1811 }
1812 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1813 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1814 aggBuffer->addSymbol(v);
1815 aggBuffer->addZeros(4);
1816 break;
1817 }
1818 }
Craig Topperbdf39a42012-05-24 07:02:50 +00001819 llvm_unreachable("unsupported integer const type");
Justin Holewinski0497ab12013-03-30 14:29:21 +00001820 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001821 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001822 long long int64 = (long long)(constInt->getZExtValue());
1823 ptr = (unsigned char *)&int64;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001824 aggBuffer->addBytes(ptr, 8, Bytes);
1825 break;
Justin Holewinski01f89f02013-05-20 12:13:32 +00001826 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1827 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
Justin Holewinski0497ab12013-03-30 14:29:21 +00001828 ConstantFoldConstantExpression(Cexpr, TD))) {
1829 long long int64 = (long long)(constInt->getZExtValue());
1830 ptr = (unsigned char *)&int64;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001831 aggBuffer->addBytes(ptr, 8, Bytes);
1832 break;
1833 }
1834 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1835 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1836 aggBuffer->addSymbol(v);
1837 aggBuffer->addZeros(8);
1838 break;
1839 }
1840 }
1841 llvm_unreachable("unsupported integer const type");
Craig Topperbdf39a42012-05-24 07:02:50 +00001842 } else
Justin Holewinskiae556d32012-05-04 20:18:50 +00001843 llvm_unreachable("unsupported integer const type");
1844 break;
1845 }
1846 case Type::FloatTyID:
1847 case Type::DoubleTyID: {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001848 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001849 const Type *Ty = CFP->getType();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001850 if (Ty == Type::getFloatTy(CPV->getContext())) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001851 float float32 = (float) CFP->getValueAPF().convertToFloat();
1852 ptr = (unsigned char *)&float32;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001853 aggBuffer->addBytes(ptr, 4, Bytes);
1854 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1855 double float64 = CFP->getValueAPF().convertToDouble();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001856 ptr = (unsigned char *)&float64;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001857 aggBuffer->addBytes(ptr, 8, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001858 } else {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001859 llvm_unreachable("unsupported fp const type");
1860 }
1861 break;
1862 }
1863 case Type::PointerTyID: {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001864 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001865 aggBuffer->addSymbol(GVar);
Justin Holewinski01f89f02013-05-20 12:13:32 +00001866 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1867 const Value *v = Cexpr->stripPointerCasts();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001868 aggBuffer->addSymbol(v);
1869 }
1870 unsigned int s = TD->getTypeAllocSize(CPV->getType());
1871 aggBuffer->addZeros(s);
1872 break;
1873 }
1874
1875 case Type::ArrayTyID:
1876 case Type::VectorTyID:
1877 case Type::StructTyID: {
1878 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
Justin Holewinski95564bd2013-09-19 12:51:46 +00001879 isa<ConstantStruct>(CPV) || isa<ConstantDataSequential>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001880 int ElementSize = TD->getTypeAllocSize(CPV->getType());
1881 bufferAggregateConstant(CPV, aggBuffer);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001882 if (Bytes > ElementSize)
1883 aggBuffer->addZeros(Bytes - ElementSize);
1884 } else if (isa<ConstantAggregateZero>(CPV))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001885 aggBuffer->addZeros(Bytes);
1886 else
1887 llvm_unreachable("Unexpected Constant type");
1888 break;
1889 }
1890
1891 default:
1892 llvm_unreachable("unsupported type");
1893 }
1894}
1895
Justin Holewinski01f89f02013-05-20 12:13:32 +00001896void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001897 AggBuffer *aggBuffer) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001898 const DataLayout *TD = TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001899 int Bytes;
1900
1901 // Old constants
1902 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1903 if (CPV->getNumOperands())
1904 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1905 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1906 return;
1907 }
1908
1909 if (const ConstantDataSequential *CDS =
Justin Holewinski0497ab12013-03-30 14:29:21 +00001910 dyn_cast<ConstantDataSequential>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001911 if (CDS->getNumElements())
1912 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1913 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1914 aggBuffer);
1915 return;
1916 }
1917
Justin Holewinskiae556d32012-05-04 20:18:50 +00001918 if (isa<ConstantStruct>(CPV)) {
1919 if (CPV->getNumOperands()) {
1920 StructType *ST = cast<StructType>(CPV->getType());
1921 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001922 if (i == (e - 1))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001923 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
Justin Holewinski0497ab12013-03-30 14:29:21 +00001924 TD->getTypeAllocSize(ST) -
1925 TD->getStructLayout(ST)->getElementOffset(i);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001926 else
Justin Holewinski0497ab12013-03-30 14:29:21 +00001927 Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
1928 TD->getStructLayout(ST)->getElementOffset(i);
1929 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001930 }
1931 }
1932 return;
1933 }
Craig Topperbdf39a42012-05-24 07:02:50 +00001934 llvm_unreachable("unsupported constant type in printAggregateConstant()");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001935}
1936
1937// buildTypeNameMap - Run through symbol table looking for type names.
1938//
1939
Justin Holewinskiae556d32012-05-04 20:18:50 +00001940bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
1941
1942 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
1943
Justin Holewinski0497ab12013-03-30 14:29:21 +00001944 if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
1945 !PI->second.compare("struct._image2d_t") ||
1946 !PI->second.compare("struct._image3d_t")))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001947 return true;
1948
1949 return false;
1950}
1951
Justin Holewinskiae556d32012-05-04 20:18:50 +00001952
Justin Holewinski0497ab12013-03-30 14:29:21 +00001953bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
1954 switch (MI.getOpcode()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001955 default:
1956 return false;
Justin Holewinski0497ab12013-03-30 14:29:21 +00001957 case NVPTX::CallArgBeginInst:
1958 case NVPTX::CallArgEndInst0:
1959 case NVPTX::CallArgEndInst1:
1960 case NVPTX::CallArgF32:
1961 case NVPTX::CallArgF64:
1962 case NVPTX::CallArgI16:
1963 case NVPTX::CallArgI32:
1964 case NVPTX::CallArgI32imm:
1965 case NVPTX::CallArgI64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001966 case NVPTX::CallArgParam:
1967 case NVPTX::CallVoidInst:
1968 case NVPTX::CallVoidInstReg:
1969 case NVPTX::Callseq_End:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001970 case NVPTX::CallVoidInstReg64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001971 case NVPTX::DeclareParamInst:
1972 case NVPTX::DeclareRetMemInst:
1973 case NVPTX::DeclareRetRegInst:
1974 case NVPTX::DeclareRetScalarInst:
1975 case NVPTX::DeclareScalarParamInst:
1976 case NVPTX::DeclareScalarRegInst:
1977 case NVPTX::StoreParamF32:
1978 case NVPTX::StoreParamF64:
1979 case NVPTX::StoreParamI16:
1980 case NVPTX::StoreParamI32:
1981 case NVPTX::StoreParamI64:
1982 case NVPTX::StoreParamI8:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001983 case NVPTX::StoreRetvalF32:
1984 case NVPTX::StoreRetvalF64:
1985 case NVPTX::StoreRetvalI16:
1986 case NVPTX::StoreRetvalI32:
1987 case NVPTX::StoreRetvalI64:
1988 case NVPTX::StoreRetvalI8:
1989 case NVPTX::LastCallArgF32:
1990 case NVPTX::LastCallArgF64:
1991 case NVPTX::LastCallArgI16:
1992 case NVPTX::LastCallArgI32:
1993 case NVPTX::LastCallArgI32imm:
1994 case NVPTX::LastCallArgI64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001995 case NVPTX::LastCallArgParam:
1996 case NVPTX::LoadParamMemF32:
1997 case NVPTX::LoadParamMemF64:
1998 case NVPTX::LoadParamMemI16:
1999 case NVPTX::LoadParamMemI32:
2000 case NVPTX::LoadParamMemI64:
2001 case NVPTX::LoadParamMemI8:
Justin Holewinski0497ab12013-03-30 14:29:21 +00002002 case NVPTX::PrototypeInst:
2003 case NVPTX::DBG_VALUE:
Justin Holewinskiae556d32012-05-04 20:18:50 +00002004 return true;
2005 }
2006 return false;
2007}
2008
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002009/// PrintAsmOperand - Print out an operand for an inline asm expression.
2010///
2011bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2012 unsigned AsmVariant,
2013 const char *ExtraCode, raw_ostream &O) {
2014 if (ExtraCode && ExtraCode[0]) {
2015 if (ExtraCode[1] != 0)
2016 return true; // Unknown modifier.
2017
2018 switch (ExtraCode[0]) {
2019 default:
2020 // See if this is a generic print operand
2021 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2022 case 'r':
2023 break;
2024 }
2025 }
2026
2027 printOperand(MI, OpNo, O);
2028
2029 return false;
2030}
2031
2032bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2033 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2034 const char *ExtraCode, raw_ostream &O) {
2035 if (ExtraCode && ExtraCode[0])
2036 return true; // Unknown modifier
2037
2038 O << '[';
2039 printMemOperand(MI, OpNo, O);
2040 O << ']';
2041
2042 return false;
2043}
2044
2045void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2046 raw_ostream &O, const char *Modifier) {
2047 const MachineOperand &MO = MI->getOperand(opNum);
2048 switch (MO.getType()) {
2049 case MachineOperand::MO_Register:
2050 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2051 if (MO.getReg() == NVPTX::VRDepot)
2052 O << DEPOTNAME << getFunctionNumber();
2053 else
2054 O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2055 } else {
Justin Holewinski660597d2013-10-11 12:39:36 +00002056 emitVirtualRegister(MO.getReg(), O);
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002057 }
2058 return;
2059
2060 case MachineOperand::MO_Immediate:
2061 if (!Modifier)
2062 O << MO.getImm();
2063 else if (strstr(Modifier, "vec") == Modifier)
2064 printVecModifiedImmediate(MO, Modifier, O);
2065 else
2066 llvm_unreachable(
2067 "Don't know how to handle modifier on immediate operand");
2068 return;
2069
2070 case MachineOperand::MO_FPImmediate:
2071 printFPConstant(MO.getFPImm(), O);
2072 break;
2073
2074 case MachineOperand::MO_GlobalAddress:
Eli Benderskye78ae052014-03-10 20:05:42 +00002075 O << getSymbolName(MO.getGlobal());
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002076 break;
2077
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002078 case MachineOperand::MO_MachineBasicBlock:
2079 O << *MO.getMBB()->getSymbol();
2080 return;
2081
2082 default:
2083 llvm_unreachable("Operand type not supported.");
2084 }
2085}
2086
2087void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2088 raw_ostream &O, const char *Modifier) {
2089 printOperand(MI, opNum, O);
2090
2091 if (Modifier && !strcmp(Modifier, "add")) {
2092 O << ", ";
2093 printOperand(MI, opNum + 1, O);
2094 } else {
2095 if (MI->getOperand(opNum + 1).isImm() &&
2096 MI->getOperand(opNum + 1).getImm() == 0)
2097 return; // don't print ',0' or '+0'
2098 O << "+";
2099 printOperand(MI, opNum + 1, O);
2100 }
2101}
2102
2103
Justin Holewinskiae556d32012-05-04 20:18:50 +00002104// Force static initialization.
2105extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2106 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2107 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2108}
2109
Justin Holewinskiae556d32012-05-04 20:18:50 +00002110void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2111 std::stringstream temp;
Justin Holewinski0497ab12013-03-30 14:29:21 +00002112 LineReader *reader = this->getReader(filename.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +00002113 temp << "\n//";
2114 temp << filename.str();
2115 temp << ":";
2116 temp << line;
2117 temp << " ";
2118 temp << reader->readLine(line);
2119 temp << "\n";
2120 this->OutStreamer.EmitRawText(Twine(temp.str()));
2121}
2122
Justin Holewinskiae556d32012-05-04 20:18:50 +00002123LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00002124 if (reader == NULL) {
2125 reader = new LineReader(filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002126 }
2127
2128 if (reader->fileName() != filename) {
2129 delete reader;
Justin Holewinski0497ab12013-03-30 14:29:21 +00002130 reader = new LineReader(filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002131 }
2132
2133 return reader;
2134}
2135
Eli Benderskye78ae052014-03-10 20:05:42 +00002136std::string NVPTXAsmPrinter::getSymbolName(const GlobalValue *GV) const {
2137 // Obtain the original symbol name.
2138 MCSymbol *Sym = getSymbol(GV);
2139 std::string OriginalName;
2140 raw_string_ostream OriginalNameStream(OriginalName);
2141 Sym->print(OriginalNameStream);
2142 OriginalNameStream.flush();
2143
2144 // MCSymbol already does symbol-name sanitizing, so names it produces are
2145 // valid for object files. The only two characters valida in that context
2146 // and indigestible by the PTX assembler are '.' and '@'.
2147 std::string CleanName;
2148 raw_string_ostream CleanNameStream(CleanName);
2149 for (unsigned I = 0, E = OriginalName.size(); I != E; ++I) {
2150 char C = OriginalName[I];
2151 if (C == '.') {
2152 CleanNameStream << "_$_";
2153 } else if (C == '@') {
2154 CleanNameStream << "_%_";
2155 } else {
2156 CleanNameStream << C;
2157 }
2158 }
2159
2160 return CleanNameStream.str();
2161}
2162
Justin Holewinski0497ab12013-03-30 14:29:21 +00002163std::string LineReader::readLine(unsigned lineNum) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00002164 if (lineNum < theCurLine) {
2165 theCurLine = 0;
Justin Holewinski0497ab12013-03-30 14:29:21 +00002166 fstr.seekg(0, std::ios::beg);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002167 }
2168 while (theCurLine < lineNum) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00002169 fstr.getline(buff, 500);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002170 theCurLine++;
2171 }
2172 return buff;
2173}
2174
2175// Force static initialization.
2176extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2177 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2178 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2179}