blob: 0b4dc15708b52cb2cef4fce543437d53c520535c [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"
Pete Cooper81902a32015-05-15 22:19:42 +000040#include "llvm/MC/MCInst.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000041#include "llvm/MC/MCStreamer.h"
42#include "llvm/MC/MCSymbol.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000043#include "llvm/Support/CommandLine.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000044#include "llvm/Support/ErrorHandling.h"
45#include "llvm/Support/FormattedStream.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000046#include "llvm/Support/Path.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000047#include "llvm/Support/TargetRegistry.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}
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000111}
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
Benjamin Kramer4fed9282016-05-27 12:30:51 +0000119 const DebugLoc &curLoc = MI.getDebugLoc();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000120
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 Smitha9308c42015-04-29 16:38:44 +0000132 auto *Scope = cast_or_null<DIScope>(curLoc.getScope());
Manman Ren983a16c2013-06-28 05:43:10 +0000133 if (!Scope)
134 return;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000135
Duncan P. N. Exon Smithb273d062015-04-16 01:37:00 +0000136 StringRef fileName(Scope->getFilename());
137 StringRef dirName(Scope->getDirectory());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000138 SmallString<128> FullPathName = dirName;
139 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
140 sys::path::append(FullPathName, fileName);
Yaron Keren075759a2015-03-30 15:42:36 +0000141 fileName = FullPathName;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000142 }
143
Yaron Keren075759a2015-03-30 15:42:36 +0000144 if (filenameMap.find(fileName) == filenameMap.end())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000145 return;
146
Justin Holewinskiae556d32012-05-04 20:18:50 +0000147 // Emit the line from the source file.
Benjamin Kramer7ad41002013-10-27 11:31:46 +0000148 if (InterleaveSrc)
Yaron Keren075759a2015-03-30 15:42:36 +0000149 this->emitSrcInText(fileName, curLoc.getLine());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000150
151 std::stringstream temp;
Yaron Keren075759a2015-03-30 15:42:36 +0000152 temp << "\t.loc " << filenameMap[fileName] << " " << curLoc.getLine()
Justin Holewinski0497ab12013-03-30 14:29:21 +0000153 << " " << curLoc.getCol();
Lang Hames9ff69c82015-04-24 19:11:51 +0000154 OutStreamer->EmitRawText(temp.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000155}
156
157void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
158 SmallString<128> Str;
159 raw_svector_ostream OS(Str);
Eric Christopherbeffc4e2015-02-19 00:08:23 +0000160 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() == NVPTX::CUDA)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000161 emitLineNumberAsDotLoc(*MI);
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000162
163 MCInst Inst;
164 lowerToMCInst(MI, Inst);
Lang Hames9ff69c82015-04-24 19:11:51 +0000165 EmitToStreamer(*OutStreamer, Inst);
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000166}
167
Justin Holewinski30d56a72014-04-09 15:39:15 +0000168// Handle symbol backtracking for targets that do not support image handles
169bool NVPTXAsmPrinter::lowerImageHandleOperand(const MachineInstr *MI,
170 unsigned OpNo, MCOperand &MCOp) {
171 const MachineOperand &MO = MI->getOperand(OpNo);
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000172 const MCInstrDesc &MCID = MI->getDesc();
Justin Holewinski30d56a72014-04-09 15:39:15 +0000173
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000174 if (MCID.TSFlags & NVPTXII::IsTexFlag) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000175 // This is a texture fetch, so operand 4 is a texref and operand 5 is
176 // a samplerref
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000177 if (OpNo == 4 && MO.isImm()) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000178 lowerImageHandleSymbol(MO.getImm(), MCOp);
179 return true;
180 }
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000181 if (OpNo == 5 && MO.isImm() && !(MCID.TSFlags & NVPTXII::IsTexModeUnifiedFlag)) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000182 lowerImageHandleSymbol(MO.getImm(), MCOp);
183 return true;
184 }
185
186 return false;
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000187 } else if (MCID.TSFlags & NVPTXII::IsSuldMask) {
188 unsigned VecSize =
189 1 << (((MCID.TSFlags & NVPTXII::IsSuldMask) >> NVPTXII::IsSuldShift) - 1);
190
191 // For a surface load of vector size N, the Nth operand will be the surfref
192 if (OpNo == VecSize && MO.isImm()) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000193 lowerImageHandleSymbol(MO.getImm(), MCOp);
194 return true;
195 }
196
197 return false;
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000198 } else if (MCID.TSFlags & NVPTXII::IsSustFlag) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000199 // This is a surface store, so operand 0 is a surfref
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000200 if (OpNo == 0 && MO.isImm()) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000201 lowerImageHandleSymbol(MO.getImm(), MCOp);
202 return true;
203 }
204
205 return false;
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000206 } else if (MCID.TSFlags & NVPTXII::IsSurfTexQueryFlag) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000207 // This is a query, so operand 1 is a surfref/texref
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000208 if (OpNo == 1 && MO.isImm()) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000209 lowerImageHandleSymbol(MO.getImm(), MCOp);
210 return true;
211 }
212
213 return false;
214 }
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000215
216 return false;
Justin Holewinski30d56a72014-04-09 15:39:15 +0000217}
218
219void NVPTXAsmPrinter::lowerImageHandleSymbol(unsigned Index, MCOperand &MCOp) {
220 // Ewwww
221 TargetMachine &TM = const_cast<TargetMachine&>(MF->getTarget());
222 NVPTXTargetMachine &nvTM = static_cast<NVPTXTargetMachine&>(TM);
223 const NVPTXMachineFunctionInfo *MFI = MF->getInfo<NVPTXMachineFunctionInfo>();
224 const char *Sym = MFI->getImageHandleSymbol(Index);
225 std::string *SymNamePtr =
226 nvTM.getManagedStrPool()->getManagedString(Sym);
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000227 MCOp = GetSymbolRef(OutContext.getOrCreateSymbol(StringRef(*SymNamePtr)));
Justin Holewinski30d56a72014-04-09 15:39:15 +0000228}
229
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000230void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
231 OutMI.setOpcode(MI->getOpcode());
Justin Holewinski3d49e5c2013-11-15 12:30:04 +0000232 // Special: Do not mangle symbol operand of CALL_PROTOTYPE
233 if (MI->getOpcode() == NVPTX::CALL_PROTOTYPE) {
234 const MachineOperand &MO = MI->getOperand(0);
Justin Holewinski30d56a72014-04-09 15:39:15 +0000235 OutMI.addOperand(GetSymbolRef(
Jim Grosbach6f482002015-05-18 18:43:14 +0000236 OutContext.getOrCreateSymbol(Twine(MO.getSymbolName()))));
Justin Holewinski3d49e5c2013-11-15 12:30:04 +0000237 return;
238 }
239
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000240 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
241 const MachineOperand &MO = MI->getOperand(i);
242
243 MCOperand MCOp;
Eric Christopher6aad8b12015-02-19 00:08:14 +0000244 if (!nvptxSubtarget->hasImageHandles()) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000245 if (lowerImageHandleOperand(MI, i, MCOp)) {
246 OutMI.addOperand(MCOp);
247 continue;
248 }
249 }
250
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000251 if (lowerOperand(MO, MCOp))
252 OutMI.addOperand(MCOp);
253 }
254}
255
256bool NVPTXAsmPrinter::lowerOperand(const MachineOperand &MO,
257 MCOperand &MCOp) {
258 switch (MO.getType()) {
259 default: llvm_unreachable("unknown operand type");
260 case MachineOperand::MO_Register:
Jim Grosbache9119e42015-05-13 18:37:00 +0000261 MCOp = MCOperand::createReg(encodeVirtualRegister(MO.getReg()));
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000262 break;
263 case MachineOperand::MO_Immediate:
Jim Grosbache9119e42015-05-13 18:37:00 +0000264 MCOp = MCOperand::createImm(MO.getImm());
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000265 break;
266 case MachineOperand::MO_MachineBasicBlock:
Jim Grosbach13760bd2015-05-30 01:25:56 +0000267 MCOp = MCOperand::createExpr(MCSymbolRefExpr::create(
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000268 MO.getMBB()->getSymbol(), OutContext));
269 break;
270 case MachineOperand::MO_ExternalSymbol:
Justin Holewinski30d56a72014-04-09 15:39:15 +0000271 MCOp = GetSymbolRef(GetExternalSymbolSymbol(MO.getSymbolName()));
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000272 break;
273 case MachineOperand::MO_GlobalAddress:
Justin Holewinski30d56a72014-04-09 15:39:15 +0000274 MCOp = GetSymbolRef(getSymbol(MO.getGlobal()));
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000275 break;
276 case MachineOperand::MO_FPImmediate: {
277 const ConstantFP *Cnt = MO.getFPImm();
Benjamin Kramer46e38f32016-06-08 10:01:20 +0000278 const APFloat &Val = Cnt->getValueAPF();
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000279
280 switch (Cnt->getType()->getTypeID()) {
281 default: report_fatal_error("Unsupported FP type"); break;
282 case Type::FloatTyID:
Jim Grosbache9119e42015-05-13 18:37:00 +0000283 MCOp = MCOperand::createExpr(
Jim Grosbach13760bd2015-05-30 01:25:56 +0000284 NVPTXFloatMCExpr::createConstantFPSingle(Val, OutContext));
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000285 break;
286 case Type::DoubleTyID:
Jim Grosbache9119e42015-05-13 18:37:00 +0000287 MCOp = MCOperand::createExpr(
Jim Grosbach13760bd2015-05-30 01:25:56 +0000288 NVPTXFloatMCExpr::createConstantFPDouble(Val, OutContext));
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000289 break;
290 }
291 break;
292 }
293 }
294 return true;
295}
296
297unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
Justin Holewinski871ec932013-08-06 14:13:31 +0000298 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
299 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000300
Justin Holewinski871ec932013-08-06 14:13:31 +0000301 DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
302 unsigned RegNum = RegMap[Reg];
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000303
Justin Holewinski871ec932013-08-06 14:13:31 +0000304 // Encode the register class in the upper 4 bits
305 // Must be kept in sync with NVPTXInstPrinter::printRegName
306 unsigned Ret = 0;
307 if (RC == &NVPTX::Int1RegsRegClass) {
308 Ret = (1 << 28);
309 } else if (RC == &NVPTX::Int16RegsRegClass) {
310 Ret = (2 << 28);
311 } else if (RC == &NVPTX::Int32RegsRegClass) {
312 Ret = (3 << 28);
313 } else if (RC == &NVPTX::Int64RegsRegClass) {
314 Ret = (4 << 28);
315 } else if (RC == &NVPTX::Float32RegsRegClass) {
316 Ret = (5 << 28);
317 } else if (RC == &NVPTX::Float64RegsRegClass) {
318 Ret = (6 << 28);
319 } else {
320 report_fatal_error("Bad register class");
321 }
322
323 // Insert the vreg number
324 Ret |= (RegNum & 0x0FFFFFFF);
325 return Ret;
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000326 } else {
Justin Holewinski871ec932013-08-06 14:13:31 +0000327 // Some special-use registers are actually physical registers.
328 // Encode this as the register class ID of 0 and the real register ID.
329 return Reg & 0x0FFFFFFF;
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000330 }
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000331}
332
Justin Holewinski30d56a72014-04-09 15:39:15 +0000333MCOperand NVPTXAsmPrinter::GetSymbolRef(const MCSymbol *Symbol) {
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000334 const MCExpr *Expr;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000335 Expr = MCSymbolRefExpr::create(Symbol, MCSymbolRefExpr::VK_None,
Justin Holewinski8b24e1e2013-08-06 23:06:42 +0000336 OutContext);
Jim Grosbache9119e42015-05-13 18:37:00 +0000337 return MCOperand::createExpr(Expr);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000338}
339
Justin Holewinski0497ab12013-03-30 14:29:21 +0000340void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
Mehdi Amini56228da2015-07-09 01:57:34 +0000341 const DataLayout &DL = getDataLayout();
Eric Christopher6aad8b12015-02-19 00:08:14 +0000342 const TargetLowering *TLI = nvptxSubtarget->getTargetLowering();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000343
344 Type *Ty = F->getReturnType();
345
Eric Christopher6aad8b12015-02-19 00:08:14 +0000346 bool isABI = (nvptxSubtarget->getSmVersion() >= 20);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000347
348 if (Ty->getTypeID() == Type::VoidTyID)
349 return;
350
351 O << " (";
352
353 if (isABI) {
Rafael Espindola08013342013-12-07 19:34:20 +0000354 if (Ty->isFloatingPointTy() || Ty->isIntegerTy()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000355 unsigned size = 0;
Craig Toppere3dcce92015-08-01 22:20:21 +0000356 if (auto *ITy = dyn_cast<IntegerType>(Ty)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000357 size = ITy->getBitWidth();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000358 if (size < 32)
359 size = 32;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000360 } else {
Justin Holewinski0497ab12013-03-30 14:29:21 +0000361 assert(Ty->isFloatingPointTy() && "Floating point type expected here");
Justin Holewinskiae556d32012-05-04 20:18:50 +0000362 size = Ty->getPrimitiveSizeInBits();
363 }
364
365 O << ".param .b" << size << " func_retval0";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000366 } else if (isa<PointerType>(Ty)) {
Mehdi Amini44ede332015-07-09 02:09:04 +0000367 O << ".param .b" << TLI->getPointerTy(DL).getSizeInBits()
Justin Holewinski0497ab12013-03-30 14:29:21 +0000368 << " func_retval0";
Artem Belevich74158b52016-07-20 18:39:52 +0000369 } else if (Ty->isAggregateType() || Ty->isVectorTy()) {
Mehdi Amini56228da2015-07-09 01:57:34 +0000370 unsigned totalsz = DL.getTypeAllocSize(Ty);
Artem Belevich74158b52016-07-20 18:39:52 +0000371 unsigned retAlignment = 0;
372 if (!llvm::getAlign(*F, 0, retAlignment))
373 retAlignment = DL.getABITypeAlignment(Ty);
374 O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
375 << "]";
Craig Topperd3c02f12015-01-05 10:15:49 +0000376 } else
377 llvm_unreachable("Unknown return type");
Justin Holewinskiae556d32012-05-04 20:18:50 +0000378 } else {
379 SmallVector<EVT, 16> vtparts;
Mehdi Amini56228da2015-07-09 01:57:34 +0000380 ComputeValueVTs(*TLI, DL, Ty, vtparts);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000381 unsigned idx = 0;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000382 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000383 unsigned elems = 1;
384 EVT elemtype = vtparts[i];
385 if (vtparts[i].isVector()) {
386 elems = vtparts[i].getVectorNumElements();
387 elemtype = vtparts[i].getVectorElementType();
388 }
389
Justin Holewinski0497ab12013-03-30 14:29:21 +0000390 for (unsigned j = 0, je = elems; j != je; ++j) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000391 unsigned sz = elemtype.getSizeInBits();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000392 if (elemtype.isInteger() && (sz < 32))
393 sz = 32;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000394 O << ".reg .b" << sz << " func_retval" << idx;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000395 if (j < je - 1)
396 O << ", ";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000397 ++idx;
398 }
Justin Holewinski0497ab12013-03-30 14:29:21 +0000399 if (i < e - 1)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000400 O << ", ";
401 }
402 }
403 O << ") ";
404 return;
405}
406
407void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
408 raw_ostream &O) {
409 const Function *F = MF.getFunction();
410 printReturnValStr(F, O);
411}
412
Jingyue Wu0220df02015-02-01 02:27:45 +0000413// Return true if MBB is the header of a loop marked with
414// llvm.loop.unroll.disable.
Jingyue Wu5bbcdaa2015-02-03 17:57:38 +0000415// TODO: consider "#pragma unroll 1" which is equivalent to "#pragma nounroll".
Jingyue Wu0220df02015-02-01 02:27:45 +0000416bool NVPTXAsmPrinter::isLoopHeaderOfNoUnroll(
417 const MachineBasicBlock &MBB) const {
418 MachineLoopInfo &LI = getAnalysis<MachineLoopInfo>();
Jingyue Wu0220df02015-02-01 02:27:45 +0000419 // We insert .pragma "nounroll" only to the loop header.
Benjamin Kramerdb220db2015-06-02 15:28:27 +0000420 if (!LI.isLoopHeader(&MBB))
Jingyue Wu0220df02015-02-01 02:27:45 +0000421 return false;
422
423 // llvm.loop.unroll.disable is marked on the back edges of a loop. Therefore,
424 // we iterate through each back edge of the loop with header MBB, and check
425 // whether its metadata contains llvm.loop.unroll.disable.
426 for (auto I = MBB.pred_begin(); I != MBB.pred_end(); ++I) {
427 const MachineBasicBlock *PMBB = *I;
428 if (LI.getLoopFor(PMBB) != LI.getLoopFor(&MBB)) {
429 // Edges from other loops to MBB are not back edges.
430 continue;
431 }
432 if (const BasicBlock *PBB = PMBB->getBasicBlock()) {
Duncan P. N. Exon Smith1d15a9f2016-03-25 00:35:38 +0000433 if (MDNode *LoopID =
434 PBB->getTerminator()->getMetadata(LLVMContext::MD_loop)) {
Jingyue Wu0220df02015-02-01 02:27:45 +0000435 if (GetUnrollMetadata(LoopID, "llvm.loop.unroll.disable"))
436 return true;
437 }
438 }
439 }
440 return false;
441}
442
443void NVPTXAsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
444 AsmPrinter::EmitBasicBlockStart(MBB);
445 if (isLoopHeaderOfNoUnroll(MBB))
Lang Hames9ff69c82015-04-24 19:11:51 +0000446 OutStreamer->EmitRawText(StringRef("\t.pragma \"nounroll\";\n"));
Jingyue Wu0220df02015-02-01 02:27:45 +0000447}
448
Justin Holewinskiae556d32012-05-04 20:18:50 +0000449void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
450 SmallString<128> Str;
451 raw_svector_ostream O(Str);
452
Justin Holewinski01f89f02013-05-20 12:13:32 +0000453 if (!GlobalsEmitted) {
454 emitGlobals(*MF->getFunction()->getParent());
455 GlobalsEmitted = true;
456 }
457
Justin Holewinskiae556d32012-05-04 20:18:50 +0000458 // Set up
459 MRI = &MF->getRegInfo();
460 F = MF->getFunction();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000461 emitLinkageDirective(F, O);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000462 if (llvm::isKernelFunction(*F))
463 O << ".entry ";
464 else {
465 O << ".func ";
466 printReturnValStr(*MF, O);
467 }
468
Matt Arsenault8b643552015-06-09 00:31:39 +0000469 CurrentFnSym->print(O, MAI);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000470
471 emitFunctionParamList(*MF, O);
472
473 if (llvm::isKernelFunction(*F))
474 emitKernelFunctionDirectives(*F, O);
475
Lang Hames9ff69c82015-04-24 19:11:51 +0000476 OutStreamer->EmitRawText(O.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000477
478 prevDebugLoc = DebugLoc();
479}
480
481void NVPTXAsmPrinter::EmitFunctionBodyStart() {
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +0000482 VRegMapping.clear();
Lang Hames9ff69c82015-04-24 19:11:51 +0000483 OutStreamer->EmitRawText(StringRef("{\n"));
Justin Holewinskiae556d32012-05-04 20:18:50 +0000484 setAndEmitFunctionVirtualRegisters(*MF);
485
486 SmallString<128> Str;
487 raw_svector_ostream O(Str);
488 emitDemotedVars(MF->getFunction(), O);
Lang Hames9ff69c82015-04-24 19:11:51 +0000489 OutStreamer->EmitRawText(O.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000490}
491
492void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
Lang Hames9ff69c82015-04-24 19:11:51 +0000493 OutStreamer->EmitRawText(StringRef("}\n"));
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +0000494 VRegMapping.clear();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000495}
496
Justin Holewinski660597d2013-10-11 12:39:36 +0000497void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
498 unsigned RegNo = MI->getOperand(0).getReg();
Andrew Kaylor5c73e1f2015-03-24 23:37:10 +0000499 if (TargetRegisterInfo::isVirtualRegister(RegNo)) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000500 OutStreamer->AddComment(Twine("implicit-def: ") +
501 getVirtualRegisterName(RegNo));
Justin Holewinski660597d2013-10-11 12:39:36 +0000502 } else {
Lang Hames9ff69c82015-04-24 19:11:51 +0000503 OutStreamer->AddComment(Twine("implicit-def: ") +
504 nvptxSubtarget->getRegisterInfo()->getName(RegNo));
Justin Holewinski660597d2013-10-11 12:39:36 +0000505 }
Lang Hames9ff69c82015-04-24 19:11:51 +0000506 OutStreamer->AddBlankLine();
Justin Holewinski660597d2013-10-11 12:39:36 +0000507}
508
Justin Holewinski0497ab12013-03-30 14:29:21 +0000509void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
510 raw_ostream &O) const {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000511 // If the NVVM IR has some of reqntid* specified, then output
512 // the reqntid directive, and set the unspecified ones to 1.
513 // If none of reqntid* is specified, don't output reqntid directive.
514 unsigned reqntidx, reqntidy, reqntidz;
515 bool specified = false;
Eli Bendersky3e840192015-03-23 16:26:23 +0000516 if (!llvm::getReqNTIDx(F, reqntidx))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000517 reqntidx = 1;
518 else
519 specified = true;
Eli Bendersky3e840192015-03-23 16:26:23 +0000520 if (!llvm::getReqNTIDy(F, reqntidy))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000521 reqntidy = 1;
522 else
523 specified = true;
Eli Bendersky3e840192015-03-23 16:26:23 +0000524 if (!llvm::getReqNTIDz(F, reqntidz))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000525 reqntidz = 1;
526 else
527 specified = true;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000528
529 if (specified)
Justin Holewinski0497ab12013-03-30 14:29:21 +0000530 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
531 << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000532
533 // If the NVVM IR has some of maxntid* specified, then output
534 // the maxntid directive, and set the unspecified ones to 1.
535 // If none of maxntid* is specified, don't output maxntid directive.
536 unsigned maxntidx, maxntidy, maxntidz;
537 specified = false;
Eli Bendersky3e840192015-03-23 16:26:23 +0000538 if (!llvm::getMaxNTIDx(F, maxntidx))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000539 maxntidx = 1;
540 else
541 specified = true;
Eli Bendersky3e840192015-03-23 16:26:23 +0000542 if (!llvm::getMaxNTIDy(F, maxntidy))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000543 maxntidy = 1;
544 else
545 specified = true;
Eli Bendersky3e840192015-03-23 16:26:23 +0000546 if (!llvm::getMaxNTIDz(F, maxntidz))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000547 maxntidz = 1;
548 else
549 specified = true;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000550
551 if (specified)
Justin Holewinski0497ab12013-03-30 14:29:21 +0000552 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
553 << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000554
555 unsigned mincta;
556 if (llvm::getMinCTASm(F, mincta))
557 O << ".minnctapersm " << mincta << "\n";
558}
559
Justin Holewinski660597d2013-10-11 12:39:36 +0000560std::string
561NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
562 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000563
Justin Holewinski660597d2013-10-11 12:39:36 +0000564 std::string Name;
565 raw_string_ostream NameStr(Name);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000566
Justin Holewinski660597d2013-10-11 12:39:36 +0000567 VRegRCMap::const_iterator I = VRegMapping.find(RC);
568 assert(I != VRegMapping.end() && "Bad register class");
569 const DenseMap<unsigned, unsigned> &RegMap = I->second;
570
571 VRegMap::const_iterator VI = RegMap.find(Reg);
572 assert(VI != RegMap.end() && "Bad virtual register");
573 unsigned MappedVR = VI->second;
574
575 NameStr << getNVPTXRegClassStr(RC) << MappedVR;
576
577 NameStr.flush();
578 return Name;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000579}
580
Justin Holewinski660597d2013-10-11 12:39:36 +0000581void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
Justin Holewinski0497ab12013-03-30 14:29:21 +0000582 raw_ostream &O) {
Justin Holewinski660597d2013-10-11 12:39:36 +0000583 O << getVirtualRegisterName(vr);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000584}
585
Justin Holewinski0497ab12013-03-30 14:29:21 +0000586void NVPTXAsmPrinter::printVecModifiedImmediate(
587 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
588 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
589 int Imm = (int) MO.getImm();
590 if (0 == strcmp(Modifier, "vecelem"))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000591 O << "_" << vecelem[Imm];
Justin Holewinski0497ab12013-03-30 14:29:21 +0000592 else if (0 == strcmp(Modifier, "vecv4comm1")) {
593 if ((Imm < 0) || (Imm > 3))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000594 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000595 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
596 if ((Imm < 4) || (Imm > 7))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000597 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000598 } else if (0 == strcmp(Modifier, "vecv4pos")) {
599 if (Imm < 0)
600 Imm = 0;
601 O << "_" << vecelem[Imm % 4];
602 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
603 if ((Imm < 0) || (Imm > 1))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000604 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000605 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
606 if ((Imm < 2) || (Imm > 3))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000607 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000608 } else if (0 == strcmp(Modifier, "vecv2pos")) {
609 if (Imm < 0)
610 Imm = 0;
611 O << "_" << vecelem[Imm % 2];
612 } else
Craig Topperbdf39a42012-05-24 07:02:50 +0000613 llvm_unreachable("Unknown Modifier on immediate operand");
Justin Holewinskiae556d32012-05-04 20:18:50 +0000614}
615
Justin Holewinskidc5e3b62013-06-28 17:58:04 +0000616
617
Justin Holewinski0497ab12013-03-30 14:29:21 +0000618void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000619
Justin Holewinski0497ab12013-03-30 14:29:21 +0000620 emitLinkageDirective(F, O);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000621 if (llvm::isKernelFunction(*F))
622 O << ".entry ";
623 else
624 O << ".func ";
625 printReturnValStr(F, O);
Matt Arsenault8b643552015-06-09 00:31:39 +0000626 getSymbol(F)->print(O, MAI);
627 O << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000628 emitFunctionParamList(F, O);
629 O << ";\n";
630}
631
Justin Holewinski0497ab12013-03-30 14:29:21 +0000632static bool usedInGlobalVarDef(const Constant *C) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000633 if (!C)
634 return false;
635
636 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
Jingyue Wu4be014a2015-07-31 05:09:47 +0000637 return GV->getName() != "llvm.used";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000638 }
639
Chandler Carruthcdf47882014-03-09 03:16:01 +0000640 for (const User *U : C->users())
641 if (const Constant *C = dyn_cast<Constant>(U))
642 if (usedInGlobalVarDef(C))
643 return true;
644
Justin Holewinskiae556d32012-05-04 20:18:50 +0000645 return false;
646}
647
Justin Holewinski0497ab12013-03-30 14:29:21 +0000648static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000649 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
Yaron Keren075759a2015-03-30 15:42:36 +0000650 if (othergv->getName() == "llvm.used")
Justin Holewinskiae556d32012-05-04 20:18:50 +0000651 return true;
652 }
653
654 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
655 if (instr->getParent() && instr->getParent()->getParent()) {
656 const Function *curFunc = instr->getParent()->getParent();
657 if (oneFunc && (curFunc != oneFunc))
658 return false;
659 oneFunc = curFunc;
660 return true;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000661 } else
Justin Holewinskiae556d32012-05-04 20:18:50 +0000662 return false;
663 }
664
Chandler Carruthcdf47882014-03-09 03:16:01 +0000665 for (const User *UU : U->users())
Eli Bendersky3e840192015-03-23 16:26:23 +0000666 if (!usedInOneFunc(UU, oneFunc))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000667 return false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000668
Justin Holewinskiae556d32012-05-04 20:18:50 +0000669 return true;
670}
671
672/* Find out if a global variable can be demoted to local scope.
673 * Currently, this is valid for CUDA shared variables, which have local
674 * scope and global lifetime. So the conditions to check are :
675 * 1. Is the global variable in shared address space?
676 * 2. Does it have internal linkage?
677 * 3. Is the global variable referenced only in one function?
678 */
679static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
Eli Bendersky3e840192015-03-23 16:26:23 +0000680 if (!gv->hasInternalLinkage())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000681 return false;
Craig Toppere3dcce92015-08-01 22:20:21 +0000682 PointerType *Pty = gv->getType();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000683 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
684 return false;
685
Craig Topper062a2ba2014-04-25 05:30:21 +0000686 const Function *oneFunc = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000687
688 bool flag = usedInOneFunc(gv, oneFunc);
Eli Bendersky3e840192015-03-23 16:26:23 +0000689 if (!flag)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000690 return false;
691 if (!oneFunc)
692 return false;
693 f = oneFunc;
694 return true;
695}
696
697static bool useFuncSeen(const Constant *C,
698 llvm::DenseMap<const Function *, bool> &seenMap) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000699 for (const User *U : C->users()) {
700 if (const Constant *cu = dyn_cast<Constant>(U)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000701 if (useFuncSeen(cu, seenMap))
702 return true;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000703 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000704 const BasicBlock *bb = I->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000705 if (!bb)
706 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000707 const Function *caller = bb->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000708 if (!caller)
709 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000710 if (seenMap.find(caller) != seenMap.end())
711 return true;
712 }
713 }
714 return false;
715}
716
Justin Holewinski01f89f02013-05-20 12:13:32 +0000717void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000718 llvm::DenseMap<const Function *, bool> seenMap;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000719 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
Duncan P. N. Exon Smith61149b82015-10-20 00:54:09 +0000720 const Function *F = &*FI;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000721
722 if (F->isDeclaration()) {
723 if (F->use_empty())
724 continue;
725 if (F->getIntrinsicID())
726 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000727 emitDeclaration(F, O);
728 continue;
729 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000730 for (const User *U : F->users()) {
731 if (const Constant *C = dyn_cast<Constant>(U)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000732 if (usedInGlobalVarDef(C)) {
733 // The use is in the initialization of a global variable
734 // that is a function pointer, so print a declaration
735 // for the original function
Justin Holewinskiae556d32012-05-04 20:18:50 +0000736 emitDeclaration(F, O);
737 break;
738 }
739 // Emit a declaration of this function if the function that
740 // uses this constant expr has already been seen.
741 if (useFuncSeen(C, seenMap)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000742 emitDeclaration(F, O);
743 break;
744 }
745 }
746
Chandler Carruthcdf47882014-03-09 03:16:01 +0000747 if (!isa<Instruction>(U))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000748 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000749 const Instruction *instr = cast<Instruction>(U);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000750 const BasicBlock *bb = instr->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000751 if (!bb)
752 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000753 const Function *caller = bb->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000754 if (!caller)
755 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000756
757 // If a caller has already been seen, then the caller is
758 // appearing in the module before the callee. so print out
759 // a declaration for the callee.
760 if (seenMap.find(caller) != seenMap.end()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000761 emitDeclaration(F, O);
762 break;
763 }
764 }
765 seenMap[F] = true;
766 }
767}
768
769void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
770 DebugInfoFinder DbgFinder;
771 DbgFinder.processModule(M);
772
Justin Holewinski0497ab12013-03-30 14:29:21 +0000773 unsigned i = 1;
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000774 for (const DICompileUnit *DIUnit : DbgFinder.compile_units()) {
Duncan P. N. Exon Smith35ef22c2015-04-15 23:19:27 +0000775 StringRef Filename = DIUnit->getFilename();
776 StringRef Dirname = DIUnit->getDirectory();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000777 SmallString<128> FullPathName = Dirname;
778 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
779 sys::path::append(FullPathName, Filename);
Yaron Keren075759a2015-03-30 15:42:36 +0000780 Filename = FullPathName;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000781 }
Yaron Keren075759a2015-03-30 15:42:36 +0000782 if (filenameMap.find(Filename) != filenameMap.end())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000783 continue;
Yaron Keren075759a2015-03-30 15:42:36 +0000784 filenameMap[Filename] = i;
Lang Hames9ff69c82015-04-24 19:11:51 +0000785 OutStreamer->EmitDwarfFileDirective(i, "", Filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000786 ++i;
787 }
788
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000789 for (DISubprogram *SP : DbgFinder.subprograms()) {
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000790 StringRef Filename = SP->getFilename();
791 StringRef Dirname = SP->getDirectory();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000792 SmallString<128> FullPathName = Dirname;
793 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
794 sys::path::append(FullPathName, Filename);
Yaron Keren075759a2015-03-30 15:42:36 +0000795 Filename = FullPathName;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000796 }
Yaron Keren075759a2015-03-30 15:42:36 +0000797 if (filenameMap.find(Filename) != filenameMap.end())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000798 continue;
Yaron Keren075759a2015-03-30 15:42:36 +0000799 filenameMap[Filename] = i;
Artem Belevicha8455f22016-02-11 18:21:47 +0000800 OutStreamer->EmitDwarfFileDirective(i, "", Filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000801 ++i;
802 }
803}
804
Justin Lebaread59f42016-01-30 01:07:38 +0000805static bool isEmptyXXStructor(GlobalVariable *GV) {
806 if (!GV) return true;
807 const ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
808 if (!InitList) return true; // Not an array; we don't know how to parse.
809 return InitList->getNumOperands() == 0;
810}
811
Justin Holewinski0497ab12013-03-30 14:29:21 +0000812bool NVPTXAsmPrinter::doInitialization(Module &M) {
Eric Christopher6aad8b12015-02-19 00:08:14 +0000813 // Construct a default subtarget off of the TargetMachine defaults. The
814 // rest of NVPTX isn't friendly to change subtargets per function and
815 // so the default TargetMachine will have all of the options.
Daniel Sandersc81f4502015-06-16 15:44:21 +0000816 const Triple &TT = TM.getTargetTriple();
Eric Christopher6aad8b12015-02-19 00:08:14 +0000817 StringRef CPU = TM.getTargetCPU();
818 StringRef FS = TM.getTargetFeatureString();
819 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
Eric Christopher02389e32015-02-19 00:08:27 +0000820 const NVPTXSubtarget STI(TT, CPU, FS, NTM);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000821
Justin Lebar3a5f5792016-01-23 21:12:20 +0000822 if (M.alias_size()) {
823 report_fatal_error("Module has aliases, which NVPTX does not support.");
824 return true; // error
825 }
Justin Lebaread59f42016-01-30 01:07:38 +0000826 if (!isEmptyXXStructor(M.getNamedGlobal("llvm.global_ctors"))) {
827 report_fatal_error(
828 "Module has a nontrivial global ctor, which NVPTX does not support.");
829 return true; // error
830 }
831 if (!isEmptyXXStructor(M.getNamedGlobal("llvm.global_dtors"))) {
832 report_fatal_error(
833 "Module has a nontrivial global dtor, which NVPTX does not support.");
834 return true; // error
835 }
Justin Lebar3a5f5792016-01-23 21:12:20 +0000836
Justin Holewinskiae556d32012-05-04 20:18:50 +0000837 SmallString<128> Str1;
838 raw_svector_ostream OS1(Str1);
839
840 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000841
842 // We need to call the parent's one explicitly.
843 //bool Result = AsmPrinter::doInitialization(M);
844
Eric Christopherb4b75a52016-09-29 02:03:47 +0000845 // Initialize TargetLoweringObjectFile since we didn't do in
846 // AsmPrinter::doInitialization either right above or where it's commented out
847 // below.
Justin Holewinski0497ab12013-03-30 14:29:21 +0000848 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
849 .Initialize(OutContext, TM);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000850
Justin Holewinskiae556d32012-05-04 20:18:50 +0000851 // Emit header before any dwarf directives are emitted below.
Eric Christopher6aad8b12015-02-19 00:08:14 +0000852 emitHeader(M, OS1, STI);
Lang Hames9ff69c82015-04-24 19:11:51 +0000853 OutStreamer->EmitRawText(OS1.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000854
Justin Holewinskiae556d32012-05-04 20:18:50 +0000855 // Already commented out
856 //bool Result = AsmPrinter::doInitialization(M);
857
Justin Holewinskid2bbdf02013-07-01 13:00:14 +0000858 // Emit module-level inline asm if it exists.
859 if (!M.getModuleInlineAsm().empty()) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000860 OutStreamer->AddComment("Start of file scope inline assembly");
861 OutStreamer->AddBlankLine();
862 OutStreamer->EmitRawText(StringRef(M.getModuleInlineAsm()));
863 OutStreamer->AddBlankLine();
864 OutStreamer->AddComment("End of file scope inline assembly");
865 OutStreamer->AddBlankLine();
Justin Holewinskid2bbdf02013-07-01 13:00:14 +0000866 }
867
Eric Christopher6aad8b12015-02-19 00:08:14 +0000868 // If we're not NVCL we're CUDA, go ahead and emit filenames.
Daniel Sandersc81f4502015-06-16 15:44:21 +0000869 if (TM.getTargetTriple().getOS() != Triple::NVCL)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000870 recordAndEmitFilenames(M);
871
Justin Holewinski01f89f02013-05-20 12:13:32 +0000872 GlobalsEmitted = false;
873
874 return false; // success
875}
876
877void NVPTXAsmPrinter::emitGlobals(const Module &M) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000878 SmallString<128> Str2;
879 raw_svector_ostream OS2(Str2);
880
881 emitDeclarations(M, OS2);
882
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000883 // As ptxas does not support forward references of globals, we need to first
884 // sort the list of module-level globals in def-use order. We visit each
885 // global variable in order, and ensure that we emit it *after* its dependent
886 // globals. We use a little extra memory maintaining both a set and a list to
887 // have fast searches while maintaining a strict ordering.
Justin Holewinski01f89f02013-05-20 12:13:32 +0000888 SmallVector<const GlobalVariable *, 8> Globals;
889 DenseSet<const GlobalVariable *> GVVisited;
890 DenseSet<const GlobalVariable *> GVVisiting;
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000891
892 // Visit each global variable, in order
Duncan P. N. Exon Smith61149b82015-10-20 00:54:09 +0000893 for (const GlobalVariable &I : M.globals())
894 VisitGlobalVariableForEmission(&I, Globals, GVVisited, GVVisiting);
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000895
Justin Holewinski0497ab12013-03-30 14:29:21 +0000896 assert(GVVisited.size() == M.getGlobalList().size() &&
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000897 "Missed a global variable");
898 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
899
900 // Print out module-level global variables in proper order
901 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
902 printModuleLevelGV(Globals[i], OS2);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000903
904 OS2 << '\n';
905
Lang Hames9ff69c82015-04-24 19:11:51 +0000906 OutStreamer->EmitRawText(OS2.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000907}
908
Eric Christopher6aad8b12015-02-19 00:08:14 +0000909void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O,
910 const NVPTXSubtarget &STI) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000911 O << "//\n";
912 O << "// Generated by LLVM NVPTX Back-End\n";
913 O << "//\n";
914 O << "\n";
915
Eric Christopher6aad8b12015-02-19 00:08:14 +0000916 unsigned PTXVersion = STI.getPTXVersion();
Justin Holewinski1812ee92012-11-12 03:16:43 +0000917 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000918
919 O << ".target ";
Eric Christopher6aad8b12015-02-19 00:08:14 +0000920 O << STI.getTargetName();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000921
Eric Christopherca929f22015-02-19 00:22:47 +0000922 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
923 if (NTM.getDrvInterface() == NVPTX::NVCL)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000924 O << ", texmode_independent";
Eric Christopherbeffc4e2015-02-19 00:08:23 +0000925 else {
Eric Christopher6aad8b12015-02-19 00:08:14 +0000926 if (!STI.hasDouble())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000927 O << ", map_f64_to_f32";
928 }
929
930 if (MAI->doesSupportDebugInformation())
931 O << ", debug";
932
933 O << "\n";
934
935 O << ".address_size ";
Eric Christopherca929f22015-02-19 00:22:47 +0000936 if (NTM.is64Bit())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000937 O << "64";
938 else
939 O << "32";
940 O << "\n";
941
942 O << "\n";
943}
944
945bool NVPTXAsmPrinter::doFinalization(Module &M) {
Justin Holewinski01f89f02013-05-20 12:13:32 +0000946 // If we did not emit any functions, then the global declarations have not
947 // yet been emitted.
948 if (!GlobalsEmitted) {
949 emitGlobals(M);
950 GlobalsEmitted = true;
951 }
952
Justin Holewinskiae556d32012-05-04 20:18:50 +0000953 // XXX Temproarily remove global variables so that doFinalization() will not
954 // emit them again (global variables are emitted at beginning).
955
956 Module::GlobalListType &global_list = M.getGlobalList();
957 int i, n = global_list.size();
Dylan Noblesmithc9e2a272014-08-26 02:03:35 +0000958 GlobalVariable **gv_array = new GlobalVariable *[n];
Justin Holewinskiae556d32012-05-04 20:18:50 +0000959
960 // first, back-up GlobalVariable in gv_array
961 i = 0;
962 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000963 I != E; ++I)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000964 gv_array[i++] = &*I;
965
966 // second, empty global_list
967 while (!global_list.empty())
968 global_list.remove(global_list.begin());
969
970 // call doFinalization
971 bool ret = AsmPrinter::doFinalization(M);
972
973 // now we restore global variables
Justin Holewinski0497ab12013-03-30 14:29:21 +0000974 for (i = 0; i < n; i++)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000975 global_list.insert(global_list.end(), gv_array[i]);
976
Justin Holewinski59596952014-04-09 15:38:52 +0000977 clearAnnotationCache(&M);
Dylan Noblesmithc9e2a272014-08-26 02:03:35 +0000978
979 delete[] gv_array;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000980 return ret;
981
Justin Holewinskiae556d32012-05-04 20:18:50 +0000982 //bool Result = AsmPrinter::doFinalization(M);
983 // Instead of calling the parents doFinalization, we may
984 // clone parents doFinalization and customize here.
985 // Currently, we if NVISA out the EmitGlobals() in
986 // parent's doFinalization, which is too intrusive.
987 //
988 // Same for the doInitialization.
989 //return Result;
990}
991
992// This function emits appropriate linkage directives for
993// functions and global variables.
994//
995// extern function declaration -> .extern
996// extern function definition -> .visible
997// external global variable with init -> .visible
998// external without init -> .extern
999// appending -> not allowed, assert.
Justin Holewinski7d5bf662014-06-27 18:35:10 +00001000// for any linkage other than
1001// internal, private, linker_private,
1002// linker_private_weak, linker_private_weak_def_auto,
1003// we emit -> .weak.
Justin Holewinskiae556d32012-05-04 20:18:50 +00001004
Justin Holewinski0497ab12013-03-30 14:29:21 +00001005void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
1006 raw_ostream &O) {
Eric Christopherbeffc4e2015-02-19 00:08:23 +00001007 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() == NVPTX::CUDA) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001008 if (V->hasExternalLinkage()) {
1009 if (isa<GlobalVariable>(V)) {
1010 const GlobalVariable *GVar = cast<GlobalVariable>(V);
1011 if (GVar) {
1012 if (GVar->hasInitializer())
1013 O << ".visible ";
1014 else
1015 O << ".extern ";
1016 }
1017 } else if (V->isDeclaration())
1018 O << ".extern ";
1019 else
1020 O << ".visible ";
1021 } else if (V->hasAppendingLinkage()) {
1022 std::string msg;
1023 msg.append("Error: ");
1024 msg.append("Symbol ");
1025 if (V->hasName())
Yaron Keren075759a2015-03-30 15:42:36 +00001026 msg.append(V->getName());
Justin Holewinskiae556d32012-05-04 20:18:50 +00001027 msg.append("has unsupported appending linkage type");
1028 llvm_unreachable(msg.c_str());
Justin Holewinski7d5bf662014-06-27 18:35:10 +00001029 } else if (!V->hasInternalLinkage() &&
1030 !V->hasPrivateLinkage()) {
1031 O << ".weak ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001032 }
1033 }
1034}
1035
Justin Holewinski01f89f02013-05-20 12:13:32 +00001036void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1037 raw_ostream &O,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001038 bool processDemoted) {
1039
1040 // Skip meta data
1041 if (GVar->hasSection()) {
Rafael Espindola83658d62016-05-11 18:21:59 +00001042 if (GVar->getSection() == "llvm.metadata")
Justin Holewinskiae556d32012-05-04 20:18:50 +00001043 return;
1044 }
1045
Justin Holewinski73cb5de2014-06-27 18:35:53 +00001046 // Skip LLVM intrinsic global variables
1047 if (GVar->getName().startswith("llvm.") ||
1048 GVar->getName().startswith("nvvm."))
1049 return;
1050
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001051 const DataLayout &DL = getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001052
1053 // GlobalVariables are always constant pointers themselves.
Craig Toppere3dcce92015-08-01 22:20:21 +00001054 PointerType *PTy = GVar->getType();
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001055 Type *ETy = GVar->getValueType();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001056
1057 if (GVar->hasExternalLinkage()) {
1058 if (GVar->hasInitializer())
1059 O << ".visible ";
1060 else
1061 O << ".extern ";
Justin Holewinskid73767a2014-06-27 18:35:56 +00001062 } else if (GVar->hasLinkOnceLinkage() || GVar->hasWeakLinkage() ||
1063 GVar->hasAvailableExternallyLinkage() ||
1064 GVar->hasCommonLinkage()) {
1065 O << ".weak ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001066 }
1067
1068 if (llvm::isTexture(*GVar)) {
1069 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1070 return;
1071 }
1072
1073 if (llvm::isSurface(*GVar)) {
1074 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1075 return;
1076 }
1077
1078 if (GVar->isDeclaration()) {
1079 // (extern) declarations, no definition or initializer
1080 // Currently the only known declaration is for an automatic __local
1081 // (.shared) promoted to global.
1082 emitPTXGlobalVariable(GVar, O);
1083 O << ";\n";
1084 return;
1085 }
1086
1087 if (llvm::isSampler(*GVar)) {
1088 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1089
Craig Topper062a2ba2014-04-25 05:30:21 +00001090 const Constant *Initializer = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001091 if (GVar->hasInitializer())
1092 Initializer = GVar->getInitializer();
Craig Topper062a2ba2014-04-25 05:30:21 +00001093 const ConstantInt *CI = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001094 if (Initializer)
1095 CI = dyn_cast<ConstantInt>(Initializer);
1096 if (CI) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001097 unsigned sample = CI->getZExtValue();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001098
1099 O << " = { ";
1100
Justin Holewinski0497ab12013-03-30 14:29:21 +00001101 for (int i = 0,
1102 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1103 i < 3; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001104 O << "addr_mode_" << i << " = ";
1105 switch (addr) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001106 case 0:
1107 O << "wrap";
1108 break;
1109 case 1:
1110 O << "clamp_to_border";
1111 break;
1112 case 2:
1113 O << "clamp_to_edge";
1114 break;
1115 case 3:
1116 O << "wrap";
1117 break;
1118 case 4:
1119 O << "mirror";
1120 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001121 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001122 O << ", ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001123 }
1124 O << "filter_mode = ";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001125 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1126 case 0:
1127 O << "nearest";
1128 break;
1129 case 1:
1130 O << "linear";
1131 break;
1132 case 2:
Craig Topper2a30d782014-06-18 05:05:13 +00001133 llvm_unreachable("Anisotropic filtering is not supported");
Justin Holewinski0497ab12013-03-30 14:29:21 +00001134 default:
1135 O << "nearest";
1136 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001137 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001138 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001139 O << ", force_unnormalized_coords = 1";
1140 }
1141 O << " }";
1142 }
1143
1144 O << ";\n";
1145 return;
1146 }
1147
1148 if (GVar->hasPrivateLinkage()) {
1149
1150 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1151 return;
1152
1153 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1154 if (!strncmp(GVar->getName().data(), "filename", 8))
1155 return;
1156 if (GVar->use_empty())
1157 return;
1158 }
1159
Craig Topper062a2ba2014-04-25 05:30:21 +00001160 const Function *demotedFunc = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001161 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
Yaron Keren075759a2015-03-30 15:42:36 +00001162 O << "// " << GVar->getName() << " has been demoted\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001163 if (localDecls.find(demotedFunc) != localDecls.end())
1164 localDecls[demotedFunc].push_back(GVar);
1165 else {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001166 std::vector<const GlobalVariable *> temp;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001167 temp.push_back(GVar);
1168 localDecls[demotedFunc] = temp;
1169 }
1170 return;
1171 }
1172
1173 O << ".";
1174 emitPTXAddressSpace(PTy->getAddressSpace(), O);
Justin Holewinski773ca402014-06-27 18:35:58 +00001175
1176 if (isManaged(*GVar)) {
1177 O << " .attribute(.managed)";
1178 }
1179
Justin Holewinskiae556d32012-05-04 20:18:50 +00001180 if (GVar->getAlignment() == 0)
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001181 O << " .align " << (int)DL.getPrefTypeAlignment(ETy);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001182 else
1183 O << " .align " << GVar->getAlignment();
1184
Jingyue Wue4c9cf02014-12-17 17:59:04 +00001185 if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001186 O << " .";
Justin Holewinski700b6fa2013-05-20 12:13:28 +00001187 // Special case: ABI requires that we use .u8 for predicates
1188 if (ETy->isIntegerTy(1))
1189 O << "u8";
1190 else
1191 O << getPTXFundamentalTypeStr(ETy, false);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001192 O << " ";
Matt Arsenault8b643552015-06-09 00:31:39 +00001193 getSymbol(GVar)->print(O, MAI);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001194
1195 // Ptx allows variable initilization only for constant and global state
1196 // spaces.
Justin Holewinski549c7732014-06-27 18:36:01 +00001197 if (GVar->hasInitializer()) {
1198 if ((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1199 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) {
1200 const Constant *Initializer = GVar->getInitializer();
Jingyue Wu312fd022015-04-24 02:57:30 +00001201 // 'undef' is treated as there is no value specified.
Justin Holewinski549c7732014-06-27 18:36:01 +00001202 if (!Initializer->isNullValue() && !isa<UndefValue>(Initializer)) {
1203 O << " = ";
1204 printScalarConstant(Initializer, O);
1205 }
1206 } else {
Jingyue Wufcec0982015-08-22 05:40:26 +00001207 // The frontend adds zero-initializer to device and constant variables
1208 // that don't have an initial value, and UndefValue to shared
1209 // variables, so skip warning for this case.
1210 if (!GVar->getInitializer()->isNullValue() &&
1211 !isa<UndefValue>(GVar->getInitializer())) {
Benjamin Kramerdba7ee92015-05-28 11:24:24 +00001212 report_fatal_error("initial value of '" + GVar->getName() +
1213 "' is not allowed in addrspace(" +
1214 Twine(PTy->getAddressSpace()) + ")");
Justin Holewinski549c7732014-06-27 18:36:01 +00001215 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001216 }
1217 }
1218 } else {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001219 unsigned int ElementSize = 0;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001220
1221 // Although PTX has direct support for struct type and array type and
1222 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1223 // targets that support these high level field accesses. Structs, arrays
1224 // and vectors are lowered into arrays of bytes.
1225 switch (ETy->getTypeID()) {
1226 case Type::StructTyID:
1227 case Type::ArrayTyID:
1228 case Type::VectorTyID:
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001229 ElementSize = DL.getTypeStoreSize(ETy);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001230 // Ptx allows variable initilization only for constant and
1231 // global state spaces.
1232 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
Justin Holewinski0497ab12013-03-30 14:29:21 +00001233 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1234 GVar->hasInitializer()) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001235 const Constant *Initializer = GVar->getInitializer();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001236 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001237 AggBuffer aggBuffer(ElementSize, O, *this);
1238 bufferAggregateConstant(Initializer, &aggBuffer);
1239 if (aggBuffer.numSymbols) {
Eric Christopher6aad8b12015-02-19 00:08:14 +00001240 if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit()) {
Matt Arsenault8b643552015-06-09 00:31:39 +00001241 O << " .u64 ";
1242 getSymbol(GVar)->print(O, MAI);
1243 O << "[";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001244 O << ElementSize / 8;
1245 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001246 O << " .u32 ";
1247 getSymbol(GVar)->print(O, MAI);
1248 O << "[";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001249 O << ElementSize / 4;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001250 }
1251 O << "]";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001252 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001253 O << " .b8 ";
1254 getSymbol(GVar)->print(O, MAI);
1255 O << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001256 O << ElementSize;
1257 O << "]";
1258 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001259 O << " = {";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001260 aggBuffer.print();
1261 O << "}";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001262 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001263 O << " .b8 ";
1264 getSymbol(GVar)->print(O, MAI);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001265 if (ElementSize) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001266 O << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001267 O << ElementSize;
1268 O << "]";
1269 }
1270 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001271 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001272 O << " .b8 ";
1273 getSymbol(GVar)->print(O, MAI);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001274 if (ElementSize) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001275 O << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001276 O << ElementSize;
1277 O << "]";
1278 }
1279 }
1280 break;
1281 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001282 llvm_unreachable("type not supported yet");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001283 }
1284
1285 }
1286 O << ";\n";
1287}
1288
1289void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1290 if (localDecls.find(f) == localDecls.end())
1291 return;
1292
Justin Holewinski01f89f02013-05-20 12:13:32 +00001293 std::vector<const GlobalVariable *> &gvars = localDecls[f];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001294
Justin Holewinski0497ab12013-03-30 14:29:21 +00001295 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001296 O << "\t// demoted variable\n\t";
1297 printModuleLevelGV(gvars[i], O, true);
1298 }
1299}
1300
1301void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1302 raw_ostream &O) const {
1303 switch (AddressSpace) {
1304 case llvm::ADDRESS_SPACE_LOCAL:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001305 O << "local";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001306 break;
1307 case llvm::ADDRESS_SPACE_GLOBAL:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001308 O << "global";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001309 break;
1310 case llvm::ADDRESS_SPACE_CONST:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001311 O << "const";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001312 break;
1313 case llvm::ADDRESS_SPACE_SHARED:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001314 O << "shared";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001315 break;
1316 default:
Justin Holewinski36a50992013-02-09 13:34:15 +00001317 report_fatal_error("Bad address space found while emitting PTX");
1318 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001319 }
1320}
1321
Justin Holewinski0497ab12013-03-30 14:29:21 +00001322std::string
Craig Toppere3dcce92015-08-01 22:20:21 +00001323NVPTXAsmPrinter::getPTXFundamentalTypeStr(Type *Ty, bool useB4PTR) const {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001324 switch (Ty->getTypeID()) {
1325 default:
1326 llvm_unreachable("unexpected type");
1327 break;
1328 case Type::IntegerTyID: {
1329 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1330 if (NumBits == 1)
1331 return "pred";
1332 else if (NumBits <= 64) {
1333 std::string name = "u";
1334 return name + utostr(NumBits);
1335 } else {
1336 llvm_unreachable("Integer too large");
1337 break;
1338 }
1339 break;
1340 }
1341 case Type::FloatTyID:
1342 return "f32";
1343 case Type::DoubleTyID:
1344 return "f64";
1345 case Type::PointerTyID:
Eric Christopher6aad8b12015-02-19 00:08:14 +00001346 if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit())
Justin Holewinski0497ab12013-03-30 14:29:21 +00001347 if (useB4PTR)
1348 return "b64";
1349 else
1350 return "u64";
1351 else if (useB4PTR)
1352 return "b32";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001353 else
Justin Holewinski0497ab12013-03-30 14:29:21 +00001354 return "u32";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001355 }
1356 llvm_unreachable("unexpected type");
Craig Topper062a2ba2014-04-25 05:30:21 +00001357 return nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001358}
1359
Justin Holewinski0497ab12013-03-30 14:29:21 +00001360void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001361 raw_ostream &O) {
1362
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001363 const DataLayout &DL = getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001364
1365 // GlobalVariables are always constant pointers themselves.
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001366 Type *ETy = GVar->getValueType();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001367
1368 O << ".";
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001369 emitPTXAddressSpace(GVar->getType()->getAddressSpace(), O);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001370 if (GVar->getAlignment() == 0)
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001371 O << " .align " << (int)DL.getPrefTypeAlignment(ETy);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001372 else
1373 O << " .align " << GVar->getAlignment();
1374
Jingyue Wue4c9cf02014-12-17 17:59:04 +00001375 if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001376 O << " .";
1377 O << getPTXFundamentalTypeStr(ETy);
1378 O << " ";
Matt Arsenault8b643552015-06-09 00:31:39 +00001379 getSymbol(GVar)->print(O, MAI);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001380 return;
1381 }
1382
Justin Holewinski0497ab12013-03-30 14:29:21 +00001383 int64_t ElementSize = 0;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001384
1385 // Although PTX has direct support for struct type and array type and LLVM IR
1386 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1387 // support these high level field accesses. Structs and arrays are lowered
1388 // into arrays of bytes.
1389 switch (ETy->getTypeID()) {
1390 case Type::StructTyID:
1391 case Type::ArrayTyID:
1392 case Type::VectorTyID:
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001393 ElementSize = DL.getTypeStoreSize(ETy);
Matt Arsenault8b643552015-06-09 00:31:39 +00001394 O << " .b8 ";
1395 getSymbol(GVar)->print(O, MAI);
1396 O << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001397 if (ElementSize) {
Benjamin Kramerdba7ee92015-05-28 11:24:24 +00001398 O << ElementSize;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001399 }
1400 O << "]";
1401 break;
1402 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001403 llvm_unreachable("type not supported yet");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001404 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001405 return;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001406}
1407
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001408static unsigned int getOpenCLAlignment(const DataLayout &DL, Type *Ty) {
Rafael Espindola08013342013-12-07 19:34:20 +00001409 if (Ty->isSingleValueType())
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001410 return DL.getPrefTypeAlignment(Ty);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001411
Craig Toppere3dcce92015-08-01 22:20:21 +00001412 auto *ATy = dyn_cast<ArrayType>(Ty);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001413 if (ATy)
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001414 return getOpenCLAlignment(DL, ATy->getElementType());
Justin Holewinskiae556d32012-05-04 20:18:50 +00001415
Craig Toppere3dcce92015-08-01 22:20:21 +00001416 auto *STy = dyn_cast<StructType>(Ty);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001417 if (STy) {
1418 unsigned int alignStruct = 1;
1419 // Go through each element of the struct and find the
1420 // largest alignment.
Justin Holewinski0497ab12013-03-30 14:29:21 +00001421 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001422 Type *ETy = STy->getElementType(i);
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001423 unsigned int align = getOpenCLAlignment(DL, ETy);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001424 if (align > alignStruct)
1425 alignStruct = align;
1426 }
1427 return alignStruct;
1428 }
1429
Craig Toppere3dcce92015-08-01 22:20:21 +00001430 auto *FTy = dyn_cast<FunctionType>(Ty);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001431 if (FTy)
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001432 return DL.getPointerPrefAlignment();
1433 return DL.getPrefTypeAlignment(Ty);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001434}
1435
1436void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1437 int paramIndex, raw_ostream &O) {
Matt Arsenault8b643552015-06-09 00:31:39 +00001438 getSymbol(I->getParent())->print(O, MAI);
1439 O << "_param_" << paramIndex;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001440}
1441
Justin Holewinski0497ab12013-03-30 14:29:21 +00001442void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001443 const DataLayout &DL = getDataLayout();
Bill Wendlinge94d8432012-12-07 23:16:57 +00001444 const AttributeSet &PAL = F->getAttributes();
Eric Christopher6aad8b12015-02-19 00:08:14 +00001445 const TargetLowering *TLI = nvptxSubtarget->getTargetLowering();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001446 Function::const_arg_iterator I, E;
1447 unsigned paramIndex = 0;
1448 bool first = true;
1449 bool isKernelFunc = llvm::isKernelFunction(*F);
Eric Christopher6aad8b12015-02-19 00:08:14 +00001450 bool isABI = (nvptxSubtarget->getSmVersion() >= 20);
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001451 MVT thePointerTy = TLI->getPointerTy(DL);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001452
Justin Lebar2a161f92016-01-23 21:12:17 +00001453 if (F->arg_empty()) {
1454 O << "()\n";
1455 return;
1456 }
1457
Justin Holewinskiae556d32012-05-04 20:18:50 +00001458 O << "(\n";
1459
1460 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
Justin Holewinskie9884092013-03-24 21:17:47 +00001461 Type *Ty = I->getType();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001462
1463 if (!first)
1464 O << ",\n";
1465
1466 first = false;
1467
1468 // Handle image/sampler parameters
Justin Holewinski30d56a72014-04-09 15:39:15 +00001469 if (isKernelFunction(*F)) {
1470 if (isSampler(*I) || isImage(*I)) {
1471 if (isImage(*I)) {
1472 std::string sname = I->getName();
1473 if (isImageWriteOnly(*I) || isImageReadWrite(*I)) {
Eric Christopher6aad8b12015-02-19 00:08:14 +00001474 if (nvptxSubtarget->hasImageHandles())
Justin Holewinski30d56a72014-04-09 15:39:15 +00001475 O << "\t.param .u64 .ptr .surfref ";
1476 else
1477 O << "\t.param .surfref ";
Matt Arsenault8b643552015-06-09 00:31:39 +00001478 CurrentFnSym->print(O, MAI);
1479 O << "_param_" << paramIndex;
Justin Holewinski30d56a72014-04-09 15:39:15 +00001480 }
1481 else { // Default image is read_only
Eric Christopher6aad8b12015-02-19 00:08:14 +00001482 if (nvptxSubtarget->hasImageHandles())
Justin Holewinski30d56a72014-04-09 15:39:15 +00001483 O << "\t.param .u64 .ptr .texref ";
1484 else
1485 O << "\t.param .texref ";
Matt Arsenault8b643552015-06-09 00:31:39 +00001486 CurrentFnSym->print(O, MAI);
1487 O << "_param_" << paramIndex;
Justin Holewinski30d56a72014-04-09 15:39:15 +00001488 }
1489 } else {
Eric Christopher6aad8b12015-02-19 00:08:14 +00001490 if (nvptxSubtarget->hasImageHandles())
Justin Holewinski30d56a72014-04-09 15:39:15 +00001491 O << "\t.param .u64 .ptr .samplerref ";
1492 else
1493 O << "\t.param .samplerref ";
Matt Arsenault8b643552015-06-09 00:31:39 +00001494 CurrentFnSym->print(O, MAI);
1495 O << "_param_" << paramIndex;
Justin Holewinski30d56a72014-04-09 15:39:15 +00001496 }
1497 continue;
1498 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001499 }
1500
Eli Bendersky3e840192015-03-23 16:26:23 +00001501 if (!PAL.hasAttribute(paramIndex + 1, Attribute::ByVal)) {
Gautam Chakrabarti2c283402014-01-28 18:35:29 +00001502 if (Ty->isAggregateType() || Ty->isVectorTy()) {
1503 // Just print .param .align <a> .b8 .param[size];
Justin Holewinskie9884092013-03-24 21:17:47 +00001504 // <a> = PAL.getparamalignment
1505 // size = typeallocsize of element type
Justin Holewinski0497ab12013-03-30 14:29:21 +00001506 unsigned align = PAL.getParamAlignment(paramIndex + 1);
Justin Holewinskie9884092013-03-24 21:17:47 +00001507 if (align == 0)
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001508 align = DL.getABITypeAlignment(Ty);
Justin Holewinskie9884092013-03-24 21:17:47 +00001509
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001510 unsigned sz = DL.getTypeAllocSize(Ty);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001511 O << "\t.param .align " << align << " .b8 ";
Justin Holewinskie9884092013-03-24 21:17:47 +00001512 printParamName(I, paramIndex, O);
1513 O << "[" << sz << "]";
1514
1515 continue;
1516 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001517 // Just a scalar
Craig Toppere3dcce92015-08-01 22:20:21 +00001518 auto *PTy = dyn_cast<PointerType>(Ty);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001519 if (isKernelFunc) {
1520 if (PTy) {
1521 // Special handling for pointer arguments to kernel
1522 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1523
Eric Christopherbeffc4e2015-02-19 00:08:23 +00001524 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() !=
1525 NVPTX::CUDA) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001526 Type *ETy = PTy->getElementType();
1527 int addrSpace = PTy->getAddressSpace();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001528 switch (addrSpace) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001529 default:
1530 O << ".ptr ";
1531 break;
Justin Holewinskib96d1392013-06-10 13:29:47 +00001532 case llvm::ADDRESS_SPACE_CONST:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001533 O << ".ptr .const ";
1534 break;
1535 case llvm::ADDRESS_SPACE_SHARED:
1536 O << ".ptr .shared ";
1537 break;
1538 case llvm::ADDRESS_SPACE_GLOBAL:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001539 O << ".ptr .global ";
1540 break;
1541 }
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001542 O << ".align " << (int)getOpenCLAlignment(DL, ETy) << " ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001543 }
1544 printParamName(I, paramIndex, O);
1545 continue;
1546 }
1547
1548 // non-pointer scalar to kernel func
Justin Holewinski700b6fa2013-05-20 12:13:28 +00001549 O << "\t.param .";
1550 // Special case: predicate operands become .u8 types
1551 if (Ty->isIntegerTy(1))
1552 O << "u8";
1553 else
1554 O << getPTXFundamentalTypeStr(Ty);
1555 O << " ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001556 printParamName(I, paramIndex, O);
1557 continue;
1558 }
1559 // Non-kernel function, just print .param .b<size> for ABI
Alp Tokerf907b892013-12-05 05:44:44 +00001560 // and .reg .b<size> for non-ABI
Justin Holewinskiae556d32012-05-04 20:18:50 +00001561 unsigned sz = 0;
1562 if (isa<IntegerType>(Ty)) {
1563 sz = cast<IntegerType>(Ty)->getBitWidth();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001564 if (sz < 32)
1565 sz = 32;
1566 } else if (isa<PointerType>(Ty))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001567 sz = thePointerTy.getSizeInBits();
1568 else
1569 sz = Ty->getPrimitiveSizeInBits();
1570 if (isABI)
1571 O << "\t.param .b" << sz << " ";
1572 else
1573 O << "\t.reg .b" << sz << " ";
1574 printParamName(I, paramIndex, O);
1575 continue;
1576 }
1577
1578 // param has byVal attribute. So should be a pointer
Craig Toppere3dcce92015-08-01 22:20:21 +00001579 auto *PTy = dyn_cast<PointerType>(Ty);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001580 assert(PTy && "Param with byval attribute should be a pointer type");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001581 Type *ETy = PTy->getElementType();
1582
1583 if (isABI || isKernelFunc) {
Gautam Chakrabarti2c283402014-01-28 18:35:29 +00001584 // Just print .param .align <a> .b8 .param[size];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001585 // <a> = PAL.getparamalignment
1586 // size = typeallocsize of element type
Justin Holewinski0497ab12013-03-30 14:29:21 +00001587 unsigned align = PAL.getParamAlignment(paramIndex + 1);
Justin Holewinski2dc9d072012-11-09 23:50:24 +00001588 if (align == 0)
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001589 align = DL.getABITypeAlignment(ETy);
Artem Belevich052b1ed2016-07-18 19:54:56 +00001590 // Work around a bug in ptxas. When PTX code takes address of
1591 // byval parameter with alignment < 4, ptxas generates code to
1592 // spill argument into memory. Alas on sm_50+ ptxas generates
1593 // SASS code that fails with misaligned access. To work around
1594 // the problem, make sure that we align byval parameters by at
1595 // least 4. Matching change must be made in LowerCall() where we
1596 // prepare parameters for the call.
1597 //
1598 // TODO: this will need to be undone when we get to support multi-TU
1599 // device-side compilation as it breaks ABI compatibility with nvcc.
1600 // Hopefully ptxas bug is fixed by then.
1601 if (!isKernelFunc && align < 4)
1602 align = 4;
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001603 unsigned sz = DL.getTypeAllocSize(ETy);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001604 O << "\t.param .align " << align << " .b8 ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001605 printParamName(I, paramIndex, O);
1606 O << "[" << sz << "]";
1607 continue;
1608 } else {
1609 // Split the ETy into constituent parts and
1610 // print .param .b<size> <name> for each part.
1611 // Further, if a part is vector, print the above for
1612 // each vector element.
1613 SmallVector<EVT, 16> vtparts;
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001614 ComputeValueVTs(*TLI, DL, ETy, vtparts);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001615 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001616 unsigned elems = 1;
1617 EVT elemtype = vtparts[i];
1618 if (vtparts[i].isVector()) {
1619 elems = vtparts[i].getVectorNumElements();
1620 elemtype = vtparts[i].getVectorElementType();
1621 }
1622
Justin Holewinski0497ab12013-03-30 14:29:21 +00001623 for (unsigned j = 0, je = elems; j != je; ++j) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001624 unsigned sz = elemtype.getSizeInBits();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001625 if (elemtype.isInteger() && (sz < 32))
1626 sz = 32;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001627 O << "\t.reg .b" << sz << " ";
1628 printParamName(I, paramIndex, O);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001629 if (j < je - 1)
1630 O << ",\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001631 ++paramIndex;
1632 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001633 if (i < e - 1)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001634 O << ",\n";
1635 }
1636 --paramIndex;
1637 continue;
1638 }
1639 }
1640
1641 O << "\n)\n";
1642}
1643
1644void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1645 raw_ostream &O) {
1646 const Function *F = MF.getFunction();
1647 emitFunctionParamList(F, O);
1648}
1649
Justin Holewinski0497ab12013-03-30 14:29:21 +00001650void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1651 const MachineFunction &MF) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001652 SmallString<128> Str;
1653 raw_svector_ostream O(Str);
1654
1655 // Map the global virtual register number to a register class specific
1656 // virtual register number starting from 1 with that class.
Eric Christopherfc6de422014-08-05 02:39:49 +00001657 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001658 //unsigned numRegClasses = TRI->getNumRegClasses();
1659
1660 // Emit the Fake Stack Object
Matthias Braun941a7052016-07-28 18:40:00 +00001661 const MachineFrameInfo &MFI = MF.getFrameInfo();
1662 int NumBytes = (int) MFI.getStackSize();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001663 if (NumBytes) {
Matthias Braun941a7052016-07-28 18:40:00 +00001664 O << "\t.local .align " << MFI.getMaxAlignment() << " .b8 \t" << DEPOTNAME
Justin Holewinski0497ab12013-03-30 14:29:21 +00001665 << getFunctionNumber() << "[" << NumBytes << "];\n";
Eric Christopher02389e32015-02-19 00:08:27 +00001666 if (static_cast<const NVPTXTargetMachine &>(MF.getTarget()).is64Bit()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001667 O << "\t.reg .b64 \t%SP;\n";
1668 O << "\t.reg .b64 \t%SPL;\n";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001669 } else {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001670 O << "\t.reg .b32 \t%SP;\n";
1671 O << "\t.reg .b32 \t%SPL;\n";
1672 }
1673 }
1674
1675 // Go through all virtual registers to establish the mapping between the
1676 // global virtual
1677 // register number and the per class virtual register number.
1678 // We use the per class virtual register number in the ptx output.
1679 unsigned int numVRs = MRI->getNumVirtRegs();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001680 for (unsigned i = 0; i < numVRs; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001681 unsigned int vr = TRI->index2VirtReg(i);
1682 const TargetRegisterClass *RC = MRI->getRegClass(vr);
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001683 DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001684 int n = regmap.size();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001685 regmap.insert(std::make_pair(vr, n + 1));
Justin Holewinskiae556d32012-05-04 20:18:50 +00001686 }
1687
1688 // Emit register declarations
1689 // @TODO: Extract out the real register usage
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001690 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1691 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1692 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1693 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
Justin Holewinski3e037d92014-07-16 16:26:58 +00001694 // O << "\t.reg .s64 %rd<" << NVPTXNumRegisters << ">;\n";
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001695 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
Justin Holewinski3e037d92014-07-16 16:26:58 +00001696 // O << "\t.reg .f64 %fd<" << NVPTXNumRegisters << ">;\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001697
1698 // Emit declaration of the virtual registers or 'physical' registers for
1699 // each register class
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001700 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1701 const TargetRegisterClass *RC = TRI->getRegClass(i);
1702 DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
1703 std::string rcname = getNVPTXRegClassName(RC);
1704 std::string rcStr = getNVPTXRegClassStr(RC);
1705 int n = regmap.size();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001706
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001707 // Only declare those registers that may be used.
1708 if (n) {
1709 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1710 << ">;\n";
1711 }
1712 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001713
Lang Hames9ff69c82015-04-24 19:11:51 +00001714 OutStreamer->EmitRawText(O.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +00001715}
1716
Justin Holewinskiae556d32012-05-04 20:18:50 +00001717void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001718 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
Justin Holewinskiae556d32012-05-04 20:18:50 +00001719 bool ignored;
1720 unsigned int numHex;
1721 const char *lead;
1722
Justin Holewinski0497ab12013-03-30 14:29:21 +00001723 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001724 numHex = 8;
1725 lead = "0f";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001726 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001727 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1728 numHex = 16;
1729 lead = "0d";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001730 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001731 } else
1732 llvm_unreachable("unsupported fp type");
1733
1734 APInt API = APF.bitcastToAPInt();
1735 std::string hexstr(utohexstr(API.getZExtValue()));
1736 O << lead;
1737 if (hexstr.length() < numHex)
1738 O << std::string(numHex - hexstr.length(), '0');
1739 O << utohexstr(API.getZExtValue());
1740}
1741
Justin Holewinski01f89f02013-05-20 12:13:32 +00001742void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1743 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001744 O << CI->getValue();
1745 return;
1746 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001747 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001748 printFPConstant(CFP, O);
1749 return;
1750 }
1751 if (isa<ConstantPointerNull>(CPV)) {
1752 O << "0";
1753 return;
1754 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001755 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
Justin Holewinski9d852a82014-04-09 15:39:11 +00001756 bool IsNonGenericPointer = false;
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001757 if (GVar->getType()->getAddressSpace() != 0) {
Justin Holewinski9d852a82014-04-09 15:39:11 +00001758 IsNonGenericPointer = true;
1759 }
1760 if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
1761 O << "generic(";
Matt Arsenault8b643552015-06-09 00:31:39 +00001762 getSymbol(GVar)->print(O, MAI);
Justin Holewinski9d852a82014-04-09 15:39:11 +00001763 O << ")";
1764 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001765 getSymbol(GVar)->print(O, MAI);
Justin Holewinski9d852a82014-04-09 15:39:11 +00001766 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001767 return;
1768 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001769 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1770 const Value *v = Cexpr->stripPointerCasts();
Justin Holewinski9d852a82014-04-09 15:39:11 +00001771 PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
1772 bool IsNonGenericPointer = false;
1773 if (PTy && PTy->getAddressSpace() != 0) {
1774 IsNonGenericPointer = true;
1775 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001776 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
Justin Holewinski9d852a82014-04-09 15:39:11 +00001777 if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
1778 O << "generic(";
Matt Arsenault8b643552015-06-09 00:31:39 +00001779 getSymbol(GVar)->print(O, MAI);
Justin Holewinski9d852a82014-04-09 15:39:11 +00001780 O << ")";
1781 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001782 getSymbol(GVar)->print(O, MAI);
Justin Holewinski9d852a82014-04-09 15:39:11 +00001783 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001784 return;
1785 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001786 lowerConstant(CPV)->print(O, MAI);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001787 return;
1788 }
1789 }
1790 llvm_unreachable("Not scalar type found in printScalarConstant()");
1791}
1792
Samuel Antaocd501352015-06-09 16:29:34 +00001793// These utility functions assure we get the right sequence of bytes for a given
1794// type even for big-endian machines
1795template <typename T> static void ConvertIntToBytes(unsigned char *p, T val) {
1796 int64_t vp = (int64_t)val;
1797 for (unsigned i = 0; i < sizeof(T); ++i) {
1798 p[i] = (unsigned char)vp;
1799 vp >>= 8;
1800 }
1801}
1802static void ConvertFloatToBytes(unsigned char *p, float val) {
1803 int32_t *vp = (int32_t *)&val;
1804 for (unsigned i = 0; i < sizeof(int32_t); ++i) {
1805 p[i] = (unsigned char)*vp;
1806 *vp >>= 8;
1807 }
1808}
1809static void ConvertDoubleToBytes(unsigned char *p, double val) {
1810 int64_t *vp = (int64_t *)&val;
1811 for (unsigned i = 0; i < sizeof(int64_t); ++i) {
1812 p[i] = (unsigned char)*vp;
1813 *vp >>= 8;
1814 }
1815}
1816
Justin Holewinski01f89f02013-05-20 12:13:32 +00001817void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001818 AggBuffer *aggBuffer) {
1819
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001820 const DataLayout &DL = getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001821
1822 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001823 int s = DL.getTypeAllocSize(CPV->getType());
Justin Holewinski0497ab12013-03-30 14:29:21 +00001824 if (s < Bytes)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001825 s = Bytes;
1826 aggBuffer->addZeros(s);
1827 return;
1828 }
1829
Samuel Antaocd501352015-06-09 16:29:34 +00001830 unsigned char ptr[8];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001831 switch (CPV->getType()->getTypeID()) {
1832
1833 case Type::IntegerTyID: {
Craig Toppere3dcce92015-08-01 22:20:21 +00001834 Type *ETy = CPV->getType();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001835 if (ETy == Type::getInt8Ty(CPV->getContext())) {
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001836 unsigned char c = (unsigned char)cast<ConstantInt>(CPV)->getZExtValue();
Samuel Antaocd501352015-06-09 16:29:34 +00001837 ConvertIntToBytes<>(ptr, c);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001838 aggBuffer->addBytes(ptr, 1, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001839 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001840 short int16 = (short)cast<ConstantInt>(CPV)->getZExtValue();
Samuel Antaocd501352015-06-09 16:29:34 +00001841 ConvertIntToBytes<>(ptr, int16);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001842 aggBuffer->addBytes(ptr, 2, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001843 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001844 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001845 int int32 = (int)(constInt->getZExtValue());
Samuel Antaocd501352015-06-09 16:29:34 +00001846 ConvertIntToBytes<>(ptr, int32);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001847 aggBuffer->addBytes(ptr, 4, Bytes);
1848 break;
David Majnemerd536f232016-07-29 03:27:26 +00001849 } else if (const auto *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1850 if (const auto *constInt = dyn_cast_or_null<ConstantInt>(
1851 ConstantFoldConstant(Cexpr, DL))) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001852 int int32 = (int)(constInt->getZExtValue());
Samuel Antaocd501352015-06-09 16:29:34 +00001853 ConvertIntToBytes<>(ptr, int32);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001854 aggBuffer->addBytes(ptr, 4, Bytes);
1855 break;
1856 }
1857 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1858 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
Jingyue Wu312fd022015-04-24 02:57:30 +00001859 aggBuffer->addSymbol(v, Cexpr->getOperand(0));
Justin Holewinskiae556d32012-05-04 20:18:50 +00001860 aggBuffer->addZeros(4);
1861 break;
1862 }
1863 }
Craig Topperbdf39a42012-05-24 07:02:50 +00001864 llvm_unreachable("unsupported integer const type");
Justin Holewinski0497ab12013-03-30 14:29:21 +00001865 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001866 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001867 long long int64 = (long long)(constInt->getZExtValue());
Samuel Antaocd501352015-06-09 16:29:34 +00001868 ConvertIntToBytes<>(ptr, int64);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001869 aggBuffer->addBytes(ptr, 8, Bytes);
1870 break;
Justin Holewinski01f89f02013-05-20 12:13:32 +00001871 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
David Majnemerd536f232016-07-29 03:27:26 +00001872 if (const auto *constInt = dyn_cast_or_null<ConstantInt>(
1873 ConstantFoldConstant(Cexpr, DL))) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001874 long long int64 = (long long)(constInt->getZExtValue());
Samuel Antaocd501352015-06-09 16:29:34 +00001875 ConvertIntToBytes<>(ptr, int64);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001876 aggBuffer->addBytes(ptr, 8, Bytes);
1877 break;
1878 }
1879 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1880 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
Jingyue Wu312fd022015-04-24 02:57:30 +00001881 aggBuffer->addSymbol(v, Cexpr->getOperand(0));
Justin Holewinskiae556d32012-05-04 20:18:50 +00001882 aggBuffer->addZeros(8);
1883 break;
1884 }
1885 }
1886 llvm_unreachable("unsupported integer const type");
Craig Topperbdf39a42012-05-24 07:02:50 +00001887 } else
Justin Holewinskiae556d32012-05-04 20:18:50 +00001888 llvm_unreachable("unsupported integer const type");
1889 break;
1890 }
1891 case Type::FloatTyID:
1892 case Type::DoubleTyID: {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001893 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
Craig Toppere3dcce92015-08-01 22:20:21 +00001894 Type *Ty = CFP->getType();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001895 if (Ty == Type::getFloatTy(CPV->getContext())) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001896 float float32 = (float) CFP->getValueAPF().convertToFloat();
Samuel Antaocd501352015-06-09 16:29:34 +00001897 ConvertFloatToBytes(ptr, float32);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001898 aggBuffer->addBytes(ptr, 4, Bytes);
1899 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1900 double float64 = CFP->getValueAPF().convertToDouble();
Samuel Antaocd501352015-06-09 16:29:34 +00001901 ConvertDoubleToBytes(ptr, float64);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001902 aggBuffer->addBytes(ptr, 8, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001903 } else {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001904 llvm_unreachable("unsupported fp const type");
1905 }
1906 break;
1907 }
1908 case Type::PointerTyID: {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001909 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
Jingyue Wu312fd022015-04-24 02:57:30 +00001910 aggBuffer->addSymbol(GVar, GVar);
Justin Holewinski01f89f02013-05-20 12:13:32 +00001911 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1912 const Value *v = Cexpr->stripPointerCasts();
Jingyue Wu312fd022015-04-24 02:57:30 +00001913 aggBuffer->addSymbol(v, Cexpr);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001914 }
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001915 unsigned int s = DL.getTypeAllocSize(CPV->getType());
Justin Holewinskiae556d32012-05-04 20:18:50 +00001916 aggBuffer->addZeros(s);
1917 break;
1918 }
1919
1920 case Type::ArrayTyID:
1921 case Type::VectorTyID:
1922 case Type::StructTyID: {
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +00001923 if (isa<ConstantAggregate>(CPV) || isa<ConstantDataSequential>(CPV)) {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001924 int ElementSize = DL.getTypeAllocSize(CPV->getType());
Justin Holewinskiae556d32012-05-04 20:18:50 +00001925 bufferAggregateConstant(CPV, aggBuffer);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001926 if (Bytes > ElementSize)
1927 aggBuffer->addZeros(Bytes - ElementSize);
1928 } else if (isa<ConstantAggregateZero>(CPV))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001929 aggBuffer->addZeros(Bytes);
1930 else
1931 llvm_unreachable("Unexpected Constant type");
1932 break;
1933 }
1934
1935 default:
1936 llvm_unreachable("unsupported type");
1937 }
1938}
1939
Justin Holewinski01f89f02013-05-20 12:13:32 +00001940void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001941 AggBuffer *aggBuffer) {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001942 const DataLayout &DL = getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001943 int Bytes;
1944
1945 // Old constants
1946 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1947 if (CPV->getNumOperands())
1948 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1949 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1950 return;
1951 }
1952
1953 if (const ConstantDataSequential *CDS =
Justin Holewinski0497ab12013-03-30 14:29:21 +00001954 dyn_cast<ConstantDataSequential>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001955 if (CDS->getNumElements())
1956 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1957 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1958 aggBuffer);
1959 return;
1960 }
1961
Justin Holewinskiae556d32012-05-04 20:18:50 +00001962 if (isa<ConstantStruct>(CPV)) {
1963 if (CPV->getNumOperands()) {
1964 StructType *ST = cast<StructType>(CPV->getType());
1965 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001966 if (i == (e - 1))
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001967 Bytes = DL.getStructLayout(ST)->getElementOffset(0) +
1968 DL.getTypeAllocSize(ST) -
1969 DL.getStructLayout(ST)->getElementOffset(i);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001970 else
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001971 Bytes = DL.getStructLayout(ST)->getElementOffset(i + 1) -
1972 DL.getStructLayout(ST)->getElementOffset(i);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001973 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001974 }
1975 }
1976 return;
1977 }
Craig Topperbdf39a42012-05-24 07:02:50 +00001978 llvm_unreachable("unsupported constant type in printAggregateConstant()");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001979}
1980
1981// buildTypeNameMap - Run through symbol table looking for type names.
1982//
1983
Justin Holewinskiae556d32012-05-04 20:18:50 +00001984
Justin Holewinski0497ab12013-03-30 14:29:21 +00001985bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
1986 switch (MI.getOpcode()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001987 default:
1988 return false;
Justin Holewinski0497ab12013-03-30 14:29:21 +00001989 case NVPTX::CallArgBeginInst:
1990 case NVPTX::CallArgEndInst0:
1991 case NVPTX::CallArgEndInst1:
1992 case NVPTX::CallArgF32:
1993 case NVPTX::CallArgF64:
1994 case NVPTX::CallArgI16:
1995 case NVPTX::CallArgI32:
1996 case NVPTX::CallArgI32imm:
1997 case NVPTX::CallArgI64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001998 case NVPTX::CallArgParam:
1999 case NVPTX::CallVoidInst:
2000 case NVPTX::CallVoidInstReg:
2001 case NVPTX::Callseq_End:
Justin Holewinskiae556d32012-05-04 20:18:50 +00002002 case NVPTX::CallVoidInstReg64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00002003 case NVPTX::DeclareParamInst:
2004 case NVPTX::DeclareRetMemInst:
2005 case NVPTX::DeclareRetRegInst:
2006 case NVPTX::DeclareRetScalarInst:
2007 case NVPTX::DeclareScalarParamInst:
2008 case NVPTX::DeclareScalarRegInst:
2009 case NVPTX::StoreParamF32:
2010 case NVPTX::StoreParamF64:
2011 case NVPTX::StoreParamI16:
2012 case NVPTX::StoreParamI32:
2013 case NVPTX::StoreParamI64:
2014 case NVPTX::StoreParamI8:
Justin Holewinski0497ab12013-03-30 14:29:21 +00002015 case NVPTX::StoreRetvalF32:
2016 case NVPTX::StoreRetvalF64:
2017 case NVPTX::StoreRetvalI16:
2018 case NVPTX::StoreRetvalI32:
2019 case NVPTX::StoreRetvalI64:
2020 case NVPTX::StoreRetvalI8:
2021 case NVPTX::LastCallArgF32:
2022 case NVPTX::LastCallArgF64:
2023 case NVPTX::LastCallArgI16:
2024 case NVPTX::LastCallArgI32:
2025 case NVPTX::LastCallArgI32imm:
2026 case NVPTX::LastCallArgI64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00002027 case NVPTX::LastCallArgParam:
2028 case NVPTX::LoadParamMemF32:
2029 case NVPTX::LoadParamMemF64:
2030 case NVPTX::LoadParamMemI16:
2031 case NVPTX::LoadParamMemI32:
2032 case NVPTX::LoadParamMemI64:
2033 case NVPTX::LoadParamMemI8:
Justin Holewinski0497ab12013-03-30 14:29:21 +00002034 case NVPTX::PrototypeInst:
2035 case NVPTX::DBG_VALUE:
Justin Holewinskiae556d32012-05-04 20:18:50 +00002036 return true;
2037 }
2038 return false;
2039}
2040
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002041/// lowerConstantForGV - Return an MCExpr for the given Constant. This is mostly
2042/// a copy from AsmPrinter::lowerConstant, except customized to only handle
2043/// expressions that are representable in PTX and create
2044/// NVPTXGenericMCSymbolRefExpr nodes for addrspacecast instructions.
2045const MCExpr *
2046NVPTXAsmPrinter::lowerConstantForGV(const Constant *CV, bool ProcessingGeneric) {
2047 MCContext &Ctx = OutContext;
2048
2049 if (CV->isNullValue() || isa<UndefValue>(CV))
Jim Grosbach13760bd2015-05-30 01:25:56 +00002050 return MCConstantExpr::create(0, Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002051
2052 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
Jim Grosbach13760bd2015-05-30 01:25:56 +00002053 return MCConstantExpr::create(CI->getZExtValue(), Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002054
2055 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
2056 const MCSymbolRefExpr *Expr =
Jim Grosbach13760bd2015-05-30 01:25:56 +00002057 MCSymbolRefExpr::create(getSymbol(GV), Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002058 if (ProcessingGeneric) {
Jim Grosbach13760bd2015-05-30 01:25:56 +00002059 return NVPTXGenericMCSymbolRefExpr::create(Expr, Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002060 } else {
2061 return Expr;
2062 }
2063 }
2064
2065 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
2066 if (!CE) {
2067 llvm_unreachable("Unknown constant value to lower!");
2068 }
2069
2070 switch (CE->getOpcode()) {
2071 default:
2072 // If the code isn't optimized, there may be outstanding folding
2073 // opportunities. Attempt to fold the expression using DataLayout as a
2074 // last resort before giving up.
David Majnemerd536f232016-07-29 03:27:26 +00002075 if (Constant *C = ConstantFoldConstant(CE, getDataLayout()))
2076 if (C && C != CE)
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002077 return lowerConstantForGV(C, ProcessingGeneric);
2078
2079 // Otherwise report the problem to the user.
2080 {
2081 std::string S;
2082 raw_string_ostream OS(S);
2083 OS << "Unsupported expression in static initializer: ";
2084 CE->printAsOperand(OS, /*PrintType=*/false,
2085 !MF ? nullptr : MF->getFunction()->getParent());
2086 report_fatal_error(OS.str());
2087 }
2088
2089 case Instruction::AddrSpaceCast: {
2090 // Strip the addrspacecast and pass along the operand
2091 PointerType *DstTy = cast<PointerType>(CE->getType());
2092 if (DstTy->getAddressSpace() == 0) {
2093 return lowerConstantForGV(cast<const Constant>(CE->getOperand(0)), true);
2094 }
2095 std::string S;
2096 raw_string_ostream OS(S);
2097 OS << "Unsupported expression in static initializer: ";
2098 CE->printAsOperand(OS, /*PrintType=*/ false,
2099 !MF ? 0 : MF->getFunction()->getParent());
2100 report_fatal_error(OS.str());
2101 }
2102
2103 case Instruction::GetElementPtr: {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00002104 const DataLayout &DL = getDataLayout();
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002105
2106 // Generate a symbolic expression for the byte address
2107 APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
2108 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
2109
2110 const MCExpr *Base = lowerConstantForGV(CE->getOperand(0),
2111 ProcessingGeneric);
2112 if (!OffsetAI)
2113 return Base;
2114
2115 int64_t Offset = OffsetAI.getSExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +00002116 return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002117 Ctx);
2118 }
2119
2120 case Instruction::Trunc:
2121 // We emit the value and depend on the assembler to truncate the generated
2122 // expression properly. This is important for differences between
2123 // blockaddress labels. Since the two labels are in the same function, it
2124 // is reasonable to treat their delta as a 32-bit value.
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002125 LLVM_FALLTHROUGH;
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002126 case Instruction::BitCast:
2127 return lowerConstantForGV(CE->getOperand(0), ProcessingGeneric);
2128
2129 case Instruction::IntToPtr: {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00002130 const DataLayout &DL = getDataLayout();
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002131
2132 // Handle casts to pointers by changing them into casts to the appropriate
2133 // integer type. This promotes constant folding and simplifies this code.
2134 Constant *Op = CE->getOperand(0);
2135 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
2136 false/*ZExt*/);
2137 return lowerConstantForGV(Op, ProcessingGeneric);
2138 }
2139
2140 case Instruction::PtrToInt: {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00002141 const DataLayout &DL = getDataLayout();
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002142
2143 // Support only foldable casts to/from pointers that can be eliminated by
2144 // changing the pointer to the appropriately sized integer type.
2145 Constant *Op = CE->getOperand(0);
2146 Type *Ty = CE->getType();
2147
2148 const MCExpr *OpExpr = lowerConstantForGV(Op, ProcessingGeneric);
2149
2150 // We can emit the pointer value into this slot if the slot is an
2151 // integer slot equal to the size of the pointer.
2152 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
2153 return OpExpr;
2154
2155 // Otherwise the pointer is smaller than the resultant integer, mask off
2156 // the high bits so we are sure to get a proper truncation if the input is
2157 // a constant expr.
2158 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
Jim Grosbach13760bd2015-05-30 01:25:56 +00002159 const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
2160 return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002161 }
2162
2163 // The MC library also has a right-shift operator, but it isn't consistently
2164 // signed or unsigned between different targets.
2165 case Instruction::Add: {
2166 const MCExpr *LHS = lowerConstantForGV(CE->getOperand(0), ProcessingGeneric);
2167 const MCExpr *RHS = lowerConstantForGV(CE->getOperand(1), ProcessingGeneric);
2168 switch (CE->getOpcode()) {
2169 default: llvm_unreachable("Unknown binary operator constant cast expr");
Jim Grosbach13760bd2015-05-30 01:25:56 +00002170 case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002171 }
2172 }
2173 }
2174}
2175
2176// Copy of MCExpr::print customized for NVPTX
2177void NVPTXAsmPrinter::printMCExpr(const MCExpr &Expr, raw_ostream &OS) {
2178 switch (Expr.getKind()) {
2179 case MCExpr::Target:
Matt Arsenault8b643552015-06-09 00:31:39 +00002180 return cast<MCTargetExpr>(&Expr)->printImpl(OS, MAI);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002181 case MCExpr::Constant:
2182 OS << cast<MCConstantExpr>(Expr).getValue();
2183 return;
2184
2185 case MCExpr::SymbolRef: {
2186 const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(Expr);
2187 const MCSymbol &Sym = SRE.getSymbol();
Matt Arsenault8b643552015-06-09 00:31:39 +00002188 Sym.print(OS, MAI);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002189 return;
2190 }
2191
2192 case MCExpr::Unary: {
2193 const MCUnaryExpr &UE = cast<MCUnaryExpr>(Expr);
2194 switch (UE.getOpcode()) {
2195 case MCUnaryExpr::LNot: OS << '!'; break;
2196 case MCUnaryExpr::Minus: OS << '-'; break;
2197 case MCUnaryExpr::Not: OS << '~'; break;
2198 case MCUnaryExpr::Plus: OS << '+'; break;
2199 }
2200 printMCExpr(*UE.getSubExpr(), OS);
2201 return;
2202 }
2203
2204 case MCExpr::Binary: {
2205 const MCBinaryExpr &BE = cast<MCBinaryExpr>(Expr);
2206
2207 // Only print parens around the LHS if it is non-trivial.
2208 if (isa<MCConstantExpr>(BE.getLHS()) || isa<MCSymbolRefExpr>(BE.getLHS()) ||
2209 isa<NVPTXGenericMCSymbolRefExpr>(BE.getLHS())) {
2210 printMCExpr(*BE.getLHS(), OS);
2211 } else {
2212 OS << '(';
2213 printMCExpr(*BE.getLHS(), OS);
2214 OS<< ')';
2215 }
2216
2217 switch (BE.getOpcode()) {
2218 case MCBinaryExpr::Add:
2219 // Print "X-42" instead of "X+-42".
2220 if (const MCConstantExpr *RHSC = dyn_cast<MCConstantExpr>(BE.getRHS())) {
2221 if (RHSC->getValue() < 0) {
2222 OS << RHSC->getValue();
2223 return;
2224 }
2225 }
2226
2227 OS << '+';
2228 break;
2229 default: llvm_unreachable("Unhandled binary operator");
2230 }
2231
2232 // Only print parens around the LHS if it is non-trivial.
2233 if (isa<MCConstantExpr>(BE.getRHS()) || isa<MCSymbolRefExpr>(BE.getRHS())) {
2234 printMCExpr(*BE.getRHS(), OS);
2235 } else {
2236 OS << '(';
2237 printMCExpr(*BE.getRHS(), OS);
2238 OS << ')';
2239 }
2240 return;
2241 }
2242 }
2243
2244 llvm_unreachable("Invalid expression kind!");
2245}
2246
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002247/// PrintAsmOperand - Print out an operand for an inline asm expression.
2248///
2249bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2250 unsigned AsmVariant,
2251 const char *ExtraCode, raw_ostream &O) {
2252 if (ExtraCode && ExtraCode[0]) {
2253 if (ExtraCode[1] != 0)
2254 return true; // Unknown modifier.
2255
2256 switch (ExtraCode[0]) {
2257 default:
2258 // See if this is a generic print operand
2259 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2260 case 'r':
2261 break;
2262 }
2263 }
2264
2265 printOperand(MI, OpNo, O);
2266
2267 return false;
2268}
2269
2270bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2271 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2272 const char *ExtraCode, raw_ostream &O) {
2273 if (ExtraCode && ExtraCode[0])
2274 return true; // Unknown modifier
2275
2276 O << '[';
2277 printMemOperand(MI, OpNo, O);
2278 O << ']';
2279
2280 return false;
2281}
2282
2283void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2284 raw_ostream &O, const char *Modifier) {
2285 const MachineOperand &MO = MI->getOperand(opNum);
2286 switch (MO.getType()) {
2287 case MachineOperand::MO_Register:
2288 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2289 if (MO.getReg() == NVPTX::VRDepot)
2290 O << DEPOTNAME << getFunctionNumber();
2291 else
2292 O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2293 } else {
Justin Holewinski660597d2013-10-11 12:39:36 +00002294 emitVirtualRegister(MO.getReg(), O);
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002295 }
2296 return;
2297
2298 case MachineOperand::MO_Immediate:
2299 if (!Modifier)
2300 O << MO.getImm();
2301 else if (strstr(Modifier, "vec") == Modifier)
2302 printVecModifiedImmediate(MO, Modifier, O);
2303 else
2304 llvm_unreachable(
2305 "Don't know how to handle modifier on immediate operand");
2306 return;
2307
2308 case MachineOperand::MO_FPImmediate:
2309 printFPConstant(MO.getFPImm(), O);
2310 break;
2311
2312 case MachineOperand::MO_GlobalAddress:
Matt Arsenault8b643552015-06-09 00:31:39 +00002313 getSymbol(MO.getGlobal())->print(O, MAI);
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002314 break;
2315
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002316 case MachineOperand::MO_MachineBasicBlock:
Matt Arsenault8b643552015-06-09 00:31:39 +00002317 MO.getMBB()->getSymbol()->print(O, MAI);
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002318 return;
2319
2320 default:
2321 llvm_unreachable("Operand type not supported.");
2322 }
2323}
2324
2325void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2326 raw_ostream &O, const char *Modifier) {
2327 printOperand(MI, opNum, O);
2328
2329 if (Modifier && !strcmp(Modifier, "add")) {
2330 O << ", ";
2331 printOperand(MI, opNum + 1, O);
2332 } else {
2333 if (MI->getOperand(opNum + 1).isImm() &&
2334 MI->getOperand(opNum + 1).getImm() == 0)
2335 return; // don't print ',0' or '+0'
2336 O << "+";
2337 printOperand(MI, opNum + 1, O);
2338 }
2339}
2340
Justin Holewinskiae556d32012-05-04 20:18:50 +00002341void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2342 std::stringstream temp;
Yaron Keren075759a2015-03-30 15:42:36 +00002343 LineReader *reader = this->getReader(filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002344 temp << "\n//";
2345 temp << filename.str();
2346 temp << ":";
2347 temp << line;
2348 temp << " ";
2349 temp << reader->readLine(line);
2350 temp << "\n";
Lang Hames9ff69c82015-04-24 19:11:51 +00002351 this->OutStreamer->EmitRawText(temp.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +00002352}
2353
Benjamin Kramerc321e532016-06-08 19:09:22 +00002354LineReader *NVPTXAsmPrinter::getReader(const std::string &filename) {
Craig Topper062a2ba2014-04-25 05:30:21 +00002355 if (!reader) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00002356 reader = new LineReader(filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002357 }
2358
2359 if (reader->fileName() != filename) {
2360 delete reader;
Justin Holewinski0497ab12013-03-30 14:29:21 +00002361 reader = new LineReader(filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002362 }
2363
2364 return reader;
2365}
2366
Justin Holewinski0497ab12013-03-30 14:29:21 +00002367std::string LineReader::readLine(unsigned lineNum) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00002368 if (lineNum < theCurLine) {
2369 theCurLine = 0;
Justin Holewinski0497ab12013-03-30 14:29:21 +00002370 fstr.seekg(0, std::ios::beg);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002371 }
2372 while (theCurLine < lineNum) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00002373 fstr.getline(buff, 500);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002374 theCurLine++;
2375 }
2376 return buff;
2377}
2378
2379// Force static initialization.
2380extern "C" void LLVMInitializeNVPTXAsmPrinter() {
Mehdi Aminif42454b2016-10-09 23:00:34 +00002381 RegisterAsmPrinter<NVPTXAsmPrinter> X(getTheNVPTXTarget32());
2382 RegisterAsmPrinter<NVPTXAsmPrinter> Y(getTheNVPTXTarget64());
Justin Holewinskiae556d32012-05-04 20:18:50 +00002383}