blob: 04c8d5c0443e17f56403b29fe47d88b8d0d4197b [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";
Justin Lebar19bf9d22016-12-14 22:32:50 +0000558
559 unsigned maxnreg;
560 if (llvm::getMaxNReg(F, maxnreg))
561 O << ".maxnreg " << maxnreg << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000562}
563
Justin Holewinski660597d2013-10-11 12:39:36 +0000564std::string
565NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
566 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000567
Justin Holewinski660597d2013-10-11 12:39:36 +0000568 std::string Name;
569 raw_string_ostream NameStr(Name);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000570
Justin Holewinski660597d2013-10-11 12:39:36 +0000571 VRegRCMap::const_iterator I = VRegMapping.find(RC);
572 assert(I != VRegMapping.end() && "Bad register class");
573 const DenseMap<unsigned, unsigned> &RegMap = I->second;
574
575 VRegMap::const_iterator VI = RegMap.find(Reg);
576 assert(VI != RegMap.end() && "Bad virtual register");
577 unsigned MappedVR = VI->second;
578
579 NameStr << getNVPTXRegClassStr(RC) << MappedVR;
580
581 NameStr.flush();
582 return Name;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000583}
584
Justin Holewinski660597d2013-10-11 12:39:36 +0000585void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
Justin Holewinski0497ab12013-03-30 14:29:21 +0000586 raw_ostream &O) {
Justin Holewinski660597d2013-10-11 12:39:36 +0000587 O << getVirtualRegisterName(vr);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000588}
589
Justin Holewinski0497ab12013-03-30 14:29:21 +0000590void NVPTXAsmPrinter::printVecModifiedImmediate(
591 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
592 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
593 int Imm = (int) MO.getImm();
594 if (0 == strcmp(Modifier, "vecelem"))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000595 O << "_" << vecelem[Imm];
Justin Holewinski0497ab12013-03-30 14:29:21 +0000596 else if (0 == strcmp(Modifier, "vecv4comm1")) {
597 if ((Imm < 0) || (Imm > 3))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000598 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000599 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
600 if ((Imm < 4) || (Imm > 7))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000601 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000602 } else if (0 == strcmp(Modifier, "vecv4pos")) {
603 if (Imm < 0)
604 Imm = 0;
605 O << "_" << vecelem[Imm % 4];
606 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
607 if ((Imm < 0) || (Imm > 1))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000608 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000609 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
610 if ((Imm < 2) || (Imm > 3))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000611 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000612 } else if (0 == strcmp(Modifier, "vecv2pos")) {
613 if (Imm < 0)
614 Imm = 0;
615 O << "_" << vecelem[Imm % 2];
616 } else
Craig Topperbdf39a42012-05-24 07:02:50 +0000617 llvm_unreachable("Unknown Modifier on immediate operand");
Justin Holewinskiae556d32012-05-04 20:18:50 +0000618}
619
Justin Holewinskidc5e3b62013-06-28 17:58:04 +0000620
621
Justin Holewinski0497ab12013-03-30 14:29:21 +0000622void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000623
Justin Holewinski0497ab12013-03-30 14:29:21 +0000624 emitLinkageDirective(F, O);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000625 if (llvm::isKernelFunction(*F))
626 O << ".entry ";
627 else
628 O << ".func ";
629 printReturnValStr(F, O);
Matt Arsenault8b643552015-06-09 00:31:39 +0000630 getSymbol(F)->print(O, MAI);
631 O << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000632 emitFunctionParamList(F, O);
633 O << ";\n";
634}
635
Justin Holewinski0497ab12013-03-30 14:29:21 +0000636static bool usedInGlobalVarDef(const Constant *C) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000637 if (!C)
638 return false;
639
640 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
Jingyue Wu4be014a2015-07-31 05:09:47 +0000641 return GV->getName() != "llvm.used";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000642 }
643
Chandler Carruthcdf47882014-03-09 03:16:01 +0000644 for (const User *U : C->users())
645 if (const Constant *C = dyn_cast<Constant>(U))
646 if (usedInGlobalVarDef(C))
647 return true;
648
Justin Holewinskiae556d32012-05-04 20:18:50 +0000649 return false;
650}
651
Justin Holewinski0497ab12013-03-30 14:29:21 +0000652static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000653 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
Yaron Keren075759a2015-03-30 15:42:36 +0000654 if (othergv->getName() == "llvm.used")
Justin Holewinskiae556d32012-05-04 20:18:50 +0000655 return true;
656 }
657
658 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
659 if (instr->getParent() && instr->getParent()->getParent()) {
660 const Function *curFunc = instr->getParent()->getParent();
661 if (oneFunc && (curFunc != oneFunc))
662 return false;
663 oneFunc = curFunc;
664 return true;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000665 } else
Justin Holewinskiae556d32012-05-04 20:18:50 +0000666 return false;
667 }
668
Chandler Carruthcdf47882014-03-09 03:16:01 +0000669 for (const User *UU : U->users())
Eli Bendersky3e840192015-03-23 16:26:23 +0000670 if (!usedInOneFunc(UU, oneFunc))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000671 return false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000672
Justin Holewinskiae556d32012-05-04 20:18:50 +0000673 return true;
674}
675
676/* Find out if a global variable can be demoted to local scope.
677 * Currently, this is valid for CUDA shared variables, which have local
678 * scope and global lifetime. So the conditions to check are :
679 * 1. Is the global variable in shared address space?
680 * 2. Does it have internal linkage?
681 * 3. Is the global variable referenced only in one function?
682 */
683static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
Eli Bendersky3e840192015-03-23 16:26:23 +0000684 if (!gv->hasInternalLinkage())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000685 return false;
Craig Toppere3dcce92015-08-01 22:20:21 +0000686 PointerType *Pty = gv->getType();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000687 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
688 return false;
689
Craig Topper062a2ba2014-04-25 05:30:21 +0000690 const Function *oneFunc = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000691
692 bool flag = usedInOneFunc(gv, oneFunc);
Eli Bendersky3e840192015-03-23 16:26:23 +0000693 if (!flag)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000694 return false;
695 if (!oneFunc)
696 return false;
697 f = oneFunc;
698 return true;
699}
700
701static bool useFuncSeen(const Constant *C,
702 llvm::DenseMap<const Function *, bool> &seenMap) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000703 for (const User *U : C->users()) {
704 if (const Constant *cu = dyn_cast<Constant>(U)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000705 if (useFuncSeen(cu, seenMap))
706 return true;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000707 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000708 const BasicBlock *bb = I->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000709 if (!bb)
710 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000711 const Function *caller = bb->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000712 if (!caller)
713 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000714 if (seenMap.find(caller) != seenMap.end())
715 return true;
716 }
717 }
718 return false;
719}
720
Justin Holewinski01f89f02013-05-20 12:13:32 +0000721void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000722 llvm::DenseMap<const Function *, bool> seenMap;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000723 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
Duncan P. N. Exon Smith61149b82015-10-20 00:54:09 +0000724 const Function *F = &*FI;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000725
726 if (F->isDeclaration()) {
727 if (F->use_empty())
728 continue;
729 if (F->getIntrinsicID())
730 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000731 emitDeclaration(F, O);
732 continue;
733 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000734 for (const User *U : F->users()) {
735 if (const Constant *C = dyn_cast<Constant>(U)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000736 if (usedInGlobalVarDef(C)) {
737 // The use is in the initialization of a global variable
738 // that is a function pointer, so print a declaration
739 // for the original function
Justin Holewinskiae556d32012-05-04 20:18:50 +0000740 emitDeclaration(F, O);
741 break;
742 }
743 // Emit a declaration of this function if the function that
744 // uses this constant expr has already been seen.
745 if (useFuncSeen(C, seenMap)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000746 emitDeclaration(F, O);
747 break;
748 }
749 }
750
Chandler Carruthcdf47882014-03-09 03:16:01 +0000751 if (!isa<Instruction>(U))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000752 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000753 const Instruction *instr = cast<Instruction>(U);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000754 const BasicBlock *bb = instr->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000755 if (!bb)
756 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000757 const Function *caller = bb->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000758 if (!caller)
759 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000760
761 // If a caller has already been seen, then the caller is
762 // appearing in the module before the callee. so print out
763 // a declaration for the callee.
764 if (seenMap.find(caller) != seenMap.end()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000765 emitDeclaration(F, O);
766 break;
767 }
768 }
769 seenMap[F] = true;
770 }
771}
772
773void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
774 DebugInfoFinder DbgFinder;
775 DbgFinder.processModule(M);
776
Justin Holewinski0497ab12013-03-30 14:29:21 +0000777 unsigned i = 1;
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000778 for (const DICompileUnit *DIUnit : DbgFinder.compile_units()) {
Duncan P. N. Exon Smith35ef22c2015-04-15 23:19:27 +0000779 StringRef Filename = DIUnit->getFilename();
780 StringRef Dirname = DIUnit->getDirectory();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000781 SmallString<128> FullPathName = Dirname;
782 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
783 sys::path::append(FullPathName, Filename);
Yaron Keren075759a2015-03-30 15:42:36 +0000784 Filename = FullPathName;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000785 }
Yaron Keren075759a2015-03-30 15:42:36 +0000786 if (filenameMap.find(Filename) != filenameMap.end())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000787 continue;
Yaron Keren075759a2015-03-30 15:42:36 +0000788 filenameMap[Filename] = i;
Lang Hames9ff69c82015-04-24 19:11:51 +0000789 OutStreamer->EmitDwarfFileDirective(i, "", Filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000790 ++i;
791 }
792
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000793 for (DISubprogram *SP : DbgFinder.subprograms()) {
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000794 StringRef Filename = SP->getFilename();
795 StringRef Dirname = SP->getDirectory();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000796 SmallString<128> FullPathName = Dirname;
797 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
798 sys::path::append(FullPathName, Filename);
Yaron Keren075759a2015-03-30 15:42:36 +0000799 Filename = FullPathName;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000800 }
Yaron Keren075759a2015-03-30 15:42:36 +0000801 if (filenameMap.find(Filename) != filenameMap.end())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000802 continue;
Yaron Keren075759a2015-03-30 15:42:36 +0000803 filenameMap[Filename] = i;
Artem Belevicha8455f22016-02-11 18:21:47 +0000804 OutStreamer->EmitDwarfFileDirective(i, "", Filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000805 ++i;
806 }
807}
808
Justin Lebaread59f42016-01-30 01:07:38 +0000809static bool isEmptyXXStructor(GlobalVariable *GV) {
810 if (!GV) return true;
811 const ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
812 if (!InitList) return true; // Not an array; we don't know how to parse.
813 return InitList->getNumOperands() == 0;
814}
815
Justin Holewinski0497ab12013-03-30 14:29:21 +0000816bool NVPTXAsmPrinter::doInitialization(Module &M) {
Eric Christopher6aad8b12015-02-19 00:08:14 +0000817 // Construct a default subtarget off of the TargetMachine defaults. The
818 // rest of NVPTX isn't friendly to change subtargets per function and
819 // so the default TargetMachine will have all of the options.
Daniel Sandersc81f4502015-06-16 15:44:21 +0000820 const Triple &TT = TM.getTargetTriple();
Eric Christopher6aad8b12015-02-19 00:08:14 +0000821 StringRef CPU = TM.getTargetCPU();
822 StringRef FS = TM.getTargetFeatureString();
823 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
Eric Christopher02389e32015-02-19 00:08:27 +0000824 const NVPTXSubtarget STI(TT, CPU, FS, NTM);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000825
Justin Lebar3a5f5792016-01-23 21:12:20 +0000826 if (M.alias_size()) {
827 report_fatal_error("Module has aliases, which NVPTX does not support.");
828 return true; // error
829 }
Justin Lebaread59f42016-01-30 01:07:38 +0000830 if (!isEmptyXXStructor(M.getNamedGlobal("llvm.global_ctors"))) {
831 report_fatal_error(
832 "Module has a nontrivial global ctor, which NVPTX does not support.");
833 return true; // error
834 }
835 if (!isEmptyXXStructor(M.getNamedGlobal("llvm.global_dtors"))) {
836 report_fatal_error(
837 "Module has a nontrivial global dtor, which NVPTX does not support.");
838 return true; // error
839 }
Justin Lebar3a5f5792016-01-23 21:12:20 +0000840
Justin Holewinskiae556d32012-05-04 20:18:50 +0000841 SmallString<128> Str1;
842 raw_svector_ostream OS1(Str1);
843
844 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000845
846 // We need to call the parent's one explicitly.
847 //bool Result = AsmPrinter::doInitialization(M);
848
Eric Christopherb4b75a52016-09-29 02:03:47 +0000849 // Initialize TargetLoweringObjectFile since we didn't do in
850 // AsmPrinter::doInitialization either right above or where it's commented out
851 // below.
Justin Holewinski0497ab12013-03-30 14:29:21 +0000852 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
853 .Initialize(OutContext, TM);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000854
Justin Holewinskiae556d32012-05-04 20:18:50 +0000855 // Emit header before any dwarf directives are emitted below.
Eric Christopher6aad8b12015-02-19 00:08:14 +0000856 emitHeader(M, OS1, STI);
Lang Hames9ff69c82015-04-24 19:11:51 +0000857 OutStreamer->EmitRawText(OS1.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000858
Justin Holewinskiae556d32012-05-04 20:18:50 +0000859 // Already commented out
860 //bool Result = AsmPrinter::doInitialization(M);
861
Justin Holewinskid2bbdf02013-07-01 13:00:14 +0000862 // Emit module-level inline asm if it exists.
863 if (!M.getModuleInlineAsm().empty()) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000864 OutStreamer->AddComment("Start of file scope inline assembly");
865 OutStreamer->AddBlankLine();
866 OutStreamer->EmitRawText(StringRef(M.getModuleInlineAsm()));
867 OutStreamer->AddBlankLine();
868 OutStreamer->AddComment("End of file scope inline assembly");
869 OutStreamer->AddBlankLine();
Justin Holewinskid2bbdf02013-07-01 13:00:14 +0000870 }
871
Eric Christopher6aad8b12015-02-19 00:08:14 +0000872 // If we're not NVCL we're CUDA, go ahead and emit filenames.
Daniel Sandersc81f4502015-06-16 15:44:21 +0000873 if (TM.getTargetTriple().getOS() != Triple::NVCL)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000874 recordAndEmitFilenames(M);
875
Justin Holewinski01f89f02013-05-20 12:13:32 +0000876 GlobalsEmitted = false;
877
878 return false; // success
879}
880
881void NVPTXAsmPrinter::emitGlobals(const Module &M) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000882 SmallString<128> Str2;
883 raw_svector_ostream OS2(Str2);
884
885 emitDeclarations(M, OS2);
886
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000887 // As ptxas does not support forward references of globals, we need to first
888 // sort the list of module-level globals in def-use order. We visit each
889 // global variable in order, and ensure that we emit it *after* its dependent
890 // globals. We use a little extra memory maintaining both a set and a list to
891 // have fast searches while maintaining a strict ordering.
Justin Holewinski01f89f02013-05-20 12:13:32 +0000892 SmallVector<const GlobalVariable *, 8> Globals;
893 DenseSet<const GlobalVariable *> GVVisited;
894 DenseSet<const GlobalVariable *> GVVisiting;
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000895
896 // Visit each global variable, in order
Duncan P. N. Exon Smith61149b82015-10-20 00:54:09 +0000897 for (const GlobalVariable &I : M.globals())
898 VisitGlobalVariableForEmission(&I, Globals, GVVisited, GVVisiting);
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000899
Justin Holewinski0497ab12013-03-30 14:29:21 +0000900 assert(GVVisited.size() == M.getGlobalList().size() &&
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000901 "Missed a global variable");
902 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
903
904 // Print out module-level global variables in proper order
905 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
906 printModuleLevelGV(Globals[i], OS2);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000907
908 OS2 << '\n';
909
Lang Hames9ff69c82015-04-24 19:11:51 +0000910 OutStreamer->EmitRawText(OS2.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000911}
912
Eric Christopher6aad8b12015-02-19 00:08:14 +0000913void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O,
914 const NVPTXSubtarget &STI) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000915 O << "//\n";
916 O << "// Generated by LLVM NVPTX Back-End\n";
917 O << "//\n";
918 O << "\n";
919
Eric Christopher6aad8b12015-02-19 00:08:14 +0000920 unsigned PTXVersion = STI.getPTXVersion();
Justin Holewinski1812ee92012-11-12 03:16:43 +0000921 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000922
923 O << ".target ";
Eric Christopher6aad8b12015-02-19 00:08:14 +0000924 O << STI.getTargetName();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000925
Eric Christopherca929f22015-02-19 00:22:47 +0000926 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
927 if (NTM.getDrvInterface() == NVPTX::NVCL)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000928 O << ", texmode_independent";
Eric Christopherbeffc4e2015-02-19 00:08:23 +0000929 else {
Eric Christopher6aad8b12015-02-19 00:08:14 +0000930 if (!STI.hasDouble())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000931 O << ", map_f64_to_f32";
932 }
933
934 if (MAI->doesSupportDebugInformation())
935 O << ", debug";
936
937 O << "\n";
938
939 O << ".address_size ";
Eric Christopherca929f22015-02-19 00:22:47 +0000940 if (NTM.is64Bit())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000941 O << "64";
942 else
943 O << "32";
944 O << "\n";
945
946 O << "\n";
947}
948
949bool NVPTXAsmPrinter::doFinalization(Module &M) {
Justin Holewinski01f89f02013-05-20 12:13:32 +0000950 // If we did not emit any functions, then the global declarations have not
951 // yet been emitted.
952 if (!GlobalsEmitted) {
953 emitGlobals(M);
954 GlobalsEmitted = true;
955 }
956
Justin Holewinskiae556d32012-05-04 20:18:50 +0000957 // XXX Temproarily remove global variables so that doFinalization() will not
958 // emit them again (global variables are emitted at beginning).
959
960 Module::GlobalListType &global_list = M.getGlobalList();
961 int i, n = global_list.size();
Dylan Noblesmithc9e2a272014-08-26 02:03:35 +0000962 GlobalVariable **gv_array = new GlobalVariable *[n];
Justin Holewinskiae556d32012-05-04 20:18:50 +0000963
964 // first, back-up GlobalVariable in gv_array
965 i = 0;
966 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000967 I != E; ++I)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000968 gv_array[i++] = &*I;
969
970 // second, empty global_list
971 while (!global_list.empty())
972 global_list.remove(global_list.begin());
973
974 // call doFinalization
975 bool ret = AsmPrinter::doFinalization(M);
976
977 // now we restore global variables
Justin Holewinski0497ab12013-03-30 14:29:21 +0000978 for (i = 0; i < n; i++)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000979 global_list.insert(global_list.end(), gv_array[i]);
980
Justin Holewinski59596952014-04-09 15:38:52 +0000981 clearAnnotationCache(&M);
Dylan Noblesmithc9e2a272014-08-26 02:03:35 +0000982
983 delete[] gv_array;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000984 return ret;
985
Justin Holewinskiae556d32012-05-04 20:18:50 +0000986 //bool Result = AsmPrinter::doFinalization(M);
987 // Instead of calling the parents doFinalization, we may
988 // clone parents doFinalization and customize here.
989 // Currently, we if NVISA out the EmitGlobals() in
990 // parent's doFinalization, which is too intrusive.
991 //
992 // Same for the doInitialization.
993 //return Result;
994}
995
996// This function emits appropriate linkage directives for
997// functions and global variables.
998//
999// extern function declaration -> .extern
1000// extern function definition -> .visible
1001// external global variable with init -> .visible
1002// external without init -> .extern
1003// appending -> not allowed, assert.
Justin Holewinski7d5bf662014-06-27 18:35:10 +00001004// for any linkage other than
1005// internal, private, linker_private,
1006// linker_private_weak, linker_private_weak_def_auto,
1007// we emit -> .weak.
Justin Holewinskiae556d32012-05-04 20:18:50 +00001008
Justin Holewinski0497ab12013-03-30 14:29:21 +00001009void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
1010 raw_ostream &O) {
Eric Christopherbeffc4e2015-02-19 00:08:23 +00001011 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() == NVPTX::CUDA) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001012 if (V->hasExternalLinkage()) {
1013 if (isa<GlobalVariable>(V)) {
1014 const GlobalVariable *GVar = cast<GlobalVariable>(V);
1015 if (GVar) {
1016 if (GVar->hasInitializer())
1017 O << ".visible ";
1018 else
1019 O << ".extern ";
1020 }
1021 } else if (V->isDeclaration())
1022 O << ".extern ";
1023 else
1024 O << ".visible ";
1025 } else if (V->hasAppendingLinkage()) {
1026 std::string msg;
1027 msg.append("Error: ");
1028 msg.append("Symbol ");
1029 if (V->hasName())
Yaron Keren075759a2015-03-30 15:42:36 +00001030 msg.append(V->getName());
Justin Holewinskiae556d32012-05-04 20:18:50 +00001031 msg.append("has unsupported appending linkage type");
1032 llvm_unreachable(msg.c_str());
Justin Holewinski7d5bf662014-06-27 18:35:10 +00001033 } else if (!V->hasInternalLinkage() &&
1034 !V->hasPrivateLinkage()) {
1035 O << ".weak ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001036 }
1037 }
1038}
1039
Justin Holewinski01f89f02013-05-20 12:13:32 +00001040void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1041 raw_ostream &O,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001042 bool processDemoted) {
1043
1044 // Skip meta data
1045 if (GVar->hasSection()) {
Rafael Espindola83658d62016-05-11 18:21:59 +00001046 if (GVar->getSection() == "llvm.metadata")
Justin Holewinskiae556d32012-05-04 20:18:50 +00001047 return;
1048 }
1049
Justin Holewinski73cb5de2014-06-27 18:35:53 +00001050 // Skip LLVM intrinsic global variables
1051 if (GVar->getName().startswith("llvm.") ||
1052 GVar->getName().startswith("nvvm."))
1053 return;
1054
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001055 const DataLayout &DL = getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001056
1057 // GlobalVariables are always constant pointers themselves.
Craig Toppere3dcce92015-08-01 22:20:21 +00001058 PointerType *PTy = GVar->getType();
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001059 Type *ETy = GVar->getValueType();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001060
1061 if (GVar->hasExternalLinkage()) {
1062 if (GVar->hasInitializer())
1063 O << ".visible ";
1064 else
1065 O << ".extern ";
Justin Holewinskid73767a2014-06-27 18:35:56 +00001066 } else if (GVar->hasLinkOnceLinkage() || GVar->hasWeakLinkage() ||
1067 GVar->hasAvailableExternallyLinkage() ||
1068 GVar->hasCommonLinkage()) {
1069 O << ".weak ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001070 }
1071
1072 if (llvm::isTexture(*GVar)) {
1073 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1074 return;
1075 }
1076
1077 if (llvm::isSurface(*GVar)) {
1078 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1079 return;
1080 }
1081
1082 if (GVar->isDeclaration()) {
1083 // (extern) declarations, no definition or initializer
1084 // Currently the only known declaration is for an automatic __local
1085 // (.shared) promoted to global.
1086 emitPTXGlobalVariable(GVar, O);
1087 O << ";\n";
1088 return;
1089 }
1090
1091 if (llvm::isSampler(*GVar)) {
1092 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1093
Craig Topper062a2ba2014-04-25 05:30:21 +00001094 const Constant *Initializer = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001095 if (GVar->hasInitializer())
1096 Initializer = GVar->getInitializer();
Craig Topper062a2ba2014-04-25 05:30:21 +00001097 const ConstantInt *CI = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001098 if (Initializer)
1099 CI = dyn_cast<ConstantInt>(Initializer);
1100 if (CI) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001101 unsigned sample = CI->getZExtValue();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001102
1103 O << " = { ";
1104
Justin Holewinski0497ab12013-03-30 14:29:21 +00001105 for (int i = 0,
1106 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1107 i < 3; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001108 O << "addr_mode_" << i << " = ";
1109 switch (addr) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001110 case 0:
1111 O << "wrap";
1112 break;
1113 case 1:
1114 O << "clamp_to_border";
1115 break;
1116 case 2:
1117 O << "clamp_to_edge";
1118 break;
1119 case 3:
1120 O << "wrap";
1121 break;
1122 case 4:
1123 O << "mirror";
1124 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001125 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001126 O << ", ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001127 }
1128 O << "filter_mode = ";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001129 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1130 case 0:
1131 O << "nearest";
1132 break;
1133 case 1:
1134 O << "linear";
1135 break;
1136 case 2:
Craig Topper2a30d782014-06-18 05:05:13 +00001137 llvm_unreachable("Anisotropic filtering is not supported");
Justin Holewinski0497ab12013-03-30 14:29:21 +00001138 default:
1139 O << "nearest";
1140 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001141 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001142 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001143 O << ", force_unnormalized_coords = 1";
1144 }
1145 O << " }";
1146 }
1147
1148 O << ";\n";
1149 return;
1150 }
1151
1152 if (GVar->hasPrivateLinkage()) {
1153
1154 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1155 return;
1156
1157 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1158 if (!strncmp(GVar->getName().data(), "filename", 8))
1159 return;
1160 if (GVar->use_empty())
1161 return;
1162 }
1163
Craig Topper062a2ba2014-04-25 05:30:21 +00001164 const Function *demotedFunc = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001165 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
Yaron Keren075759a2015-03-30 15:42:36 +00001166 O << "// " << GVar->getName() << " has been demoted\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001167 if (localDecls.find(demotedFunc) != localDecls.end())
1168 localDecls[demotedFunc].push_back(GVar);
1169 else {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001170 std::vector<const GlobalVariable *> temp;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001171 temp.push_back(GVar);
1172 localDecls[demotedFunc] = temp;
1173 }
1174 return;
1175 }
1176
1177 O << ".";
1178 emitPTXAddressSpace(PTy->getAddressSpace(), O);
Justin Holewinski773ca402014-06-27 18:35:58 +00001179
1180 if (isManaged(*GVar)) {
1181 O << " .attribute(.managed)";
1182 }
1183
Justin Holewinskiae556d32012-05-04 20:18:50 +00001184 if (GVar->getAlignment() == 0)
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001185 O << " .align " << (int)DL.getPrefTypeAlignment(ETy);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001186 else
1187 O << " .align " << GVar->getAlignment();
1188
Jingyue Wue4c9cf02014-12-17 17:59:04 +00001189 if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001190 O << " .";
Justin Holewinski700b6fa2013-05-20 12:13:28 +00001191 // Special case: ABI requires that we use .u8 for predicates
1192 if (ETy->isIntegerTy(1))
1193 O << "u8";
1194 else
1195 O << getPTXFundamentalTypeStr(ETy, false);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001196 O << " ";
Matt Arsenault8b643552015-06-09 00:31:39 +00001197 getSymbol(GVar)->print(O, MAI);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001198
1199 // Ptx allows variable initilization only for constant and global state
1200 // spaces.
Justin Holewinski549c7732014-06-27 18:36:01 +00001201 if (GVar->hasInitializer()) {
1202 if ((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1203 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) {
1204 const Constant *Initializer = GVar->getInitializer();
Jingyue Wu312fd022015-04-24 02:57:30 +00001205 // 'undef' is treated as there is no value specified.
Justin Holewinski549c7732014-06-27 18:36:01 +00001206 if (!Initializer->isNullValue() && !isa<UndefValue>(Initializer)) {
1207 O << " = ";
1208 printScalarConstant(Initializer, O);
1209 }
1210 } else {
Jingyue Wufcec0982015-08-22 05:40:26 +00001211 // The frontend adds zero-initializer to device and constant variables
1212 // that don't have an initial value, and UndefValue to shared
1213 // variables, so skip warning for this case.
1214 if (!GVar->getInitializer()->isNullValue() &&
1215 !isa<UndefValue>(GVar->getInitializer())) {
Benjamin Kramerdba7ee92015-05-28 11:24:24 +00001216 report_fatal_error("initial value of '" + GVar->getName() +
1217 "' is not allowed in addrspace(" +
1218 Twine(PTy->getAddressSpace()) + ")");
Justin Holewinski549c7732014-06-27 18:36:01 +00001219 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001220 }
1221 }
1222 } else {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001223 unsigned int ElementSize = 0;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001224
1225 // Although PTX has direct support for struct type and array type and
1226 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1227 // targets that support these high level field accesses. Structs, arrays
1228 // and vectors are lowered into arrays of bytes.
1229 switch (ETy->getTypeID()) {
1230 case Type::StructTyID:
1231 case Type::ArrayTyID:
1232 case Type::VectorTyID:
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001233 ElementSize = DL.getTypeStoreSize(ETy);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001234 // Ptx allows variable initilization only for constant and
1235 // global state spaces.
1236 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
Justin Holewinski0497ab12013-03-30 14:29:21 +00001237 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1238 GVar->hasInitializer()) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001239 const Constant *Initializer = GVar->getInitializer();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001240 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001241 AggBuffer aggBuffer(ElementSize, O, *this);
1242 bufferAggregateConstant(Initializer, &aggBuffer);
1243 if (aggBuffer.numSymbols) {
Eric Christopher6aad8b12015-02-19 00:08:14 +00001244 if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit()) {
Matt Arsenault8b643552015-06-09 00:31:39 +00001245 O << " .u64 ";
1246 getSymbol(GVar)->print(O, MAI);
1247 O << "[";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001248 O << ElementSize / 8;
1249 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001250 O << " .u32 ";
1251 getSymbol(GVar)->print(O, MAI);
1252 O << "[";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001253 O << ElementSize / 4;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001254 }
1255 O << "]";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001256 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001257 O << " .b8 ";
1258 getSymbol(GVar)->print(O, MAI);
1259 O << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001260 O << ElementSize;
1261 O << "]";
1262 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001263 O << " = {";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001264 aggBuffer.print();
1265 O << "}";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001266 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001267 O << " .b8 ";
1268 getSymbol(GVar)->print(O, MAI);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001269 if (ElementSize) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001270 O << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001271 O << ElementSize;
1272 O << "]";
1273 }
1274 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001275 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001276 O << " .b8 ";
1277 getSymbol(GVar)->print(O, MAI);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001278 if (ElementSize) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001279 O << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001280 O << ElementSize;
1281 O << "]";
1282 }
1283 }
1284 break;
1285 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001286 llvm_unreachable("type not supported yet");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001287 }
1288
1289 }
1290 O << ";\n";
1291}
1292
1293void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1294 if (localDecls.find(f) == localDecls.end())
1295 return;
1296
Justin Holewinski01f89f02013-05-20 12:13:32 +00001297 std::vector<const GlobalVariable *> &gvars = localDecls[f];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001298
Justin Holewinski0497ab12013-03-30 14:29:21 +00001299 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001300 O << "\t// demoted variable\n\t";
1301 printModuleLevelGV(gvars[i], O, true);
1302 }
1303}
1304
1305void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1306 raw_ostream &O) const {
1307 switch (AddressSpace) {
1308 case llvm::ADDRESS_SPACE_LOCAL:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001309 O << "local";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001310 break;
1311 case llvm::ADDRESS_SPACE_GLOBAL:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001312 O << "global";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001313 break;
1314 case llvm::ADDRESS_SPACE_CONST:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001315 O << "const";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001316 break;
1317 case llvm::ADDRESS_SPACE_SHARED:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001318 O << "shared";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001319 break;
1320 default:
Justin Holewinski36a50992013-02-09 13:34:15 +00001321 report_fatal_error("Bad address space found while emitting PTX");
1322 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001323 }
1324}
1325
Justin Holewinski0497ab12013-03-30 14:29:21 +00001326std::string
Craig Toppere3dcce92015-08-01 22:20:21 +00001327NVPTXAsmPrinter::getPTXFundamentalTypeStr(Type *Ty, bool useB4PTR) const {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001328 switch (Ty->getTypeID()) {
1329 default:
1330 llvm_unreachable("unexpected type");
1331 break;
1332 case Type::IntegerTyID: {
1333 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1334 if (NumBits == 1)
1335 return "pred";
1336 else if (NumBits <= 64) {
1337 std::string name = "u";
1338 return name + utostr(NumBits);
1339 } else {
1340 llvm_unreachable("Integer too large");
1341 break;
1342 }
1343 break;
1344 }
1345 case Type::FloatTyID:
1346 return "f32";
1347 case Type::DoubleTyID:
1348 return "f64";
1349 case Type::PointerTyID:
Eric Christopher6aad8b12015-02-19 00:08:14 +00001350 if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit())
Justin Holewinski0497ab12013-03-30 14:29:21 +00001351 if (useB4PTR)
1352 return "b64";
1353 else
1354 return "u64";
1355 else if (useB4PTR)
1356 return "b32";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001357 else
Justin Holewinski0497ab12013-03-30 14:29:21 +00001358 return "u32";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001359 }
1360 llvm_unreachable("unexpected type");
Craig Topper062a2ba2014-04-25 05:30:21 +00001361 return nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001362}
1363
Justin Holewinski0497ab12013-03-30 14:29:21 +00001364void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001365 raw_ostream &O) {
1366
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001367 const DataLayout &DL = getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001368
1369 // GlobalVariables are always constant pointers themselves.
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001370 Type *ETy = GVar->getValueType();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001371
1372 O << ".";
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001373 emitPTXAddressSpace(GVar->getType()->getAddressSpace(), O);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001374 if (GVar->getAlignment() == 0)
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001375 O << " .align " << (int)DL.getPrefTypeAlignment(ETy);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001376 else
1377 O << " .align " << GVar->getAlignment();
1378
Jingyue Wue4c9cf02014-12-17 17:59:04 +00001379 if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001380 O << " .";
1381 O << getPTXFundamentalTypeStr(ETy);
1382 O << " ";
Matt Arsenault8b643552015-06-09 00:31:39 +00001383 getSymbol(GVar)->print(O, MAI);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001384 return;
1385 }
1386
Justin Holewinski0497ab12013-03-30 14:29:21 +00001387 int64_t ElementSize = 0;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001388
1389 // Although PTX has direct support for struct type and array type and LLVM IR
1390 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1391 // support these high level field accesses. Structs and arrays are lowered
1392 // into arrays of bytes.
1393 switch (ETy->getTypeID()) {
1394 case Type::StructTyID:
1395 case Type::ArrayTyID:
1396 case Type::VectorTyID:
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001397 ElementSize = DL.getTypeStoreSize(ETy);
Matt Arsenault8b643552015-06-09 00:31:39 +00001398 O << " .b8 ";
1399 getSymbol(GVar)->print(O, MAI);
1400 O << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001401 if (ElementSize) {
Benjamin Kramerdba7ee92015-05-28 11:24:24 +00001402 O << ElementSize;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001403 }
1404 O << "]";
1405 break;
1406 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001407 llvm_unreachable("type not supported yet");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001408 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001409 return;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001410}
1411
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001412static unsigned int getOpenCLAlignment(const DataLayout &DL, Type *Ty) {
Rafael Espindola08013342013-12-07 19:34:20 +00001413 if (Ty->isSingleValueType())
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001414 return DL.getPrefTypeAlignment(Ty);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001415
Craig Toppere3dcce92015-08-01 22:20:21 +00001416 auto *ATy = dyn_cast<ArrayType>(Ty);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001417 if (ATy)
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001418 return getOpenCLAlignment(DL, ATy->getElementType());
Justin Holewinskiae556d32012-05-04 20:18:50 +00001419
Craig Toppere3dcce92015-08-01 22:20:21 +00001420 auto *STy = dyn_cast<StructType>(Ty);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001421 if (STy) {
1422 unsigned int alignStruct = 1;
1423 // Go through each element of the struct and find the
1424 // largest alignment.
Justin Holewinski0497ab12013-03-30 14:29:21 +00001425 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001426 Type *ETy = STy->getElementType(i);
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001427 unsigned int align = getOpenCLAlignment(DL, ETy);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001428 if (align > alignStruct)
1429 alignStruct = align;
1430 }
1431 return alignStruct;
1432 }
1433
Craig Toppere3dcce92015-08-01 22:20:21 +00001434 auto *FTy = dyn_cast<FunctionType>(Ty);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001435 if (FTy)
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001436 return DL.getPointerPrefAlignment();
1437 return DL.getPrefTypeAlignment(Ty);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001438}
1439
1440void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1441 int paramIndex, raw_ostream &O) {
Matt Arsenault8b643552015-06-09 00:31:39 +00001442 getSymbol(I->getParent())->print(O, MAI);
1443 O << "_param_" << paramIndex;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001444}
1445
Justin Holewinski0497ab12013-03-30 14:29:21 +00001446void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001447 const DataLayout &DL = getDataLayout();
Bill Wendlinge94d8432012-12-07 23:16:57 +00001448 const AttributeSet &PAL = F->getAttributes();
Eric Christopher6aad8b12015-02-19 00:08:14 +00001449 const TargetLowering *TLI = nvptxSubtarget->getTargetLowering();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001450 Function::const_arg_iterator I, E;
1451 unsigned paramIndex = 0;
1452 bool first = true;
1453 bool isKernelFunc = llvm::isKernelFunction(*F);
Eric Christopher6aad8b12015-02-19 00:08:14 +00001454 bool isABI = (nvptxSubtarget->getSmVersion() >= 20);
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001455 MVT thePointerTy = TLI->getPointerTy(DL);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001456
Justin Lebar2a161f92016-01-23 21:12:17 +00001457 if (F->arg_empty()) {
1458 O << "()\n";
1459 return;
1460 }
1461
Justin Holewinskiae556d32012-05-04 20:18:50 +00001462 O << "(\n";
1463
1464 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
Justin Holewinskie9884092013-03-24 21:17:47 +00001465 Type *Ty = I->getType();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001466
1467 if (!first)
1468 O << ",\n";
1469
1470 first = false;
1471
1472 // Handle image/sampler parameters
Justin Holewinski30d56a72014-04-09 15:39:15 +00001473 if (isKernelFunction(*F)) {
1474 if (isSampler(*I) || isImage(*I)) {
1475 if (isImage(*I)) {
1476 std::string sname = I->getName();
1477 if (isImageWriteOnly(*I) || isImageReadWrite(*I)) {
Eric Christopher6aad8b12015-02-19 00:08:14 +00001478 if (nvptxSubtarget->hasImageHandles())
Justin Holewinski30d56a72014-04-09 15:39:15 +00001479 O << "\t.param .u64 .ptr .surfref ";
1480 else
1481 O << "\t.param .surfref ";
Matt Arsenault8b643552015-06-09 00:31:39 +00001482 CurrentFnSym->print(O, MAI);
1483 O << "_param_" << paramIndex;
Justin Holewinski30d56a72014-04-09 15:39:15 +00001484 }
1485 else { // Default image is read_only
Eric Christopher6aad8b12015-02-19 00:08:14 +00001486 if (nvptxSubtarget->hasImageHandles())
Justin Holewinski30d56a72014-04-09 15:39:15 +00001487 O << "\t.param .u64 .ptr .texref ";
1488 else
1489 O << "\t.param .texref ";
Matt Arsenault8b643552015-06-09 00:31:39 +00001490 CurrentFnSym->print(O, MAI);
1491 O << "_param_" << paramIndex;
Justin Holewinski30d56a72014-04-09 15:39:15 +00001492 }
1493 } else {
Eric Christopher6aad8b12015-02-19 00:08:14 +00001494 if (nvptxSubtarget->hasImageHandles())
Justin Holewinski30d56a72014-04-09 15:39:15 +00001495 O << "\t.param .u64 .ptr .samplerref ";
1496 else
1497 O << "\t.param .samplerref ";
Matt Arsenault8b643552015-06-09 00:31:39 +00001498 CurrentFnSym->print(O, MAI);
1499 O << "_param_" << paramIndex;
Justin Holewinski30d56a72014-04-09 15:39:15 +00001500 }
1501 continue;
1502 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001503 }
1504
Eli Bendersky3e840192015-03-23 16:26:23 +00001505 if (!PAL.hasAttribute(paramIndex + 1, Attribute::ByVal)) {
Gautam Chakrabarti2c283402014-01-28 18:35:29 +00001506 if (Ty->isAggregateType() || Ty->isVectorTy()) {
1507 // Just print .param .align <a> .b8 .param[size];
Justin Holewinskie9884092013-03-24 21:17:47 +00001508 // <a> = PAL.getparamalignment
1509 // size = typeallocsize of element type
Justin Holewinski0497ab12013-03-30 14:29:21 +00001510 unsigned align = PAL.getParamAlignment(paramIndex + 1);
Justin Holewinskie9884092013-03-24 21:17:47 +00001511 if (align == 0)
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001512 align = DL.getABITypeAlignment(Ty);
Justin Holewinskie9884092013-03-24 21:17:47 +00001513
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001514 unsigned sz = DL.getTypeAllocSize(Ty);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001515 O << "\t.param .align " << align << " .b8 ";
Justin Holewinskie9884092013-03-24 21:17:47 +00001516 printParamName(I, paramIndex, O);
1517 O << "[" << sz << "]";
1518
1519 continue;
1520 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001521 // Just a scalar
Craig Toppere3dcce92015-08-01 22:20:21 +00001522 auto *PTy = dyn_cast<PointerType>(Ty);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001523 if (isKernelFunc) {
1524 if (PTy) {
1525 // Special handling for pointer arguments to kernel
1526 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1527
Eric Christopherbeffc4e2015-02-19 00:08:23 +00001528 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() !=
1529 NVPTX::CUDA) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001530 Type *ETy = PTy->getElementType();
1531 int addrSpace = PTy->getAddressSpace();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001532 switch (addrSpace) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001533 default:
1534 O << ".ptr ";
1535 break;
Justin Holewinskib96d1392013-06-10 13:29:47 +00001536 case llvm::ADDRESS_SPACE_CONST:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001537 O << ".ptr .const ";
1538 break;
1539 case llvm::ADDRESS_SPACE_SHARED:
1540 O << ".ptr .shared ";
1541 break;
1542 case llvm::ADDRESS_SPACE_GLOBAL:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001543 O << ".ptr .global ";
1544 break;
1545 }
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001546 O << ".align " << (int)getOpenCLAlignment(DL, ETy) << " ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001547 }
1548 printParamName(I, paramIndex, O);
1549 continue;
1550 }
1551
1552 // non-pointer scalar to kernel func
Justin Holewinski700b6fa2013-05-20 12:13:28 +00001553 O << "\t.param .";
1554 // Special case: predicate operands become .u8 types
1555 if (Ty->isIntegerTy(1))
1556 O << "u8";
1557 else
1558 O << getPTXFundamentalTypeStr(Ty);
1559 O << " ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001560 printParamName(I, paramIndex, O);
1561 continue;
1562 }
1563 // Non-kernel function, just print .param .b<size> for ABI
Alp Tokerf907b892013-12-05 05:44:44 +00001564 // and .reg .b<size> for non-ABI
Justin Holewinskiae556d32012-05-04 20:18:50 +00001565 unsigned sz = 0;
1566 if (isa<IntegerType>(Ty)) {
1567 sz = cast<IntegerType>(Ty)->getBitWidth();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001568 if (sz < 32)
1569 sz = 32;
1570 } else if (isa<PointerType>(Ty))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001571 sz = thePointerTy.getSizeInBits();
1572 else
1573 sz = Ty->getPrimitiveSizeInBits();
1574 if (isABI)
1575 O << "\t.param .b" << sz << " ";
1576 else
1577 O << "\t.reg .b" << sz << " ";
1578 printParamName(I, paramIndex, O);
1579 continue;
1580 }
1581
1582 // param has byVal attribute. So should be a pointer
Craig Toppere3dcce92015-08-01 22:20:21 +00001583 auto *PTy = dyn_cast<PointerType>(Ty);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001584 assert(PTy && "Param with byval attribute should be a pointer type");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001585 Type *ETy = PTy->getElementType();
1586
1587 if (isABI || isKernelFunc) {
Gautam Chakrabarti2c283402014-01-28 18:35:29 +00001588 // Just print .param .align <a> .b8 .param[size];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001589 // <a> = PAL.getparamalignment
1590 // size = typeallocsize of element type
Justin Holewinski0497ab12013-03-30 14:29:21 +00001591 unsigned align = PAL.getParamAlignment(paramIndex + 1);
Justin Holewinski2dc9d072012-11-09 23:50:24 +00001592 if (align == 0)
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001593 align = DL.getABITypeAlignment(ETy);
Artem Belevich052b1ed2016-07-18 19:54:56 +00001594 // Work around a bug in ptxas. When PTX code takes address of
1595 // byval parameter with alignment < 4, ptxas generates code to
1596 // spill argument into memory. Alas on sm_50+ ptxas generates
1597 // SASS code that fails with misaligned access. To work around
1598 // the problem, make sure that we align byval parameters by at
1599 // least 4. Matching change must be made in LowerCall() where we
1600 // prepare parameters for the call.
1601 //
1602 // TODO: this will need to be undone when we get to support multi-TU
1603 // device-side compilation as it breaks ABI compatibility with nvcc.
1604 // Hopefully ptxas bug is fixed by then.
1605 if (!isKernelFunc && align < 4)
1606 align = 4;
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001607 unsigned sz = DL.getTypeAllocSize(ETy);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001608 O << "\t.param .align " << align << " .b8 ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001609 printParamName(I, paramIndex, O);
1610 O << "[" << sz << "]";
1611 continue;
1612 } else {
1613 // Split the ETy into constituent parts and
1614 // print .param .b<size> <name> for each part.
1615 // Further, if a part is vector, print the above for
1616 // each vector element.
1617 SmallVector<EVT, 16> vtparts;
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001618 ComputeValueVTs(*TLI, DL, ETy, vtparts);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001619 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001620 unsigned elems = 1;
1621 EVT elemtype = vtparts[i];
1622 if (vtparts[i].isVector()) {
1623 elems = vtparts[i].getVectorNumElements();
1624 elemtype = vtparts[i].getVectorElementType();
1625 }
1626
Justin Holewinski0497ab12013-03-30 14:29:21 +00001627 for (unsigned j = 0, je = elems; j != je; ++j) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001628 unsigned sz = elemtype.getSizeInBits();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001629 if (elemtype.isInteger() && (sz < 32))
1630 sz = 32;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001631 O << "\t.reg .b" << sz << " ";
1632 printParamName(I, paramIndex, O);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001633 if (j < je - 1)
1634 O << ",\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001635 ++paramIndex;
1636 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001637 if (i < e - 1)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001638 O << ",\n";
1639 }
1640 --paramIndex;
1641 continue;
1642 }
1643 }
1644
1645 O << "\n)\n";
1646}
1647
1648void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1649 raw_ostream &O) {
1650 const Function *F = MF.getFunction();
1651 emitFunctionParamList(F, O);
1652}
1653
Justin Holewinski0497ab12013-03-30 14:29:21 +00001654void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1655 const MachineFunction &MF) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001656 SmallString<128> Str;
1657 raw_svector_ostream O(Str);
1658
1659 // Map the global virtual register number to a register class specific
1660 // virtual register number starting from 1 with that class.
Eric Christopherfc6de422014-08-05 02:39:49 +00001661 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001662 //unsigned numRegClasses = TRI->getNumRegClasses();
1663
1664 // Emit the Fake Stack Object
Matthias Braun941a7052016-07-28 18:40:00 +00001665 const MachineFrameInfo &MFI = MF.getFrameInfo();
1666 int NumBytes = (int) MFI.getStackSize();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001667 if (NumBytes) {
Matthias Braun941a7052016-07-28 18:40:00 +00001668 O << "\t.local .align " << MFI.getMaxAlignment() << " .b8 \t" << DEPOTNAME
Justin Holewinski0497ab12013-03-30 14:29:21 +00001669 << getFunctionNumber() << "[" << NumBytes << "];\n";
Eric Christopher02389e32015-02-19 00:08:27 +00001670 if (static_cast<const NVPTXTargetMachine &>(MF.getTarget()).is64Bit()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001671 O << "\t.reg .b64 \t%SP;\n";
1672 O << "\t.reg .b64 \t%SPL;\n";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001673 } else {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001674 O << "\t.reg .b32 \t%SP;\n";
1675 O << "\t.reg .b32 \t%SPL;\n";
1676 }
1677 }
1678
1679 // Go through all virtual registers to establish the mapping between the
1680 // global virtual
1681 // register number and the per class virtual register number.
1682 // We use the per class virtual register number in the ptx output.
1683 unsigned int numVRs = MRI->getNumVirtRegs();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001684 for (unsigned i = 0; i < numVRs; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001685 unsigned int vr = TRI->index2VirtReg(i);
1686 const TargetRegisterClass *RC = MRI->getRegClass(vr);
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001687 DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001688 int n = regmap.size();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001689 regmap.insert(std::make_pair(vr, n + 1));
Justin Holewinskiae556d32012-05-04 20:18:50 +00001690 }
1691
1692 // Emit register declarations
1693 // @TODO: Extract out the real register usage
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001694 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1695 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1696 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1697 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
Justin Holewinski3e037d92014-07-16 16:26:58 +00001698 // O << "\t.reg .s64 %rd<" << NVPTXNumRegisters << ">;\n";
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001699 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
Justin Holewinski3e037d92014-07-16 16:26:58 +00001700 // O << "\t.reg .f64 %fd<" << NVPTXNumRegisters << ">;\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001701
1702 // Emit declaration of the virtual registers or 'physical' registers for
1703 // each register class
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001704 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1705 const TargetRegisterClass *RC = TRI->getRegClass(i);
1706 DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
1707 std::string rcname = getNVPTXRegClassName(RC);
1708 std::string rcStr = getNVPTXRegClassStr(RC);
1709 int n = regmap.size();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001710
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001711 // Only declare those registers that may be used.
1712 if (n) {
1713 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1714 << ">;\n";
1715 }
1716 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001717
Lang Hames9ff69c82015-04-24 19:11:51 +00001718 OutStreamer->EmitRawText(O.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +00001719}
1720
Justin Holewinskiae556d32012-05-04 20:18:50 +00001721void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001722 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
Justin Holewinskiae556d32012-05-04 20:18:50 +00001723 bool ignored;
1724 unsigned int numHex;
1725 const char *lead;
1726
Justin Holewinski0497ab12013-03-30 14:29:21 +00001727 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001728 numHex = 8;
1729 lead = "0f";
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001730 APF.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &ignored);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001731 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1732 numHex = 16;
1733 lead = "0d";
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001734 APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &ignored);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001735 } else
1736 llvm_unreachable("unsupported fp type");
1737
1738 APInt API = APF.bitcastToAPInt();
1739 std::string hexstr(utohexstr(API.getZExtValue()));
1740 O << lead;
1741 if (hexstr.length() < numHex)
1742 O << std::string(numHex - hexstr.length(), '0');
1743 O << utohexstr(API.getZExtValue());
1744}
1745
Justin Holewinski01f89f02013-05-20 12:13:32 +00001746void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1747 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001748 O << CI->getValue();
1749 return;
1750 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001751 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001752 printFPConstant(CFP, O);
1753 return;
1754 }
1755 if (isa<ConstantPointerNull>(CPV)) {
1756 O << "0";
1757 return;
1758 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001759 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
Justin Holewinski9d852a82014-04-09 15:39:11 +00001760 bool IsNonGenericPointer = false;
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001761 if (GVar->getType()->getAddressSpace() != 0) {
Justin Holewinski9d852a82014-04-09 15:39:11 +00001762 IsNonGenericPointer = true;
1763 }
1764 if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
1765 O << "generic(";
Matt Arsenault8b643552015-06-09 00:31:39 +00001766 getSymbol(GVar)->print(O, MAI);
Justin Holewinski9d852a82014-04-09 15:39:11 +00001767 O << ")";
1768 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001769 getSymbol(GVar)->print(O, MAI);
Justin Holewinski9d852a82014-04-09 15:39:11 +00001770 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001771 return;
1772 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001773 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1774 const Value *v = Cexpr->stripPointerCasts();
Justin Holewinski9d852a82014-04-09 15:39:11 +00001775 PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
1776 bool IsNonGenericPointer = false;
1777 if (PTy && PTy->getAddressSpace() != 0) {
1778 IsNonGenericPointer = true;
1779 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001780 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
Justin Holewinski9d852a82014-04-09 15:39:11 +00001781 if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
1782 O << "generic(";
Matt Arsenault8b643552015-06-09 00:31:39 +00001783 getSymbol(GVar)->print(O, MAI);
Justin Holewinski9d852a82014-04-09 15:39:11 +00001784 O << ")";
1785 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001786 getSymbol(GVar)->print(O, MAI);
Justin Holewinski9d852a82014-04-09 15:39:11 +00001787 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001788 return;
1789 } else {
Matt Arsenault8b643552015-06-09 00:31:39 +00001790 lowerConstant(CPV)->print(O, MAI);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001791 return;
1792 }
1793 }
1794 llvm_unreachable("Not scalar type found in printScalarConstant()");
1795}
1796
Samuel Antaocd501352015-06-09 16:29:34 +00001797// These utility functions assure we get the right sequence of bytes for a given
1798// type even for big-endian machines
1799template <typename T> static void ConvertIntToBytes(unsigned char *p, T val) {
1800 int64_t vp = (int64_t)val;
1801 for (unsigned i = 0; i < sizeof(T); ++i) {
1802 p[i] = (unsigned char)vp;
1803 vp >>= 8;
1804 }
1805}
1806static void ConvertFloatToBytes(unsigned char *p, float val) {
1807 int32_t *vp = (int32_t *)&val;
1808 for (unsigned i = 0; i < sizeof(int32_t); ++i) {
1809 p[i] = (unsigned char)*vp;
1810 *vp >>= 8;
1811 }
1812}
1813static void ConvertDoubleToBytes(unsigned char *p, double val) {
1814 int64_t *vp = (int64_t *)&val;
1815 for (unsigned i = 0; i < sizeof(int64_t); ++i) {
1816 p[i] = (unsigned char)*vp;
1817 *vp >>= 8;
1818 }
1819}
1820
Justin Holewinski01f89f02013-05-20 12:13:32 +00001821void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001822 AggBuffer *aggBuffer) {
1823
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001824 const DataLayout &DL = getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001825
1826 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001827 int s = DL.getTypeAllocSize(CPV->getType());
Justin Holewinski0497ab12013-03-30 14:29:21 +00001828 if (s < Bytes)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001829 s = Bytes;
1830 aggBuffer->addZeros(s);
1831 return;
1832 }
1833
Samuel Antaocd501352015-06-09 16:29:34 +00001834 unsigned char ptr[8];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001835 switch (CPV->getType()->getTypeID()) {
1836
1837 case Type::IntegerTyID: {
Craig Toppere3dcce92015-08-01 22:20:21 +00001838 Type *ETy = CPV->getType();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001839 if (ETy == Type::getInt8Ty(CPV->getContext())) {
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001840 unsigned char c = (unsigned char)cast<ConstantInt>(CPV)->getZExtValue();
Samuel Antaocd501352015-06-09 16:29:34 +00001841 ConvertIntToBytes<>(ptr, c);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001842 aggBuffer->addBytes(ptr, 1, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001843 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001844 short int16 = (short)cast<ConstantInt>(CPV)->getZExtValue();
Samuel Antaocd501352015-06-09 16:29:34 +00001845 ConvertIntToBytes<>(ptr, int16);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001846 aggBuffer->addBytes(ptr, 2, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001847 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001848 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001849 int int32 = (int)(constInt->getZExtValue());
Samuel Antaocd501352015-06-09 16:29:34 +00001850 ConvertIntToBytes<>(ptr, int32);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001851 aggBuffer->addBytes(ptr, 4, Bytes);
1852 break;
David Majnemerd536f232016-07-29 03:27:26 +00001853 } else if (const auto *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1854 if (const auto *constInt = dyn_cast_or_null<ConstantInt>(
1855 ConstantFoldConstant(Cexpr, DL))) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001856 int int32 = (int)(constInt->getZExtValue());
Samuel Antaocd501352015-06-09 16:29:34 +00001857 ConvertIntToBytes<>(ptr, int32);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001858 aggBuffer->addBytes(ptr, 4, Bytes);
1859 break;
1860 }
1861 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1862 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
Jingyue Wu312fd022015-04-24 02:57:30 +00001863 aggBuffer->addSymbol(v, Cexpr->getOperand(0));
Justin Holewinskiae556d32012-05-04 20:18:50 +00001864 aggBuffer->addZeros(4);
1865 break;
1866 }
1867 }
Craig Topperbdf39a42012-05-24 07:02:50 +00001868 llvm_unreachable("unsupported integer const type");
Justin Holewinski0497ab12013-03-30 14:29:21 +00001869 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001870 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001871 long long int64 = (long long)(constInt->getZExtValue());
Samuel Antaocd501352015-06-09 16:29:34 +00001872 ConvertIntToBytes<>(ptr, int64);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001873 aggBuffer->addBytes(ptr, 8, Bytes);
1874 break;
Justin Holewinski01f89f02013-05-20 12:13:32 +00001875 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
David Majnemerd536f232016-07-29 03:27:26 +00001876 if (const auto *constInt = dyn_cast_or_null<ConstantInt>(
1877 ConstantFoldConstant(Cexpr, DL))) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001878 long long int64 = (long long)(constInt->getZExtValue());
Samuel Antaocd501352015-06-09 16:29:34 +00001879 ConvertIntToBytes<>(ptr, int64);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001880 aggBuffer->addBytes(ptr, 8, Bytes);
1881 break;
1882 }
1883 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1884 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
Jingyue Wu312fd022015-04-24 02:57:30 +00001885 aggBuffer->addSymbol(v, Cexpr->getOperand(0));
Justin Holewinskiae556d32012-05-04 20:18:50 +00001886 aggBuffer->addZeros(8);
1887 break;
1888 }
1889 }
1890 llvm_unreachable("unsupported integer const type");
Craig Topperbdf39a42012-05-24 07:02:50 +00001891 } else
Justin Holewinskiae556d32012-05-04 20:18:50 +00001892 llvm_unreachable("unsupported integer const type");
1893 break;
1894 }
1895 case Type::FloatTyID:
1896 case Type::DoubleTyID: {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001897 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
Craig Toppere3dcce92015-08-01 22:20:21 +00001898 Type *Ty = CFP->getType();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001899 if (Ty == Type::getFloatTy(CPV->getContext())) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001900 float float32 = (float) CFP->getValueAPF().convertToFloat();
Samuel Antaocd501352015-06-09 16:29:34 +00001901 ConvertFloatToBytes(ptr, float32);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001902 aggBuffer->addBytes(ptr, 4, Bytes);
1903 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1904 double float64 = CFP->getValueAPF().convertToDouble();
Samuel Antaocd501352015-06-09 16:29:34 +00001905 ConvertDoubleToBytes(ptr, float64);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001906 aggBuffer->addBytes(ptr, 8, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001907 } else {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001908 llvm_unreachable("unsupported fp const type");
1909 }
1910 break;
1911 }
1912 case Type::PointerTyID: {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001913 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
Jingyue Wu312fd022015-04-24 02:57:30 +00001914 aggBuffer->addSymbol(GVar, GVar);
Justin Holewinski01f89f02013-05-20 12:13:32 +00001915 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1916 const Value *v = Cexpr->stripPointerCasts();
Jingyue Wu312fd022015-04-24 02:57:30 +00001917 aggBuffer->addSymbol(v, Cexpr);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001918 }
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001919 unsigned int s = DL.getTypeAllocSize(CPV->getType());
Justin Holewinskiae556d32012-05-04 20:18:50 +00001920 aggBuffer->addZeros(s);
1921 break;
1922 }
1923
1924 case Type::ArrayTyID:
1925 case Type::VectorTyID:
1926 case Type::StructTyID: {
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +00001927 if (isa<ConstantAggregate>(CPV) || isa<ConstantDataSequential>(CPV)) {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001928 int ElementSize = DL.getTypeAllocSize(CPV->getType());
Justin Holewinskiae556d32012-05-04 20:18:50 +00001929 bufferAggregateConstant(CPV, aggBuffer);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001930 if (Bytes > ElementSize)
1931 aggBuffer->addZeros(Bytes - ElementSize);
1932 } else if (isa<ConstantAggregateZero>(CPV))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001933 aggBuffer->addZeros(Bytes);
1934 else
1935 llvm_unreachable("Unexpected Constant type");
1936 break;
1937 }
1938
1939 default:
1940 llvm_unreachable("unsupported type");
1941 }
1942}
1943
Justin Holewinski01f89f02013-05-20 12:13:32 +00001944void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001945 AggBuffer *aggBuffer) {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001946 const DataLayout &DL = getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001947 int Bytes;
1948
1949 // Old constants
1950 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1951 if (CPV->getNumOperands())
1952 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1953 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1954 return;
1955 }
1956
1957 if (const ConstantDataSequential *CDS =
Justin Holewinski0497ab12013-03-30 14:29:21 +00001958 dyn_cast<ConstantDataSequential>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001959 if (CDS->getNumElements())
1960 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1961 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1962 aggBuffer);
1963 return;
1964 }
1965
Justin Holewinskiae556d32012-05-04 20:18:50 +00001966 if (isa<ConstantStruct>(CPV)) {
1967 if (CPV->getNumOperands()) {
1968 StructType *ST = cast<StructType>(CPV->getType());
1969 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001970 if (i == (e - 1))
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001971 Bytes = DL.getStructLayout(ST)->getElementOffset(0) +
1972 DL.getTypeAllocSize(ST) -
1973 DL.getStructLayout(ST)->getElementOffset(i);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001974 else
Mehdi Aminibd7287e2015-07-16 06:11:10 +00001975 Bytes = DL.getStructLayout(ST)->getElementOffset(i + 1) -
1976 DL.getStructLayout(ST)->getElementOffset(i);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001977 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001978 }
1979 }
1980 return;
1981 }
Craig Topperbdf39a42012-05-24 07:02:50 +00001982 llvm_unreachable("unsupported constant type in printAggregateConstant()");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001983}
1984
1985// buildTypeNameMap - Run through symbol table looking for type names.
1986//
1987
Justin Holewinskiae556d32012-05-04 20:18:50 +00001988
Justin Holewinski0497ab12013-03-30 14:29:21 +00001989bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
1990 switch (MI.getOpcode()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001991 default:
1992 return false;
Justin Holewinski0497ab12013-03-30 14:29:21 +00001993 case NVPTX::CallArgBeginInst:
1994 case NVPTX::CallArgEndInst0:
1995 case NVPTX::CallArgEndInst1:
1996 case NVPTX::CallArgF32:
1997 case NVPTX::CallArgF64:
1998 case NVPTX::CallArgI16:
1999 case NVPTX::CallArgI32:
2000 case NVPTX::CallArgI32imm:
2001 case NVPTX::CallArgI64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00002002 case NVPTX::CallArgParam:
2003 case NVPTX::CallVoidInst:
2004 case NVPTX::CallVoidInstReg:
2005 case NVPTX::Callseq_End:
Justin Holewinskiae556d32012-05-04 20:18:50 +00002006 case NVPTX::CallVoidInstReg64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00002007 case NVPTX::DeclareParamInst:
2008 case NVPTX::DeclareRetMemInst:
2009 case NVPTX::DeclareRetRegInst:
2010 case NVPTX::DeclareRetScalarInst:
2011 case NVPTX::DeclareScalarParamInst:
2012 case NVPTX::DeclareScalarRegInst:
2013 case NVPTX::StoreParamF32:
2014 case NVPTX::StoreParamF64:
2015 case NVPTX::StoreParamI16:
2016 case NVPTX::StoreParamI32:
2017 case NVPTX::StoreParamI64:
2018 case NVPTX::StoreParamI8:
Justin Holewinski0497ab12013-03-30 14:29:21 +00002019 case NVPTX::StoreRetvalF32:
2020 case NVPTX::StoreRetvalF64:
2021 case NVPTX::StoreRetvalI16:
2022 case NVPTX::StoreRetvalI32:
2023 case NVPTX::StoreRetvalI64:
2024 case NVPTX::StoreRetvalI8:
2025 case NVPTX::LastCallArgF32:
2026 case NVPTX::LastCallArgF64:
2027 case NVPTX::LastCallArgI16:
2028 case NVPTX::LastCallArgI32:
2029 case NVPTX::LastCallArgI32imm:
2030 case NVPTX::LastCallArgI64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00002031 case NVPTX::LastCallArgParam:
2032 case NVPTX::LoadParamMemF32:
2033 case NVPTX::LoadParamMemF64:
2034 case NVPTX::LoadParamMemI16:
2035 case NVPTX::LoadParamMemI32:
2036 case NVPTX::LoadParamMemI64:
2037 case NVPTX::LoadParamMemI8:
Justin Holewinski0497ab12013-03-30 14:29:21 +00002038 case NVPTX::PrototypeInst:
2039 case NVPTX::DBG_VALUE:
Justin Holewinskiae556d32012-05-04 20:18:50 +00002040 return true;
2041 }
2042 return false;
2043}
2044
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002045/// lowerConstantForGV - Return an MCExpr for the given Constant. This is mostly
2046/// a copy from AsmPrinter::lowerConstant, except customized to only handle
2047/// expressions that are representable in PTX and create
2048/// NVPTXGenericMCSymbolRefExpr nodes for addrspacecast instructions.
2049const MCExpr *
2050NVPTXAsmPrinter::lowerConstantForGV(const Constant *CV, bool ProcessingGeneric) {
2051 MCContext &Ctx = OutContext;
2052
2053 if (CV->isNullValue() || isa<UndefValue>(CV))
Jim Grosbach13760bd2015-05-30 01:25:56 +00002054 return MCConstantExpr::create(0, Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002055
2056 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
Jim Grosbach13760bd2015-05-30 01:25:56 +00002057 return MCConstantExpr::create(CI->getZExtValue(), Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002058
2059 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
2060 const MCSymbolRefExpr *Expr =
Jim Grosbach13760bd2015-05-30 01:25:56 +00002061 MCSymbolRefExpr::create(getSymbol(GV), Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002062 if (ProcessingGeneric) {
Jim Grosbach13760bd2015-05-30 01:25:56 +00002063 return NVPTXGenericMCSymbolRefExpr::create(Expr, Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002064 } else {
2065 return Expr;
2066 }
2067 }
2068
2069 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
2070 if (!CE) {
2071 llvm_unreachable("Unknown constant value to lower!");
2072 }
2073
2074 switch (CE->getOpcode()) {
2075 default:
2076 // If the code isn't optimized, there may be outstanding folding
2077 // opportunities. Attempt to fold the expression using DataLayout as a
2078 // last resort before giving up.
David Majnemerd536f232016-07-29 03:27:26 +00002079 if (Constant *C = ConstantFoldConstant(CE, getDataLayout()))
2080 if (C && C != CE)
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002081 return lowerConstantForGV(C, ProcessingGeneric);
2082
2083 // Otherwise report the problem to the user.
2084 {
2085 std::string S;
2086 raw_string_ostream OS(S);
2087 OS << "Unsupported expression in static initializer: ";
2088 CE->printAsOperand(OS, /*PrintType=*/false,
2089 !MF ? nullptr : MF->getFunction()->getParent());
2090 report_fatal_error(OS.str());
2091 }
2092
2093 case Instruction::AddrSpaceCast: {
2094 // Strip the addrspacecast and pass along the operand
2095 PointerType *DstTy = cast<PointerType>(CE->getType());
2096 if (DstTy->getAddressSpace() == 0) {
2097 return lowerConstantForGV(cast<const Constant>(CE->getOperand(0)), true);
2098 }
2099 std::string S;
2100 raw_string_ostream OS(S);
2101 OS << "Unsupported expression in static initializer: ";
2102 CE->printAsOperand(OS, /*PrintType=*/ false,
2103 !MF ? 0 : MF->getFunction()->getParent());
2104 report_fatal_error(OS.str());
2105 }
2106
2107 case Instruction::GetElementPtr: {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00002108 const DataLayout &DL = getDataLayout();
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002109
2110 // Generate a symbolic expression for the byte address
2111 APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
2112 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
2113
2114 const MCExpr *Base = lowerConstantForGV(CE->getOperand(0),
2115 ProcessingGeneric);
2116 if (!OffsetAI)
2117 return Base;
2118
2119 int64_t Offset = OffsetAI.getSExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +00002120 return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002121 Ctx);
2122 }
2123
2124 case Instruction::Trunc:
2125 // We emit the value and depend on the assembler to truncate the generated
2126 // expression properly. This is important for differences between
2127 // blockaddress labels. Since the two labels are in the same function, it
2128 // is reasonable to treat their delta as a 32-bit value.
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002129 LLVM_FALLTHROUGH;
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002130 case Instruction::BitCast:
2131 return lowerConstantForGV(CE->getOperand(0), ProcessingGeneric);
2132
2133 case Instruction::IntToPtr: {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00002134 const DataLayout &DL = getDataLayout();
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002135
2136 // Handle casts to pointers by changing them into casts to the appropriate
2137 // integer type. This promotes constant folding and simplifies this code.
2138 Constant *Op = CE->getOperand(0);
2139 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
2140 false/*ZExt*/);
2141 return lowerConstantForGV(Op, ProcessingGeneric);
2142 }
2143
2144 case Instruction::PtrToInt: {
Mehdi Aminibd7287e2015-07-16 06:11:10 +00002145 const DataLayout &DL = getDataLayout();
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002146
2147 // Support only foldable casts to/from pointers that can be eliminated by
2148 // changing the pointer to the appropriately sized integer type.
2149 Constant *Op = CE->getOperand(0);
2150 Type *Ty = CE->getType();
2151
2152 const MCExpr *OpExpr = lowerConstantForGV(Op, ProcessingGeneric);
2153
2154 // We can emit the pointer value into this slot if the slot is an
2155 // integer slot equal to the size of the pointer.
2156 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
2157 return OpExpr;
2158
2159 // Otherwise the pointer is smaller than the resultant integer, mask off
2160 // the high bits so we are sure to get a proper truncation if the input is
2161 // a constant expr.
2162 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
Jim Grosbach13760bd2015-05-30 01:25:56 +00002163 const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
2164 return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002165 }
2166
2167 // The MC library also has a right-shift operator, but it isn't consistently
2168 // signed or unsigned between different targets.
2169 case Instruction::Add: {
2170 const MCExpr *LHS = lowerConstantForGV(CE->getOperand(0), ProcessingGeneric);
2171 const MCExpr *RHS = lowerConstantForGV(CE->getOperand(1), ProcessingGeneric);
2172 switch (CE->getOpcode()) {
2173 default: llvm_unreachable("Unknown binary operator constant cast expr");
Jim Grosbach13760bd2015-05-30 01:25:56 +00002174 case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002175 }
2176 }
2177 }
2178}
2179
2180// Copy of MCExpr::print customized for NVPTX
2181void NVPTXAsmPrinter::printMCExpr(const MCExpr &Expr, raw_ostream &OS) {
2182 switch (Expr.getKind()) {
2183 case MCExpr::Target:
Matt Arsenault8b643552015-06-09 00:31:39 +00002184 return cast<MCTargetExpr>(&Expr)->printImpl(OS, MAI);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002185 case MCExpr::Constant:
2186 OS << cast<MCConstantExpr>(Expr).getValue();
2187 return;
2188
2189 case MCExpr::SymbolRef: {
2190 const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(Expr);
2191 const MCSymbol &Sym = SRE.getSymbol();
Matt Arsenault8b643552015-06-09 00:31:39 +00002192 Sym.print(OS, MAI);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002193 return;
2194 }
2195
2196 case MCExpr::Unary: {
2197 const MCUnaryExpr &UE = cast<MCUnaryExpr>(Expr);
2198 switch (UE.getOpcode()) {
2199 case MCUnaryExpr::LNot: OS << '!'; break;
2200 case MCUnaryExpr::Minus: OS << '-'; break;
2201 case MCUnaryExpr::Not: OS << '~'; break;
2202 case MCUnaryExpr::Plus: OS << '+'; break;
2203 }
2204 printMCExpr(*UE.getSubExpr(), OS);
2205 return;
2206 }
2207
2208 case MCExpr::Binary: {
2209 const MCBinaryExpr &BE = cast<MCBinaryExpr>(Expr);
2210
2211 // Only print parens around the LHS if it is non-trivial.
2212 if (isa<MCConstantExpr>(BE.getLHS()) || isa<MCSymbolRefExpr>(BE.getLHS()) ||
2213 isa<NVPTXGenericMCSymbolRefExpr>(BE.getLHS())) {
2214 printMCExpr(*BE.getLHS(), OS);
2215 } else {
2216 OS << '(';
2217 printMCExpr(*BE.getLHS(), OS);
2218 OS<< ')';
2219 }
2220
2221 switch (BE.getOpcode()) {
2222 case MCBinaryExpr::Add:
2223 // Print "X-42" instead of "X+-42".
2224 if (const MCConstantExpr *RHSC = dyn_cast<MCConstantExpr>(BE.getRHS())) {
2225 if (RHSC->getValue() < 0) {
2226 OS << RHSC->getValue();
2227 return;
2228 }
2229 }
2230
2231 OS << '+';
2232 break;
2233 default: llvm_unreachable("Unhandled binary operator");
2234 }
2235
2236 // Only print parens around the LHS if it is non-trivial.
2237 if (isa<MCConstantExpr>(BE.getRHS()) || isa<MCSymbolRefExpr>(BE.getRHS())) {
2238 printMCExpr(*BE.getRHS(), OS);
2239 } else {
2240 OS << '(';
2241 printMCExpr(*BE.getRHS(), OS);
2242 OS << ')';
2243 }
2244 return;
2245 }
2246 }
2247
2248 llvm_unreachable("Invalid expression kind!");
2249}
2250
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002251/// PrintAsmOperand - Print out an operand for an inline asm expression.
2252///
2253bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2254 unsigned AsmVariant,
2255 const char *ExtraCode, raw_ostream &O) {
2256 if (ExtraCode && ExtraCode[0]) {
2257 if (ExtraCode[1] != 0)
2258 return true; // Unknown modifier.
2259
2260 switch (ExtraCode[0]) {
2261 default:
2262 // See if this is a generic print operand
2263 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2264 case 'r':
2265 break;
2266 }
2267 }
2268
2269 printOperand(MI, OpNo, O);
2270
2271 return false;
2272}
2273
2274bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2275 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2276 const char *ExtraCode, raw_ostream &O) {
2277 if (ExtraCode && ExtraCode[0])
2278 return true; // Unknown modifier
2279
2280 O << '[';
2281 printMemOperand(MI, OpNo, O);
2282 O << ']';
2283
2284 return false;
2285}
2286
2287void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2288 raw_ostream &O, const char *Modifier) {
2289 const MachineOperand &MO = MI->getOperand(opNum);
2290 switch (MO.getType()) {
2291 case MachineOperand::MO_Register:
2292 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2293 if (MO.getReg() == NVPTX::VRDepot)
2294 O << DEPOTNAME << getFunctionNumber();
2295 else
2296 O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2297 } else {
Justin Holewinski660597d2013-10-11 12:39:36 +00002298 emitVirtualRegister(MO.getReg(), O);
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002299 }
2300 return;
2301
2302 case MachineOperand::MO_Immediate:
2303 if (!Modifier)
2304 O << MO.getImm();
2305 else if (strstr(Modifier, "vec") == Modifier)
2306 printVecModifiedImmediate(MO, Modifier, O);
2307 else
2308 llvm_unreachable(
2309 "Don't know how to handle modifier on immediate operand");
2310 return;
2311
2312 case MachineOperand::MO_FPImmediate:
2313 printFPConstant(MO.getFPImm(), O);
2314 break;
2315
2316 case MachineOperand::MO_GlobalAddress:
Matt Arsenault8b643552015-06-09 00:31:39 +00002317 getSymbol(MO.getGlobal())->print(O, MAI);
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002318 break;
2319
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002320 case MachineOperand::MO_MachineBasicBlock:
Matt Arsenault8b643552015-06-09 00:31:39 +00002321 MO.getMBB()->getSymbol()->print(O, MAI);
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002322 return;
2323
2324 default:
2325 llvm_unreachable("Operand type not supported.");
2326 }
2327}
2328
2329void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2330 raw_ostream &O, const char *Modifier) {
2331 printOperand(MI, opNum, O);
2332
2333 if (Modifier && !strcmp(Modifier, "add")) {
2334 O << ", ";
2335 printOperand(MI, opNum + 1, O);
2336 } else {
2337 if (MI->getOperand(opNum + 1).isImm() &&
2338 MI->getOperand(opNum + 1).getImm() == 0)
2339 return; // don't print ',0' or '+0'
2340 O << "+";
2341 printOperand(MI, opNum + 1, O);
2342 }
2343}
2344
Justin Holewinskiae556d32012-05-04 20:18:50 +00002345void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2346 std::stringstream temp;
Yaron Keren075759a2015-03-30 15:42:36 +00002347 LineReader *reader = this->getReader(filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002348 temp << "\n//";
2349 temp << filename.str();
2350 temp << ":";
2351 temp << line;
2352 temp << " ";
2353 temp << reader->readLine(line);
2354 temp << "\n";
Lang Hames9ff69c82015-04-24 19:11:51 +00002355 this->OutStreamer->EmitRawText(temp.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +00002356}
2357
Benjamin Kramerc321e532016-06-08 19:09:22 +00002358LineReader *NVPTXAsmPrinter::getReader(const std::string &filename) {
Craig Topper062a2ba2014-04-25 05:30:21 +00002359 if (!reader) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00002360 reader = new LineReader(filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002361 }
2362
2363 if (reader->fileName() != filename) {
2364 delete reader;
Justin Holewinski0497ab12013-03-30 14:29:21 +00002365 reader = new LineReader(filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002366 }
2367
2368 return reader;
2369}
2370
Justin Holewinski0497ab12013-03-30 14:29:21 +00002371std::string LineReader::readLine(unsigned lineNum) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00002372 if (lineNum < theCurLine) {
2373 theCurLine = 0;
Justin Holewinski0497ab12013-03-30 14:29:21 +00002374 fstr.seekg(0, std::ios::beg);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002375 }
2376 while (theCurLine < lineNum) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00002377 fstr.getline(buff, 500);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002378 theCurLine++;
2379 }
2380 return buff;
2381}
2382
2383// Force static initialization.
2384extern "C" void LLVMInitializeNVPTXAsmPrinter() {
Mehdi Aminif42454b2016-10-09 23:00:34 +00002385 RegisterAsmPrinter<NVPTXAsmPrinter> X(getTheNVPTXTarget32());
2386 RegisterAsmPrinter<NVPTXAsmPrinter> Y(getTheNVPTXTarget64());
Justin Holewinskiae556d32012-05-04 20:18:50 +00002387}