blob: e3187a4dd8fb0c44718dbdc934bbb7c76a15b9f9 [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 Carruthd9903882015-01-14 11:23:27 +000021#include "NVPTXMachineFunctionInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "NVPTXRegisterInfo.h"
23#include "NVPTXTargetMachine.h"
24#include "NVPTXUtilities.h"
25#include "cl_common_defines.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000026#include "llvm/ADT/StringExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/Analysis/ConstantFolding.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000028#include "llvm/CodeGen/Analysis.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000029#include "llvm/CodeGen/MachineFrameInfo.h"
Jingyue Wu0220df02015-02-01 02:27:45 +000030#include "llvm/CodeGen/MachineLoopInfo.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000031#include "llvm/CodeGen/MachineModuleInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include "llvm/CodeGen/MachineRegisterInfo.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000033#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/DerivedTypes.h"
35#include "llvm/IR/Function.h"
36#include "llvm/IR/GlobalVariable.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000037#include "llvm/IR/Mangler.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/Module.h"
39#include "llvm/IR/Operator.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000040#include "llvm/MC/MCStreamer.h"
41#include "llvm/MC/MCSymbol.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000042#include "llvm/Support/CommandLine.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000043#include "llvm/Support/ErrorHandling.h"
44#include "llvm/Support/FormattedStream.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000045#include "llvm/Support/Path.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000046#include "llvm/Support/TargetRegistry.h"
47#include "llvm/Support/TimeValue.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000048#include "llvm/Target/TargetLoweringObjectFile.h"
Jingyue Wu0220df02015-02-01 02:27:45 +000049#include "llvm/Transforms/Utils/UnrollLoop.h"
Bill Wendlinge38859d2012-06-28 00:05:13 +000050#include <sstream>
Justin Holewinskiae556d32012-05-04 20:18:50 +000051using namespace llvm;
52
Justin Holewinskiae556d32012-05-04 20:18:50 +000053#define DEPOTNAME "__local_depot"
54
55static cl::opt<bool>
Nadav Rotem7f27e0b2013-10-18 23:38:13 +000056EmitLineNumbers("nvptx-emit-line-numbers", cl::Hidden,
Justin Holewinskiae556d32012-05-04 20:18:50 +000057 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
58 cl::init(true));
59
Benjamin Kramer7ad41002013-10-27 11:31:46 +000060static cl::opt<bool>
Nadav Rotem7f27e0b2013-10-18 23:38:13 +000061InterleaveSrc("nvptx-emit-src", cl::ZeroOrMore, cl::Hidden,
Justin Holewinski0497ab12013-03-30 14:29:21 +000062 cl::desc("NVPTX Specific: Emit source line in ptx file"),
Benjamin Kramer7ad41002013-10-27 11:31:46 +000063 cl::init(false));
Justin Holewinskiae556d32012-05-04 20:18:50 +000064
Justin Holewinski2c5ac702012-11-16 21:03:51 +000065namespace {
66/// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
67/// depends.
Justin Holewinski01f89f02013-05-20 12:13:32 +000068void DiscoverDependentGlobals(const Value *V,
69 DenseSet<const GlobalVariable *> &Globals) {
70 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
Justin Holewinski2c5ac702012-11-16 21:03:51 +000071 Globals.insert(GV);
72 else {
Justin Holewinski01f89f02013-05-20 12:13:32 +000073 if (const User *U = dyn_cast<User>(V)) {
Justin Holewinski2c5ac702012-11-16 21:03:51 +000074 for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
75 DiscoverDependentGlobals(U->getOperand(i), Globals);
76 }
77 }
78 }
79}
Justin Holewinskiae556d32012-05-04 20:18:50 +000080
Justin Holewinski2c5ac702012-11-16 21:03:51 +000081/// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
82/// instances to be emitted, but only after any dependents have been added
83/// first.
Justin Holewinski0497ab12013-03-30 14:29:21 +000084void VisitGlobalVariableForEmission(
Justin Holewinski01f89f02013-05-20 12:13:32 +000085 const GlobalVariable *GV, SmallVectorImpl<const GlobalVariable *> &Order,
86 DenseSet<const GlobalVariable *> &Visited,
87 DenseSet<const GlobalVariable *> &Visiting) {
Justin Holewinski2c5ac702012-11-16 21:03:51 +000088 // Have we already visited this one?
Justin Holewinski0497ab12013-03-30 14:29:21 +000089 if (Visited.count(GV))
90 return;
Justin Holewinski2c5ac702012-11-16 21:03:51 +000091
92 // Do we have a circular dependency?
Benjamin Kramer2c99e412014-10-10 15:32:50 +000093 if (!Visiting.insert(GV).second)
Justin Holewinski2c5ac702012-11-16 21:03:51 +000094 report_fatal_error("Circular dependency found in global variable set");
95
Justin Holewinski2c5ac702012-11-16 21:03:51 +000096 // 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
Justin Holewinski0497ab12013-03-30 14:29:21 +0000113void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000114 if (!EmitLineNumbers)
115 return;
116 if (ignoreLoc(MI))
117 return;
118
119 DebugLoc curLoc = MI.getDebugLoc();
120
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +0000121 if (!prevDebugLoc && !curLoc)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000122 return;
123
124 if (prevDebugLoc == curLoc)
125 return;
126
127 prevDebugLoc = curLoc;
128
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +0000129 if (!curLoc)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000130 return;
131
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +0000132 DIScope Scope(curLoc.getScope());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000133
Manman Ren983a16c2013-06-28 05:43:10 +0000134 assert((!Scope || Scope.isScope()) &&
135 "Scope of a DebugLoc should be null or a DIScope.");
136 if (!Scope)
137 return;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000138
139 StringRef fileName(Scope.getFilename());
140 StringRef dirName(Scope.getDirectory());
141 SmallString<128> FullPathName = dirName;
142 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
143 sys::path::append(FullPathName, fileName);
Yaron Keren075759a2015-03-30 15:42:36 +0000144 fileName = FullPathName;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000145 }
146
Yaron Keren075759a2015-03-30 15:42:36 +0000147 if (filenameMap.find(fileName) == filenameMap.end())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000148 return;
149
Justin Holewinskiae556d32012-05-04 20:18:50 +0000150 // Emit the line from the source file.
Benjamin Kramer7ad41002013-10-27 11:31:46 +0000151 if (InterleaveSrc)
Yaron Keren075759a2015-03-30 15:42:36 +0000152 this->emitSrcInText(fileName, curLoc.getLine());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000153
154 std::stringstream temp;
Yaron Keren075759a2015-03-30 15:42:36 +0000155 temp << "\t.loc " << filenameMap[fileName] << " " << curLoc.getLine()
Justin Holewinski0497ab12013-03-30 14:29:21 +0000156 << " " << curLoc.getCol();
Yaron Keren075759a2015-03-30 15:42:36 +0000157 OutStreamer.EmitRawText(temp.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000158}
159
160void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
161 SmallString<128> Str;
162 raw_svector_ostream OS(Str);
Eric Christopherbeffc4e2015-02-19 00:08:23 +0000163 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() == NVPTX::CUDA)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000164 emitLineNumberAsDotLoc(*MI);
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000165
166 MCInst Inst;
167 lowerToMCInst(MI, Inst);
David Woodhousee6c13e42014-01-28 23:12:42 +0000168 EmitToStreamer(OutStreamer, Inst);
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000169}
170
Justin Holewinski30d56a72014-04-09 15:39:15 +0000171// Handle symbol backtracking for targets that do not support image handles
172bool NVPTXAsmPrinter::lowerImageHandleOperand(const MachineInstr *MI,
173 unsigned OpNo, MCOperand &MCOp) {
174 const MachineOperand &MO = MI->getOperand(OpNo);
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000175 const MCInstrDesc &MCID = MI->getDesc();
Justin Holewinski30d56a72014-04-09 15:39:15 +0000176
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000177 if (MCID.TSFlags & NVPTXII::IsTexFlag) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000178 // This is a texture fetch, so operand 4 is a texref and operand 5 is
179 // a samplerref
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000180 if (OpNo == 4 && MO.isImm()) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000181 lowerImageHandleSymbol(MO.getImm(), MCOp);
182 return true;
183 }
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000184 if (OpNo == 5 && MO.isImm() && !(MCID.TSFlags & NVPTXII::IsTexModeUnifiedFlag)) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000185 lowerImageHandleSymbol(MO.getImm(), MCOp);
186 return true;
187 }
188
189 return false;
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000190 } else if (MCID.TSFlags & NVPTXII::IsSuldMask) {
191 unsigned VecSize =
192 1 << (((MCID.TSFlags & NVPTXII::IsSuldMask) >> NVPTXII::IsSuldShift) - 1);
193
194 // For a surface load of vector size N, the Nth operand will be the surfref
195 if (OpNo == VecSize && MO.isImm()) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000196 lowerImageHandleSymbol(MO.getImm(), MCOp);
197 return true;
198 }
199
200 return false;
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000201 } else if (MCID.TSFlags & NVPTXII::IsSustFlag) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000202 // This is a surface store, so operand 0 is a surfref
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000203 if (OpNo == 0 && MO.isImm()) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000204 lowerImageHandleSymbol(MO.getImm(), MCOp);
205 return true;
206 }
207
208 return false;
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000209 } else if (MCID.TSFlags & NVPTXII::IsSurfTexQueryFlag) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000210 // This is a query, so operand 1 is a surfref/texref
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000211 if (OpNo == 1 && MO.isImm()) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000212 lowerImageHandleSymbol(MO.getImm(), MCOp);
213 return true;
214 }
215
216 return false;
217 }
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000218
219 return false;
Justin Holewinski30d56a72014-04-09 15:39:15 +0000220}
221
222void NVPTXAsmPrinter::lowerImageHandleSymbol(unsigned Index, MCOperand &MCOp) {
223 // Ewwww
224 TargetMachine &TM = const_cast<TargetMachine&>(MF->getTarget());
225 NVPTXTargetMachine &nvTM = static_cast<NVPTXTargetMachine&>(TM);
226 const NVPTXMachineFunctionInfo *MFI = MF->getInfo<NVPTXMachineFunctionInfo>();
227 const char *Sym = MFI->getImageHandleSymbol(Index);
228 std::string *SymNamePtr =
229 nvTM.getManagedStrPool()->getManagedString(Sym);
230 MCOp = GetSymbolRef(OutContext.GetOrCreateSymbol(
231 StringRef(SymNamePtr->c_str())));
232}
233
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000234void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
235 OutMI.setOpcode(MI->getOpcode());
Justin Holewinski3d49e5c2013-11-15 12:30:04 +0000236 // Special: Do not mangle symbol operand of CALL_PROTOTYPE
237 if (MI->getOpcode() == NVPTX::CALL_PROTOTYPE) {
238 const MachineOperand &MO = MI->getOperand(0);
Justin Holewinski30d56a72014-04-09 15:39:15 +0000239 OutMI.addOperand(GetSymbolRef(
Justin Holewinski3d49e5c2013-11-15 12:30:04 +0000240 OutContext.GetOrCreateSymbol(Twine(MO.getSymbolName()))));
241 return;
242 }
243
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000244 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
245 const MachineOperand &MO = MI->getOperand(i);
246
247 MCOperand MCOp;
Eric Christopher6aad8b12015-02-19 00:08:14 +0000248 if (!nvptxSubtarget->hasImageHandles()) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000249 if (lowerImageHandleOperand(MI, i, MCOp)) {
250 OutMI.addOperand(MCOp);
251 continue;
252 }
253 }
254
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000255 if (lowerOperand(MO, MCOp))
256 OutMI.addOperand(MCOp);
257 }
258}
259
260bool NVPTXAsmPrinter::lowerOperand(const MachineOperand &MO,
261 MCOperand &MCOp) {
262 switch (MO.getType()) {
263 default: llvm_unreachable("unknown operand type");
264 case MachineOperand::MO_Register:
265 MCOp = MCOperand::CreateReg(encodeVirtualRegister(MO.getReg()));
266 break;
267 case MachineOperand::MO_Immediate:
268 MCOp = MCOperand::CreateImm(MO.getImm());
269 break;
270 case MachineOperand::MO_MachineBasicBlock:
271 MCOp = MCOperand::CreateExpr(MCSymbolRefExpr::Create(
272 MO.getMBB()->getSymbol(), OutContext));
273 break;
274 case MachineOperand::MO_ExternalSymbol:
Justin Holewinski30d56a72014-04-09 15:39:15 +0000275 MCOp = GetSymbolRef(GetExternalSymbolSymbol(MO.getSymbolName()));
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000276 break;
277 case MachineOperand::MO_GlobalAddress:
Justin Holewinski30d56a72014-04-09 15:39:15 +0000278 MCOp = GetSymbolRef(getSymbol(MO.getGlobal()));
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000279 break;
280 case MachineOperand::MO_FPImmediate: {
281 const ConstantFP *Cnt = MO.getFPImm();
282 APFloat Val = Cnt->getValueAPF();
283
284 switch (Cnt->getType()->getTypeID()) {
285 default: report_fatal_error("Unsupported FP type"); break;
286 case Type::FloatTyID:
287 MCOp = MCOperand::CreateExpr(
288 NVPTXFloatMCExpr::CreateConstantFPSingle(Val, OutContext));
289 break;
290 case Type::DoubleTyID:
291 MCOp = MCOperand::CreateExpr(
292 NVPTXFloatMCExpr::CreateConstantFPDouble(Val, OutContext));
293 break;
294 }
295 break;
296 }
297 }
298 return true;
299}
300
301unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
Justin Holewinski871ec932013-08-06 14:13:31 +0000302 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
303 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000304
Justin Holewinski871ec932013-08-06 14:13:31 +0000305 DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
306 unsigned RegNum = RegMap[Reg];
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000307
Justin Holewinski871ec932013-08-06 14:13:31 +0000308 // Encode the register class in the upper 4 bits
309 // Must be kept in sync with NVPTXInstPrinter::printRegName
310 unsigned Ret = 0;
311 if (RC == &NVPTX::Int1RegsRegClass) {
312 Ret = (1 << 28);
313 } else if (RC == &NVPTX::Int16RegsRegClass) {
314 Ret = (2 << 28);
315 } else if (RC == &NVPTX::Int32RegsRegClass) {
316 Ret = (3 << 28);
317 } else if (RC == &NVPTX::Int64RegsRegClass) {
318 Ret = (4 << 28);
319 } else if (RC == &NVPTX::Float32RegsRegClass) {
320 Ret = (5 << 28);
321 } else if (RC == &NVPTX::Float64RegsRegClass) {
322 Ret = (6 << 28);
323 } else {
324 report_fatal_error("Bad register class");
325 }
326
327 // Insert the vreg number
328 Ret |= (RegNum & 0x0FFFFFFF);
329 return Ret;
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000330 } else {
Justin Holewinski871ec932013-08-06 14:13:31 +0000331 // Some special-use registers are actually physical registers.
332 // Encode this as the register class ID of 0 and the real register ID.
333 return Reg & 0x0FFFFFFF;
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000334 }
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000335}
336
Justin Holewinski30d56a72014-04-09 15:39:15 +0000337MCOperand NVPTXAsmPrinter::GetSymbolRef(const MCSymbol *Symbol) {
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000338 const MCExpr *Expr;
Justin Holewinski8b24e1e2013-08-06 23:06:42 +0000339 Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None,
340 OutContext);
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000341 return MCOperand::CreateExpr(Expr);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000342}
343
Justin Holewinski0497ab12013-03-30 14:29:21 +0000344void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
Eric Christopher8b770652015-01-26 19:03:15 +0000345 const DataLayout *TD = TM.getDataLayout();
Eric Christopher6aad8b12015-02-19 00:08:14 +0000346 const TargetLowering *TLI = nvptxSubtarget->getTargetLowering();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000347
348 Type *Ty = F->getReturnType();
349
Eric Christopher6aad8b12015-02-19 00:08:14 +0000350 bool isABI = (nvptxSubtarget->getSmVersion() >= 20);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000351
352 if (Ty->getTypeID() == Type::VoidTyID)
353 return;
354
355 O << " (";
356
357 if (isABI) {
Rafael Espindola08013342013-12-07 19:34:20 +0000358 if (Ty->isFloatingPointTy() || Ty->isIntegerTy()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000359 unsigned size = 0;
360 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
361 size = ITy->getBitWidth();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000362 if (size < 32)
363 size = 32;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000364 } else {
Justin Holewinski0497ab12013-03-30 14:29:21 +0000365 assert(Ty->isFloatingPointTy() && "Floating point type expected here");
Justin Holewinskiae556d32012-05-04 20:18:50 +0000366 size = Ty->getPrimitiveSizeInBits();
367 }
368
369 O << ".param .b" << size << " func_retval0";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000370 } else if (isa<PointerType>(Ty)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000371 O << ".param .b" << TLI->getPointerTy().getSizeInBits()
Justin Holewinski0497ab12013-03-30 14:29:21 +0000372 << " func_retval0";
Craig Topperd3c02f12015-01-05 10:15:49 +0000373 } else if ((Ty->getTypeID() == Type::StructTyID) || isa<VectorType>(Ty)) {
374 unsigned totalsz = TD->getTypeAllocSize(Ty);
375 unsigned retAlignment = 0;
376 if (!llvm::getAlign(*F, 0, retAlignment))
377 retAlignment = TD->getABITypeAlignment(Ty);
378 O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
379 << "]";
380 } else
381 llvm_unreachable("Unknown return type");
Justin Holewinskiae556d32012-05-04 20:18:50 +0000382 } else {
383 SmallVector<EVT, 16> vtparts;
384 ComputeValueVTs(*TLI, Ty, vtparts);
385 unsigned idx = 0;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000386 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000387 unsigned elems = 1;
388 EVT elemtype = vtparts[i];
389 if (vtparts[i].isVector()) {
390 elems = vtparts[i].getVectorNumElements();
391 elemtype = vtparts[i].getVectorElementType();
392 }
393
Justin Holewinski0497ab12013-03-30 14:29:21 +0000394 for (unsigned j = 0, je = elems; j != je; ++j) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000395 unsigned sz = elemtype.getSizeInBits();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000396 if (elemtype.isInteger() && (sz < 32))
397 sz = 32;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000398 O << ".reg .b" << sz << " func_retval" << idx;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000399 if (j < je - 1)
400 O << ", ";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000401 ++idx;
402 }
Justin Holewinski0497ab12013-03-30 14:29:21 +0000403 if (i < e - 1)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000404 O << ", ";
405 }
406 }
407 O << ") ";
408 return;
409}
410
411void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
412 raw_ostream &O) {
413 const Function *F = MF.getFunction();
414 printReturnValStr(F, O);
415}
416
Jingyue Wu0220df02015-02-01 02:27:45 +0000417// Return true if MBB is the header of a loop marked with
418// llvm.loop.unroll.disable.
Jingyue Wu5bbcdaa2015-02-03 17:57:38 +0000419// TODO: consider "#pragma unroll 1" which is equivalent to "#pragma nounroll".
Jingyue Wu0220df02015-02-01 02:27:45 +0000420bool NVPTXAsmPrinter::isLoopHeaderOfNoUnroll(
421 const MachineBasicBlock &MBB) const {
422 MachineLoopInfo &LI = getAnalysis<MachineLoopInfo>();
Jingyue Wu5bbcdaa2015-02-03 17:57:38 +0000423 // TODO: isLoopHeader() should take "const MachineBasicBlock *".
Jingyue Wu0220df02015-02-01 02:27:45 +0000424 // We insert .pragma "nounroll" only to the loop header.
425 if (!LI.isLoopHeader(const_cast<MachineBasicBlock *>(&MBB)))
426 return false;
427
428 // llvm.loop.unroll.disable is marked on the back edges of a loop. Therefore,
429 // we iterate through each back edge of the loop with header MBB, and check
430 // whether its metadata contains llvm.loop.unroll.disable.
431 for (auto I = MBB.pred_begin(); I != MBB.pred_end(); ++I) {
432 const MachineBasicBlock *PMBB = *I;
433 if (LI.getLoopFor(PMBB) != LI.getLoopFor(&MBB)) {
434 // Edges from other loops to MBB are not back edges.
435 continue;
436 }
437 if (const BasicBlock *PBB = PMBB->getBasicBlock()) {
Jingyue Wu49a766e2015-02-02 20:41:11 +0000438 if (MDNode *LoopID = PBB->getTerminator()->getMetadata("llvm.loop")) {
Jingyue Wu0220df02015-02-01 02:27:45 +0000439 if (GetUnrollMetadata(LoopID, "llvm.loop.unroll.disable"))
440 return true;
441 }
442 }
443 }
444 return false;
445}
446
447void NVPTXAsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
448 AsmPrinter::EmitBasicBlockStart(MBB);
449 if (isLoopHeaderOfNoUnroll(MBB))
450 OutStreamer.EmitRawText(StringRef("\t.pragma \"nounroll\";\n"));
451}
452
Justin Holewinskiae556d32012-05-04 20:18:50 +0000453void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
454 SmallString<128> Str;
455 raw_svector_ostream O(Str);
456
Justin Holewinski01f89f02013-05-20 12:13:32 +0000457 if (!GlobalsEmitted) {
458 emitGlobals(*MF->getFunction()->getParent());
459 GlobalsEmitted = true;
460 }
461
Justin Holewinskiae556d32012-05-04 20:18:50 +0000462 // Set up
463 MRI = &MF->getRegInfo();
464 F = MF->getFunction();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000465 emitLinkageDirective(F, O);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000466 if (llvm::isKernelFunction(*F))
467 O << ".entry ";
468 else {
469 O << ".func ";
470 printReturnValStr(*MF, O);
471 }
472
473 O << *CurrentFnSym;
474
475 emitFunctionParamList(*MF, O);
476
477 if (llvm::isKernelFunction(*F))
478 emitKernelFunctionDirectives(*F, O);
479
480 OutStreamer.EmitRawText(O.str());
481
482 prevDebugLoc = DebugLoc();
483}
484
485void NVPTXAsmPrinter::EmitFunctionBodyStart() {
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +0000486 VRegMapping.clear();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000487 OutStreamer.EmitRawText(StringRef("{\n"));
488 setAndEmitFunctionVirtualRegisters(*MF);
489
490 SmallString<128> Str;
491 raw_svector_ostream O(Str);
492 emitDemotedVars(MF->getFunction(), O);
493 OutStreamer.EmitRawText(O.str());
494}
495
496void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
497 OutStreamer.EmitRawText(StringRef("}\n"));
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +0000498 VRegMapping.clear();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000499}
500
Justin Holewinski660597d2013-10-11 12:39:36 +0000501void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
502 unsigned RegNo = MI->getOperand(0).getReg();
Andrew Kaylor5c73e1f2015-03-24 23:37:10 +0000503 if (TargetRegisterInfo::isVirtualRegister(RegNo)) {
Justin Holewinski660597d2013-10-11 12:39:36 +0000504 OutStreamer.AddComment(Twine("implicit-def: ") +
505 getVirtualRegisterName(RegNo));
506 } else {
Eric Christopher6aad8b12015-02-19 00:08:14 +0000507 OutStreamer.AddComment(Twine("implicit-def: ") +
508 nvptxSubtarget->getRegisterInfo()->getName(RegNo));
Justin Holewinski660597d2013-10-11 12:39:36 +0000509 }
510 OutStreamer.AddBlankLine();
511}
512
Justin Holewinski0497ab12013-03-30 14:29:21 +0000513void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
514 raw_ostream &O) const {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000515 // If the NVVM IR has some of reqntid* specified, then output
516 // the reqntid directive, and set the unspecified ones to 1.
517 // If none of reqntid* is specified, don't output reqntid directive.
518 unsigned reqntidx, reqntidy, reqntidz;
519 bool specified = false;
Eli Bendersky3e840192015-03-23 16:26:23 +0000520 if (!llvm::getReqNTIDx(F, reqntidx))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000521 reqntidx = 1;
522 else
523 specified = true;
Eli Bendersky3e840192015-03-23 16:26:23 +0000524 if (!llvm::getReqNTIDy(F, reqntidy))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000525 reqntidy = 1;
526 else
527 specified = true;
Eli Bendersky3e840192015-03-23 16:26:23 +0000528 if (!llvm::getReqNTIDz(F, reqntidz))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000529 reqntidz = 1;
530 else
531 specified = true;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000532
533 if (specified)
Justin Holewinski0497ab12013-03-30 14:29:21 +0000534 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
535 << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000536
537 // If the NVVM IR has some of maxntid* specified, then output
538 // the maxntid directive, and set the unspecified ones to 1.
539 // If none of maxntid* is specified, don't output maxntid directive.
540 unsigned maxntidx, maxntidy, maxntidz;
541 specified = false;
Eli Bendersky3e840192015-03-23 16:26:23 +0000542 if (!llvm::getMaxNTIDx(F, maxntidx))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000543 maxntidx = 1;
544 else
545 specified = true;
Eli Bendersky3e840192015-03-23 16:26:23 +0000546 if (!llvm::getMaxNTIDy(F, maxntidy))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000547 maxntidy = 1;
548 else
549 specified = true;
Eli Bendersky3e840192015-03-23 16:26:23 +0000550 if (!llvm::getMaxNTIDz(F, maxntidz))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000551 maxntidz = 1;
552 else
553 specified = true;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000554
555 if (specified)
Justin Holewinski0497ab12013-03-30 14:29:21 +0000556 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
557 << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000558
559 unsigned mincta;
560 if (llvm::getMinCTASm(F, mincta))
561 O << ".minnctapersm " << mincta << "\n";
562}
563
Justin Holewinski660597d2013-10-11 12:39:36 +0000564std::string
565NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
566 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000567
Justin Holewinski660597d2013-10-11 12:39:36 +0000568 std::string Name;
569 raw_string_ostream NameStr(Name);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000570
Justin Holewinski660597d2013-10-11 12:39:36 +0000571 VRegRCMap::const_iterator I = VRegMapping.find(RC);
572 assert(I != VRegMapping.end() && "Bad register class");
573 const DenseMap<unsigned, unsigned> &RegMap = I->second;
574
575 VRegMap::const_iterator VI = RegMap.find(Reg);
576 assert(VI != RegMap.end() && "Bad virtual register");
577 unsigned MappedVR = VI->second;
578
579 NameStr << getNVPTXRegClassStr(RC) << MappedVR;
580
581 NameStr.flush();
582 return Name;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000583}
584
Justin Holewinski660597d2013-10-11 12:39:36 +0000585void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
Justin Holewinski0497ab12013-03-30 14:29:21 +0000586 raw_ostream &O) {
Justin Holewinski660597d2013-10-11 12:39:36 +0000587 O << getVirtualRegisterName(vr);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000588}
589
Justin Holewinski0497ab12013-03-30 14:29:21 +0000590void NVPTXAsmPrinter::printVecModifiedImmediate(
591 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
592 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
593 int Imm = (int) MO.getImm();
594 if (0 == strcmp(Modifier, "vecelem"))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000595 O << "_" << vecelem[Imm];
Justin Holewinski0497ab12013-03-30 14:29:21 +0000596 else if (0 == strcmp(Modifier, "vecv4comm1")) {
597 if ((Imm < 0) || (Imm > 3))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000598 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000599 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
600 if ((Imm < 4) || (Imm > 7))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000601 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000602 } else if (0 == strcmp(Modifier, "vecv4pos")) {
603 if (Imm < 0)
604 Imm = 0;
605 O << "_" << vecelem[Imm % 4];
606 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
607 if ((Imm < 0) || (Imm > 1))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000608 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000609 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
610 if ((Imm < 2) || (Imm > 3))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000611 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000612 } else if (0 == strcmp(Modifier, "vecv2pos")) {
613 if (Imm < 0)
614 Imm = 0;
615 O << "_" << vecelem[Imm % 2];
616 } else
Craig Topperbdf39a42012-05-24 07:02:50 +0000617 llvm_unreachable("Unknown Modifier on immediate operand");
Justin Holewinskiae556d32012-05-04 20:18:50 +0000618}
619
Justin Holewinskidc5e3b62013-06-28 17:58:04 +0000620
621
Justin Holewinski0497ab12013-03-30 14:29:21 +0000622void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000623
Justin Holewinski0497ab12013-03-30 14:29:21 +0000624 emitLinkageDirective(F, O);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000625 if (llvm::isKernelFunction(*F))
626 O << ".entry ";
627 else
628 O << ".func ";
629 printReturnValStr(F, O);
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +0000630 O << *getSymbol(F) << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000631 emitFunctionParamList(F, O);
632 O << ";\n";
633}
634
Justin Holewinski0497ab12013-03-30 14:29:21 +0000635static bool usedInGlobalVarDef(const Constant *C) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000636 if (!C)
637 return false;
638
639 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
Yaron Keren075759a2015-03-30 15:42:36 +0000640 if (GV->getName() == "llvm.used")
Justin Holewinskiae556d32012-05-04 20:18:50 +0000641 return false;
642 return true;
643 }
644
Chandler Carruthcdf47882014-03-09 03:16:01 +0000645 for (const User *U : C->users())
646 if (const Constant *C = dyn_cast<Constant>(U))
647 if (usedInGlobalVarDef(C))
648 return true;
649
Justin Holewinskiae556d32012-05-04 20:18:50 +0000650 return false;
651}
652
Justin Holewinski0497ab12013-03-30 14:29:21 +0000653static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000654 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
Yaron Keren075759a2015-03-30 15:42:36 +0000655 if (othergv->getName() == "llvm.used")
Justin Holewinskiae556d32012-05-04 20:18:50 +0000656 return true;
657 }
658
659 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
660 if (instr->getParent() && instr->getParent()->getParent()) {
661 const Function *curFunc = instr->getParent()->getParent();
662 if (oneFunc && (curFunc != oneFunc))
663 return false;
664 oneFunc = curFunc;
665 return true;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000666 } else
Justin Holewinskiae556d32012-05-04 20:18:50 +0000667 return false;
668 }
669
Chandler Carruthcdf47882014-03-09 03:16:01 +0000670 for (const User *UU : U->users())
Eli Bendersky3e840192015-03-23 16:26:23 +0000671 if (!usedInOneFunc(UU, oneFunc))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000672 return false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000673
Justin Holewinskiae556d32012-05-04 20:18:50 +0000674 return true;
675}
676
677/* Find out if a global variable can be demoted to local scope.
678 * Currently, this is valid for CUDA shared variables, which have local
679 * scope and global lifetime. So the conditions to check are :
680 * 1. Is the global variable in shared address space?
681 * 2. Does it have internal linkage?
682 * 3. Is the global variable referenced only in one function?
683 */
684static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
Eli Bendersky3e840192015-03-23 16:26:23 +0000685 if (!gv->hasInternalLinkage())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000686 return false;
687 const PointerType *Pty = gv->getType();
688 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
689 return false;
690
Craig Topper062a2ba2014-04-25 05:30:21 +0000691 const Function *oneFunc = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000692
693 bool flag = usedInOneFunc(gv, oneFunc);
Eli Bendersky3e840192015-03-23 16:26:23 +0000694 if (!flag)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000695 return false;
696 if (!oneFunc)
697 return false;
698 f = oneFunc;
699 return true;
700}
701
702static bool useFuncSeen(const Constant *C,
703 llvm::DenseMap<const Function *, bool> &seenMap) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000704 for (const User *U : C->users()) {
705 if (const Constant *cu = dyn_cast<Constant>(U)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000706 if (useFuncSeen(cu, seenMap))
707 return true;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000708 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000709 const BasicBlock *bb = I->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000710 if (!bb)
711 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000712 const Function *caller = bb->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000713 if (!caller)
714 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000715 if (seenMap.find(caller) != seenMap.end())
716 return true;
717 }
718 }
719 return false;
720}
721
Justin Holewinski01f89f02013-05-20 12:13:32 +0000722void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000723 llvm::DenseMap<const Function *, bool> seenMap;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000724 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000725 const Function *F = FI;
726
727 if (F->isDeclaration()) {
728 if (F->use_empty())
729 continue;
730 if (F->getIntrinsicID())
731 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000732 emitDeclaration(F, O);
733 continue;
734 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000735 for (const User *U : F->users()) {
736 if (const Constant *C = dyn_cast<Constant>(U)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000737 if (usedInGlobalVarDef(C)) {
738 // The use is in the initialization of a global variable
739 // that is a function pointer, so print a declaration
740 // for the original function
Justin Holewinskiae556d32012-05-04 20:18:50 +0000741 emitDeclaration(F, O);
742 break;
743 }
744 // Emit a declaration of this function if the function that
745 // uses this constant expr has already been seen.
746 if (useFuncSeen(C, seenMap)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000747 emitDeclaration(F, O);
748 break;
749 }
750 }
751
Chandler Carruthcdf47882014-03-09 03:16:01 +0000752 if (!isa<Instruction>(U))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000753 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000754 const Instruction *instr = cast<Instruction>(U);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000755 const BasicBlock *bb = instr->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000756 if (!bb)
757 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000758 const Function *caller = bb->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000759 if (!caller)
760 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000761
762 // If a caller has already been seen, then the caller is
763 // appearing in the module before the callee. so print out
764 // a declaration for the callee.
765 if (seenMap.find(caller) != seenMap.end()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000766 emitDeclaration(F, O);
767 break;
768 }
769 }
770 seenMap[F] = true;
771 }
772}
773
774void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
775 DebugInfoFinder DbgFinder;
776 DbgFinder.processModule(M);
777
Justin Holewinski0497ab12013-03-30 14:29:21 +0000778 unsigned i = 1;
Alon Mishnead312152014-03-18 09:41:07 +0000779 for (DICompileUnit DIUnit : DbgFinder.compile_units()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000780 StringRef Filename(DIUnit.getFilename());
781 StringRef Dirname(DIUnit.getDirectory());
782 SmallString<128> FullPathName = Dirname;
783 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
784 sys::path::append(FullPathName, Filename);
Yaron Keren075759a2015-03-30 15:42:36 +0000785 Filename = FullPathName;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000786 }
Yaron Keren075759a2015-03-30 15:42:36 +0000787 if (filenameMap.find(Filename) != filenameMap.end())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000788 continue;
Yaron Keren075759a2015-03-30 15:42:36 +0000789 filenameMap[Filename] = i;
790 OutStreamer.EmitDwarfFileDirective(i, "", Filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000791 ++i;
792 }
793
Alon Mishnead312152014-03-18 09:41:07 +0000794 for (DISubprogram SP : DbgFinder.subprograms()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000795 StringRef Filename(SP.getFilename());
796 StringRef Dirname(SP.getDirectory());
797 SmallString<128> FullPathName = Dirname;
798 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
799 sys::path::append(FullPathName, Filename);
Yaron Keren075759a2015-03-30 15:42:36 +0000800 Filename = FullPathName;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000801 }
Yaron Keren075759a2015-03-30 15:42:36 +0000802 if (filenameMap.find(Filename) != filenameMap.end())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000803 continue;
Yaron Keren075759a2015-03-30 15:42:36 +0000804 filenameMap[Filename] = i;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000805 ++i;
806 }
807}
808
Justin Holewinski0497ab12013-03-30 14:29:21 +0000809bool NVPTXAsmPrinter::doInitialization(Module &M) {
Eric Christopher6aad8b12015-02-19 00:08:14 +0000810 // Construct a default subtarget off of the TargetMachine defaults. The
811 // rest of NVPTX isn't friendly to change subtargets per function and
812 // so the default TargetMachine will have all of the options.
813 StringRef TT = TM.getTargetTriple();
814 StringRef CPU = TM.getTargetCPU();
815 StringRef FS = TM.getTargetFeatureString();
816 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
Eric Christopher02389e32015-02-19 00:08:27 +0000817 const NVPTXSubtarget STI(TT, CPU, FS, NTM);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000818
819 SmallString<128> Str1;
820 raw_svector_ostream OS1(Str1);
821
822 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
823 MMI->AnalyzeModule(M);
824
825 // We need to call the parent's one explicitly.
826 //bool Result = AsmPrinter::doInitialization(M);
827
828 // Initialize TargetLoweringObjectFile.
Justin Holewinski0497ab12013-03-30 14:29:21 +0000829 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
830 .Initialize(OutContext, TM);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000831
Eric Christopher8b770652015-01-26 19:03:15 +0000832 Mang = new Mangler(TM.getDataLayout());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000833
834 // Emit header before any dwarf directives are emitted below.
Eric Christopher6aad8b12015-02-19 00:08:14 +0000835 emitHeader(M, OS1, STI);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000836 OutStreamer.EmitRawText(OS1.str());
837
Justin Holewinskiae556d32012-05-04 20:18:50 +0000838 // Already commented out
839 //bool Result = AsmPrinter::doInitialization(M);
840
Justin Holewinskid2bbdf02013-07-01 13:00:14 +0000841 // Emit module-level inline asm if it exists.
842 if (!M.getModuleInlineAsm().empty()) {
843 OutStreamer.AddComment("Start of file scope inline assembly");
844 OutStreamer.AddBlankLine();
845 OutStreamer.EmitRawText(StringRef(M.getModuleInlineAsm()));
846 OutStreamer.AddBlankLine();
847 OutStreamer.AddComment("End of file scope inline assembly");
848 OutStreamer.AddBlankLine();
849 }
850
Eric Christopher6aad8b12015-02-19 00:08:14 +0000851 // If we're not NVCL we're CUDA, go ahead and emit filenames.
852 if (Triple(TM.getTargetTriple()).getOS() != Triple::NVCL)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000853 recordAndEmitFilenames(M);
854
Justin Holewinski01f89f02013-05-20 12:13:32 +0000855 GlobalsEmitted = false;
856
857 return false; // success
858}
859
860void NVPTXAsmPrinter::emitGlobals(const Module &M) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000861 SmallString<128> Str2;
862 raw_svector_ostream OS2(Str2);
863
864 emitDeclarations(M, OS2);
865
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000866 // As ptxas does not support forward references of globals, we need to first
867 // sort the list of module-level globals in def-use order. We visit each
868 // global variable in order, and ensure that we emit it *after* its dependent
869 // globals. We use a little extra memory maintaining both a set and a list to
870 // have fast searches while maintaining a strict ordering.
Justin Holewinski01f89f02013-05-20 12:13:32 +0000871 SmallVector<const GlobalVariable *, 8> Globals;
872 DenseSet<const GlobalVariable *> GVVisited;
873 DenseSet<const GlobalVariable *> GVVisiting;
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000874
875 // Visit each global variable, in order
Justin Holewinski01f89f02013-05-20 12:13:32 +0000876 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
877 I != E; ++I)
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000878 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
879
Justin Holewinski0497ab12013-03-30 14:29:21 +0000880 assert(GVVisited.size() == M.getGlobalList().size() &&
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000881 "Missed a global variable");
882 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
883
884 // Print out module-level global variables in proper order
885 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
886 printModuleLevelGV(Globals[i], OS2);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000887
888 OS2 << '\n';
889
890 OutStreamer.EmitRawText(OS2.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000891}
892
Eric Christopher6aad8b12015-02-19 00:08:14 +0000893void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O,
894 const NVPTXSubtarget &STI) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000895 O << "//\n";
896 O << "// Generated by LLVM NVPTX Back-End\n";
897 O << "//\n";
898 O << "\n";
899
Eric Christopher6aad8b12015-02-19 00:08:14 +0000900 unsigned PTXVersion = STI.getPTXVersion();
Justin Holewinski1812ee92012-11-12 03:16:43 +0000901 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000902
903 O << ".target ";
Eric Christopher6aad8b12015-02-19 00:08:14 +0000904 O << STI.getTargetName();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000905
Eric Christopherca929f22015-02-19 00:22:47 +0000906 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
907 if (NTM.getDrvInterface() == NVPTX::NVCL)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000908 O << ", texmode_independent";
Eric Christopherbeffc4e2015-02-19 00:08:23 +0000909 else {
Eric Christopher6aad8b12015-02-19 00:08:14 +0000910 if (!STI.hasDouble())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000911 O << ", map_f64_to_f32";
912 }
913
914 if (MAI->doesSupportDebugInformation())
915 O << ", debug";
916
917 O << "\n";
918
919 O << ".address_size ";
Eric Christopherca929f22015-02-19 00:22:47 +0000920 if (NTM.is64Bit())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000921 O << "64";
922 else
923 O << "32";
924 O << "\n";
925
926 O << "\n";
927}
928
929bool NVPTXAsmPrinter::doFinalization(Module &M) {
Justin Holewinski01f89f02013-05-20 12:13:32 +0000930 // If we did not emit any functions, then the global declarations have not
931 // yet been emitted.
932 if (!GlobalsEmitted) {
933 emitGlobals(M);
934 GlobalsEmitted = true;
935 }
936
Justin Holewinskiae556d32012-05-04 20:18:50 +0000937 // XXX Temproarily remove global variables so that doFinalization() will not
938 // emit them again (global variables are emitted at beginning).
939
940 Module::GlobalListType &global_list = M.getGlobalList();
941 int i, n = global_list.size();
Dylan Noblesmithc9e2a272014-08-26 02:03:35 +0000942 GlobalVariable **gv_array = new GlobalVariable *[n];
Justin Holewinskiae556d32012-05-04 20:18:50 +0000943
944 // first, back-up GlobalVariable in gv_array
945 i = 0;
946 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000947 I != E; ++I)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000948 gv_array[i++] = &*I;
949
950 // second, empty global_list
951 while (!global_list.empty())
952 global_list.remove(global_list.begin());
953
954 // call doFinalization
955 bool ret = AsmPrinter::doFinalization(M);
956
957 // now we restore global variables
Justin Holewinski0497ab12013-03-30 14:29:21 +0000958 for (i = 0; i < n; i++)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000959 global_list.insert(global_list.end(), gv_array[i]);
960
Justin Holewinski59596952014-04-09 15:38:52 +0000961 clearAnnotationCache(&M);
Dylan Noblesmithc9e2a272014-08-26 02:03:35 +0000962
963 delete[] gv_array;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000964 return ret;
965
Justin Holewinskiae556d32012-05-04 20:18:50 +0000966 //bool Result = AsmPrinter::doFinalization(M);
967 // Instead of calling the parents doFinalization, we may
968 // clone parents doFinalization and customize here.
969 // Currently, we if NVISA out the EmitGlobals() in
970 // parent's doFinalization, which is too intrusive.
971 //
972 // Same for the doInitialization.
973 //return Result;
974}
975
976// This function emits appropriate linkage directives for
977// functions and global variables.
978//
979// extern function declaration -> .extern
980// extern function definition -> .visible
981// external global variable with init -> .visible
982// external without init -> .extern
983// appending -> not allowed, assert.
Justin Holewinski7d5bf662014-06-27 18:35:10 +0000984// for any linkage other than
985// internal, private, linker_private,
986// linker_private_weak, linker_private_weak_def_auto,
987// we emit -> .weak.
Justin Holewinskiae556d32012-05-04 20:18:50 +0000988
Justin Holewinski0497ab12013-03-30 14:29:21 +0000989void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
990 raw_ostream &O) {
Eric Christopherbeffc4e2015-02-19 00:08:23 +0000991 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() == NVPTX::CUDA) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000992 if (V->hasExternalLinkage()) {
993 if (isa<GlobalVariable>(V)) {
994 const GlobalVariable *GVar = cast<GlobalVariable>(V);
995 if (GVar) {
996 if (GVar->hasInitializer())
997 O << ".visible ";
998 else
999 O << ".extern ";
1000 }
1001 } else if (V->isDeclaration())
1002 O << ".extern ";
1003 else
1004 O << ".visible ";
1005 } else if (V->hasAppendingLinkage()) {
1006 std::string msg;
1007 msg.append("Error: ");
1008 msg.append("Symbol ");
1009 if (V->hasName())
Yaron Keren075759a2015-03-30 15:42:36 +00001010 msg.append(V->getName());
Justin Holewinskiae556d32012-05-04 20:18:50 +00001011 msg.append("has unsupported appending linkage type");
1012 llvm_unreachable(msg.c_str());
Justin Holewinski7d5bf662014-06-27 18:35:10 +00001013 } else if (!V->hasInternalLinkage() &&
1014 !V->hasPrivateLinkage()) {
1015 O << ".weak ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001016 }
1017 }
1018}
1019
Justin Holewinski01f89f02013-05-20 12:13:32 +00001020void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1021 raw_ostream &O,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001022 bool processDemoted) {
1023
1024 // Skip meta data
1025 if (GVar->hasSection()) {
Rafael Espindola64c1e182014-06-03 02:41:57 +00001026 if (GVar->getSection() == StringRef("llvm.metadata"))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001027 return;
1028 }
1029
Justin Holewinski73cb5de2014-06-27 18:35:53 +00001030 // Skip LLVM intrinsic global variables
1031 if (GVar->getName().startswith("llvm.") ||
1032 GVar->getName().startswith("nvvm."))
1033 return;
1034
Eric Christopher8b770652015-01-26 19:03:15 +00001035 const DataLayout *TD = TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001036
1037 // GlobalVariables are always constant pointers themselves.
1038 const PointerType *PTy = GVar->getType();
1039 Type *ETy = PTy->getElementType();
1040
1041 if (GVar->hasExternalLinkage()) {
1042 if (GVar->hasInitializer())
1043 O << ".visible ";
1044 else
1045 O << ".extern ";
Justin Holewinskid73767a2014-06-27 18:35:56 +00001046 } else if (GVar->hasLinkOnceLinkage() || GVar->hasWeakLinkage() ||
1047 GVar->hasAvailableExternallyLinkage() ||
1048 GVar->hasCommonLinkage()) {
1049 O << ".weak ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001050 }
1051
1052 if (llvm::isTexture(*GVar)) {
1053 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1054 return;
1055 }
1056
1057 if (llvm::isSurface(*GVar)) {
1058 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1059 return;
1060 }
1061
1062 if (GVar->isDeclaration()) {
1063 // (extern) declarations, no definition or initializer
1064 // Currently the only known declaration is for an automatic __local
1065 // (.shared) promoted to global.
1066 emitPTXGlobalVariable(GVar, O);
1067 O << ";\n";
1068 return;
1069 }
1070
1071 if (llvm::isSampler(*GVar)) {
1072 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1073
Craig Topper062a2ba2014-04-25 05:30:21 +00001074 const Constant *Initializer = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001075 if (GVar->hasInitializer())
1076 Initializer = GVar->getInitializer();
Craig Topper062a2ba2014-04-25 05:30:21 +00001077 const ConstantInt *CI = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001078 if (Initializer)
1079 CI = dyn_cast<ConstantInt>(Initializer);
1080 if (CI) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001081 unsigned sample = CI->getZExtValue();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001082
1083 O << " = { ";
1084
Justin Holewinski0497ab12013-03-30 14:29:21 +00001085 for (int i = 0,
1086 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1087 i < 3; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001088 O << "addr_mode_" << i << " = ";
1089 switch (addr) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001090 case 0:
1091 O << "wrap";
1092 break;
1093 case 1:
1094 O << "clamp_to_border";
1095 break;
1096 case 2:
1097 O << "clamp_to_edge";
1098 break;
1099 case 3:
1100 O << "wrap";
1101 break;
1102 case 4:
1103 O << "mirror";
1104 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001105 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001106 O << ", ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001107 }
1108 O << "filter_mode = ";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001109 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1110 case 0:
1111 O << "nearest";
1112 break;
1113 case 1:
1114 O << "linear";
1115 break;
1116 case 2:
Craig Topper2a30d782014-06-18 05:05:13 +00001117 llvm_unreachable("Anisotropic filtering is not supported");
Justin Holewinski0497ab12013-03-30 14:29:21 +00001118 default:
1119 O << "nearest";
1120 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001121 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001122 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001123 O << ", force_unnormalized_coords = 1";
1124 }
1125 O << " }";
1126 }
1127
1128 O << ";\n";
1129 return;
1130 }
1131
1132 if (GVar->hasPrivateLinkage()) {
1133
1134 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1135 return;
1136
1137 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1138 if (!strncmp(GVar->getName().data(), "filename", 8))
1139 return;
1140 if (GVar->use_empty())
1141 return;
1142 }
1143
Craig Topper062a2ba2014-04-25 05:30:21 +00001144 const Function *demotedFunc = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001145 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
Yaron Keren075759a2015-03-30 15:42:36 +00001146 O << "// " << GVar->getName() << " has been demoted\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001147 if (localDecls.find(demotedFunc) != localDecls.end())
1148 localDecls[demotedFunc].push_back(GVar);
1149 else {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001150 std::vector<const GlobalVariable *> temp;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001151 temp.push_back(GVar);
1152 localDecls[demotedFunc] = temp;
1153 }
1154 return;
1155 }
1156
1157 O << ".";
1158 emitPTXAddressSpace(PTy->getAddressSpace(), O);
Justin Holewinski773ca402014-06-27 18:35:58 +00001159
1160 if (isManaged(*GVar)) {
1161 O << " .attribute(.managed)";
1162 }
1163
Justin Holewinskiae556d32012-05-04 20:18:50 +00001164 if (GVar->getAlignment() == 0)
1165 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1166 else
1167 O << " .align " << GVar->getAlignment();
1168
Jingyue Wue4c9cf02014-12-17 17:59:04 +00001169 if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001170 O << " .";
Justin Holewinski700b6fa2013-05-20 12:13:28 +00001171 // Special case: ABI requires that we use .u8 for predicates
1172 if (ETy->isIntegerTy(1))
1173 O << "u8";
1174 else
1175 O << getPTXFundamentalTypeStr(ETy, false);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001176 O << " ";
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00001177 O << *getSymbol(GVar);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001178
1179 // Ptx allows variable initilization only for constant and global state
1180 // spaces.
Justin Holewinski549c7732014-06-27 18:36:01 +00001181 if (GVar->hasInitializer()) {
1182 if ((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1183 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) {
1184 const Constant *Initializer = GVar->getInitializer();
1185 // 'undef' is treated as there is no value spefied.
1186 if (!Initializer->isNullValue() && !isa<UndefValue>(Initializer)) {
1187 O << " = ";
1188 printScalarConstant(Initializer, O);
1189 }
1190 } else {
1191 // The frontend adds zero-initializer to variables that don't have an
1192 // initial value, so skip warning for this case.
1193 if (!GVar->getInitializer()->isNullValue()) {
Yaron Keren075759a2015-03-30 15:42:36 +00001194 std::string warnMsg =
1195 ("initial value of '" + GVar->getName() +
1196 "' is not allowed in addrspace(" +
1197 Twine(llvm::utostr_32(PTy->getAddressSpace())) + ")").str();
Justin Holewinski549c7732014-06-27 18:36:01 +00001198 report_fatal_error(warnMsg.c_str());
1199 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001200 }
1201 }
1202 } else {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001203 unsigned int ElementSize = 0;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001204
1205 // Although PTX has direct support for struct type and array type and
1206 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1207 // targets that support these high level field accesses. Structs, arrays
1208 // and vectors are lowered into arrays of bytes.
1209 switch (ETy->getTypeID()) {
1210 case Type::StructTyID:
1211 case Type::ArrayTyID:
1212 case Type::VectorTyID:
1213 ElementSize = TD->getTypeStoreSize(ETy);
1214 // Ptx allows variable initilization only for constant and
1215 // global state spaces.
1216 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
Justin Holewinski0497ab12013-03-30 14:29:21 +00001217 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1218 GVar->hasInitializer()) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001219 const Constant *Initializer = GVar->getInitializer();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001220 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001221 AggBuffer aggBuffer(ElementSize, O, *this);
1222 bufferAggregateConstant(Initializer, &aggBuffer);
1223 if (aggBuffer.numSymbols) {
Eric Christopher6aad8b12015-02-19 00:08:14 +00001224 if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit()) {
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00001225 O << " .u64 " << *getSymbol(GVar) << "[";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001226 O << ElementSize / 8;
1227 } else {
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00001228 O << " .u32 " << *getSymbol(GVar) << "[";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001229 O << ElementSize / 4;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001230 }
1231 O << "]";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001232 } else {
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00001233 O << " .b8 " << *getSymbol(GVar) << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001234 O << ElementSize;
1235 O << "]";
1236 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001237 O << " = {";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001238 aggBuffer.print();
1239 O << "}";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001240 } else {
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00001241 O << " .b8 " << *getSymbol(GVar);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001242 if (ElementSize) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001243 O << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001244 O << ElementSize;
1245 O << "]";
1246 }
1247 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001248 } else {
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00001249 O << " .b8 " << *getSymbol(GVar);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001250 if (ElementSize) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001251 O << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001252 O << ElementSize;
1253 O << "]";
1254 }
1255 }
1256 break;
1257 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001258 llvm_unreachable("type not supported yet");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001259 }
1260
1261 }
1262 O << ";\n";
1263}
1264
1265void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1266 if (localDecls.find(f) == localDecls.end())
1267 return;
1268
Justin Holewinski01f89f02013-05-20 12:13:32 +00001269 std::vector<const GlobalVariable *> &gvars = localDecls[f];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001270
Justin Holewinski0497ab12013-03-30 14:29:21 +00001271 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001272 O << "\t// demoted variable\n\t";
1273 printModuleLevelGV(gvars[i], O, true);
1274 }
1275}
1276
1277void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1278 raw_ostream &O) const {
1279 switch (AddressSpace) {
1280 case llvm::ADDRESS_SPACE_LOCAL:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001281 O << "local";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001282 break;
1283 case llvm::ADDRESS_SPACE_GLOBAL:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001284 O << "global";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001285 break;
1286 case llvm::ADDRESS_SPACE_CONST:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001287 O << "const";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001288 break;
1289 case llvm::ADDRESS_SPACE_SHARED:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001290 O << "shared";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001291 break;
1292 default:
Justin Holewinski36a50992013-02-09 13:34:15 +00001293 report_fatal_error("Bad address space found while emitting PTX");
1294 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001295 }
1296}
1297
Justin Holewinski0497ab12013-03-30 14:29:21 +00001298std::string
1299NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001300 switch (Ty->getTypeID()) {
1301 default:
1302 llvm_unreachable("unexpected type");
1303 break;
1304 case Type::IntegerTyID: {
1305 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1306 if (NumBits == 1)
1307 return "pred";
1308 else if (NumBits <= 64) {
1309 std::string name = "u";
1310 return name + utostr(NumBits);
1311 } else {
1312 llvm_unreachable("Integer too large");
1313 break;
1314 }
1315 break;
1316 }
1317 case Type::FloatTyID:
1318 return "f32";
1319 case Type::DoubleTyID:
1320 return "f64";
1321 case Type::PointerTyID:
Eric Christopher6aad8b12015-02-19 00:08:14 +00001322 if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit())
Justin Holewinski0497ab12013-03-30 14:29:21 +00001323 if (useB4PTR)
1324 return "b64";
1325 else
1326 return "u64";
1327 else if (useB4PTR)
1328 return "b32";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001329 else
Justin Holewinski0497ab12013-03-30 14:29:21 +00001330 return "u32";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001331 }
1332 llvm_unreachable("unexpected type");
Craig Topper062a2ba2014-04-25 05:30:21 +00001333 return nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001334}
1335
Justin Holewinski0497ab12013-03-30 14:29:21 +00001336void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001337 raw_ostream &O) {
1338
Eric Christopher8b770652015-01-26 19:03:15 +00001339 const DataLayout *TD = TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001340
1341 // GlobalVariables are always constant pointers themselves.
1342 const PointerType *PTy = GVar->getType();
1343 Type *ETy = PTy->getElementType();
1344
1345 O << ".";
1346 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1347 if (GVar->getAlignment() == 0)
1348 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1349 else
1350 O << " .align " << GVar->getAlignment();
1351
Jingyue Wue4c9cf02014-12-17 17:59:04 +00001352 if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001353 O << " .";
1354 O << getPTXFundamentalTypeStr(ETy);
1355 O << " ";
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00001356 O << *getSymbol(GVar);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001357 return;
1358 }
1359
Justin Holewinski0497ab12013-03-30 14:29:21 +00001360 int64_t ElementSize = 0;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001361
1362 // Although PTX has direct support for struct type and array type and LLVM IR
1363 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1364 // support these high level field accesses. Structs and arrays are lowered
1365 // into arrays of bytes.
1366 switch (ETy->getTypeID()) {
1367 case Type::StructTyID:
1368 case Type::ArrayTyID:
1369 case Type::VectorTyID:
1370 ElementSize = TD->getTypeStoreSize(ETy);
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00001371 O << " .b8 " << *getSymbol(GVar) << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001372 if (ElementSize) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001373 O << itostr(ElementSize);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001374 }
1375 O << "]";
1376 break;
1377 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001378 llvm_unreachable("type not supported yet");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001379 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001380 return;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001381}
1382
Justin Holewinski0497ab12013-03-30 14:29:21 +00001383static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
Rafael Espindola08013342013-12-07 19:34:20 +00001384 if (Ty->isSingleValueType())
Justin Holewinskiae556d32012-05-04 20:18:50 +00001385 return TD->getPrefTypeAlignment(Ty);
1386
1387 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1388 if (ATy)
1389 return getOpenCLAlignment(TD, ATy->getElementType());
1390
Justin Holewinskiae556d32012-05-04 20:18:50 +00001391 const StructType *STy = dyn_cast<StructType>(Ty);
1392 if (STy) {
1393 unsigned int alignStruct = 1;
1394 // Go through each element of the struct and find the
1395 // largest alignment.
Justin Holewinski0497ab12013-03-30 14:29:21 +00001396 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001397 Type *ETy = STy->getElementType(i);
1398 unsigned int align = getOpenCLAlignment(TD, ETy);
1399 if (align > alignStruct)
1400 alignStruct = align;
1401 }
1402 return alignStruct;
1403 }
1404
1405 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1406 if (FTy)
Chandler Carruth5da3f052012-11-01 09:14:31 +00001407 return TD->getPointerPrefAlignment();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001408 return TD->getPrefTypeAlignment(Ty);
1409}
1410
1411void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1412 int paramIndex, raw_ostream &O) {
Eric Christopherbeffc4e2015-02-19 00:08:23 +00001413 O << *getSymbol(I->getParent()) << "_param_" << paramIndex;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001414}
1415
1416void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
Eric Christopherbeffc4e2015-02-19 00:08:23 +00001417 O << *CurrentFnSym << "_param_" << paramIndex;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001418}
1419
Justin Holewinski0497ab12013-03-30 14:29:21 +00001420void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
Eric Christopher8b770652015-01-26 19:03:15 +00001421 const DataLayout *TD = TM.getDataLayout();
Bill Wendlinge94d8432012-12-07 23:16:57 +00001422 const AttributeSet &PAL = F->getAttributes();
Eric Christopher6aad8b12015-02-19 00:08:14 +00001423 const TargetLowering *TLI = nvptxSubtarget->getTargetLowering();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001424 Function::const_arg_iterator I, E;
1425 unsigned paramIndex = 0;
1426 bool first = true;
1427 bool isKernelFunc = llvm::isKernelFunction(*F);
Eric Christopher6aad8b12015-02-19 00:08:14 +00001428 bool isABI = (nvptxSubtarget->getSmVersion() >= 20);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001429 MVT thePointerTy = TLI->getPointerTy();
1430
1431 O << "(\n";
1432
1433 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
Justin Holewinskie9884092013-03-24 21:17:47 +00001434 Type *Ty = I->getType();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001435
1436 if (!first)
1437 O << ",\n";
1438
1439 first = false;
1440
1441 // Handle image/sampler parameters
Justin Holewinski30d56a72014-04-09 15:39:15 +00001442 if (isKernelFunction(*F)) {
1443 if (isSampler(*I) || isImage(*I)) {
1444 if (isImage(*I)) {
1445 std::string sname = I->getName();
1446 if (isImageWriteOnly(*I) || isImageReadWrite(*I)) {
Eric Christopher6aad8b12015-02-19 00:08:14 +00001447 if (nvptxSubtarget->hasImageHandles())
Justin Holewinski30d56a72014-04-09 15:39:15 +00001448 O << "\t.param .u64 .ptr .surfref ";
1449 else
1450 O << "\t.param .surfref ";
1451 O << *CurrentFnSym << "_param_" << paramIndex;
1452 }
1453 else { // Default image is read_only
Eric Christopher6aad8b12015-02-19 00:08:14 +00001454 if (nvptxSubtarget->hasImageHandles())
Justin Holewinski30d56a72014-04-09 15:39:15 +00001455 O << "\t.param .u64 .ptr .texref ";
1456 else
1457 O << "\t.param .texref ";
1458 O << *CurrentFnSym << "_param_" << paramIndex;
1459 }
1460 } else {
Eric Christopher6aad8b12015-02-19 00:08:14 +00001461 if (nvptxSubtarget->hasImageHandles())
Justin Holewinski30d56a72014-04-09 15:39:15 +00001462 O << "\t.param .u64 .ptr .samplerref ";
1463 else
1464 O << "\t.param .samplerref ";
1465 O << *CurrentFnSym << "_param_" << paramIndex;
1466 }
1467 continue;
1468 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001469 }
1470
Eli Bendersky3e840192015-03-23 16:26:23 +00001471 if (!PAL.hasAttribute(paramIndex + 1, Attribute::ByVal)) {
Gautam Chakrabarti2c283402014-01-28 18:35:29 +00001472 if (Ty->isAggregateType() || Ty->isVectorTy()) {
1473 // Just print .param .align <a> .b8 .param[size];
Justin Holewinskie9884092013-03-24 21:17:47 +00001474 // <a> = PAL.getparamalignment
1475 // size = typeallocsize of element type
Justin Holewinski0497ab12013-03-30 14:29:21 +00001476 unsigned align = PAL.getParamAlignment(paramIndex + 1);
Justin Holewinskie9884092013-03-24 21:17:47 +00001477 if (align == 0)
1478 align = TD->getABITypeAlignment(Ty);
1479
1480 unsigned sz = TD->getTypeAllocSize(Ty);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001481 O << "\t.param .align " << align << " .b8 ";
Justin Holewinskie9884092013-03-24 21:17:47 +00001482 printParamName(I, paramIndex, O);
1483 O << "[" << sz << "]";
1484
1485 continue;
1486 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001487 // Just a scalar
1488 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1489 if (isKernelFunc) {
1490 if (PTy) {
1491 // Special handling for pointer arguments to kernel
1492 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1493
Eric Christopherbeffc4e2015-02-19 00:08:23 +00001494 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() !=
1495 NVPTX::CUDA) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001496 Type *ETy = PTy->getElementType();
1497 int addrSpace = PTy->getAddressSpace();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001498 switch (addrSpace) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001499 default:
1500 O << ".ptr ";
1501 break;
Justin Holewinskib96d1392013-06-10 13:29:47 +00001502 case llvm::ADDRESS_SPACE_CONST:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001503 O << ".ptr .const ";
1504 break;
1505 case llvm::ADDRESS_SPACE_SHARED:
1506 O << ".ptr .shared ";
1507 break;
1508 case llvm::ADDRESS_SPACE_GLOBAL:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001509 O << ".ptr .global ";
1510 break;
1511 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001512 O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001513 }
1514 printParamName(I, paramIndex, O);
1515 continue;
1516 }
1517
1518 // non-pointer scalar to kernel func
Justin Holewinski700b6fa2013-05-20 12:13:28 +00001519 O << "\t.param .";
1520 // Special case: predicate operands become .u8 types
1521 if (Ty->isIntegerTy(1))
1522 O << "u8";
1523 else
1524 O << getPTXFundamentalTypeStr(Ty);
1525 O << " ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001526 printParamName(I, paramIndex, O);
1527 continue;
1528 }
1529 // Non-kernel function, just print .param .b<size> for ABI
Alp Tokerf907b892013-12-05 05:44:44 +00001530 // and .reg .b<size> for non-ABI
Justin Holewinskiae556d32012-05-04 20:18:50 +00001531 unsigned sz = 0;
1532 if (isa<IntegerType>(Ty)) {
1533 sz = cast<IntegerType>(Ty)->getBitWidth();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001534 if (sz < 32)
1535 sz = 32;
1536 } else if (isa<PointerType>(Ty))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001537 sz = thePointerTy.getSizeInBits();
1538 else
1539 sz = Ty->getPrimitiveSizeInBits();
1540 if (isABI)
1541 O << "\t.param .b" << sz << " ";
1542 else
1543 O << "\t.reg .b" << sz << " ";
1544 printParamName(I, paramIndex, O);
1545 continue;
1546 }
1547
1548 // param has byVal attribute. So should be a pointer
1549 const PointerType *PTy = dyn_cast<PointerType>(Ty);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001550 assert(PTy && "Param with byval attribute should be a pointer type");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001551 Type *ETy = PTy->getElementType();
1552
1553 if (isABI || isKernelFunc) {
Gautam Chakrabarti2c283402014-01-28 18:35:29 +00001554 // Just print .param .align <a> .b8 .param[size];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001555 // <a> = PAL.getparamalignment
1556 // size = typeallocsize of element type
Justin Holewinski0497ab12013-03-30 14:29:21 +00001557 unsigned align = PAL.getParamAlignment(paramIndex + 1);
Justin Holewinski2dc9d072012-11-09 23:50:24 +00001558 if (align == 0)
1559 align = TD->getABITypeAlignment(ETy);
1560
Justin Holewinskiae556d32012-05-04 20:18:50 +00001561 unsigned sz = TD->getTypeAllocSize(ETy);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001562 O << "\t.param .align " << align << " .b8 ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001563 printParamName(I, paramIndex, O);
1564 O << "[" << sz << "]";
1565 continue;
1566 } else {
1567 // Split the ETy into constituent parts and
1568 // print .param .b<size> <name> for each part.
1569 // Further, if a part is vector, print the above for
1570 // each vector element.
1571 SmallVector<EVT, 16> vtparts;
1572 ComputeValueVTs(*TLI, ETy, vtparts);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001573 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001574 unsigned elems = 1;
1575 EVT elemtype = vtparts[i];
1576 if (vtparts[i].isVector()) {
1577 elems = vtparts[i].getVectorNumElements();
1578 elemtype = vtparts[i].getVectorElementType();
1579 }
1580
Justin Holewinski0497ab12013-03-30 14:29:21 +00001581 for (unsigned j = 0, je = elems; j != je; ++j) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001582 unsigned sz = elemtype.getSizeInBits();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001583 if (elemtype.isInteger() && (sz < 32))
1584 sz = 32;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001585 O << "\t.reg .b" << sz << " ";
1586 printParamName(I, paramIndex, O);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001587 if (j < je - 1)
1588 O << ",\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001589 ++paramIndex;
1590 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001591 if (i < e - 1)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001592 O << ",\n";
1593 }
1594 --paramIndex;
1595 continue;
1596 }
1597 }
1598
1599 O << "\n)\n";
1600}
1601
1602void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1603 raw_ostream &O) {
1604 const Function *F = MF.getFunction();
1605 emitFunctionParamList(F, O);
1606}
1607
Justin Holewinski0497ab12013-03-30 14:29:21 +00001608void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1609 const MachineFunction &MF) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001610 SmallString<128> Str;
1611 raw_svector_ostream O(Str);
1612
1613 // Map the global virtual register number to a register class specific
1614 // virtual register number starting from 1 with that class.
Eric Christopherfc6de422014-08-05 02:39:49 +00001615 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001616 //unsigned numRegClasses = TRI->getNumRegClasses();
1617
1618 // Emit the Fake Stack Object
1619 const MachineFrameInfo *MFI = MF.getFrameInfo();
1620 int NumBytes = (int) MFI->getStackSize();
1621 if (NumBytes) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001622 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1623 << getFunctionNumber() << "[" << NumBytes << "];\n";
Eric Christopher02389e32015-02-19 00:08:27 +00001624 if (static_cast<const NVPTXTargetMachine &>(MF.getTarget()).is64Bit()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001625 O << "\t.reg .b64 \t%SP;\n";
1626 O << "\t.reg .b64 \t%SPL;\n";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001627 } else {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001628 O << "\t.reg .b32 \t%SP;\n";
1629 O << "\t.reg .b32 \t%SPL;\n";
1630 }
1631 }
1632
1633 // Go through all virtual registers to establish the mapping between the
1634 // global virtual
1635 // register number and the per class virtual register number.
1636 // We use the per class virtual register number in the ptx output.
1637 unsigned int numVRs = MRI->getNumVirtRegs();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001638 for (unsigned i = 0; i < numVRs; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001639 unsigned int vr = TRI->index2VirtReg(i);
1640 const TargetRegisterClass *RC = MRI->getRegClass(vr);
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001641 DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001642 int n = regmap.size();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001643 regmap.insert(std::make_pair(vr, n + 1));
Justin Holewinskiae556d32012-05-04 20:18:50 +00001644 }
1645
1646 // Emit register declarations
1647 // @TODO: Extract out the real register usage
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001648 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1649 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1650 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1651 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
Justin Holewinski3e037d92014-07-16 16:26:58 +00001652 // O << "\t.reg .s64 %rd<" << NVPTXNumRegisters << ">;\n";
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001653 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
Justin Holewinski3e037d92014-07-16 16:26:58 +00001654 // O << "\t.reg .f64 %fd<" << NVPTXNumRegisters << ">;\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001655
1656 // Emit declaration of the virtual registers or 'physical' registers for
1657 // each register class
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001658 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1659 const TargetRegisterClass *RC = TRI->getRegClass(i);
1660 DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
1661 std::string rcname = getNVPTXRegClassName(RC);
1662 std::string rcStr = getNVPTXRegClassStr(RC);
1663 int n = regmap.size();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001664
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001665 // Only declare those registers that may be used.
1666 if (n) {
1667 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1668 << ">;\n";
1669 }
1670 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001671
1672 OutStreamer.EmitRawText(O.str());
1673}
1674
Justin Holewinskiae556d32012-05-04 20:18:50 +00001675void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001676 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
Justin Holewinskiae556d32012-05-04 20:18:50 +00001677 bool ignored;
1678 unsigned int numHex;
1679 const char *lead;
1680
Justin Holewinski0497ab12013-03-30 14:29:21 +00001681 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001682 numHex = 8;
1683 lead = "0f";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001684 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001685 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1686 numHex = 16;
1687 lead = "0d";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001688 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001689 } else
1690 llvm_unreachable("unsupported fp type");
1691
1692 APInt API = APF.bitcastToAPInt();
1693 std::string hexstr(utohexstr(API.getZExtValue()));
1694 O << lead;
1695 if (hexstr.length() < numHex)
1696 O << std::string(numHex - hexstr.length(), '0');
1697 O << utohexstr(API.getZExtValue());
1698}
1699
Justin Holewinski01f89f02013-05-20 12:13:32 +00001700void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1701 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001702 O << CI->getValue();
1703 return;
1704 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001705 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001706 printFPConstant(CFP, O);
1707 return;
1708 }
1709 if (isa<ConstantPointerNull>(CPV)) {
1710 O << "0";
1711 return;
1712 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001713 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
Justin Holewinski9d852a82014-04-09 15:39:11 +00001714 PointerType *PTy = dyn_cast<PointerType>(GVar->getType());
1715 bool IsNonGenericPointer = false;
1716 if (PTy && PTy->getAddressSpace() != 0) {
1717 IsNonGenericPointer = true;
1718 }
1719 if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
1720 O << "generic(";
1721 O << *getSymbol(GVar);
1722 O << ")";
1723 } else {
1724 O << *getSymbol(GVar);
1725 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001726 return;
1727 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001728 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1729 const Value *v = Cexpr->stripPointerCasts();
Justin Holewinski9d852a82014-04-09 15:39:11 +00001730 PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
1731 bool IsNonGenericPointer = false;
1732 if (PTy && PTy->getAddressSpace() != 0) {
1733 IsNonGenericPointer = true;
1734 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001735 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
Justin Holewinski9d852a82014-04-09 15:39:11 +00001736 if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
1737 O << "generic(";
1738 O << *getSymbol(GVar);
1739 O << ")";
1740 } else {
1741 O << *getSymbol(GVar);
1742 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001743 return;
1744 } else {
Matt Arsenault31a52ad2014-12-16 19:16:17 +00001745 O << *lowerConstant(CPV);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001746 return;
1747 }
1748 }
1749 llvm_unreachable("Not scalar type found in printScalarConstant()");
1750}
1751
Justin Holewinski01f89f02013-05-20 12:13:32 +00001752void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001753 AggBuffer *aggBuffer) {
1754
Eric Christopher8b770652015-01-26 19:03:15 +00001755 const DataLayout *TD = TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001756
1757 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1758 int s = TD->getTypeAllocSize(CPV->getType());
Justin Holewinski0497ab12013-03-30 14:29:21 +00001759 if (s < Bytes)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001760 s = Bytes;
1761 aggBuffer->addZeros(s);
1762 return;
1763 }
1764
1765 unsigned char *ptr;
1766 switch (CPV->getType()->getTypeID()) {
1767
1768 case Type::IntegerTyID: {
1769 const Type *ETy = CPV->getType();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001770 if (ETy == Type::getInt8Ty(CPV->getContext())) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001771 unsigned char c =
1772 (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1773 ptr = &c;
1774 aggBuffer->addBytes(ptr, 1, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001775 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1776 short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1777 ptr = (unsigned char *)&int16;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001778 aggBuffer->addBytes(ptr, 2, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001779 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001780 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001781 int int32 = (int)(constInt->getZExtValue());
1782 ptr = (unsigned char *)&int32;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001783 aggBuffer->addBytes(ptr, 4, Bytes);
1784 break;
Justin Holewinski01f89f02013-05-20 12:13:32 +00001785 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1786 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001787 ConstantFoldConstantExpression(Cexpr, *TD))) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001788 int int32 = (int)(constInt->getZExtValue());
1789 ptr = (unsigned char *)&int32;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001790 aggBuffer->addBytes(ptr, 4, Bytes);
1791 break;
1792 }
1793 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1794 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1795 aggBuffer->addSymbol(v);
1796 aggBuffer->addZeros(4);
1797 break;
1798 }
1799 }
Craig Topperbdf39a42012-05-24 07:02:50 +00001800 llvm_unreachable("unsupported integer const type");
Justin Holewinski0497ab12013-03-30 14:29:21 +00001801 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001802 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001803 long long int64 = (long long)(constInt->getZExtValue());
1804 ptr = (unsigned char *)&int64;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001805 aggBuffer->addBytes(ptr, 8, Bytes);
1806 break;
Justin Holewinski01f89f02013-05-20 12:13:32 +00001807 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1808 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001809 ConstantFoldConstantExpression(Cexpr, *TD))) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001810 long long int64 = (long long)(constInt->getZExtValue());
1811 ptr = (unsigned char *)&int64;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001812 aggBuffer->addBytes(ptr, 8, Bytes);
1813 break;
1814 }
1815 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1816 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1817 aggBuffer->addSymbol(v);
1818 aggBuffer->addZeros(8);
1819 break;
1820 }
1821 }
1822 llvm_unreachable("unsupported integer const type");
Craig Topperbdf39a42012-05-24 07:02:50 +00001823 } else
Justin Holewinskiae556d32012-05-04 20:18:50 +00001824 llvm_unreachable("unsupported integer const type");
1825 break;
1826 }
1827 case Type::FloatTyID:
1828 case Type::DoubleTyID: {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001829 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001830 const Type *Ty = CFP->getType();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001831 if (Ty == Type::getFloatTy(CPV->getContext())) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001832 float float32 = (float) CFP->getValueAPF().convertToFloat();
1833 ptr = (unsigned char *)&float32;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001834 aggBuffer->addBytes(ptr, 4, Bytes);
1835 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1836 double float64 = CFP->getValueAPF().convertToDouble();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001837 ptr = (unsigned char *)&float64;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001838 aggBuffer->addBytes(ptr, 8, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001839 } else {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001840 llvm_unreachable("unsupported fp const type");
1841 }
1842 break;
1843 }
1844 case Type::PointerTyID: {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001845 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001846 aggBuffer->addSymbol(GVar);
Justin Holewinski01f89f02013-05-20 12:13:32 +00001847 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1848 const Value *v = Cexpr->stripPointerCasts();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001849 aggBuffer->addSymbol(v);
1850 }
1851 unsigned int s = TD->getTypeAllocSize(CPV->getType());
1852 aggBuffer->addZeros(s);
1853 break;
1854 }
1855
1856 case Type::ArrayTyID:
1857 case Type::VectorTyID:
1858 case Type::StructTyID: {
1859 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
Justin Holewinski95564bd2013-09-19 12:51:46 +00001860 isa<ConstantStruct>(CPV) || isa<ConstantDataSequential>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001861 int ElementSize = TD->getTypeAllocSize(CPV->getType());
1862 bufferAggregateConstant(CPV, aggBuffer);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001863 if (Bytes > ElementSize)
1864 aggBuffer->addZeros(Bytes - ElementSize);
1865 } else if (isa<ConstantAggregateZero>(CPV))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001866 aggBuffer->addZeros(Bytes);
1867 else
1868 llvm_unreachable("Unexpected Constant type");
1869 break;
1870 }
1871
1872 default:
1873 llvm_unreachable("unsupported type");
1874 }
1875}
1876
Justin Holewinski01f89f02013-05-20 12:13:32 +00001877void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001878 AggBuffer *aggBuffer) {
Eric Christopher8b770652015-01-26 19:03:15 +00001879 const DataLayout *TD = TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001880 int Bytes;
1881
1882 // Old constants
1883 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1884 if (CPV->getNumOperands())
1885 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1886 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1887 return;
1888 }
1889
1890 if (const ConstantDataSequential *CDS =
Justin Holewinski0497ab12013-03-30 14:29:21 +00001891 dyn_cast<ConstantDataSequential>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001892 if (CDS->getNumElements())
1893 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1894 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1895 aggBuffer);
1896 return;
1897 }
1898
Justin Holewinskiae556d32012-05-04 20:18:50 +00001899 if (isa<ConstantStruct>(CPV)) {
1900 if (CPV->getNumOperands()) {
1901 StructType *ST = cast<StructType>(CPV->getType());
1902 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001903 if (i == (e - 1))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001904 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
Justin Holewinski0497ab12013-03-30 14:29:21 +00001905 TD->getTypeAllocSize(ST) -
1906 TD->getStructLayout(ST)->getElementOffset(i);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001907 else
Justin Holewinski0497ab12013-03-30 14:29:21 +00001908 Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
1909 TD->getStructLayout(ST)->getElementOffset(i);
1910 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001911 }
1912 }
1913 return;
1914 }
Craig Topperbdf39a42012-05-24 07:02:50 +00001915 llvm_unreachable("unsupported constant type in printAggregateConstant()");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001916}
1917
1918// buildTypeNameMap - Run through symbol table looking for type names.
1919//
1920
Justin Holewinskiae556d32012-05-04 20:18:50 +00001921bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
1922
1923 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
1924
Justin Holewinski0497ab12013-03-30 14:29:21 +00001925 if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
1926 !PI->second.compare("struct._image2d_t") ||
1927 !PI->second.compare("struct._image3d_t")))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001928 return true;
1929
1930 return false;
1931}
1932
Justin Holewinskiae556d32012-05-04 20:18:50 +00001933
Justin Holewinski0497ab12013-03-30 14:29:21 +00001934bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
1935 switch (MI.getOpcode()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001936 default:
1937 return false;
Justin Holewinski0497ab12013-03-30 14:29:21 +00001938 case NVPTX::CallArgBeginInst:
1939 case NVPTX::CallArgEndInst0:
1940 case NVPTX::CallArgEndInst1:
1941 case NVPTX::CallArgF32:
1942 case NVPTX::CallArgF64:
1943 case NVPTX::CallArgI16:
1944 case NVPTX::CallArgI32:
1945 case NVPTX::CallArgI32imm:
1946 case NVPTX::CallArgI64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001947 case NVPTX::CallArgParam:
1948 case NVPTX::CallVoidInst:
1949 case NVPTX::CallVoidInstReg:
1950 case NVPTX::Callseq_End:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001951 case NVPTX::CallVoidInstReg64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001952 case NVPTX::DeclareParamInst:
1953 case NVPTX::DeclareRetMemInst:
1954 case NVPTX::DeclareRetRegInst:
1955 case NVPTX::DeclareRetScalarInst:
1956 case NVPTX::DeclareScalarParamInst:
1957 case NVPTX::DeclareScalarRegInst:
1958 case NVPTX::StoreParamF32:
1959 case NVPTX::StoreParamF64:
1960 case NVPTX::StoreParamI16:
1961 case NVPTX::StoreParamI32:
1962 case NVPTX::StoreParamI64:
1963 case NVPTX::StoreParamI8:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001964 case NVPTX::StoreRetvalF32:
1965 case NVPTX::StoreRetvalF64:
1966 case NVPTX::StoreRetvalI16:
1967 case NVPTX::StoreRetvalI32:
1968 case NVPTX::StoreRetvalI64:
1969 case NVPTX::StoreRetvalI8:
1970 case NVPTX::LastCallArgF32:
1971 case NVPTX::LastCallArgF64:
1972 case NVPTX::LastCallArgI16:
1973 case NVPTX::LastCallArgI32:
1974 case NVPTX::LastCallArgI32imm:
1975 case NVPTX::LastCallArgI64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001976 case NVPTX::LastCallArgParam:
1977 case NVPTX::LoadParamMemF32:
1978 case NVPTX::LoadParamMemF64:
1979 case NVPTX::LoadParamMemI16:
1980 case NVPTX::LoadParamMemI32:
1981 case NVPTX::LoadParamMemI64:
1982 case NVPTX::LoadParamMemI8:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001983 case NVPTX::PrototypeInst:
1984 case NVPTX::DBG_VALUE:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001985 return true;
1986 }
1987 return false;
1988}
1989
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00001990/// PrintAsmOperand - Print out an operand for an inline asm expression.
1991///
1992bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1993 unsigned AsmVariant,
1994 const char *ExtraCode, raw_ostream &O) {
1995 if (ExtraCode && ExtraCode[0]) {
1996 if (ExtraCode[1] != 0)
1997 return true; // Unknown modifier.
1998
1999 switch (ExtraCode[0]) {
2000 default:
2001 // See if this is a generic print operand
2002 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2003 case 'r':
2004 break;
2005 }
2006 }
2007
2008 printOperand(MI, OpNo, O);
2009
2010 return false;
2011}
2012
2013bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2014 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2015 const char *ExtraCode, raw_ostream &O) {
2016 if (ExtraCode && ExtraCode[0])
2017 return true; // Unknown modifier
2018
2019 O << '[';
2020 printMemOperand(MI, OpNo, O);
2021 O << ']';
2022
2023 return false;
2024}
2025
2026void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2027 raw_ostream &O, const char *Modifier) {
2028 const MachineOperand &MO = MI->getOperand(opNum);
2029 switch (MO.getType()) {
2030 case MachineOperand::MO_Register:
2031 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2032 if (MO.getReg() == NVPTX::VRDepot)
2033 O << DEPOTNAME << getFunctionNumber();
2034 else
2035 O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2036 } else {
Justin Holewinski660597d2013-10-11 12:39:36 +00002037 emitVirtualRegister(MO.getReg(), O);
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002038 }
2039 return;
2040
2041 case MachineOperand::MO_Immediate:
2042 if (!Modifier)
2043 O << MO.getImm();
2044 else if (strstr(Modifier, "vec") == Modifier)
2045 printVecModifiedImmediate(MO, Modifier, O);
2046 else
2047 llvm_unreachable(
2048 "Don't know how to handle modifier on immediate operand");
2049 return;
2050
2051 case MachineOperand::MO_FPImmediate:
2052 printFPConstant(MO.getFPImm(), O);
2053 break;
2054
2055 case MachineOperand::MO_GlobalAddress:
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00002056 O << *getSymbol(MO.getGlobal());
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002057 break;
2058
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002059 case MachineOperand::MO_MachineBasicBlock:
2060 O << *MO.getMBB()->getSymbol();
2061 return;
2062
2063 default:
2064 llvm_unreachable("Operand type not supported.");
2065 }
2066}
2067
2068void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2069 raw_ostream &O, const char *Modifier) {
2070 printOperand(MI, opNum, O);
2071
2072 if (Modifier && !strcmp(Modifier, "add")) {
2073 O << ", ";
2074 printOperand(MI, opNum + 1, O);
2075 } else {
2076 if (MI->getOperand(opNum + 1).isImm() &&
2077 MI->getOperand(opNum + 1).getImm() == 0)
2078 return; // don't print ',0' or '+0'
2079 O << "+";
2080 printOperand(MI, opNum + 1, O);
2081 }
2082}
2083
Justin Holewinskiae556d32012-05-04 20:18:50 +00002084void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2085 std::stringstream temp;
Yaron Keren075759a2015-03-30 15:42:36 +00002086 LineReader *reader = this->getReader(filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002087 temp << "\n//";
2088 temp << filename.str();
2089 temp << ":";
2090 temp << line;
2091 temp << " ";
2092 temp << reader->readLine(line);
2093 temp << "\n";
Yaron Keren075759a2015-03-30 15:42:36 +00002094 this->OutStreamer.EmitRawText(temp.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +00002095}
2096
Justin Holewinskiae556d32012-05-04 20:18:50 +00002097LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
Craig Topper062a2ba2014-04-25 05:30:21 +00002098 if (!reader) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00002099 reader = new LineReader(filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002100 }
2101
2102 if (reader->fileName() != filename) {
2103 delete reader;
Justin Holewinski0497ab12013-03-30 14:29:21 +00002104 reader = new LineReader(filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002105 }
2106
2107 return reader;
2108}
2109
Justin Holewinski0497ab12013-03-30 14:29:21 +00002110std::string LineReader::readLine(unsigned lineNum) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00002111 if (lineNum < theCurLine) {
2112 theCurLine = 0;
Justin Holewinski0497ab12013-03-30 14:29:21 +00002113 fstr.seekg(0, std::ios::beg);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002114 }
2115 while (theCurLine < lineNum) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00002116 fstr.getline(buff, 500);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002117 theCurLine++;
2118 }
2119 return buff;
2120}
2121
2122// Force static initialization.
2123extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2124 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2125 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2126}