blob: 2d57e6485eef2a27bcbe1e56cea1ae855f86a65e [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"
48#include "llvm/Support/TimeValue.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000049#include "llvm/Target/TargetLoweringObjectFile.h"
Jingyue Wu0220df02015-02-01 02:27:45 +000050#include "llvm/Transforms/Utils/UnrollLoop.h"
Bill Wendlinge38859d2012-06-28 00:05:13 +000051#include <sstream>
Justin Holewinskiae556d32012-05-04 20:18:50 +000052using namespace llvm;
53
Justin Holewinskiae556d32012-05-04 20:18:50 +000054#define DEPOTNAME "__local_depot"
55
56static cl::opt<bool>
Nadav Rotem7f27e0b2013-10-18 23:38:13 +000057EmitLineNumbers("nvptx-emit-line-numbers", cl::Hidden,
Justin Holewinskiae556d32012-05-04 20:18:50 +000058 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
59 cl::init(true));
60
Benjamin Kramer7ad41002013-10-27 11:31:46 +000061static cl::opt<bool>
Nadav Rotem7f27e0b2013-10-18 23:38:13 +000062InterleaveSrc("nvptx-emit-src", cl::ZeroOrMore, cl::Hidden,
Justin Holewinski0497ab12013-03-30 14:29:21 +000063 cl::desc("NVPTX Specific: Emit source line in ptx file"),
Benjamin Kramer7ad41002013-10-27 11:31:46 +000064 cl::init(false));
Justin Holewinskiae556d32012-05-04 20:18:50 +000065
Justin Holewinski2c5ac702012-11-16 21:03:51 +000066namespace {
67/// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
68/// depends.
Justin Holewinski01f89f02013-05-20 12:13:32 +000069void DiscoverDependentGlobals(const Value *V,
70 DenseSet<const GlobalVariable *> &Globals) {
71 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
Justin Holewinski2c5ac702012-11-16 21:03:51 +000072 Globals.insert(GV);
73 else {
Justin Holewinski01f89f02013-05-20 12:13:32 +000074 if (const User *U = dyn_cast<User>(V)) {
Justin Holewinski2c5ac702012-11-16 21:03:51 +000075 for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
76 DiscoverDependentGlobals(U->getOperand(i), Globals);
77 }
78 }
79 }
80}
Justin Holewinskiae556d32012-05-04 20:18:50 +000081
Justin Holewinski2c5ac702012-11-16 21:03:51 +000082/// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
83/// instances to be emitted, but only after any dependents have been added
84/// first.
Justin Holewinski0497ab12013-03-30 14:29:21 +000085void VisitGlobalVariableForEmission(
Justin Holewinski01f89f02013-05-20 12:13:32 +000086 const GlobalVariable *GV, SmallVectorImpl<const GlobalVariable *> &Order,
87 DenseSet<const GlobalVariable *> &Visited,
88 DenseSet<const GlobalVariable *> &Visiting) {
Justin Holewinski2c5ac702012-11-16 21:03:51 +000089 // Have we already visited this one?
Justin Holewinski0497ab12013-03-30 14:29:21 +000090 if (Visited.count(GV))
91 return;
Justin Holewinski2c5ac702012-11-16 21:03:51 +000092
93 // Do we have a circular dependency?
Benjamin Kramer2c99e412014-10-10 15:32:50 +000094 if (!Visiting.insert(GV).second)
Justin Holewinski2c5ac702012-11-16 21:03:51 +000095 report_fatal_error("Circular dependency found in global variable set");
96
Justin Holewinski2c5ac702012-11-16 21:03:51 +000097 // Make sure we visit all dependents first
Justin Holewinski01f89f02013-05-20 12:13:32 +000098 DenseSet<const GlobalVariable *> Others;
Justin Holewinski2c5ac702012-11-16 21:03:51 +000099 for (unsigned i = 0, e = GV->getNumOperands(); i != e; ++i)
100 DiscoverDependentGlobals(GV->getOperand(i), Others);
Justin Holewinski0497ab12013-03-30 14:29:21 +0000101
Justin Holewinski01f89f02013-05-20 12:13:32 +0000102 for (DenseSet<const GlobalVariable *>::iterator I = Others.begin(),
103 E = Others.end();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000104 I != E; ++I)
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000105 VisitGlobalVariableForEmission(*I, Order, Visited, Visiting);
106
107 // Now we can visit ourself
108 Order.push_back(GV);
109 Visited.insert(GV);
110 Visiting.erase(GV);
111}
112}
Justin Holewinskiae556d32012-05-04 20:18:50 +0000113
Justin Holewinski0497ab12013-03-30 14:29:21 +0000114void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000115 if (!EmitLineNumbers)
116 return;
117 if (ignoreLoc(MI))
118 return;
119
120 DebugLoc curLoc = MI.getDebugLoc();
121
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +0000122 if (!prevDebugLoc && !curLoc)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000123 return;
124
125 if (prevDebugLoc == curLoc)
126 return;
127
128 prevDebugLoc = curLoc;
129
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +0000130 if (!curLoc)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000131 return;
132
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000133 auto *Scope = cast_or_null<DIScope>(curLoc.getScope());
Manman Ren983a16c2013-06-28 05:43:10 +0000134 if (!Scope)
135 return;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000136
Duncan P. N. Exon Smithb273d062015-04-16 01:37:00 +0000137 StringRef fileName(Scope->getFilename());
138 StringRef dirName(Scope->getDirectory());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000139 SmallString<128> FullPathName = dirName;
140 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
141 sys::path::append(FullPathName, fileName);
Yaron Keren075759a2015-03-30 15:42:36 +0000142 fileName = FullPathName;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000143 }
144
Yaron Keren075759a2015-03-30 15:42:36 +0000145 if (filenameMap.find(fileName) == filenameMap.end())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000146 return;
147
Justin Holewinskiae556d32012-05-04 20:18:50 +0000148 // Emit the line from the source file.
Benjamin Kramer7ad41002013-10-27 11:31:46 +0000149 if (InterleaveSrc)
Yaron Keren075759a2015-03-30 15:42:36 +0000150 this->emitSrcInText(fileName, curLoc.getLine());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000151
152 std::stringstream temp;
Yaron Keren075759a2015-03-30 15:42:36 +0000153 temp << "\t.loc " << filenameMap[fileName] << " " << curLoc.getLine()
Justin Holewinski0497ab12013-03-30 14:29:21 +0000154 << " " << curLoc.getCol();
Lang Hames9ff69c82015-04-24 19:11:51 +0000155 OutStreamer->EmitRawText(temp.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000156}
157
158void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
159 SmallString<128> Str;
160 raw_svector_ostream OS(Str);
Eric Christopherbeffc4e2015-02-19 00:08:23 +0000161 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() == NVPTX::CUDA)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000162 emitLineNumberAsDotLoc(*MI);
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000163
164 MCInst Inst;
165 lowerToMCInst(MI, Inst);
Lang Hames9ff69c82015-04-24 19:11:51 +0000166 EmitToStreamer(*OutStreamer, Inst);
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000167}
168
Justin Holewinski30d56a72014-04-09 15:39:15 +0000169// Handle symbol backtracking for targets that do not support image handles
170bool NVPTXAsmPrinter::lowerImageHandleOperand(const MachineInstr *MI,
171 unsigned OpNo, MCOperand &MCOp) {
172 const MachineOperand &MO = MI->getOperand(OpNo);
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000173 const MCInstrDesc &MCID = MI->getDesc();
Justin Holewinski30d56a72014-04-09 15:39:15 +0000174
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000175 if (MCID.TSFlags & NVPTXII::IsTexFlag) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000176 // This is a texture fetch, so operand 4 is a texref and operand 5 is
177 // a samplerref
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000178 if (OpNo == 4 && MO.isImm()) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000179 lowerImageHandleSymbol(MO.getImm(), MCOp);
180 return true;
181 }
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000182 if (OpNo == 5 && MO.isImm() && !(MCID.TSFlags & NVPTXII::IsTexModeUnifiedFlag)) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000183 lowerImageHandleSymbol(MO.getImm(), MCOp);
184 return true;
185 }
186
187 return false;
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000188 } else if (MCID.TSFlags & NVPTXII::IsSuldMask) {
189 unsigned VecSize =
190 1 << (((MCID.TSFlags & NVPTXII::IsSuldMask) >> NVPTXII::IsSuldShift) - 1);
191
192 // For a surface load of vector size N, the Nth operand will be the surfref
193 if (OpNo == VecSize && MO.isImm()) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000194 lowerImageHandleSymbol(MO.getImm(), MCOp);
195 return true;
196 }
197
198 return false;
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000199 } else if (MCID.TSFlags & NVPTXII::IsSustFlag) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000200 // This is a surface store, so operand 0 is a surfref
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000201 if (OpNo == 0 && MO.isImm()) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000202 lowerImageHandleSymbol(MO.getImm(), MCOp);
203 return true;
204 }
205
206 return false;
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000207 } else if (MCID.TSFlags & NVPTXII::IsSurfTexQueryFlag) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000208 // This is a query, so operand 1 is a surfref/texref
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000209 if (OpNo == 1 && MO.isImm()) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000210 lowerImageHandleSymbol(MO.getImm(), MCOp);
211 return true;
212 }
213
214 return false;
215 }
Justin Holewinski9a2350e2014-07-17 11:59:04 +0000216
217 return false;
Justin Holewinski30d56a72014-04-09 15:39:15 +0000218}
219
220void NVPTXAsmPrinter::lowerImageHandleSymbol(unsigned Index, MCOperand &MCOp) {
221 // Ewwww
222 TargetMachine &TM = const_cast<TargetMachine&>(MF->getTarget());
223 NVPTXTargetMachine &nvTM = static_cast<NVPTXTargetMachine&>(TM);
224 const NVPTXMachineFunctionInfo *MFI = MF->getInfo<NVPTXMachineFunctionInfo>();
225 const char *Sym = MFI->getImageHandleSymbol(Index);
226 std::string *SymNamePtr =
227 nvTM.getManagedStrPool()->getManagedString(Sym);
Jim Grosbach6f482002015-05-18 18:43:14 +0000228 MCOp = GetSymbolRef(OutContext.getOrCreateSymbol(
Justin Holewinski30d56a72014-04-09 15:39:15 +0000229 StringRef(SymNamePtr->c_str())));
230}
231
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000232void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
233 OutMI.setOpcode(MI->getOpcode());
Justin Holewinski3d49e5c2013-11-15 12:30:04 +0000234 // Special: Do not mangle symbol operand of CALL_PROTOTYPE
235 if (MI->getOpcode() == NVPTX::CALL_PROTOTYPE) {
236 const MachineOperand &MO = MI->getOperand(0);
Justin Holewinski30d56a72014-04-09 15:39:15 +0000237 OutMI.addOperand(GetSymbolRef(
Jim Grosbach6f482002015-05-18 18:43:14 +0000238 OutContext.getOrCreateSymbol(Twine(MO.getSymbolName()))));
Justin Holewinski3d49e5c2013-11-15 12:30:04 +0000239 return;
240 }
241
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000242 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
243 const MachineOperand &MO = MI->getOperand(i);
244
245 MCOperand MCOp;
Eric Christopher6aad8b12015-02-19 00:08:14 +0000246 if (!nvptxSubtarget->hasImageHandles()) {
Justin Holewinski30d56a72014-04-09 15:39:15 +0000247 if (lowerImageHandleOperand(MI, i, MCOp)) {
248 OutMI.addOperand(MCOp);
249 continue;
250 }
251 }
252
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000253 if (lowerOperand(MO, MCOp))
254 OutMI.addOperand(MCOp);
255 }
256}
257
258bool NVPTXAsmPrinter::lowerOperand(const MachineOperand &MO,
259 MCOperand &MCOp) {
260 switch (MO.getType()) {
261 default: llvm_unreachable("unknown operand type");
262 case MachineOperand::MO_Register:
Jim Grosbache9119e42015-05-13 18:37:00 +0000263 MCOp = MCOperand::createReg(encodeVirtualRegister(MO.getReg()));
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000264 break;
265 case MachineOperand::MO_Immediate:
Jim Grosbache9119e42015-05-13 18:37:00 +0000266 MCOp = MCOperand::createImm(MO.getImm());
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000267 break;
268 case MachineOperand::MO_MachineBasicBlock:
Jim Grosbach13760bd2015-05-30 01:25:56 +0000269 MCOp = MCOperand::createExpr(MCSymbolRefExpr::create(
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000270 MO.getMBB()->getSymbol(), OutContext));
271 break;
272 case MachineOperand::MO_ExternalSymbol:
Justin Holewinski30d56a72014-04-09 15:39:15 +0000273 MCOp = GetSymbolRef(GetExternalSymbolSymbol(MO.getSymbolName()));
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000274 break;
275 case MachineOperand::MO_GlobalAddress:
Justin Holewinski30d56a72014-04-09 15:39:15 +0000276 MCOp = GetSymbolRef(getSymbol(MO.getGlobal()));
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000277 break;
278 case MachineOperand::MO_FPImmediate: {
279 const ConstantFP *Cnt = MO.getFPImm();
280 APFloat Val = Cnt->getValueAPF();
281
282 switch (Cnt->getType()->getTypeID()) {
283 default: report_fatal_error("Unsupported FP type"); break;
284 case Type::FloatTyID:
Jim Grosbache9119e42015-05-13 18:37:00 +0000285 MCOp = MCOperand::createExpr(
Jim Grosbach13760bd2015-05-30 01:25:56 +0000286 NVPTXFloatMCExpr::createConstantFPSingle(Val, OutContext));
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000287 break;
288 case Type::DoubleTyID:
Jim Grosbache9119e42015-05-13 18:37:00 +0000289 MCOp = MCOperand::createExpr(
Jim Grosbach13760bd2015-05-30 01:25:56 +0000290 NVPTXFloatMCExpr::createConstantFPDouble(Val, OutContext));
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000291 break;
292 }
293 break;
294 }
295 }
296 return true;
297}
298
299unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
Justin Holewinski871ec932013-08-06 14:13:31 +0000300 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
301 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000302
Justin Holewinski871ec932013-08-06 14:13:31 +0000303 DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
304 unsigned RegNum = RegMap[Reg];
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000305
Justin Holewinski871ec932013-08-06 14:13:31 +0000306 // Encode the register class in the upper 4 bits
307 // Must be kept in sync with NVPTXInstPrinter::printRegName
308 unsigned Ret = 0;
309 if (RC == &NVPTX::Int1RegsRegClass) {
310 Ret = (1 << 28);
311 } else if (RC == &NVPTX::Int16RegsRegClass) {
312 Ret = (2 << 28);
313 } else if (RC == &NVPTX::Int32RegsRegClass) {
314 Ret = (3 << 28);
315 } else if (RC == &NVPTX::Int64RegsRegClass) {
316 Ret = (4 << 28);
317 } else if (RC == &NVPTX::Float32RegsRegClass) {
318 Ret = (5 << 28);
319 } else if (RC == &NVPTX::Float64RegsRegClass) {
320 Ret = (6 << 28);
321 } else {
322 report_fatal_error("Bad register class");
323 }
324
325 // Insert the vreg number
326 Ret |= (RegNum & 0x0FFFFFFF);
327 return Ret;
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000328 } else {
Justin Holewinski871ec932013-08-06 14:13:31 +0000329 // Some special-use registers are actually physical registers.
330 // Encode this as the register class ID of 0 and the real register ID.
331 return Reg & 0x0FFFFFFF;
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000332 }
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000333}
334
Justin Holewinski30d56a72014-04-09 15:39:15 +0000335MCOperand NVPTXAsmPrinter::GetSymbolRef(const MCSymbol *Symbol) {
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000336 const MCExpr *Expr;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000337 Expr = MCSymbolRefExpr::create(Symbol, MCSymbolRefExpr::VK_None,
Justin Holewinski8b24e1e2013-08-06 23:06:42 +0000338 OutContext);
Jim Grosbache9119e42015-05-13 18:37:00 +0000339 return MCOperand::createExpr(Expr);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000340}
341
Justin Holewinski0497ab12013-03-30 14:29:21 +0000342void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
Eric Christopher8b770652015-01-26 19:03:15 +0000343 const DataLayout *TD = TM.getDataLayout();
Eric Christopher6aad8b12015-02-19 00:08:14 +0000344 const TargetLowering *TLI = nvptxSubtarget->getTargetLowering();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000345
346 Type *Ty = F->getReturnType();
347
Eric Christopher6aad8b12015-02-19 00:08:14 +0000348 bool isABI = (nvptxSubtarget->getSmVersion() >= 20);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000349
350 if (Ty->getTypeID() == Type::VoidTyID)
351 return;
352
353 O << " (";
354
355 if (isABI) {
Rafael Espindola08013342013-12-07 19:34:20 +0000356 if (Ty->isFloatingPointTy() || Ty->isIntegerTy()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000357 unsigned size = 0;
358 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
359 size = ITy->getBitWidth();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000360 if (size < 32)
361 size = 32;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000362 } else {
Justin Holewinski0497ab12013-03-30 14:29:21 +0000363 assert(Ty->isFloatingPointTy() && "Floating point type expected here");
Justin Holewinskiae556d32012-05-04 20:18:50 +0000364 size = Ty->getPrimitiveSizeInBits();
365 }
366
367 O << ".param .b" << size << " func_retval0";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000368 } else if (isa<PointerType>(Ty)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000369 O << ".param .b" << TLI->getPointerTy().getSizeInBits()
Justin Holewinski0497ab12013-03-30 14:29:21 +0000370 << " func_retval0";
Craig Topperd3c02f12015-01-05 10:15:49 +0000371 } else if ((Ty->getTypeID() == Type::StructTyID) || isa<VectorType>(Ty)) {
372 unsigned totalsz = TD->getTypeAllocSize(Ty);
373 unsigned retAlignment = 0;
374 if (!llvm::getAlign(*F, 0, retAlignment))
375 retAlignment = TD->getABITypeAlignment(Ty);
376 O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
377 << "]";
378 } else
379 llvm_unreachable("Unknown return type");
Justin Holewinskiae556d32012-05-04 20:18:50 +0000380 } else {
381 SmallVector<EVT, 16> vtparts;
382 ComputeValueVTs(*TLI, Ty, vtparts);
383 unsigned idx = 0;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000384 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000385 unsigned elems = 1;
386 EVT elemtype = vtparts[i];
387 if (vtparts[i].isVector()) {
388 elems = vtparts[i].getVectorNumElements();
389 elemtype = vtparts[i].getVectorElementType();
390 }
391
Justin Holewinski0497ab12013-03-30 14:29:21 +0000392 for (unsigned j = 0, je = elems; j != je; ++j) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000393 unsigned sz = elemtype.getSizeInBits();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000394 if (elemtype.isInteger() && (sz < 32))
395 sz = 32;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000396 O << ".reg .b" << sz << " func_retval" << idx;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000397 if (j < je - 1)
398 O << ", ";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000399 ++idx;
400 }
Justin Holewinski0497ab12013-03-30 14:29:21 +0000401 if (i < e - 1)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000402 O << ", ";
403 }
404 }
405 O << ") ";
406 return;
407}
408
409void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
410 raw_ostream &O) {
411 const Function *F = MF.getFunction();
412 printReturnValStr(F, O);
413}
414
Jingyue Wu0220df02015-02-01 02:27:45 +0000415// Return true if MBB is the header of a loop marked with
416// llvm.loop.unroll.disable.
Jingyue Wu5bbcdaa2015-02-03 17:57:38 +0000417// TODO: consider "#pragma unroll 1" which is equivalent to "#pragma nounroll".
Jingyue Wu0220df02015-02-01 02:27:45 +0000418bool NVPTXAsmPrinter::isLoopHeaderOfNoUnroll(
419 const MachineBasicBlock &MBB) const {
420 MachineLoopInfo &LI = getAnalysis<MachineLoopInfo>();
Jingyue Wu0220df02015-02-01 02:27:45 +0000421 // We insert .pragma "nounroll" only to the loop header.
Benjamin Kramerdb220db2015-06-02 15:28:27 +0000422 if (!LI.isLoopHeader(&MBB))
Jingyue Wu0220df02015-02-01 02:27:45 +0000423 return false;
424
425 // llvm.loop.unroll.disable is marked on the back edges of a loop. Therefore,
426 // we iterate through each back edge of the loop with header MBB, and check
427 // whether its metadata contains llvm.loop.unroll.disable.
428 for (auto I = MBB.pred_begin(); I != MBB.pred_end(); ++I) {
429 const MachineBasicBlock *PMBB = *I;
430 if (LI.getLoopFor(PMBB) != LI.getLoopFor(&MBB)) {
431 // Edges from other loops to MBB are not back edges.
432 continue;
433 }
434 if (const BasicBlock *PBB = PMBB->getBasicBlock()) {
Jingyue Wu49a766e2015-02-02 20:41:11 +0000435 if (MDNode *LoopID = PBB->getTerminator()->getMetadata("llvm.loop")) {
Jingyue Wu0220df02015-02-01 02:27:45 +0000436 if (GetUnrollMetadata(LoopID, "llvm.loop.unroll.disable"))
437 return true;
438 }
439 }
440 }
441 return false;
442}
443
444void NVPTXAsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
445 AsmPrinter::EmitBasicBlockStart(MBB);
446 if (isLoopHeaderOfNoUnroll(MBB))
Lang Hames9ff69c82015-04-24 19:11:51 +0000447 OutStreamer->EmitRawText(StringRef("\t.pragma \"nounroll\";\n"));
Jingyue Wu0220df02015-02-01 02:27:45 +0000448}
449
Justin Holewinskiae556d32012-05-04 20:18:50 +0000450void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
451 SmallString<128> Str;
452 raw_svector_ostream O(Str);
453
Justin Holewinski01f89f02013-05-20 12:13:32 +0000454 if (!GlobalsEmitted) {
455 emitGlobals(*MF->getFunction()->getParent());
456 GlobalsEmitted = true;
457 }
458
Justin Holewinskiae556d32012-05-04 20:18:50 +0000459 // Set up
460 MRI = &MF->getRegInfo();
461 F = MF->getFunction();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000462 emitLinkageDirective(F, O);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000463 if (llvm::isKernelFunction(*F))
464 O << ".entry ";
465 else {
466 O << ".func ";
467 printReturnValStr(*MF, O);
468 }
469
470 O << *CurrentFnSym;
471
472 emitFunctionParamList(*MF, O);
473
474 if (llvm::isKernelFunction(*F))
475 emitKernelFunctionDirectives(*F, O);
476
Lang Hames9ff69c82015-04-24 19:11:51 +0000477 OutStreamer->EmitRawText(O.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000478
479 prevDebugLoc = DebugLoc();
480}
481
482void NVPTXAsmPrinter::EmitFunctionBodyStart() {
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +0000483 VRegMapping.clear();
Lang Hames9ff69c82015-04-24 19:11:51 +0000484 OutStreamer->EmitRawText(StringRef("{\n"));
Justin Holewinskiae556d32012-05-04 20:18:50 +0000485 setAndEmitFunctionVirtualRegisters(*MF);
486
487 SmallString<128> Str;
488 raw_svector_ostream O(Str);
489 emitDemotedVars(MF->getFunction(), O);
Lang Hames9ff69c82015-04-24 19:11:51 +0000490 OutStreamer->EmitRawText(O.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000491}
492
493void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
Lang Hames9ff69c82015-04-24 19:11:51 +0000494 OutStreamer->EmitRawText(StringRef("}\n"));
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +0000495 VRegMapping.clear();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000496}
497
Justin Holewinski660597d2013-10-11 12:39:36 +0000498void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
499 unsigned RegNo = MI->getOperand(0).getReg();
Andrew Kaylor5c73e1f2015-03-24 23:37:10 +0000500 if (TargetRegisterInfo::isVirtualRegister(RegNo)) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000501 OutStreamer->AddComment(Twine("implicit-def: ") +
502 getVirtualRegisterName(RegNo));
Justin Holewinski660597d2013-10-11 12:39:36 +0000503 } else {
Lang Hames9ff69c82015-04-24 19:11:51 +0000504 OutStreamer->AddComment(Twine("implicit-def: ") +
505 nvptxSubtarget->getRegisterInfo()->getName(RegNo));
Justin Holewinski660597d2013-10-11 12:39:36 +0000506 }
Lang Hames9ff69c82015-04-24 19:11:51 +0000507 OutStreamer->AddBlankLine();
Justin Holewinski660597d2013-10-11 12:39:36 +0000508}
509
Justin Holewinski0497ab12013-03-30 14:29:21 +0000510void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
511 raw_ostream &O) const {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000512 // If the NVVM IR has some of reqntid* specified, then output
513 // the reqntid directive, and set the unspecified ones to 1.
514 // If none of reqntid* is specified, don't output reqntid directive.
515 unsigned reqntidx, reqntidy, reqntidz;
516 bool specified = false;
Eli Bendersky3e840192015-03-23 16:26:23 +0000517 if (!llvm::getReqNTIDx(F, reqntidx))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000518 reqntidx = 1;
519 else
520 specified = true;
Eli Bendersky3e840192015-03-23 16:26:23 +0000521 if (!llvm::getReqNTIDy(F, reqntidy))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000522 reqntidy = 1;
523 else
524 specified = true;
Eli Bendersky3e840192015-03-23 16:26:23 +0000525 if (!llvm::getReqNTIDz(F, reqntidz))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000526 reqntidz = 1;
527 else
528 specified = true;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000529
530 if (specified)
Justin Holewinski0497ab12013-03-30 14:29:21 +0000531 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
532 << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000533
534 // If the NVVM IR has some of maxntid* specified, then output
535 // the maxntid directive, and set the unspecified ones to 1.
536 // If none of maxntid* is specified, don't output maxntid directive.
537 unsigned maxntidx, maxntidy, maxntidz;
538 specified = false;
Eli Bendersky3e840192015-03-23 16:26:23 +0000539 if (!llvm::getMaxNTIDx(F, maxntidx))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000540 maxntidx = 1;
541 else
542 specified = true;
Eli Bendersky3e840192015-03-23 16:26:23 +0000543 if (!llvm::getMaxNTIDy(F, maxntidy))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000544 maxntidy = 1;
545 else
546 specified = true;
Eli Bendersky3e840192015-03-23 16:26:23 +0000547 if (!llvm::getMaxNTIDz(F, maxntidz))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000548 maxntidz = 1;
549 else
550 specified = true;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000551
552 if (specified)
Justin Holewinski0497ab12013-03-30 14:29:21 +0000553 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
554 << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000555
556 unsigned mincta;
557 if (llvm::getMinCTASm(F, mincta))
558 O << ".minnctapersm " << mincta << "\n";
559}
560
Justin Holewinski660597d2013-10-11 12:39:36 +0000561std::string
562NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
563 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000564
Justin Holewinski660597d2013-10-11 12:39:36 +0000565 std::string Name;
566 raw_string_ostream NameStr(Name);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000567
Justin Holewinski660597d2013-10-11 12:39:36 +0000568 VRegRCMap::const_iterator I = VRegMapping.find(RC);
569 assert(I != VRegMapping.end() && "Bad register class");
570 const DenseMap<unsigned, unsigned> &RegMap = I->second;
571
572 VRegMap::const_iterator VI = RegMap.find(Reg);
573 assert(VI != RegMap.end() && "Bad virtual register");
574 unsigned MappedVR = VI->second;
575
576 NameStr << getNVPTXRegClassStr(RC) << MappedVR;
577
578 NameStr.flush();
579 return Name;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000580}
581
Justin Holewinski660597d2013-10-11 12:39:36 +0000582void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
Justin Holewinski0497ab12013-03-30 14:29:21 +0000583 raw_ostream &O) {
Justin Holewinski660597d2013-10-11 12:39:36 +0000584 O << getVirtualRegisterName(vr);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000585}
586
Justin Holewinski0497ab12013-03-30 14:29:21 +0000587void NVPTXAsmPrinter::printVecModifiedImmediate(
588 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
589 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
590 int Imm = (int) MO.getImm();
591 if (0 == strcmp(Modifier, "vecelem"))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000592 O << "_" << vecelem[Imm];
Justin Holewinski0497ab12013-03-30 14:29:21 +0000593 else if (0 == strcmp(Modifier, "vecv4comm1")) {
594 if ((Imm < 0) || (Imm > 3))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000595 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000596 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
597 if ((Imm < 4) || (Imm > 7))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000598 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000599 } else if (0 == strcmp(Modifier, "vecv4pos")) {
600 if (Imm < 0)
601 Imm = 0;
602 O << "_" << vecelem[Imm % 4];
603 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
604 if ((Imm < 0) || (Imm > 1))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000605 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000606 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
607 if ((Imm < 2) || (Imm > 3))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000608 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000609 } else if (0 == strcmp(Modifier, "vecv2pos")) {
610 if (Imm < 0)
611 Imm = 0;
612 O << "_" << vecelem[Imm % 2];
613 } else
Craig Topperbdf39a42012-05-24 07:02:50 +0000614 llvm_unreachable("Unknown Modifier on immediate operand");
Justin Holewinskiae556d32012-05-04 20:18:50 +0000615}
616
Justin Holewinskidc5e3b62013-06-28 17:58:04 +0000617
618
Justin Holewinski0497ab12013-03-30 14:29:21 +0000619void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000620
Justin Holewinski0497ab12013-03-30 14:29:21 +0000621 emitLinkageDirective(F, O);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000622 if (llvm::isKernelFunction(*F))
623 O << ".entry ";
624 else
625 O << ".func ";
626 printReturnValStr(F, O);
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +0000627 O << *getSymbol(F) << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000628 emitFunctionParamList(F, O);
629 O << ";\n";
630}
631
Justin Holewinski0497ab12013-03-30 14:29:21 +0000632static bool usedInGlobalVarDef(const Constant *C) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000633 if (!C)
634 return false;
635
636 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
Yaron Keren075759a2015-03-30 15:42:36 +0000637 if (GV->getName() == "llvm.used")
Justin Holewinskiae556d32012-05-04 20:18:50 +0000638 return false;
639 return true;
640 }
641
Chandler Carruthcdf47882014-03-09 03:16:01 +0000642 for (const User *U : C->users())
643 if (const Constant *C = dyn_cast<Constant>(U))
644 if (usedInGlobalVarDef(C))
645 return true;
646
Justin Holewinskiae556d32012-05-04 20:18:50 +0000647 return false;
648}
649
Justin Holewinski0497ab12013-03-30 14:29:21 +0000650static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000651 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
Yaron Keren075759a2015-03-30 15:42:36 +0000652 if (othergv->getName() == "llvm.used")
Justin Holewinskiae556d32012-05-04 20:18:50 +0000653 return true;
654 }
655
656 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
657 if (instr->getParent() && instr->getParent()->getParent()) {
658 const Function *curFunc = instr->getParent()->getParent();
659 if (oneFunc && (curFunc != oneFunc))
660 return false;
661 oneFunc = curFunc;
662 return true;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000663 } else
Justin Holewinskiae556d32012-05-04 20:18:50 +0000664 return false;
665 }
666
Chandler Carruthcdf47882014-03-09 03:16:01 +0000667 for (const User *UU : U->users())
Eli Bendersky3e840192015-03-23 16:26:23 +0000668 if (!usedInOneFunc(UU, oneFunc))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000669 return false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000670
Justin Holewinskiae556d32012-05-04 20:18:50 +0000671 return true;
672}
673
674/* Find out if a global variable can be demoted to local scope.
675 * Currently, this is valid for CUDA shared variables, which have local
676 * scope and global lifetime. So the conditions to check are :
677 * 1. Is the global variable in shared address space?
678 * 2. Does it have internal linkage?
679 * 3. Is the global variable referenced only in one function?
680 */
681static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
Eli Bendersky3e840192015-03-23 16:26:23 +0000682 if (!gv->hasInternalLinkage())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000683 return false;
684 const PointerType *Pty = gv->getType();
685 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
686 return false;
687
Craig Topper062a2ba2014-04-25 05:30:21 +0000688 const Function *oneFunc = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000689
690 bool flag = usedInOneFunc(gv, oneFunc);
Eli Bendersky3e840192015-03-23 16:26:23 +0000691 if (!flag)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000692 return false;
693 if (!oneFunc)
694 return false;
695 f = oneFunc;
696 return true;
697}
698
699static bool useFuncSeen(const Constant *C,
700 llvm::DenseMap<const Function *, bool> &seenMap) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000701 for (const User *U : C->users()) {
702 if (const Constant *cu = dyn_cast<Constant>(U)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000703 if (useFuncSeen(cu, seenMap))
704 return true;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000705 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000706 const BasicBlock *bb = I->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000707 if (!bb)
708 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000709 const Function *caller = bb->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000710 if (!caller)
711 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000712 if (seenMap.find(caller) != seenMap.end())
713 return true;
714 }
715 }
716 return false;
717}
718
Justin Holewinski01f89f02013-05-20 12:13:32 +0000719void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000720 llvm::DenseMap<const Function *, bool> seenMap;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000721 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000722 const Function *F = FI;
723
724 if (F->isDeclaration()) {
725 if (F->use_empty())
726 continue;
727 if (F->getIntrinsicID())
728 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000729 emitDeclaration(F, O);
730 continue;
731 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000732 for (const User *U : F->users()) {
733 if (const Constant *C = dyn_cast<Constant>(U)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000734 if (usedInGlobalVarDef(C)) {
735 // The use is in the initialization of a global variable
736 // that is a function pointer, so print a declaration
737 // for the original function
Justin Holewinskiae556d32012-05-04 20:18:50 +0000738 emitDeclaration(F, O);
739 break;
740 }
741 // Emit a declaration of this function if the function that
742 // uses this constant expr has already been seen.
743 if (useFuncSeen(C, seenMap)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000744 emitDeclaration(F, O);
745 break;
746 }
747 }
748
Chandler Carruthcdf47882014-03-09 03:16:01 +0000749 if (!isa<Instruction>(U))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000750 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000751 const Instruction *instr = cast<Instruction>(U);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000752 const BasicBlock *bb = instr->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000753 if (!bb)
754 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000755 const Function *caller = bb->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000756 if (!caller)
757 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000758
759 // If a caller has already been seen, then the caller is
760 // appearing in the module before the callee. so print out
761 // a declaration for the callee.
762 if (seenMap.find(caller) != seenMap.end()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000763 emitDeclaration(F, O);
764 break;
765 }
766 }
767 seenMap[F] = true;
768 }
769}
770
771void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
772 DebugInfoFinder DbgFinder;
773 DbgFinder.processModule(M);
774
Justin Holewinski0497ab12013-03-30 14:29:21 +0000775 unsigned i = 1;
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000776 for (const DICompileUnit *DIUnit : DbgFinder.compile_units()) {
Duncan P. N. Exon Smith35ef22c2015-04-15 23:19:27 +0000777 StringRef Filename = DIUnit->getFilename();
778 StringRef Dirname = DIUnit->getDirectory();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000779 SmallString<128> FullPathName = Dirname;
780 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
781 sys::path::append(FullPathName, Filename);
Yaron Keren075759a2015-03-30 15:42:36 +0000782 Filename = FullPathName;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000783 }
Yaron Keren075759a2015-03-30 15:42:36 +0000784 if (filenameMap.find(Filename) != filenameMap.end())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000785 continue;
Yaron Keren075759a2015-03-30 15:42:36 +0000786 filenameMap[Filename] = i;
Lang Hames9ff69c82015-04-24 19:11:51 +0000787 OutStreamer->EmitDwarfFileDirective(i, "", Filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000788 ++i;
789 }
790
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000791 for (DISubprogram *SP : DbgFinder.subprograms()) {
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000792 StringRef Filename = SP->getFilename();
793 StringRef Dirname = SP->getDirectory();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000794 SmallString<128> FullPathName = Dirname;
795 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
796 sys::path::append(FullPathName, Filename);
Yaron Keren075759a2015-03-30 15:42:36 +0000797 Filename = FullPathName;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000798 }
Yaron Keren075759a2015-03-30 15:42:36 +0000799 if (filenameMap.find(Filename) != filenameMap.end())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000800 continue;
Yaron Keren075759a2015-03-30 15:42:36 +0000801 filenameMap[Filename] = i;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000802 ++i;
803 }
804}
805
Justin Holewinski0497ab12013-03-30 14:29:21 +0000806bool NVPTXAsmPrinter::doInitialization(Module &M) {
Eric Christopher6aad8b12015-02-19 00:08:14 +0000807 // Construct a default subtarget off of the TargetMachine defaults. The
808 // rest of NVPTX isn't friendly to change subtargets per function and
809 // so the default TargetMachine will have all of the options.
810 StringRef TT = TM.getTargetTriple();
811 StringRef CPU = TM.getTargetCPU();
812 StringRef FS = TM.getTargetFeatureString();
813 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
Eric Christopher02389e32015-02-19 00:08:27 +0000814 const NVPTXSubtarget STI(TT, CPU, FS, NTM);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000815
816 SmallString<128> Str1;
817 raw_svector_ostream OS1(Str1);
818
819 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
820 MMI->AnalyzeModule(M);
821
822 // We need to call the parent's one explicitly.
823 //bool Result = AsmPrinter::doInitialization(M);
824
825 // Initialize TargetLoweringObjectFile.
Justin Holewinski0497ab12013-03-30 14:29:21 +0000826 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
827 .Initialize(OutContext, TM);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000828
Eric Christopher8b770652015-01-26 19:03:15 +0000829 Mang = new Mangler(TM.getDataLayout());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000830
831 // Emit header before any dwarf directives are emitted below.
Eric Christopher6aad8b12015-02-19 00:08:14 +0000832 emitHeader(M, OS1, STI);
Lang Hames9ff69c82015-04-24 19:11:51 +0000833 OutStreamer->EmitRawText(OS1.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000834
Justin Holewinskiae556d32012-05-04 20:18:50 +0000835 // Already commented out
836 //bool Result = AsmPrinter::doInitialization(M);
837
Justin Holewinskid2bbdf02013-07-01 13:00:14 +0000838 // Emit module-level inline asm if it exists.
839 if (!M.getModuleInlineAsm().empty()) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000840 OutStreamer->AddComment("Start of file scope inline assembly");
841 OutStreamer->AddBlankLine();
842 OutStreamer->EmitRawText(StringRef(M.getModuleInlineAsm()));
843 OutStreamer->AddBlankLine();
844 OutStreamer->AddComment("End of file scope inline assembly");
845 OutStreamer->AddBlankLine();
Justin Holewinskid2bbdf02013-07-01 13:00:14 +0000846 }
847
Eric Christopher6aad8b12015-02-19 00:08:14 +0000848 // If we're not NVCL we're CUDA, go ahead and emit filenames.
849 if (Triple(TM.getTargetTriple()).getOS() != Triple::NVCL)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000850 recordAndEmitFilenames(M);
851
Justin Holewinski01f89f02013-05-20 12:13:32 +0000852 GlobalsEmitted = false;
853
854 return false; // success
855}
856
857void NVPTXAsmPrinter::emitGlobals(const Module &M) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000858 SmallString<128> Str2;
859 raw_svector_ostream OS2(Str2);
860
861 emitDeclarations(M, OS2);
862
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000863 // As ptxas does not support forward references of globals, we need to first
864 // sort the list of module-level globals in def-use order. We visit each
865 // global variable in order, and ensure that we emit it *after* its dependent
866 // globals. We use a little extra memory maintaining both a set and a list to
867 // have fast searches while maintaining a strict ordering.
Justin Holewinski01f89f02013-05-20 12:13:32 +0000868 SmallVector<const GlobalVariable *, 8> Globals;
869 DenseSet<const GlobalVariable *> GVVisited;
870 DenseSet<const GlobalVariable *> GVVisiting;
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000871
872 // Visit each global variable, in order
Justin Holewinski01f89f02013-05-20 12:13:32 +0000873 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
874 I != E; ++I)
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000875 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
876
Justin Holewinski0497ab12013-03-30 14:29:21 +0000877 assert(GVVisited.size() == M.getGlobalList().size() &&
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000878 "Missed a global variable");
879 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
880
881 // Print out module-level global variables in proper order
882 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
883 printModuleLevelGV(Globals[i], OS2);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000884
885 OS2 << '\n';
886
Lang Hames9ff69c82015-04-24 19:11:51 +0000887 OutStreamer->EmitRawText(OS2.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000888}
889
Eric Christopher6aad8b12015-02-19 00:08:14 +0000890void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O,
891 const NVPTXSubtarget &STI) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000892 O << "//\n";
893 O << "// Generated by LLVM NVPTX Back-End\n";
894 O << "//\n";
895 O << "\n";
896
Eric Christopher6aad8b12015-02-19 00:08:14 +0000897 unsigned PTXVersion = STI.getPTXVersion();
Justin Holewinski1812ee92012-11-12 03:16:43 +0000898 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000899
900 O << ".target ";
Eric Christopher6aad8b12015-02-19 00:08:14 +0000901 O << STI.getTargetName();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000902
Eric Christopherca929f22015-02-19 00:22:47 +0000903 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
904 if (NTM.getDrvInterface() == NVPTX::NVCL)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000905 O << ", texmode_independent";
Eric Christopherbeffc4e2015-02-19 00:08:23 +0000906 else {
Eric Christopher6aad8b12015-02-19 00:08:14 +0000907 if (!STI.hasDouble())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000908 O << ", map_f64_to_f32";
909 }
910
911 if (MAI->doesSupportDebugInformation())
912 O << ", debug";
913
914 O << "\n";
915
916 O << ".address_size ";
Eric Christopherca929f22015-02-19 00:22:47 +0000917 if (NTM.is64Bit())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000918 O << "64";
919 else
920 O << "32";
921 O << "\n";
922
923 O << "\n";
924}
925
926bool NVPTXAsmPrinter::doFinalization(Module &M) {
Justin Holewinski01f89f02013-05-20 12:13:32 +0000927 // If we did not emit any functions, then the global declarations have not
928 // yet been emitted.
929 if (!GlobalsEmitted) {
930 emitGlobals(M);
931 GlobalsEmitted = true;
932 }
933
Justin Holewinskiae556d32012-05-04 20:18:50 +0000934 // XXX Temproarily remove global variables so that doFinalization() will not
935 // emit them again (global variables are emitted at beginning).
936
937 Module::GlobalListType &global_list = M.getGlobalList();
938 int i, n = global_list.size();
Dylan Noblesmithc9e2a272014-08-26 02:03:35 +0000939 GlobalVariable **gv_array = new GlobalVariable *[n];
Justin Holewinskiae556d32012-05-04 20:18:50 +0000940
941 // first, back-up GlobalVariable in gv_array
942 i = 0;
943 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000944 I != E; ++I)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000945 gv_array[i++] = &*I;
946
947 // second, empty global_list
948 while (!global_list.empty())
949 global_list.remove(global_list.begin());
950
951 // call doFinalization
952 bool ret = AsmPrinter::doFinalization(M);
953
954 // now we restore global variables
Justin Holewinski0497ab12013-03-30 14:29:21 +0000955 for (i = 0; i < n; i++)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000956 global_list.insert(global_list.end(), gv_array[i]);
957
Justin Holewinski59596952014-04-09 15:38:52 +0000958 clearAnnotationCache(&M);
Dylan Noblesmithc9e2a272014-08-26 02:03:35 +0000959
960 delete[] gv_array;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000961 return ret;
962
Justin Holewinskiae556d32012-05-04 20:18:50 +0000963 //bool Result = AsmPrinter::doFinalization(M);
964 // Instead of calling the parents doFinalization, we may
965 // clone parents doFinalization and customize here.
966 // Currently, we if NVISA out the EmitGlobals() in
967 // parent's doFinalization, which is too intrusive.
968 //
969 // Same for the doInitialization.
970 //return Result;
971}
972
973// This function emits appropriate linkage directives for
974// functions and global variables.
975//
976// extern function declaration -> .extern
977// extern function definition -> .visible
978// external global variable with init -> .visible
979// external without init -> .extern
980// appending -> not allowed, assert.
Justin Holewinski7d5bf662014-06-27 18:35:10 +0000981// for any linkage other than
982// internal, private, linker_private,
983// linker_private_weak, linker_private_weak_def_auto,
984// we emit -> .weak.
Justin Holewinskiae556d32012-05-04 20:18:50 +0000985
Justin Holewinski0497ab12013-03-30 14:29:21 +0000986void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
987 raw_ostream &O) {
Eric Christopherbeffc4e2015-02-19 00:08:23 +0000988 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() == NVPTX::CUDA) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000989 if (V->hasExternalLinkage()) {
990 if (isa<GlobalVariable>(V)) {
991 const GlobalVariable *GVar = cast<GlobalVariable>(V);
992 if (GVar) {
993 if (GVar->hasInitializer())
994 O << ".visible ";
995 else
996 O << ".extern ";
997 }
998 } else if (V->isDeclaration())
999 O << ".extern ";
1000 else
1001 O << ".visible ";
1002 } else if (V->hasAppendingLinkage()) {
1003 std::string msg;
1004 msg.append("Error: ");
1005 msg.append("Symbol ");
1006 if (V->hasName())
Yaron Keren075759a2015-03-30 15:42:36 +00001007 msg.append(V->getName());
Justin Holewinskiae556d32012-05-04 20:18:50 +00001008 msg.append("has unsupported appending linkage type");
1009 llvm_unreachable(msg.c_str());
Justin Holewinski7d5bf662014-06-27 18:35:10 +00001010 } else if (!V->hasInternalLinkage() &&
1011 !V->hasPrivateLinkage()) {
1012 O << ".weak ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001013 }
1014 }
1015}
1016
Justin Holewinski01f89f02013-05-20 12:13:32 +00001017void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1018 raw_ostream &O,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001019 bool processDemoted) {
1020
1021 // Skip meta data
1022 if (GVar->hasSection()) {
Rafael Espindola64c1e182014-06-03 02:41:57 +00001023 if (GVar->getSection() == StringRef("llvm.metadata"))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001024 return;
1025 }
1026
Justin Holewinski73cb5de2014-06-27 18:35:53 +00001027 // Skip LLVM intrinsic global variables
1028 if (GVar->getName().startswith("llvm.") ||
1029 GVar->getName().startswith("nvvm."))
1030 return;
1031
Eric Christopher8b770652015-01-26 19:03:15 +00001032 const DataLayout *TD = TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001033
1034 // GlobalVariables are always constant pointers themselves.
1035 const PointerType *PTy = GVar->getType();
1036 Type *ETy = PTy->getElementType();
1037
1038 if (GVar->hasExternalLinkage()) {
1039 if (GVar->hasInitializer())
1040 O << ".visible ";
1041 else
1042 O << ".extern ";
Justin Holewinskid73767a2014-06-27 18:35:56 +00001043 } else if (GVar->hasLinkOnceLinkage() || GVar->hasWeakLinkage() ||
1044 GVar->hasAvailableExternallyLinkage() ||
1045 GVar->hasCommonLinkage()) {
1046 O << ".weak ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001047 }
1048
1049 if (llvm::isTexture(*GVar)) {
1050 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1051 return;
1052 }
1053
1054 if (llvm::isSurface(*GVar)) {
1055 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1056 return;
1057 }
1058
1059 if (GVar->isDeclaration()) {
1060 // (extern) declarations, no definition or initializer
1061 // Currently the only known declaration is for an automatic __local
1062 // (.shared) promoted to global.
1063 emitPTXGlobalVariable(GVar, O);
1064 O << ";\n";
1065 return;
1066 }
1067
1068 if (llvm::isSampler(*GVar)) {
1069 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1070
Craig Topper062a2ba2014-04-25 05:30:21 +00001071 const Constant *Initializer = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001072 if (GVar->hasInitializer())
1073 Initializer = GVar->getInitializer();
Craig Topper062a2ba2014-04-25 05:30:21 +00001074 const ConstantInt *CI = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001075 if (Initializer)
1076 CI = dyn_cast<ConstantInt>(Initializer);
1077 if (CI) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001078 unsigned sample = CI->getZExtValue();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001079
1080 O << " = { ";
1081
Justin Holewinski0497ab12013-03-30 14:29:21 +00001082 for (int i = 0,
1083 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1084 i < 3; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001085 O << "addr_mode_" << i << " = ";
1086 switch (addr) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001087 case 0:
1088 O << "wrap";
1089 break;
1090 case 1:
1091 O << "clamp_to_border";
1092 break;
1093 case 2:
1094 O << "clamp_to_edge";
1095 break;
1096 case 3:
1097 O << "wrap";
1098 break;
1099 case 4:
1100 O << "mirror";
1101 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001102 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001103 O << ", ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001104 }
1105 O << "filter_mode = ";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001106 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1107 case 0:
1108 O << "nearest";
1109 break;
1110 case 1:
1111 O << "linear";
1112 break;
1113 case 2:
Craig Topper2a30d782014-06-18 05:05:13 +00001114 llvm_unreachable("Anisotropic filtering is not supported");
Justin Holewinski0497ab12013-03-30 14:29:21 +00001115 default:
1116 O << "nearest";
1117 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001118 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001119 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001120 O << ", force_unnormalized_coords = 1";
1121 }
1122 O << " }";
1123 }
1124
1125 O << ";\n";
1126 return;
1127 }
1128
1129 if (GVar->hasPrivateLinkage()) {
1130
1131 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1132 return;
1133
1134 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1135 if (!strncmp(GVar->getName().data(), "filename", 8))
1136 return;
1137 if (GVar->use_empty())
1138 return;
1139 }
1140
Craig Topper062a2ba2014-04-25 05:30:21 +00001141 const Function *demotedFunc = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001142 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
Yaron Keren075759a2015-03-30 15:42:36 +00001143 O << "// " << GVar->getName() << " has been demoted\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001144 if (localDecls.find(demotedFunc) != localDecls.end())
1145 localDecls[demotedFunc].push_back(GVar);
1146 else {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001147 std::vector<const GlobalVariable *> temp;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001148 temp.push_back(GVar);
1149 localDecls[demotedFunc] = temp;
1150 }
1151 return;
1152 }
1153
1154 O << ".";
1155 emitPTXAddressSpace(PTy->getAddressSpace(), O);
Justin Holewinski773ca402014-06-27 18:35:58 +00001156
1157 if (isManaged(*GVar)) {
1158 O << " .attribute(.managed)";
1159 }
1160
Justin Holewinskiae556d32012-05-04 20:18:50 +00001161 if (GVar->getAlignment() == 0)
1162 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1163 else
1164 O << " .align " << GVar->getAlignment();
1165
Jingyue Wue4c9cf02014-12-17 17:59:04 +00001166 if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001167 O << " .";
Justin Holewinski700b6fa2013-05-20 12:13:28 +00001168 // Special case: ABI requires that we use .u8 for predicates
1169 if (ETy->isIntegerTy(1))
1170 O << "u8";
1171 else
1172 O << getPTXFundamentalTypeStr(ETy, false);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001173 O << " ";
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00001174 O << *getSymbol(GVar);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001175
1176 // Ptx allows variable initilization only for constant and global state
1177 // spaces.
Justin Holewinski549c7732014-06-27 18:36:01 +00001178 if (GVar->hasInitializer()) {
1179 if ((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1180 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) {
1181 const Constant *Initializer = GVar->getInitializer();
Jingyue Wu312fd022015-04-24 02:57:30 +00001182 // 'undef' is treated as there is no value specified.
Justin Holewinski549c7732014-06-27 18:36:01 +00001183 if (!Initializer->isNullValue() && !isa<UndefValue>(Initializer)) {
1184 O << " = ";
1185 printScalarConstant(Initializer, O);
1186 }
1187 } else {
1188 // The frontend adds zero-initializer to variables that don't have an
1189 // initial value, so skip warning for this case.
1190 if (!GVar->getInitializer()->isNullValue()) {
Benjamin Kramerdba7ee92015-05-28 11:24:24 +00001191 report_fatal_error("initial value of '" + GVar->getName() +
1192 "' is not allowed in addrspace(" +
1193 Twine(PTy->getAddressSpace()) + ")");
Justin Holewinski549c7732014-06-27 18:36:01 +00001194 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001195 }
1196 }
1197 } else {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001198 unsigned int ElementSize = 0;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001199
1200 // Although PTX has direct support for struct type and array type and
1201 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1202 // targets that support these high level field accesses. Structs, arrays
1203 // and vectors are lowered into arrays of bytes.
1204 switch (ETy->getTypeID()) {
1205 case Type::StructTyID:
1206 case Type::ArrayTyID:
1207 case Type::VectorTyID:
1208 ElementSize = TD->getTypeStoreSize(ETy);
1209 // Ptx allows variable initilization only for constant and
1210 // global state spaces.
1211 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
Justin Holewinski0497ab12013-03-30 14:29:21 +00001212 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1213 GVar->hasInitializer()) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001214 const Constant *Initializer = GVar->getInitializer();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001215 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001216 AggBuffer aggBuffer(ElementSize, O, *this);
1217 bufferAggregateConstant(Initializer, &aggBuffer);
1218 if (aggBuffer.numSymbols) {
Eric Christopher6aad8b12015-02-19 00:08:14 +00001219 if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit()) {
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00001220 O << " .u64 " << *getSymbol(GVar) << "[";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001221 O << ElementSize / 8;
1222 } else {
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00001223 O << " .u32 " << *getSymbol(GVar) << "[";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001224 O << ElementSize / 4;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001225 }
1226 O << "]";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001227 } else {
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00001228 O << " .b8 " << *getSymbol(GVar) << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001229 O << ElementSize;
1230 O << "]";
1231 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001232 O << " = {";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001233 aggBuffer.print();
1234 O << "}";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001235 } else {
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00001236 O << " .b8 " << *getSymbol(GVar);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001237 if (ElementSize) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001238 O << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001239 O << ElementSize;
1240 O << "]";
1241 }
1242 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001243 } else {
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00001244 O << " .b8 " << *getSymbol(GVar);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001245 if (ElementSize) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001246 O << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001247 O << ElementSize;
1248 O << "]";
1249 }
1250 }
1251 break;
1252 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001253 llvm_unreachable("type not supported yet");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001254 }
1255
1256 }
1257 O << ";\n";
1258}
1259
1260void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1261 if (localDecls.find(f) == localDecls.end())
1262 return;
1263
Justin Holewinski01f89f02013-05-20 12:13:32 +00001264 std::vector<const GlobalVariable *> &gvars = localDecls[f];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001265
Justin Holewinski0497ab12013-03-30 14:29:21 +00001266 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001267 O << "\t// demoted variable\n\t";
1268 printModuleLevelGV(gvars[i], O, true);
1269 }
1270}
1271
1272void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1273 raw_ostream &O) const {
1274 switch (AddressSpace) {
1275 case llvm::ADDRESS_SPACE_LOCAL:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001276 O << "local";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001277 break;
1278 case llvm::ADDRESS_SPACE_GLOBAL:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001279 O << "global";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001280 break;
1281 case llvm::ADDRESS_SPACE_CONST:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001282 O << "const";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001283 break;
1284 case llvm::ADDRESS_SPACE_SHARED:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001285 O << "shared";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001286 break;
1287 default:
Justin Holewinski36a50992013-02-09 13:34:15 +00001288 report_fatal_error("Bad address space found while emitting PTX");
1289 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001290 }
1291}
1292
Justin Holewinski0497ab12013-03-30 14:29:21 +00001293std::string
1294NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001295 switch (Ty->getTypeID()) {
1296 default:
1297 llvm_unreachable("unexpected type");
1298 break;
1299 case Type::IntegerTyID: {
1300 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1301 if (NumBits == 1)
1302 return "pred";
1303 else if (NumBits <= 64) {
1304 std::string name = "u";
1305 return name + utostr(NumBits);
1306 } else {
1307 llvm_unreachable("Integer too large");
1308 break;
1309 }
1310 break;
1311 }
1312 case Type::FloatTyID:
1313 return "f32";
1314 case Type::DoubleTyID:
1315 return "f64";
1316 case Type::PointerTyID:
Eric Christopher6aad8b12015-02-19 00:08:14 +00001317 if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit())
Justin Holewinski0497ab12013-03-30 14:29:21 +00001318 if (useB4PTR)
1319 return "b64";
1320 else
1321 return "u64";
1322 else if (useB4PTR)
1323 return "b32";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001324 else
Justin Holewinski0497ab12013-03-30 14:29:21 +00001325 return "u32";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001326 }
1327 llvm_unreachable("unexpected type");
Craig Topper062a2ba2014-04-25 05:30:21 +00001328 return nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001329}
1330
Justin Holewinski0497ab12013-03-30 14:29:21 +00001331void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001332 raw_ostream &O) {
1333
Eric Christopher8b770652015-01-26 19:03:15 +00001334 const DataLayout *TD = TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001335
1336 // GlobalVariables are always constant pointers themselves.
1337 const PointerType *PTy = GVar->getType();
1338 Type *ETy = PTy->getElementType();
1339
1340 O << ".";
1341 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1342 if (GVar->getAlignment() == 0)
1343 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1344 else
1345 O << " .align " << GVar->getAlignment();
1346
Jingyue Wue4c9cf02014-12-17 17:59:04 +00001347 if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001348 O << " .";
1349 O << getPTXFundamentalTypeStr(ETy);
1350 O << " ";
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00001351 O << *getSymbol(GVar);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001352 return;
1353 }
1354
Justin Holewinski0497ab12013-03-30 14:29:21 +00001355 int64_t ElementSize = 0;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001356
1357 // Although PTX has direct support for struct type and array type and LLVM IR
1358 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1359 // support these high level field accesses. Structs and arrays are lowered
1360 // into arrays of bytes.
1361 switch (ETy->getTypeID()) {
1362 case Type::StructTyID:
1363 case Type::ArrayTyID:
1364 case Type::VectorTyID:
1365 ElementSize = TD->getTypeStoreSize(ETy);
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00001366 O << " .b8 " << *getSymbol(GVar) << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001367 if (ElementSize) {
Benjamin Kramerdba7ee92015-05-28 11:24:24 +00001368 O << ElementSize;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001369 }
1370 O << "]";
1371 break;
1372 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001373 llvm_unreachable("type not supported yet");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001374 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001375 return;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001376}
1377
Justin Holewinski0497ab12013-03-30 14:29:21 +00001378static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
Rafael Espindola08013342013-12-07 19:34:20 +00001379 if (Ty->isSingleValueType())
Justin Holewinskiae556d32012-05-04 20:18:50 +00001380 return TD->getPrefTypeAlignment(Ty);
1381
1382 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1383 if (ATy)
1384 return getOpenCLAlignment(TD, ATy->getElementType());
1385
Justin Holewinskiae556d32012-05-04 20:18:50 +00001386 const StructType *STy = dyn_cast<StructType>(Ty);
1387 if (STy) {
1388 unsigned int alignStruct = 1;
1389 // Go through each element of the struct and find the
1390 // largest alignment.
Justin Holewinski0497ab12013-03-30 14:29:21 +00001391 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001392 Type *ETy = STy->getElementType(i);
1393 unsigned int align = getOpenCLAlignment(TD, ETy);
1394 if (align > alignStruct)
1395 alignStruct = align;
1396 }
1397 return alignStruct;
1398 }
1399
1400 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1401 if (FTy)
Chandler Carruth5da3f052012-11-01 09:14:31 +00001402 return TD->getPointerPrefAlignment();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001403 return TD->getPrefTypeAlignment(Ty);
1404}
1405
1406void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1407 int paramIndex, raw_ostream &O) {
Eric Christopherbeffc4e2015-02-19 00:08:23 +00001408 O << *getSymbol(I->getParent()) << "_param_" << paramIndex;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001409}
1410
1411void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
Eric Christopherbeffc4e2015-02-19 00:08:23 +00001412 O << *CurrentFnSym << "_param_" << paramIndex;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001413}
1414
Justin Holewinski0497ab12013-03-30 14:29:21 +00001415void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
Eric Christopher8b770652015-01-26 19:03:15 +00001416 const DataLayout *TD = TM.getDataLayout();
Bill Wendlinge94d8432012-12-07 23:16:57 +00001417 const AttributeSet &PAL = F->getAttributes();
Eric Christopher6aad8b12015-02-19 00:08:14 +00001418 const TargetLowering *TLI = nvptxSubtarget->getTargetLowering();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001419 Function::const_arg_iterator I, E;
1420 unsigned paramIndex = 0;
1421 bool first = true;
1422 bool isKernelFunc = llvm::isKernelFunction(*F);
Eric Christopher6aad8b12015-02-19 00:08:14 +00001423 bool isABI = (nvptxSubtarget->getSmVersion() >= 20);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001424 MVT thePointerTy = TLI->getPointerTy();
1425
1426 O << "(\n";
1427
1428 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
Justin Holewinskie9884092013-03-24 21:17:47 +00001429 Type *Ty = I->getType();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001430
1431 if (!first)
1432 O << ",\n";
1433
1434 first = false;
1435
1436 // Handle image/sampler parameters
Justin Holewinski30d56a72014-04-09 15:39:15 +00001437 if (isKernelFunction(*F)) {
1438 if (isSampler(*I) || isImage(*I)) {
1439 if (isImage(*I)) {
1440 std::string sname = I->getName();
1441 if (isImageWriteOnly(*I) || isImageReadWrite(*I)) {
Eric Christopher6aad8b12015-02-19 00:08:14 +00001442 if (nvptxSubtarget->hasImageHandles())
Justin Holewinski30d56a72014-04-09 15:39:15 +00001443 O << "\t.param .u64 .ptr .surfref ";
1444 else
1445 O << "\t.param .surfref ";
1446 O << *CurrentFnSym << "_param_" << paramIndex;
1447 }
1448 else { // Default image is read_only
Eric Christopher6aad8b12015-02-19 00:08:14 +00001449 if (nvptxSubtarget->hasImageHandles())
Justin Holewinski30d56a72014-04-09 15:39:15 +00001450 O << "\t.param .u64 .ptr .texref ";
1451 else
1452 O << "\t.param .texref ";
1453 O << *CurrentFnSym << "_param_" << paramIndex;
1454 }
1455 } else {
Eric Christopher6aad8b12015-02-19 00:08:14 +00001456 if (nvptxSubtarget->hasImageHandles())
Justin Holewinski30d56a72014-04-09 15:39:15 +00001457 O << "\t.param .u64 .ptr .samplerref ";
1458 else
1459 O << "\t.param .samplerref ";
1460 O << *CurrentFnSym << "_param_" << paramIndex;
1461 }
1462 continue;
1463 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001464 }
1465
Eli Bendersky3e840192015-03-23 16:26:23 +00001466 if (!PAL.hasAttribute(paramIndex + 1, Attribute::ByVal)) {
Gautam Chakrabarti2c283402014-01-28 18:35:29 +00001467 if (Ty->isAggregateType() || Ty->isVectorTy()) {
1468 // Just print .param .align <a> .b8 .param[size];
Justin Holewinskie9884092013-03-24 21:17:47 +00001469 // <a> = PAL.getparamalignment
1470 // size = typeallocsize of element type
Justin Holewinski0497ab12013-03-30 14:29:21 +00001471 unsigned align = PAL.getParamAlignment(paramIndex + 1);
Justin Holewinskie9884092013-03-24 21:17:47 +00001472 if (align == 0)
1473 align = TD->getABITypeAlignment(Ty);
1474
1475 unsigned sz = TD->getTypeAllocSize(Ty);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001476 O << "\t.param .align " << align << " .b8 ";
Justin Holewinskie9884092013-03-24 21:17:47 +00001477 printParamName(I, paramIndex, O);
1478 O << "[" << sz << "]";
1479
1480 continue;
1481 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001482 // Just a scalar
1483 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1484 if (isKernelFunc) {
1485 if (PTy) {
1486 // Special handling for pointer arguments to kernel
1487 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1488
Eric Christopherbeffc4e2015-02-19 00:08:23 +00001489 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() !=
1490 NVPTX::CUDA) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001491 Type *ETy = PTy->getElementType();
1492 int addrSpace = PTy->getAddressSpace();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001493 switch (addrSpace) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001494 default:
1495 O << ".ptr ";
1496 break;
Justin Holewinskib96d1392013-06-10 13:29:47 +00001497 case llvm::ADDRESS_SPACE_CONST:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001498 O << ".ptr .const ";
1499 break;
1500 case llvm::ADDRESS_SPACE_SHARED:
1501 O << ".ptr .shared ";
1502 break;
1503 case llvm::ADDRESS_SPACE_GLOBAL:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001504 O << ".ptr .global ";
1505 break;
1506 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001507 O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001508 }
1509 printParamName(I, paramIndex, O);
1510 continue;
1511 }
1512
1513 // non-pointer scalar to kernel func
Justin Holewinski700b6fa2013-05-20 12:13:28 +00001514 O << "\t.param .";
1515 // Special case: predicate operands become .u8 types
1516 if (Ty->isIntegerTy(1))
1517 O << "u8";
1518 else
1519 O << getPTXFundamentalTypeStr(Ty);
1520 O << " ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001521 printParamName(I, paramIndex, O);
1522 continue;
1523 }
1524 // Non-kernel function, just print .param .b<size> for ABI
Alp Tokerf907b892013-12-05 05:44:44 +00001525 // and .reg .b<size> for non-ABI
Justin Holewinskiae556d32012-05-04 20:18:50 +00001526 unsigned sz = 0;
1527 if (isa<IntegerType>(Ty)) {
1528 sz = cast<IntegerType>(Ty)->getBitWidth();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001529 if (sz < 32)
1530 sz = 32;
1531 } else if (isa<PointerType>(Ty))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001532 sz = thePointerTy.getSizeInBits();
1533 else
1534 sz = Ty->getPrimitiveSizeInBits();
1535 if (isABI)
1536 O << "\t.param .b" << sz << " ";
1537 else
1538 O << "\t.reg .b" << sz << " ";
1539 printParamName(I, paramIndex, O);
1540 continue;
1541 }
1542
1543 // param has byVal attribute. So should be a pointer
1544 const PointerType *PTy = dyn_cast<PointerType>(Ty);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001545 assert(PTy && "Param with byval attribute should be a pointer type");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001546 Type *ETy = PTy->getElementType();
1547
1548 if (isABI || isKernelFunc) {
Gautam Chakrabarti2c283402014-01-28 18:35:29 +00001549 // Just print .param .align <a> .b8 .param[size];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001550 // <a> = PAL.getparamalignment
1551 // size = typeallocsize of element type
Justin Holewinski0497ab12013-03-30 14:29:21 +00001552 unsigned align = PAL.getParamAlignment(paramIndex + 1);
Justin Holewinski2dc9d072012-11-09 23:50:24 +00001553 if (align == 0)
1554 align = TD->getABITypeAlignment(ETy);
1555
Justin Holewinskiae556d32012-05-04 20:18:50 +00001556 unsigned sz = TD->getTypeAllocSize(ETy);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001557 O << "\t.param .align " << align << " .b8 ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001558 printParamName(I, paramIndex, O);
1559 O << "[" << sz << "]";
1560 continue;
1561 } else {
1562 // Split the ETy into constituent parts and
1563 // print .param .b<size> <name> for each part.
1564 // Further, if a part is vector, print the above for
1565 // each vector element.
1566 SmallVector<EVT, 16> vtparts;
1567 ComputeValueVTs(*TLI, ETy, vtparts);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001568 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001569 unsigned elems = 1;
1570 EVT elemtype = vtparts[i];
1571 if (vtparts[i].isVector()) {
1572 elems = vtparts[i].getVectorNumElements();
1573 elemtype = vtparts[i].getVectorElementType();
1574 }
1575
Justin Holewinski0497ab12013-03-30 14:29:21 +00001576 for (unsigned j = 0, je = elems; j != je; ++j) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001577 unsigned sz = elemtype.getSizeInBits();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001578 if (elemtype.isInteger() && (sz < 32))
1579 sz = 32;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001580 O << "\t.reg .b" << sz << " ";
1581 printParamName(I, paramIndex, O);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001582 if (j < je - 1)
1583 O << ",\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001584 ++paramIndex;
1585 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001586 if (i < e - 1)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001587 O << ",\n";
1588 }
1589 --paramIndex;
1590 continue;
1591 }
1592 }
1593
1594 O << "\n)\n";
1595}
1596
1597void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1598 raw_ostream &O) {
1599 const Function *F = MF.getFunction();
1600 emitFunctionParamList(F, O);
1601}
1602
Justin Holewinski0497ab12013-03-30 14:29:21 +00001603void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1604 const MachineFunction &MF) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001605 SmallString<128> Str;
1606 raw_svector_ostream O(Str);
1607
1608 // Map the global virtual register number to a register class specific
1609 // virtual register number starting from 1 with that class.
Eric Christopherfc6de422014-08-05 02:39:49 +00001610 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001611 //unsigned numRegClasses = TRI->getNumRegClasses();
1612
1613 // Emit the Fake Stack Object
1614 const MachineFrameInfo *MFI = MF.getFrameInfo();
1615 int NumBytes = (int) MFI->getStackSize();
1616 if (NumBytes) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001617 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1618 << getFunctionNumber() << "[" << NumBytes << "];\n";
Eric Christopher02389e32015-02-19 00:08:27 +00001619 if (static_cast<const NVPTXTargetMachine &>(MF.getTarget()).is64Bit()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001620 O << "\t.reg .b64 \t%SP;\n";
1621 O << "\t.reg .b64 \t%SPL;\n";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001622 } else {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001623 O << "\t.reg .b32 \t%SP;\n";
1624 O << "\t.reg .b32 \t%SPL;\n";
1625 }
1626 }
1627
1628 // Go through all virtual registers to establish the mapping between the
1629 // global virtual
1630 // register number and the per class virtual register number.
1631 // We use the per class virtual register number in the ptx output.
1632 unsigned int numVRs = MRI->getNumVirtRegs();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001633 for (unsigned i = 0; i < numVRs; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001634 unsigned int vr = TRI->index2VirtReg(i);
1635 const TargetRegisterClass *RC = MRI->getRegClass(vr);
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001636 DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001637 int n = regmap.size();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001638 regmap.insert(std::make_pair(vr, n + 1));
Justin Holewinskiae556d32012-05-04 20:18:50 +00001639 }
1640
1641 // Emit register declarations
1642 // @TODO: Extract out the real register usage
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001643 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1644 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1645 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1646 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
Justin Holewinski3e037d92014-07-16 16:26:58 +00001647 // O << "\t.reg .s64 %rd<" << NVPTXNumRegisters << ">;\n";
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001648 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
Justin Holewinski3e037d92014-07-16 16:26:58 +00001649 // O << "\t.reg .f64 %fd<" << NVPTXNumRegisters << ">;\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001650
1651 // Emit declaration of the virtual registers or 'physical' registers for
1652 // each register class
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001653 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1654 const TargetRegisterClass *RC = TRI->getRegClass(i);
1655 DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
1656 std::string rcname = getNVPTXRegClassName(RC);
1657 std::string rcStr = getNVPTXRegClassStr(RC);
1658 int n = regmap.size();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001659
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001660 // Only declare those registers that may be used.
1661 if (n) {
1662 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1663 << ">;\n";
1664 }
1665 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001666
Lang Hames9ff69c82015-04-24 19:11:51 +00001667 OutStreamer->EmitRawText(O.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +00001668}
1669
Justin Holewinskiae556d32012-05-04 20:18:50 +00001670void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001671 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
Justin Holewinskiae556d32012-05-04 20:18:50 +00001672 bool ignored;
1673 unsigned int numHex;
1674 const char *lead;
1675
Justin Holewinski0497ab12013-03-30 14:29:21 +00001676 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001677 numHex = 8;
1678 lead = "0f";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001679 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001680 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1681 numHex = 16;
1682 lead = "0d";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001683 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001684 } else
1685 llvm_unreachable("unsupported fp type");
1686
1687 APInt API = APF.bitcastToAPInt();
1688 std::string hexstr(utohexstr(API.getZExtValue()));
1689 O << lead;
1690 if (hexstr.length() < numHex)
1691 O << std::string(numHex - hexstr.length(), '0');
1692 O << utohexstr(API.getZExtValue());
1693}
1694
Justin Holewinski01f89f02013-05-20 12:13:32 +00001695void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1696 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001697 O << CI->getValue();
1698 return;
1699 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001700 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001701 printFPConstant(CFP, O);
1702 return;
1703 }
1704 if (isa<ConstantPointerNull>(CPV)) {
1705 O << "0";
1706 return;
1707 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001708 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
Justin Holewinski9d852a82014-04-09 15:39:11 +00001709 PointerType *PTy = dyn_cast<PointerType>(GVar->getType());
1710 bool IsNonGenericPointer = false;
1711 if (PTy && PTy->getAddressSpace() != 0) {
1712 IsNonGenericPointer = true;
1713 }
1714 if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
1715 O << "generic(";
1716 O << *getSymbol(GVar);
1717 O << ")";
1718 } else {
1719 O << *getSymbol(GVar);
1720 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001721 return;
1722 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001723 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1724 const Value *v = Cexpr->stripPointerCasts();
Justin Holewinski9d852a82014-04-09 15:39:11 +00001725 PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
1726 bool IsNonGenericPointer = false;
1727 if (PTy && PTy->getAddressSpace() != 0) {
1728 IsNonGenericPointer = true;
1729 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001730 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
Justin Holewinski9d852a82014-04-09 15:39:11 +00001731 if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
1732 O << "generic(";
1733 O << *getSymbol(GVar);
1734 O << ")";
1735 } else {
1736 O << *getSymbol(GVar);
1737 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001738 return;
1739 } else {
Matt Arsenault31a52ad2014-12-16 19:16:17 +00001740 O << *lowerConstant(CPV);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001741 return;
1742 }
1743 }
1744 llvm_unreachable("Not scalar type found in printScalarConstant()");
1745}
1746
Justin Holewinski01f89f02013-05-20 12:13:32 +00001747void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001748 AggBuffer *aggBuffer) {
1749
Eric Christopher8b770652015-01-26 19:03:15 +00001750 const DataLayout *TD = TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001751
1752 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1753 int s = TD->getTypeAllocSize(CPV->getType());
Justin Holewinski0497ab12013-03-30 14:29:21 +00001754 if (s < Bytes)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001755 s = Bytes;
1756 aggBuffer->addZeros(s);
1757 return;
1758 }
1759
1760 unsigned char *ptr;
1761 switch (CPV->getType()->getTypeID()) {
1762
1763 case Type::IntegerTyID: {
1764 const Type *ETy = CPV->getType();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001765 if (ETy == Type::getInt8Ty(CPV->getContext())) {
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001766 unsigned char c = (unsigned char)cast<ConstantInt>(CPV)->getZExtValue();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001767 ptr = &c;
1768 aggBuffer->addBytes(ptr, 1, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001769 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001770 short int16 = (short)cast<ConstantInt>(CPV)->getZExtValue();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001771 ptr = (unsigned char *)&int16;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001772 aggBuffer->addBytes(ptr, 2, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001773 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001774 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001775 int int32 = (int)(constInt->getZExtValue());
1776 ptr = (unsigned char *)&int32;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001777 aggBuffer->addBytes(ptr, 4, Bytes);
1778 break;
Justin Holewinski01f89f02013-05-20 12:13:32 +00001779 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1780 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001781 ConstantFoldConstantExpression(Cexpr, *TD))) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001782 int int32 = (int)(constInt->getZExtValue());
1783 ptr = (unsigned char *)&int32;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001784 aggBuffer->addBytes(ptr, 4, Bytes);
1785 break;
1786 }
1787 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1788 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
Jingyue Wu312fd022015-04-24 02:57:30 +00001789 aggBuffer->addSymbol(v, Cexpr->getOperand(0));
Justin Holewinskiae556d32012-05-04 20:18:50 +00001790 aggBuffer->addZeros(4);
1791 break;
1792 }
1793 }
Craig Topperbdf39a42012-05-24 07:02:50 +00001794 llvm_unreachable("unsupported integer const type");
Justin Holewinski0497ab12013-03-30 14:29:21 +00001795 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001796 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001797 long long int64 = (long long)(constInt->getZExtValue());
1798 ptr = (unsigned char *)&int64;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001799 aggBuffer->addBytes(ptr, 8, Bytes);
1800 break;
Justin Holewinski01f89f02013-05-20 12:13:32 +00001801 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1802 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001803 ConstantFoldConstantExpression(Cexpr, *TD))) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001804 long long int64 = (long long)(constInt->getZExtValue());
1805 ptr = (unsigned char *)&int64;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001806 aggBuffer->addBytes(ptr, 8, Bytes);
1807 break;
1808 }
1809 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1810 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
Jingyue Wu312fd022015-04-24 02:57:30 +00001811 aggBuffer->addSymbol(v, Cexpr->getOperand(0));
Justin Holewinskiae556d32012-05-04 20:18:50 +00001812 aggBuffer->addZeros(8);
1813 break;
1814 }
1815 }
1816 llvm_unreachable("unsupported integer const type");
Craig Topperbdf39a42012-05-24 07:02:50 +00001817 } else
Justin Holewinskiae556d32012-05-04 20:18:50 +00001818 llvm_unreachable("unsupported integer const type");
1819 break;
1820 }
1821 case Type::FloatTyID:
1822 case Type::DoubleTyID: {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001823 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001824 const Type *Ty = CFP->getType();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001825 if (Ty == Type::getFloatTy(CPV->getContext())) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001826 float float32 = (float) CFP->getValueAPF().convertToFloat();
1827 ptr = (unsigned char *)&float32;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001828 aggBuffer->addBytes(ptr, 4, Bytes);
1829 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1830 double float64 = CFP->getValueAPF().convertToDouble();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001831 ptr = (unsigned char *)&float64;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001832 aggBuffer->addBytes(ptr, 8, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001833 } else {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001834 llvm_unreachable("unsupported fp const type");
1835 }
1836 break;
1837 }
1838 case Type::PointerTyID: {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001839 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
Jingyue Wu312fd022015-04-24 02:57:30 +00001840 aggBuffer->addSymbol(GVar, GVar);
Justin Holewinski01f89f02013-05-20 12:13:32 +00001841 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1842 const Value *v = Cexpr->stripPointerCasts();
Jingyue Wu312fd022015-04-24 02:57:30 +00001843 aggBuffer->addSymbol(v, Cexpr);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001844 }
1845 unsigned int s = TD->getTypeAllocSize(CPV->getType());
1846 aggBuffer->addZeros(s);
1847 break;
1848 }
1849
1850 case Type::ArrayTyID:
1851 case Type::VectorTyID:
1852 case Type::StructTyID: {
1853 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
Justin Holewinski95564bd2013-09-19 12:51:46 +00001854 isa<ConstantStruct>(CPV) || isa<ConstantDataSequential>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001855 int ElementSize = TD->getTypeAllocSize(CPV->getType());
1856 bufferAggregateConstant(CPV, aggBuffer);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001857 if (Bytes > ElementSize)
1858 aggBuffer->addZeros(Bytes - ElementSize);
1859 } else if (isa<ConstantAggregateZero>(CPV))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001860 aggBuffer->addZeros(Bytes);
1861 else
1862 llvm_unreachable("Unexpected Constant type");
1863 break;
1864 }
1865
1866 default:
1867 llvm_unreachable("unsupported type");
1868 }
1869}
1870
Justin Holewinski01f89f02013-05-20 12:13:32 +00001871void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001872 AggBuffer *aggBuffer) {
Eric Christopher8b770652015-01-26 19:03:15 +00001873 const DataLayout *TD = TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001874 int Bytes;
1875
1876 // Old constants
1877 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1878 if (CPV->getNumOperands())
1879 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1880 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1881 return;
1882 }
1883
1884 if (const ConstantDataSequential *CDS =
Justin Holewinski0497ab12013-03-30 14:29:21 +00001885 dyn_cast<ConstantDataSequential>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001886 if (CDS->getNumElements())
1887 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1888 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1889 aggBuffer);
1890 return;
1891 }
1892
Justin Holewinskiae556d32012-05-04 20:18:50 +00001893 if (isa<ConstantStruct>(CPV)) {
1894 if (CPV->getNumOperands()) {
1895 StructType *ST = cast<StructType>(CPV->getType());
1896 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001897 if (i == (e - 1))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001898 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
Justin Holewinski0497ab12013-03-30 14:29:21 +00001899 TD->getTypeAllocSize(ST) -
1900 TD->getStructLayout(ST)->getElementOffset(i);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001901 else
Justin Holewinski0497ab12013-03-30 14:29:21 +00001902 Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
1903 TD->getStructLayout(ST)->getElementOffset(i);
1904 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001905 }
1906 }
1907 return;
1908 }
Craig Topperbdf39a42012-05-24 07:02:50 +00001909 llvm_unreachable("unsupported constant type in printAggregateConstant()");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001910}
1911
1912// buildTypeNameMap - Run through symbol table looking for type names.
1913//
1914
Justin Holewinskiae556d32012-05-04 20:18:50 +00001915bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
1916
1917 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
1918
Justin Holewinski0497ab12013-03-30 14:29:21 +00001919 if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
1920 !PI->second.compare("struct._image2d_t") ||
1921 !PI->second.compare("struct._image3d_t")))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001922 return true;
1923
1924 return false;
1925}
1926
Justin Holewinskiae556d32012-05-04 20:18:50 +00001927
Justin Holewinski0497ab12013-03-30 14:29:21 +00001928bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
1929 switch (MI.getOpcode()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001930 default:
1931 return false;
Justin Holewinski0497ab12013-03-30 14:29:21 +00001932 case NVPTX::CallArgBeginInst:
1933 case NVPTX::CallArgEndInst0:
1934 case NVPTX::CallArgEndInst1:
1935 case NVPTX::CallArgF32:
1936 case NVPTX::CallArgF64:
1937 case NVPTX::CallArgI16:
1938 case NVPTX::CallArgI32:
1939 case NVPTX::CallArgI32imm:
1940 case NVPTX::CallArgI64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001941 case NVPTX::CallArgParam:
1942 case NVPTX::CallVoidInst:
1943 case NVPTX::CallVoidInstReg:
1944 case NVPTX::Callseq_End:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001945 case NVPTX::CallVoidInstReg64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001946 case NVPTX::DeclareParamInst:
1947 case NVPTX::DeclareRetMemInst:
1948 case NVPTX::DeclareRetRegInst:
1949 case NVPTX::DeclareRetScalarInst:
1950 case NVPTX::DeclareScalarParamInst:
1951 case NVPTX::DeclareScalarRegInst:
1952 case NVPTX::StoreParamF32:
1953 case NVPTX::StoreParamF64:
1954 case NVPTX::StoreParamI16:
1955 case NVPTX::StoreParamI32:
1956 case NVPTX::StoreParamI64:
1957 case NVPTX::StoreParamI8:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001958 case NVPTX::StoreRetvalF32:
1959 case NVPTX::StoreRetvalF64:
1960 case NVPTX::StoreRetvalI16:
1961 case NVPTX::StoreRetvalI32:
1962 case NVPTX::StoreRetvalI64:
1963 case NVPTX::StoreRetvalI8:
1964 case NVPTX::LastCallArgF32:
1965 case NVPTX::LastCallArgF64:
1966 case NVPTX::LastCallArgI16:
1967 case NVPTX::LastCallArgI32:
1968 case NVPTX::LastCallArgI32imm:
1969 case NVPTX::LastCallArgI64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001970 case NVPTX::LastCallArgParam:
1971 case NVPTX::LoadParamMemF32:
1972 case NVPTX::LoadParamMemF64:
1973 case NVPTX::LoadParamMemI16:
1974 case NVPTX::LoadParamMemI32:
1975 case NVPTX::LoadParamMemI64:
1976 case NVPTX::LoadParamMemI8:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001977 case NVPTX::PrototypeInst:
1978 case NVPTX::DBG_VALUE:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001979 return true;
1980 }
1981 return false;
1982}
1983
Justin Holewinski3d2a9762015-04-28 17:18:30 +00001984/// lowerConstantForGV - Return an MCExpr for the given Constant. This is mostly
1985/// a copy from AsmPrinter::lowerConstant, except customized to only handle
1986/// expressions that are representable in PTX and create
1987/// NVPTXGenericMCSymbolRefExpr nodes for addrspacecast instructions.
1988const MCExpr *
1989NVPTXAsmPrinter::lowerConstantForGV(const Constant *CV, bool ProcessingGeneric) {
1990 MCContext &Ctx = OutContext;
1991
1992 if (CV->isNullValue() || isa<UndefValue>(CV))
Jim Grosbach13760bd2015-05-30 01:25:56 +00001993 return MCConstantExpr::create(0, Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00001994
1995 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
Jim Grosbach13760bd2015-05-30 01:25:56 +00001996 return MCConstantExpr::create(CI->getZExtValue(), Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00001997
1998 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
1999 const MCSymbolRefExpr *Expr =
Jim Grosbach13760bd2015-05-30 01:25:56 +00002000 MCSymbolRefExpr::create(getSymbol(GV), Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002001 if (ProcessingGeneric) {
Jim Grosbach13760bd2015-05-30 01:25:56 +00002002 return NVPTXGenericMCSymbolRefExpr::create(Expr, Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002003 } else {
2004 return Expr;
2005 }
2006 }
2007
2008 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
2009 if (!CE) {
2010 llvm_unreachable("Unknown constant value to lower!");
2011 }
2012
2013 switch (CE->getOpcode()) {
2014 default:
2015 // If the code isn't optimized, there may be outstanding folding
2016 // opportunities. Attempt to fold the expression using DataLayout as a
2017 // last resort before giving up.
2018 if (Constant *C = ConstantFoldConstantExpression(CE, *TM.getDataLayout()))
2019 if (C != CE)
2020 return lowerConstantForGV(C, ProcessingGeneric);
2021
2022 // Otherwise report the problem to the user.
2023 {
2024 std::string S;
2025 raw_string_ostream OS(S);
2026 OS << "Unsupported expression in static initializer: ";
2027 CE->printAsOperand(OS, /*PrintType=*/false,
2028 !MF ? nullptr : MF->getFunction()->getParent());
2029 report_fatal_error(OS.str());
2030 }
2031
2032 case Instruction::AddrSpaceCast: {
2033 // Strip the addrspacecast and pass along the operand
2034 PointerType *DstTy = cast<PointerType>(CE->getType());
2035 if (DstTy->getAddressSpace() == 0) {
2036 return lowerConstantForGV(cast<const Constant>(CE->getOperand(0)), true);
2037 }
2038 std::string S;
2039 raw_string_ostream OS(S);
2040 OS << "Unsupported expression in static initializer: ";
2041 CE->printAsOperand(OS, /*PrintType=*/ false,
2042 !MF ? 0 : MF->getFunction()->getParent());
2043 report_fatal_error(OS.str());
2044 }
2045
2046 case Instruction::GetElementPtr: {
2047 const DataLayout &DL = *TM.getDataLayout();
2048
2049 // Generate a symbolic expression for the byte address
2050 APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
2051 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
2052
2053 const MCExpr *Base = lowerConstantForGV(CE->getOperand(0),
2054 ProcessingGeneric);
2055 if (!OffsetAI)
2056 return Base;
2057
2058 int64_t Offset = OffsetAI.getSExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +00002059 return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002060 Ctx);
2061 }
2062
2063 case Instruction::Trunc:
2064 // We emit the value and depend on the assembler to truncate the generated
2065 // expression properly. This is important for differences between
2066 // blockaddress labels. Since the two labels are in the same function, it
2067 // is reasonable to treat their delta as a 32-bit value.
2068 // FALL THROUGH.
2069 case Instruction::BitCast:
2070 return lowerConstantForGV(CE->getOperand(0), ProcessingGeneric);
2071
2072 case Instruction::IntToPtr: {
2073 const DataLayout &DL = *TM.getDataLayout();
2074
2075 // Handle casts to pointers by changing them into casts to the appropriate
2076 // integer type. This promotes constant folding and simplifies this code.
2077 Constant *Op = CE->getOperand(0);
2078 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
2079 false/*ZExt*/);
2080 return lowerConstantForGV(Op, ProcessingGeneric);
2081 }
2082
2083 case Instruction::PtrToInt: {
2084 const DataLayout &DL = *TM.getDataLayout();
2085
2086 // Support only foldable casts to/from pointers that can be eliminated by
2087 // changing the pointer to the appropriately sized integer type.
2088 Constant *Op = CE->getOperand(0);
2089 Type *Ty = CE->getType();
2090
2091 const MCExpr *OpExpr = lowerConstantForGV(Op, ProcessingGeneric);
2092
2093 // We can emit the pointer value into this slot if the slot is an
2094 // integer slot equal to the size of the pointer.
2095 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
2096 return OpExpr;
2097
2098 // Otherwise the pointer is smaller than the resultant integer, mask off
2099 // the high bits so we are sure to get a proper truncation if the input is
2100 // a constant expr.
2101 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
Jim Grosbach13760bd2015-05-30 01:25:56 +00002102 const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
2103 return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002104 }
2105
2106 // The MC library also has a right-shift operator, but it isn't consistently
2107 // signed or unsigned between different targets.
2108 case Instruction::Add: {
2109 const MCExpr *LHS = lowerConstantForGV(CE->getOperand(0), ProcessingGeneric);
2110 const MCExpr *RHS = lowerConstantForGV(CE->getOperand(1), ProcessingGeneric);
2111 switch (CE->getOpcode()) {
2112 default: llvm_unreachable("Unknown binary operator constant cast expr");
Jim Grosbach13760bd2015-05-30 01:25:56 +00002113 case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002114 }
2115 }
2116 }
2117}
2118
2119// Copy of MCExpr::print customized for NVPTX
2120void NVPTXAsmPrinter::printMCExpr(const MCExpr &Expr, raw_ostream &OS) {
2121 switch (Expr.getKind()) {
2122 case MCExpr::Target:
Jim Grosbach13760bd2015-05-30 01:25:56 +00002123 return cast<MCTargetExpr>(&Expr)->printImpl(OS);
Justin Holewinski3d2a9762015-04-28 17:18:30 +00002124 case MCExpr::Constant:
2125 OS << cast<MCConstantExpr>(Expr).getValue();
2126 return;
2127
2128 case MCExpr::SymbolRef: {
2129 const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(Expr);
2130 const MCSymbol &Sym = SRE.getSymbol();
2131 OS << Sym;
2132 return;
2133 }
2134
2135 case MCExpr::Unary: {
2136 const MCUnaryExpr &UE = cast<MCUnaryExpr>(Expr);
2137 switch (UE.getOpcode()) {
2138 case MCUnaryExpr::LNot: OS << '!'; break;
2139 case MCUnaryExpr::Minus: OS << '-'; break;
2140 case MCUnaryExpr::Not: OS << '~'; break;
2141 case MCUnaryExpr::Plus: OS << '+'; break;
2142 }
2143 printMCExpr(*UE.getSubExpr(), OS);
2144 return;
2145 }
2146
2147 case MCExpr::Binary: {
2148 const MCBinaryExpr &BE = cast<MCBinaryExpr>(Expr);
2149
2150 // Only print parens around the LHS if it is non-trivial.
2151 if (isa<MCConstantExpr>(BE.getLHS()) || isa<MCSymbolRefExpr>(BE.getLHS()) ||
2152 isa<NVPTXGenericMCSymbolRefExpr>(BE.getLHS())) {
2153 printMCExpr(*BE.getLHS(), OS);
2154 } else {
2155 OS << '(';
2156 printMCExpr(*BE.getLHS(), OS);
2157 OS<< ')';
2158 }
2159
2160 switch (BE.getOpcode()) {
2161 case MCBinaryExpr::Add:
2162 // Print "X-42" instead of "X+-42".
2163 if (const MCConstantExpr *RHSC = dyn_cast<MCConstantExpr>(BE.getRHS())) {
2164 if (RHSC->getValue() < 0) {
2165 OS << RHSC->getValue();
2166 return;
2167 }
2168 }
2169
2170 OS << '+';
2171 break;
2172 default: llvm_unreachable("Unhandled binary operator");
2173 }
2174
2175 // Only print parens around the LHS if it is non-trivial.
2176 if (isa<MCConstantExpr>(BE.getRHS()) || isa<MCSymbolRefExpr>(BE.getRHS())) {
2177 printMCExpr(*BE.getRHS(), OS);
2178 } else {
2179 OS << '(';
2180 printMCExpr(*BE.getRHS(), OS);
2181 OS << ')';
2182 }
2183 return;
2184 }
2185 }
2186
2187 llvm_unreachable("Invalid expression kind!");
2188}
2189
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002190/// PrintAsmOperand - Print out an operand for an inline asm expression.
2191///
2192bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2193 unsigned AsmVariant,
2194 const char *ExtraCode, raw_ostream &O) {
2195 if (ExtraCode && ExtraCode[0]) {
2196 if (ExtraCode[1] != 0)
2197 return true; // Unknown modifier.
2198
2199 switch (ExtraCode[0]) {
2200 default:
2201 // See if this is a generic print operand
2202 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2203 case 'r':
2204 break;
2205 }
2206 }
2207
2208 printOperand(MI, OpNo, O);
2209
2210 return false;
2211}
2212
2213bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2214 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2215 const char *ExtraCode, raw_ostream &O) {
2216 if (ExtraCode && ExtraCode[0])
2217 return true; // Unknown modifier
2218
2219 O << '[';
2220 printMemOperand(MI, OpNo, O);
2221 O << ']';
2222
2223 return false;
2224}
2225
2226void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2227 raw_ostream &O, const char *Modifier) {
2228 const MachineOperand &MO = MI->getOperand(opNum);
2229 switch (MO.getType()) {
2230 case MachineOperand::MO_Register:
2231 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2232 if (MO.getReg() == NVPTX::VRDepot)
2233 O << DEPOTNAME << getFunctionNumber();
2234 else
2235 O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2236 } else {
Justin Holewinski660597d2013-10-11 12:39:36 +00002237 emitVirtualRegister(MO.getReg(), O);
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002238 }
2239 return;
2240
2241 case MachineOperand::MO_Immediate:
2242 if (!Modifier)
2243 O << MO.getImm();
2244 else if (strstr(Modifier, "vec") == Modifier)
2245 printVecModifiedImmediate(MO, Modifier, O);
2246 else
2247 llvm_unreachable(
2248 "Don't know how to handle modifier on immediate operand");
2249 return;
2250
2251 case MachineOperand::MO_FPImmediate:
2252 printFPConstant(MO.getFPImm(), O);
2253 break;
2254
2255 case MachineOperand::MO_GlobalAddress:
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00002256 O << *getSymbol(MO.getGlobal());
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002257 break;
2258
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002259 case MachineOperand::MO_MachineBasicBlock:
2260 O << *MO.getMBB()->getSymbol();
2261 return;
2262
2263 default:
2264 llvm_unreachable("Operand type not supported.");
2265 }
2266}
2267
2268void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2269 raw_ostream &O, const char *Modifier) {
2270 printOperand(MI, opNum, O);
2271
2272 if (Modifier && !strcmp(Modifier, "add")) {
2273 O << ", ";
2274 printOperand(MI, opNum + 1, O);
2275 } else {
2276 if (MI->getOperand(opNum + 1).isImm() &&
2277 MI->getOperand(opNum + 1).getImm() == 0)
2278 return; // don't print ',0' or '+0'
2279 O << "+";
2280 printOperand(MI, opNum + 1, O);
2281 }
2282}
2283
Justin Holewinskiae556d32012-05-04 20:18:50 +00002284void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2285 std::stringstream temp;
Yaron Keren075759a2015-03-30 15:42:36 +00002286 LineReader *reader = this->getReader(filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002287 temp << "\n//";
2288 temp << filename.str();
2289 temp << ":";
2290 temp << line;
2291 temp << " ";
2292 temp << reader->readLine(line);
2293 temp << "\n";
Lang Hames9ff69c82015-04-24 19:11:51 +00002294 this->OutStreamer->EmitRawText(temp.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +00002295}
2296
Justin Holewinskiae556d32012-05-04 20:18:50 +00002297LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
Craig Topper062a2ba2014-04-25 05:30:21 +00002298 if (!reader) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00002299 reader = new LineReader(filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002300 }
2301
2302 if (reader->fileName() != filename) {
2303 delete reader;
Justin Holewinski0497ab12013-03-30 14:29:21 +00002304 reader = new LineReader(filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002305 }
2306
2307 return reader;
2308}
2309
Justin Holewinski0497ab12013-03-30 14:29:21 +00002310std::string LineReader::readLine(unsigned lineNum) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00002311 if (lineNum < theCurLine) {
2312 theCurLine = 0;
Justin Holewinski0497ab12013-03-30 14:29:21 +00002313 fstr.seekg(0, std::ios::beg);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002314 }
2315 while (theCurLine < lineNum) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00002316 fstr.getline(buff, 500);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002317 theCurLine++;
2318 }
2319 return buff;
2320}
2321
2322// Force static initialization.
2323extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2324 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2325 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2326}