blob: e47388544bd29b660bf51c6740f912ad986868d3 [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);
228 MCOp = GetSymbolRef(OutContext.GetOrCreateSymbol(
229 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(
Justin Holewinski3d49e5c2013-11-15 12:30:04 +0000238 OutContext.GetOrCreateSymbol(Twine(MO.getSymbolName()))));
239 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 Grosbache9119e42015-05-13 18:37:00 +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(
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000286 NVPTXFloatMCExpr::CreateConstantFPSingle(Val, OutContext));
287 break;
288 case Type::DoubleTyID:
Jim Grosbache9119e42015-05-13 18:37:00 +0000289 MCOp = MCOperand::createExpr(
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000290 NVPTXFloatMCExpr::CreateConstantFPDouble(Val, OutContext));
291 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;
Justin Holewinski8b24e1e2013-08-06 23:06:42 +0000337 Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None,
338 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 Wu5bbcdaa2015-02-03 17:57:38 +0000421 // TODO: isLoopHeader() should take "const MachineBasicBlock *".
Jingyue Wu0220df02015-02-01 02:27:45 +0000422 // We insert .pragma "nounroll" only to the loop header.
423 if (!LI.isLoopHeader(const_cast<MachineBasicBlock *>(&MBB)))
424 return false;
425
426 // llvm.loop.unroll.disable is marked on the back edges of a loop. Therefore,
427 // we iterate through each back edge of the loop with header MBB, and check
428 // whether its metadata contains llvm.loop.unroll.disable.
429 for (auto I = MBB.pred_begin(); I != MBB.pred_end(); ++I) {
430 const MachineBasicBlock *PMBB = *I;
431 if (LI.getLoopFor(PMBB) != LI.getLoopFor(&MBB)) {
432 // Edges from other loops to MBB are not back edges.
433 continue;
434 }
435 if (const BasicBlock *PBB = PMBB->getBasicBlock()) {
Jingyue Wu49a766e2015-02-02 20:41:11 +0000436 if (MDNode *LoopID = PBB->getTerminator()->getMetadata("llvm.loop")) {
Jingyue Wu0220df02015-02-01 02:27:45 +0000437 if (GetUnrollMetadata(LoopID, "llvm.loop.unroll.disable"))
438 return true;
439 }
440 }
441 }
442 return false;
443}
444
445void NVPTXAsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
446 AsmPrinter::EmitBasicBlockStart(MBB);
447 if (isLoopHeaderOfNoUnroll(MBB))
Lang Hames9ff69c82015-04-24 19:11:51 +0000448 OutStreamer->EmitRawText(StringRef("\t.pragma \"nounroll\";\n"));
Jingyue Wu0220df02015-02-01 02:27:45 +0000449}
450
Justin Holewinskiae556d32012-05-04 20:18:50 +0000451void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
452 SmallString<128> Str;
453 raw_svector_ostream O(Str);
454
Justin Holewinski01f89f02013-05-20 12:13:32 +0000455 if (!GlobalsEmitted) {
456 emitGlobals(*MF->getFunction()->getParent());
457 GlobalsEmitted = true;
458 }
459
Justin Holewinskiae556d32012-05-04 20:18:50 +0000460 // Set up
461 MRI = &MF->getRegInfo();
462 F = MF->getFunction();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000463 emitLinkageDirective(F, O);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000464 if (llvm::isKernelFunction(*F))
465 O << ".entry ";
466 else {
467 O << ".func ";
468 printReturnValStr(*MF, O);
469 }
470
471 O << *CurrentFnSym;
472
473 emitFunctionParamList(*MF, O);
474
475 if (llvm::isKernelFunction(*F))
476 emitKernelFunctionDirectives(*F, O);
477
Lang Hames9ff69c82015-04-24 19:11:51 +0000478 OutStreamer->EmitRawText(O.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000479
480 prevDebugLoc = DebugLoc();
481}
482
483void NVPTXAsmPrinter::EmitFunctionBodyStart() {
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +0000484 VRegMapping.clear();
Lang Hames9ff69c82015-04-24 19:11:51 +0000485 OutStreamer->EmitRawText(StringRef("{\n"));
Justin Holewinskiae556d32012-05-04 20:18:50 +0000486 setAndEmitFunctionVirtualRegisters(*MF);
487
488 SmallString<128> Str;
489 raw_svector_ostream O(Str);
490 emitDemotedVars(MF->getFunction(), O);
Lang Hames9ff69c82015-04-24 19:11:51 +0000491 OutStreamer->EmitRawText(O.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000492}
493
494void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
Lang Hames9ff69c82015-04-24 19:11:51 +0000495 OutStreamer->EmitRawText(StringRef("}\n"));
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +0000496 VRegMapping.clear();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000497}
498
Justin Holewinski660597d2013-10-11 12:39:36 +0000499void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
500 unsigned RegNo = MI->getOperand(0).getReg();
Andrew Kaylor5c73e1f2015-03-24 23:37:10 +0000501 if (TargetRegisterInfo::isVirtualRegister(RegNo)) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000502 OutStreamer->AddComment(Twine("implicit-def: ") +
503 getVirtualRegisterName(RegNo));
Justin Holewinski660597d2013-10-11 12:39:36 +0000504 } else {
Lang Hames9ff69c82015-04-24 19:11:51 +0000505 OutStreamer->AddComment(Twine("implicit-def: ") +
506 nvptxSubtarget->getRegisterInfo()->getName(RegNo));
Justin Holewinski660597d2013-10-11 12:39:36 +0000507 }
Lang Hames9ff69c82015-04-24 19:11:51 +0000508 OutStreamer->AddBlankLine();
Justin Holewinski660597d2013-10-11 12:39:36 +0000509}
510
Justin Holewinski0497ab12013-03-30 14:29:21 +0000511void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
512 raw_ostream &O) const {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000513 // If the NVVM IR has some of reqntid* specified, then output
514 // the reqntid directive, and set the unspecified ones to 1.
515 // If none of reqntid* is specified, don't output reqntid directive.
516 unsigned reqntidx, reqntidy, reqntidz;
517 bool specified = false;
Eli Bendersky3e840192015-03-23 16:26:23 +0000518 if (!llvm::getReqNTIDx(F, reqntidx))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000519 reqntidx = 1;
520 else
521 specified = true;
Eli Bendersky3e840192015-03-23 16:26:23 +0000522 if (!llvm::getReqNTIDy(F, reqntidy))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000523 reqntidy = 1;
524 else
525 specified = true;
Eli Bendersky3e840192015-03-23 16:26:23 +0000526 if (!llvm::getReqNTIDz(F, reqntidz))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000527 reqntidz = 1;
528 else
529 specified = true;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000530
531 if (specified)
Justin Holewinski0497ab12013-03-30 14:29:21 +0000532 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
533 << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000534
535 // If the NVVM IR has some of maxntid* specified, then output
536 // the maxntid directive, and set the unspecified ones to 1.
537 // If none of maxntid* is specified, don't output maxntid directive.
538 unsigned maxntidx, maxntidy, maxntidz;
539 specified = false;
Eli Bendersky3e840192015-03-23 16:26:23 +0000540 if (!llvm::getMaxNTIDx(F, maxntidx))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000541 maxntidx = 1;
542 else
543 specified = true;
Eli Bendersky3e840192015-03-23 16:26:23 +0000544 if (!llvm::getMaxNTIDy(F, maxntidy))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000545 maxntidy = 1;
546 else
547 specified = true;
Eli Bendersky3e840192015-03-23 16:26:23 +0000548 if (!llvm::getMaxNTIDz(F, maxntidz))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000549 maxntidz = 1;
550 else
551 specified = true;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000552
553 if (specified)
Justin Holewinski0497ab12013-03-30 14:29:21 +0000554 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
555 << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000556
557 unsigned mincta;
558 if (llvm::getMinCTASm(F, mincta))
559 O << ".minnctapersm " << mincta << "\n";
560}
561
Justin Holewinski660597d2013-10-11 12:39:36 +0000562std::string
563NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
564 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000565
Justin Holewinski660597d2013-10-11 12:39:36 +0000566 std::string Name;
567 raw_string_ostream NameStr(Name);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000568
Justin Holewinski660597d2013-10-11 12:39:36 +0000569 VRegRCMap::const_iterator I = VRegMapping.find(RC);
570 assert(I != VRegMapping.end() && "Bad register class");
571 const DenseMap<unsigned, unsigned> &RegMap = I->second;
572
573 VRegMap::const_iterator VI = RegMap.find(Reg);
574 assert(VI != RegMap.end() && "Bad virtual register");
575 unsigned MappedVR = VI->second;
576
577 NameStr << getNVPTXRegClassStr(RC) << MappedVR;
578
579 NameStr.flush();
580 return Name;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000581}
582
Justin Holewinski660597d2013-10-11 12:39:36 +0000583void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
Justin Holewinski0497ab12013-03-30 14:29:21 +0000584 raw_ostream &O) {
Justin Holewinski660597d2013-10-11 12:39:36 +0000585 O << getVirtualRegisterName(vr);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000586}
587
Justin Holewinski0497ab12013-03-30 14:29:21 +0000588void NVPTXAsmPrinter::printVecModifiedImmediate(
589 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
590 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
591 int Imm = (int) MO.getImm();
592 if (0 == strcmp(Modifier, "vecelem"))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000593 O << "_" << vecelem[Imm];
Justin Holewinski0497ab12013-03-30 14:29:21 +0000594 else if (0 == strcmp(Modifier, "vecv4comm1")) {
595 if ((Imm < 0) || (Imm > 3))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000596 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000597 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
598 if ((Imm < 4) || (Imm > 7))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000599 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000600 } else if (0 == strcmp(Modifier, "vecv4pos")) {
601 if (Imm < 0)
602 Imm = 0;
603 O << "_" << vecelem[Imm % 4];
604 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
605 if ((Imm < 0) || (Imm > 1))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000606 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000607 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
608 if ((Imm < 2) || (Imm > 3))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000609 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000610 } else if (0 == strcmp(Modifier, "vecv2pos")) {
611 if (Imm < 0)
612 Imm = 0;
613 O << "_" << vecelem[Imm % 2];
614 } else
Craig Topperbdf39a42012-05-24 07:02:50 +0000615 llvm_unreachable("Unknown Modifier on immediate operand");
Justin Holewinskiae556d32012-05-04 20:18:50 +0000616}
617
Justin Holewinskidc5e3b62013-06-28 17:58:04 +0000618
619
Justin Holewinski0497ab12013-03-30 14:29:21 +0000620void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000621
Justin Holewinski0497ab12013-03-30 14:29:21 +0000622 emitLinkageDirective(F, O);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000623 if (llvm::isKernelFunction(*F))
624 O << ".entry ";
625 else
626 O << ".func ";
627 printReturnValStr(F, O);
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +0000628 O << *getSymbol(F) << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000629 emitFunctionParamList(F, O);
630 O << ";\n";
631}
632
Justin Holewinski0497ab12013-03-30 14:29:21 +0000633static bool usedInGlobalVarDef(const Constant *C) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000634 if (!C)
635 return false;
636
637 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
Yaron Keren075759a2015-03-30 15:42:36 +0000638 if (GV->getName() == "llvm.used")
Justin Holewinskiae556d32012-05-04 20:18:50 +0000639 return false;
640 return true;
641 }
642
Chandler Carruthcdf47882014-03-09 03:16:01 +0000643 for (const User *U : C->users())
644 if (const Constant *C = dyn_cast<Constant>(U))
645 if (usedInGlobalVarDef(C))
646 return true;
647
Justin Holewinskiae556d32012-05-04 20:18:50 +0000648 return false;
649}
650
Justin Holewinski0497ab12013-03-30 14:29:21 +0000651static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000652 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
Yaron Keren075759a2015-03-30 15:42:36 +0000653 if (othergv->getName() == "llvm.used")
Justin Holewinskiae556d32012-05-04 20:18:50 +0000654 return true;
655 }
656
657 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
658 if (instr->getParent() && instr->getParent()->getParent()) {
659 const Function *curFunc = instr->getParent()->getParent();
660 if (oneFunc && (curFunc != oneFunc))
661 return false;
662 oneFunc = curFunc;
663 return true;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000664 } else
Justin Holewinskiae556d32012-05-04 20:18:50 +0000665 return false;
666 }
667
Chandler Carruthcdf47882014-03-09 03:16:01 +0000668 for (const User *UU : U->users())
Eli Bendersky3e840192015-03-23 16:26:23 +0000669 if (!usedInOneFunc(UU, oneFunc))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000670 return false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000671
Justin Holewinskiae556d32012-05-04 20:18:50 +0000672 return true;
673}
674
675/* Find out if a global variable can be demoted to local scope.
676 * Currently, this is valid for CUDA shared variables, which have local
677 * scope and global lifetime. So the conditions to check are :
678 * 1. Is the global variable in shared address space?
679 * 2. Does it have internal linkage?
680 * 3. Is the global variable referenced only in one function?
681 */
682static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
Eli Bendersky3e840192015-03-23 16:26:23 +0000683 if (!gv->hasInternalLinkage())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000684 return false;
685 const PointerType *Pty = gv->getType();
686 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
687 return false;
688
Craig Topper062a2ba2014-04-25 05:30:21 +0000689 const Function *oneFunc = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000690
691 bool flag = usedInOneFunc(gv, oneFunc);
Eli Bendersky3e840192015-03-23 16:26:23 +0000692 if (!flag)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000693 return false;
694 if (!oneFunc)
695 return false;
696 f = oneFunc;
697 return true;
698}
699
700static bool useFuncSeen(const Constant *C,
701 llvm::DenseMap<const Function *, bool> &seenMap) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000702 for (const User *U : C->users()) {
703 if (const Constant *cu = dyn_cast<Constant>(U)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000704 if (useFuncSeen(cu, seenMap))
705 return true;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000706 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000707 const BasicBlock *bb = I->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000708 if (!bb)
709 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000710 const Function *caller = bb->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000711 if (!caller)
712 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000713 if (seenMap.find(caller) != seenMap.end())
714 return true;
715 }
716 }
717 return false;
718}
719
Justin Holewinski01f89f02013-05-20 12:13:32 +0000720void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000721 llvm::DenseMap<const Function *, bool> seenMap;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000722 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000723 const Function *F = FI;
724
725 if (F->isDeclaration()) {
726 if (F->use_empty())
727 continue;
728 if (F->getIntrinsicID())
729 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000730 emitDeclaration(F, O);
731 continue;
732 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000733 for (const User *U : F->users()) {
734 if (const Constant *C = dyn_cast<Constant>(U)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000735 if (usedInGlobalVarDef(C)) {
736 // The use is in the initialization of a global variable
737 // that is a function pointer, so print a declaration
738 // for the original function
Justin Holewinskiae556d32012-05-04 20:18:50 +0000739 emitDeclaration(F, O);
740 break;
741 }
742 // Emit a declaration of this function if the function that
743 // uses this constant expr has already been seen.
744 if (useFuncSeen(C, seenMap)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000745 emitDeclaration(F, O);
746 break;
747 }
748 }
749
Chandler Carruthcdf47882014-03-09 03:16:01 +0000750 if (!isa<Instruction>(U))
Justin Holewinski0497ab12013-03-30 14:29:21 +0000751 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000752 const Instruction *instr = cast<Instruction>(U);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000753 const BasicBlock *bb = instr->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000754 if (!bb)
755 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000756 const Function *caller = bb->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000757 if (!caller)
758 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000759
760 // If a caller has already been seen, then the caller is
761 // appearing in the module before the callee. so print out
762 // a declaration for the callee.
763 if (seenMap.find(caller) != seenMap.end()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000764 emitDeclaration(F, O);
765 break;
766 }
767 }
768 seenMap[F] = true;
769 }
770}
771
772void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
773 DebugInfoFinder DbgFinder;
774 DbgFinder.processModule(M);
775
Justin Holewinski0497ab12013-03-30 14:29:21 +0000776 unsigned i = 1;
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000777 for (const DICompileUnit *DIUnit : DbgFinder.compile_units()) {
Duncan P. N. Exon Smith35ef22c2015-04-15 23:19:27 +0000778 StringRef Filename = DIUnit->getFilename();
779 StringRef Dirname = DIUnit->getDirectory();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000780 SmallString<128> FullPathName = Dirname;
781 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
782 sys::path::append(FullPathName, Filename);
Yaron Keren075759a2015-03-30 15:42:36 +0000783 Filename = FullPathName;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000784 }
Yaron Keren075759a2015-03-30 15:42:36 +0000785 if (filenameMap.find(Filename) != filenameMap.end())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000786 continue;
Yaron Keren075759a2015-03-30 15:42:36 +0000787 filenameMap[Filename] = i;
Lang Hames9ff69c82015-04-24 19:11:51 +0000788 OutStreamer->EmitDwarfFileDirective(i, "", Filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000789 ++i;
790 }
791
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000792 for (DISubprogram *SP : DbgFinder.subprograms()) {
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000793 StringRef Filename = SP->getFilename();
794 StringRef Dirname = SP->getDirectory();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000795 SmallString<128> FullPathName = Dirname;
796 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
797 sys::path::append(FullPathName, Filename);
Yaron Keren075759a2015-03-30 15:42:36 +0000798 Filename = FullPathName;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000799 }
Yaron Keren075759a2015-03-30 15:42:36 +0000800 if (filenameMap.find(Filename) != filenameMap.end())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000801 continue;
Yaron Keren075759a2015-03-30 15:42:36 +0000802 filenameMap[Filename] = i;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000803 ++i;
804 }
805}
806
Justin Holewinski0497ab12013-03-30 14:29:21 +0000807bool NVPTXAsmPrinter::doInitialization(Module &M) {
Eric Christopher6aad8b12015-02-19 00:08:14 +0000808 // Construct a default subtarget off of the TargetMachine defaults. The
809 // rest of NVPTX isn't friendly to change subtargets per function and
810 // so the default TargetMachine will have all of the options.
811 StringRef TT = TM.getTargetTriple();
812 StringRef CPU = TM.getTargetCPU();
813 StringRef FS = TM.getTargetFeatureString();
814 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
Eric Christopher02389e32015-02-19 00:08:27 +0000815 const NVPTXSubtarget STI(TT, CPU, FS, NTM);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000816
817 SmallString<128> Str1;
818 raw_svector_ostream OS1(Str1);
819
820 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
821 MMI->AnalyzeModule(M);
822
823 // We need to call the parent's one explicitly.
824 //bool Result = AsmPrinter::doInitialization(M);
825
826 // Initialize TargetLoweringObjectFile.
Justin Holewinski0497ab12013-03-30 14:29:21 +0000827 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
828 .Initialize(OutContext, TM);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000829
Eric Christopher8b770652015-01-26 19:03:15 +0000830 Mang = new Mangler(TM.getDataLayout());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000831
832 // Emit header before any dwarf directives are emitted below.
Eric Christopher6aad8b12015-02-19 00:08:14 +0000833 emitHeader(M, OS1, STI);
Lang Hames9ff69c82015-04-24 19:11:51 +0000834 OutStreamer->EmitRawText(OS1.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000835
Justin Holewinskiae556d32012-05-04 20:18:50 +0000836 // Already commented out
837 //bool Result = AsmPrinter::doInitialization(M);
838
Justin Holewinskid2bbdf02013-07-01 13:00:14 +0000839 // Emit module-level inline asm if it exists.
840 if (!M.getModuleInlineAsm().empty()) {
Lang Hames9ff69c82015-04-24 19:11:51 +0000841 OutStreamer->AddComment("Start of file scope inline assembly");
842 OutStreamer->AddBlankLine();
843 OutStreamer->EmitRawText(StringRef(M.getModuleInlineAsm()));
844 OutStreamer->AddBlankLine();
845 OutStreamer->AddComment("End of file scope inline assembly");
846 OutStreamer->AddBlankLine();
Justin Holewinskid2bbdf02013-07-01 13:00:14 +0000847 }
848
Eric Christopher6aad8b12015-02-19 00:08:14 +0000849 // If we're not NVCL we're CUDA, go ahead and emit filenames.
850 if (Triple(TM.getTargetTriple()).getOS() != Triple::NVCL)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000851 recordAndEmitFilenames(M);
852
Justin Holewinski01f89f02013-05-20 12:13:32 +0000853 GlobalsEmitted = false;
854
855 return false; // success
856}
857
858void NVPTXAsmPrinter::emitGlobals(const Module &M) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000859 SmallString<128> Str2;
860 raw_svector_ostream OS2(Str2);
861
862 emitDeclarations(M, OS2);
863
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000864 // As ptxas does not support forward references of globals, we need to first
865 // sort the list of module-level globals in def-use order. We visit each
866 // global variable in order, and ensure that we emit it *after* its dependent
867 // globals. We use a little extra memory maintaining both a set and a list to
868 // have fast searches while maintaining a strict ordering.
Justin Holewinski01f89f02013-05-20 12:13:32 +0000869 SmallVector<const GlobalVariable *, 8> Globals;
870 DenseSet<const GlobalVariable *> GVVisited;
871 DenseSet<const GlobalVariable *> GVVisiting;
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000872
873 // Visit each global variable, in order
Justin Holewinski01f89f02013-05-20 12:13:32 +0000874 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
875 I != E; ++I)
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000876 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
877
Justin Holewinski0497ab12013-03-30 14:29:21 +0000878 assert(GVVisited.size() == M.getGlobalList().size() &&
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000879 "Missed a global variable");
880 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
881
882 // Print out module-level global variables in proper order
883 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
884 printModuleLevelGV(Globals[i], OS2);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000885
886 OS2 << '\n';
887
Lang Hames9ff69c82015-04-24 19:11:51 +0000888 OutStreamer->EmitRawText(OS2.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000889}
890
Eric Christopher6aad8b12015-02-19 00:08:14 +0000891void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O,
892 const NVPTXSubtarget &STI) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000893 O << "//\n";
894 O << "// Generated by LLVM NVPTX Back-End\n";
895 O << "//\n";
896 O << "\n";
897
Eric Christopher6aad8b12015-02-19 00:08:14 +0000898 unsigned PTXVersion = STI.getPTXVersion();
Justin Holewinski1812ee92012-11-12 03:16:43 +0000899 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000900
901 O << ".target ";
Eric Christopher6aad8b12015-02-19 00:08:14 +0000902 O << STI.getTargetName();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000903
Eric Christopherca929f22015-02-19 00:22:47 +0000904 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
905 if (NTM.getDrvInterface() == NVPTX::NVCL)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000906 O << ", texmode_independent";
Eric Christopherbeffc4e2015-02-19 00:08:23 +0000907 else {
Eric Christopher6aad8b12015-02-19 00:08:14 +0000908 if (!STI.hasDouble())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000909 O << ", map_f64_to_f32";
910 }
911
912 if (MAI->doesSupportDebugInformation())
913 O << ", debug";
914
915 O << "\n";
916
917 O << ".address_size ";
Eric Christopherca929f22015-02-19 00:22:47 +0000918 if (NTM.is64Bit())
Justin Holewinskiae556d32012-05-04 20:18:50 +0000919 O << "64";
920 else
921 O << "32";
922 O << "\n";
923
924 O << "\n";
925}
926
927bool NVPTXAsmPrinter::doFinalization(Module &M) {
Justin Holewinski01f89f02013-05-20 12:13:32 +0000928 // If we did not emit any functions, then the global declarations have not
929 // yet been emitted.
930 if (!GlobalsEmitted) {
931 emitGlobals(M);
932 GlobalsEmitted = true;
933 }
934
Justin Holewinskiae556d32012-05-04 20:18:50 +0000935 // XXX Temproarily remove global variables so that doFinalization() will not
936 // emit them again (global variables are emitted at beginning).
937
938 Module::GlobalListType &global_list = M.getGlobalList();
939 int i, n = global_list.size();
Dylan Noblesmithc9e2a272014-08-26 02:03:35 +0000940 GlobalVariable **gv_array = new GlobalVariable *[n];
Justin Holewinskiae556d32012-05-04 20:18:50 +0000941
942 // first, back-up GlobalVariable in gv_array
943 i = 0;
944 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000945 I != E; ++I)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000946 gv_array[i++] = &*I;
947
948 // second, empty global_list
949 while (!global_list.empty())
950 global_list.remove(global_list.begin());
951
952 // call doFinalization
953 bool ret = AsmPrinter::doFinalization(M);
954
955 // now we restore global variables
Justin Holewinski0497ab12013-03-30 14:29:21 +0000956 for (i = 0; i < n; i++)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000957 global_list.insert(global_list.end(), gv_array[i]);
958
Justin Holewinski59596952014-04-09 15:38:52 +0000959 clearAnnotationCache(&M);
Dylan Noblesmithc9e2a272014-08-26 02:03:35 +0000960
961 delete[] gv_array;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000962 return ret;
963
Justin Holewinskiae556d32012-05-04 20:18:50 +0000964 //bool Result = AsmPrinter::doFinalization(M);
965 // Instead of calling the parents doFinalization, we may
966 // clone parents doFinalization and customize here.
967 // Currently, we if NVISA out the EmitGlobals() in
968 // parent's doFinalization, which is too intrusive.
969 //
970 // Same for the doInitialization.
971 //return Result;
972}
973
974// This function emits appropriate linkage directives for
975// functions and global variables.
976//
977// extern function declaration -> .extern
978// extern function definition -> .visible
979// external global variable with init -> .visible
980// external without init -> .extern
981// appending -> not allowed, assert.
Justin Holewinski7d5bf662014-06-27 18:35:10 +0000982// for any linkage other than
983// internal, private, linker_private,
984// linker_private_weak, linker_private_weak_def_auto,
985// we emit -> .weak.
Justin Holewinskiae556d32012-05-04 20:18:50 +0000986
Justin Holewinski0497ab12013-03-30 14:29:21 +0000987void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
988 raw_ostream &O) {
Eric Christopherbeffc4e2015-02-19 00:08:23 +0000989 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() == NVPTX::CUDA) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000990 if (V->hasExternalLinkage()) {
991 if (isa<GlobalVariable>(V)) {
992 const GlobalVariable *GVar = cast<GlobalVariable>(V);
993 if (GVar) {
994 if (GVar->hasInitializer())
995 O << ".visible ";
996 else
997 O << ".extern ";
998 }
999 } else if (V->isDeclaration())
1000 O << ".extern ";
1001 else
1002 O << ".visible ";
1003 } else if (V->hasAppendingLinkage()) {
1004 std::string msg;
1005 msg.append("Error: ");
1006 msg.append("Symbol ");
1007 if (V->hasName())
Yaron Keren075759a2015-03-30 15:42:36 +00001008 msg.append(V->getName());
Justin Holewinskiae556d32012-05-04 20:18:50 +00001009 msg.append("has unsupported appending linkage type");
1010 llvm_unreachable(msg.c_str());
Justin Holewinski7d5bf662014-06-27 18:35:10 +00001011 } else if (!V->hasInternalLinkage() &&
1012 !V->hasPrivateLinkage()) {
1013 O << ".weak ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001014 }
1015 }
1016}
1017
Justin Holewinski01f89f02013-05-20 12:13:32 +00001018void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1019 raw_ostream &O,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001020 bool processDemoted) {
1021
1022 // Skip meta data
1023 if (GVar->hasSection()) {
Rafael Espindola64c1e182014-06-03 02:41:57 +00001024 if (GVar->getSection() == StringRef("llvm.metadata"))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001025 return;
1026 }
1027
Justin Holewinski73cb5de2014-06-27 18:35:53 +00001028 // Skip LLVM intrinsic global variables
1029 if (GVar->getName().startswith("llvm.") ||
1030 GVar->getName().startswith("nvvm."))
1031 return;
1032
Eric Christopher8b770652015-01-26 19:03:15 +00001033 const DataLayout *TD = TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001034
1035 // GlobalVariables are always constant pointers themselves.
1036 const PointerType *PTy = GVar->getType();
1037 Type *ETy = PTy->getElementType();
1038
1039 if (GVar->hasExternalLinkage()) {
1040 if (GVar->hasInitializer())
1041 O << ".visible ";
1042 else
1043 O << ".extern ";
Justin Holewinskid73767a2014-06-27 18:35:56 +00001044 } else if (GVar->hasLinkOnceLinkage() || GVar->hasWeakLinkage() ||
1045 GVar->hasAvailableExternallyLinkage() ||
1046 GVar->hasCommonLinkage()) {
1047 O << ".weak ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001048 }
1049
1050 if (llvm::isTexture(*GVar)) {
1051 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1052 return;
1053 }
1054
1055 if (llvm::isSurface(*GVar)) {
1056 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1057 return;
1058 }
1059
1060 if (GVar->isDeclaration()) {
1061 // (extern) declarations, no definition or initializer
1062 // Currently the only known declaration is for an automatic __local
1063 // (.shared) promoted to global.
1064 emitPTXGlobalVariable(GVar, O);
1065 O << ";\n";
1066 return;
1067 }
1068
1069 if (llvm::isSampler(*GVar)) {
1070 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1071
Craig Topper062a2ba2014-04-25 05:30:21 +00001072 const Constant *Initializer = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001073 if (GVar->hasInitializer())
1074 Initializer = GVar->getInitializer();
Craig Topper062a2ba2014-04-25 05:30:21 +00001075 const ConstantInt *CI = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001076 if (Initializer)
1077 CI = dyn_cast<ConstantInt>(Initializer);
1078 if (CI) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001079 unsigned sample = CI->getZExtValue();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001080
1081 O << " = { ";
1082
Justin Holewinski0497ab12013-03-30 14:29:21 +00001083 for (int i = 0,
1084 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1085 i < 3; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001086 O << "addr_mode_" << i << " = ";
1087 switch (addr) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001088 case 0:
1089 O << "wrap";
1090 break;
1091 case 1:
1092 O << "clamp_to_border";
1093 break;
1094 case 2:
1095 O << "clamp_to_edge";
1096 break;
1097 case 3:
1098 O << "wrap";
1099 break;
1100 case 4:
1101 O << "mirror";
1102 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001103 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001104 O << ", ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001105 }
1106 O << "filter_mode = ";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001107 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1108 case 0:
1109 O << "nearest";
1110 break;
1111 case 1:
1112 O << "linear";
1113 break;
1114 case 2:
Craig Topper2a30d782014-06-18 05:05:13 +00001115 llvm_unreachable("Anisotropic filtering is not supported");
Justin Holewinski0497ab12013-03-30 14:29:21 +00001116 default:
1117 O << "nearest";
1118 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001119 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001120 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001121 O << ", force_unnormalized_coords = 1";
1122 }
1123 O << " }";
1124 }
1125
1126 O << ";\n";
1127 return;
1128 }
1129
1130 if (GVar->hasPrivateLinkage()) {
1131
1132 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1133 return;
1134
1135 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1136 if (!strncmp(GVar->getName().data(), "filename", 8))
1137 return;
1138 if (GVar->use_empty())
1139 return;
1140 }
1141
Craig Topper062a2ba2014-04-25 05:30:21 +00001142 const Function *demotedFunc = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001143 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
Yaron Keren075759a2015-03-30 15:42:36 +00001144 O << "// " << GVar->getName() << " has been demoted\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001145 if (localDecls.find(demotedFunc) != localDecls.end())
1146 localDecls[demotedFunc].push_back(GVar);
1147 else {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001148 std::vector<const GlobalVariable *> temp;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001149 temp.push_back(GVar);
1150 localDecls[demotedFunc] = temp;
1151 }
1152 return;
1153 }
1154
1155 O << ".";
1156 emitPTXAddressSpace(PTy->getAddressSpace(), O);
Justin Holewinski773ca402014-06-27 18:35:58 +00001157
1158 if (isManaged(*GVar)) {
1159 O << " .attribute(.managed)";
1160 }
1161
Justin Holewinskiae556d32012-05-04 20:18:50 +00001162 if (GVar->getAlignment() == 0)
1163 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1164 else
1165 O << " .align " << GVar->getAlignment();
1166
Jingyue Wue4c9cf02014-12-17 17:59:04 +00001167 if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001168 O << " .";
Justin Holewinski700b6fa2013-05-20 12:13:28 +00001169 // Special case: ABI requires that we use .u8 for predicates
1170 if (ETy->isIntegerTy(1))
1171 O << "u8";
1172 else
1173 O << getPTXFundamentalTypeStr(ETy, false);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001174 O << " ";
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00001175 O << *getSymbol(GVar);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001176
1177 // Ptx allows variable initilization only for constant and global state
1178 // spaces.
Justin Holewinski549c7732014-06-27 18:36:01 +00001179 if (GVar->hasInitializer()) {
1180 if ((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1181 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) {
1182 const Constant *Initializer = GVar->getInitializer();
Jingyue Wu312fd022015-04-24 02:57:30 +00001183 // 'undef' is treated as there is no value specified.
Justin Holewinski549c7732014-06-27 18:36:01 +00001184 if (!Initializer->isNullValue() && !isa<UndefValue>(Initializer)) {
1185 O << " = ";
1186 printScalarConstant(Initializer, O);
1187 }
1188 } else {
1189 // The frontend adds zero-initializer to variables that don't have an
1190 // initial value, so skip warning for this case.
1191 if (!GVar->getInitializer()->isNullValue()) {
Yaron Keren075759a2015-03-30 15:42:36 +00001192 std::string warnMsg =
1193 ("initial value of '" + GVar->getName() +
1194 "' is not allowed in addrspace(" +
1195 Twine(llvm::utostr_32(PTy->getAddressSpace())) + ")").str();
Justin Holewinski549c7732014-06-27 18:36:01 +00001196 report_fatal_error(warnMsg.c_str());
1197 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001198 }
1199 }
1200 } else {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001201 unsigned int ElementSize = 0;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001202
1203 // Although PTX has direct support for struct type and array type and
1204 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1205 // targets that support these high level field accesses. Structs, arrays
1206 // and vectors are lowered into arrays of bytes.
1207 switch (ETy->getTypeID()) {
1208 case Type::StructTyID:
1209 case Type::ArrayTyID:
1210 case Type::VectorTyID:
1211 ElementSize = TD->getTypeStoreSize(ETy);
1212 // Ptx allows variable initilization only for constant and
1213 // global state spaces.
1214 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
Justin Holewinski0497ab12013-03-30 14:29:21 +00001215 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1216 GVar->hasInitializer()) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001217 const Constant *Initializer = GVar->getInitializer();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001218 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001219 AggBuffer aggBuffer(ElementSize, O, *this);
1220 bufferAggregateConstant(Initializer, &aggBuffer);
1221 if (aggBuffer.numSymbols) {
Eric Christopher6aad8b12015-02-19 00:08:14 +00001222 if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit()) {
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00001223 O << " .u64 " << *getSymbol(GVar) << "[";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001224 O << ElementSize / 8;
1225 } else {
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00001226 O << " .u32 " << *getSymbol(GVar) << "[";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001227 O << ElementSize / 4;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001228 }
1229 O << "]";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001230 } else {
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00001231 O << " .b8 " << *getSymbol(GVar) << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001232 O << ElementSize;
1233 O << "]";
1234 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001235 O << " = {";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001236 aggBuffer.print();
1237 O << "}";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001238 } else {
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00001239 O << " .b8 " << *getSymbol(GVar);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001240 if (ElementSize) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001241 O << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001242 O << ElementSize;
1243 O << "]";
1244 }
1245 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001246 } else {
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00001247 O << " .b8 " << *getSymbol(GVar);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001248 if (ElementSize) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001249 O << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001250 O << ElementSize;
1251 O << "]";
1252 }
1253 }
1254 break;
1255 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001256 llvm_unreachable("type not supported yet");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001257 }
1258
1259 }
1260 O << ";\n";
1261}
1262
1263void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1264 if (localDecls.find(f) == localDecls.end())
1265 return;
1266
Justin Holewinski01f89f02013-05-20 12:13:32 +00001267 std::vector<const GlobalVariable *> &gvars = localDecls[f];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001268
Justin Holewinski0497ab12013-03-30 14:29:21 +00001269 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001270 O << "\t// demoted variable\n\t";
1271 printModuleLevelGV(gvars[i], O, true);
1272 }
1273}
1274
1275void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1276 raw_ostream &O) const {
1277 switch (AddressSpace) {
1278 case llvm::ADDRESS_SPACE_LOCAL:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001279 O << "local";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001280 break;
1281 case llvm::ADDRESS_SPACE_GLOBAL:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001282 O << "global";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001283 break;
1284 case llvm::ADDRESS_SPACE_CONST:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001285 O << "const";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001286 break;
1287 case llvm::ADDRESS_SPACE_SHARED:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001288 O << "shared";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001289 break;
1290 default:
Justin Holewinski36a50992013-02-09 13:34:15 +00001291 report_fatal_error("Bad address space found while emitting PTX");
1292 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001293 }
1294}
1295
Justin Holewinski0497ab12013-03-30 14:29:21 +00001296std::string
1297NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001298 switch (Ty->getTypeID()) {
1299 default:
1300 llvm_unreachable("unexpected type");
1301 break;
1302 case Type::IntegerTyID: {
1303 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1304 if (NumBits == 1)
1305 return "pred";
1306 else if (NumBits <= 64) {
1307 std::string name = "u";
1308 return name + utostr(NumBits);
1309 } else {
1310 llvm_unreachable("Integer too large");
1311 break;
1312 }
1313 break;
1314 }
1315 case Type::FloatTyID:
1316 return "f32";
1317 case Type::DoubleTyID:
1318 return "f64";
1319 case Type::PointerTyID:
Eric Christopher6aad8b12015-02-19 00:08:14 +00001320 if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit())
Justin Holewinski0497ab12013-03-30 14:29:21 +00001321 if (useB4PTR)
1322 return "b64";
1323 else
1324 return "u64";
1325 else if (useB4PTR)
1326 return "b32";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001327 else
Justin Holewinski0497ab12013-03-30 14:29:21 +00001328 return "u32";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001329 }
1330 llvm_unreachable("unexpected type");
Craig Topper062a2ba2014-04-25 05:30:21 +00001331 return nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001332}
1333
Justin Holewinski0497ab12013-03-30 14:29:21 +00001334void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001335 raw_ostream &O) {
1336
Eric Christopher8b770652015-01-26 19:03:15 +00001337 const DataLayout *TD = TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001338
1339 // GlobalVariables are always constant pointers themselves.
1340 const PointerType *PTy = GVar->getType();
1341 Type *ETy = PTy->getElementType();
1342
1343 O << ".";
1344 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1345 if (GVar->getAlignment() == 0)
1346 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1347 else
1348 O << " .align " << GVar->getAlignment();
1349
Jingyue Wue4c9cf02014-12-17 17:59:04 +00001350 if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001351 O << " .";
1352 O << getPTXFundamentalTypeStr(ETy);
1353 O << " ";
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00001354 O << *getSymbol(GVar);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001355 return;
1356 }
1357
Justin Holewinski0497ab12013-03-30 14:29:21 +00001358 int64_t ElementSize = 0;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001359
1360 // Although PTX has direct support for struct type and array type and LLVM IR
1361 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1362 // support these high level field accesses. Structs and arrays are lowered
1363 // into arrays of bytes.
1364 switch (ETy->getTypeID()) {
1365 case Type::StructTyID:
1366 case Type::ArrayTyID:
1367 case Type::VectorTyID:
1368 ElementSize = TD->getTypeStoreSize(ETy);
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00001369 O << " .b8 " << *getSymbol(GVar) << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001370 if (ElementSize) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001371 O << itostr(ElementSize);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001372 }
1373 O << "]";
1374 break;
1375 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001376 llvm_unreachable("type not supported yet");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001377 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001378 return;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001379}
1380
Justin Holewinski0497ab12013-03-30 14:29:21 +00001381static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
Rafael Espindola08013342013-12-07 19:34:20 +00001382 if (Ty->isSingleValueType())
Justin Holewinskiae556d32012-05-04 20:18:50 +00001383 return TD->getPrefTypeAlignment(Ty);
1384
1385 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1386 if (ATy)
1387 return getOpenCLAlignment(TD, ATy->getElementType());
1388
Justin Holewinskiae556d32012-05-04 20:18:50 +00001389 const StructType *STy = dyn_cast<StructType>(Ty);
1390 if (STy) {
1391 unsigned int alignStruct = 1;
1392 // Go through each element of the struct and find the
1393 // largest alignment.
Justin Holewinski0497ab12013-03-30 14:29:21 +00001394 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001395 Type *ETy = STy->getElementType(i);
1396 unsigned int align = getOpenCLAlignment(TD, ETy);
1397 if (align > alignStruct)
1398 alignStruct = align;
1399 }
1400 return alignStruct;
1401 }
1402
1403 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1404 if (FTy)
Chandler Carruth5da3f052012-11-01 09:14:31 +00001405 return TD->getPointerPrefAlignment();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001406 return TD->getPrefTypeAlignment(Ty);
1407}
1408
1409void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1410 int paramIndex, raw_ostream &O) {
Eric Christopherbeffc4e2015-02-19 00:08:23 +00001411 O << *getSymbol(I->getParent()) << "_param_" << paramIndex;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001412}
1413
1414void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
Eric Christopherbeffc4e2015-02-19 00:08:23 +00001415 O << *CurrentFnSym << "_param_" << paramIndex;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001416}
1417
Justin Holewinski0497ab12013-03-30 14:29:21 +00001418void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
Eric Christopher8b770652015-01-26 19:03:15 +00001419 const DataLayout *TD = TM.getDataLayout();
Bill Wendlinge94d8432012-12-07 23:16:57 +00001420 const AttributeSet &PAL = F->getAttributes();
Eric Christopher6aad8b12015-02-19 00:08:14 +00001421 const TargetLowering *TLI = nvptxSubtarget->getTargetLowering();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001422 Function::const_arg_iterator I, E;
1423 unsigned paramIndex = 0;
1424 bool first = true;
1425 bool isKernelFunc = llvm::isKernelFunction(*F);
Eric Christopher6aad8b12015-02-19 00:08:14 +00001426 bool isABI = (nvptxSubtarget->getSmVersion() >= 20);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001427 MVT thePointerTy = TLI->getPointerTy();
1428
1429 O << "(\n";
1430
1431 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
Justin Holewinskie9884092013-03-24 21:17:47 +00001432 Type *Ty = I->getType();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001433
1434 if (!first)
1435 O << ",\n";
1436
1437 first = false;
1438
1439 // Handle image/sampler parameters
Justin Holewinski30d56a72014-04-09 15:39:15 +00001440 if (isKernelFunction(*F)) {
1441 if (isSampler(*I) || isImage(*I)) {
1442 if (isImage(*I)) {
1443 std::string sname = I->getName();
1444 if (isImageWriteOnly(*I) || isImageReadWrite(*I)) {
Eric Christopher6aad8b12015-02-19 00:08:14 +00001445 if (nvptxSubtarget->hasImageHandles())
Justin Holewinski30d56a72014-04-09 15:39:15 +00001446 O << "\t.param .u64 .ptr .surfref ";
1447 else
1448 O << "\t.param .surfref ";
1449 O << *CurrentFnSym << "_param_" << paramIndex;
1450 }
1451 else { // Default image is read_only
Eric Christopher6aad8b12015-02-19 00:08:14 +00001452 if (nvptxSubtarget->hasImageHandles())
Justin Holewinski30d56a72014-04-09 15:39:15 +00001453 O << "\t.param .u64 .ptr .texref ";
1454 else
1455 O << "\t.param .texref ";
1456 O << *CurrentFnSym << "_param_" << paramIndex;
1457 }
1458 } else {
Eric Christopher6aad8b12015-02-19 00:08:14 +00001459 if (nvptxSubtarget->hasImageHandles())
Justin Holewinski30d56a72014-04-09 15:39:15 +00001460 O << "\t.param .u64 .ptr .samplerref ";
1461 else
1462 O << "\t.param .samplerref ";
1463 O << *CurrentFnSym << "_param_" << paramIndex;
1464 }
1465 continue;
1466 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001467 }
1468
Eli Bendersky3e840192015-03-23 16:26:23 +00001469 if (!PAL.hasAttribute(paramIndex + 1, Attribute::ByVal)) {
Gautam Chakrabarti2c283402014-01-28 18:35:29 +00001470 if (Ty->isAggregateType() || Ty->isVectorTy()) {
1471 // Just print .param .align <a> .b8 .param[size];
Justin Holewinskie9884092013-03-24 21:17:47 +00001472 // <a> = PAL.getparamalignment
1473 // size = typeallocsize of element type
Justin Holewinski0497ab12013-03-30 14:29:21 +00001474 unsigned align = PAL.getParamAlignment(paramIndex + 1);
Justin Holewinskie9884092013-03-24 21:17:47 +00001475 if (align == 0)
1476 align = TD->getABITypeAlignment(Ty);
1477
1478 unsigned sz = TD->getTypeAllocSize(Ty);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001479 O << "\t.param .align " << align << " .b8 ";
Justin Holewinskie9884092013-03-24 21:17:47 +00001480 printParamName(I, paramIndex, O);
1481 O << "[" << sz << "]";
1482
1483 continue;
1484 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001485 // Just a scalar
1486 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1487 if (isKernelFunc) {
1488 if (PTy) {
1489 // Special handling for pointer arguments to kernel
1490 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1491
Eric Christopherbeffc4e2015-02-19 00:08:23 +00001492 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() !=
1493 NVPTX::CUDA) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001494 Type *ETy = PTy->getElementType();
1495 int addrSpace = PTy->getAddressSpace();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001496 switch (addrSpace) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001497 default:
1498 O << ".ptr ";
1499 break;
Justin Holewinskib96d1392013-06-10 13:29:47 +00001500 case llvm::ADDRESS_SPACE_CONST:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001501 O << ".ptr .const ";
1502 break;
1503 case llvm::ADDRESS_SPACE_SHARED:
1504 O << ".ptr .shared ";
1505 break;
1506 case llvm::ADDRESS_SPACE_GLOBAL:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001507 O << ".ptr .global ";
1508 break;
1509 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001510 O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001511 }
1512 printParamName(I, paramIndex, O);
1513 continue;
1514 }
1515
1516 // non-pointer scalar to kernel func
Justin Holewinski700b6fa2013-05-20 12:13:28 +00001517 O << "\t.param .";
1518 // Special case: predicate operands become .u8 types
1519 if (Ty->isIntegerTy(1))
1520 O << "u8";
1521 else
1522 O << getPTXFundamentalTypeStr(Ty);
1523 O << " ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001524 printParamName(I, paramIndex, O);
1525 continue;
1526 }
1527 // Non-kernel function, just print .param .b<size> for ABI
Alp Tokerf907b892013-12-05 05:44:44 +00001528 // and .reg .b<size> for non-ABI
Justin Holewinskiae556d32012-05-04 20:18:50 +00001529 unsigned sz = 0;
1530 if (isa<IntegerType>(Ty)) {
1531 sz = cast<IntegerType>(Ty)->getBitWidth();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001532 if (sz < 32)
1533 sz = 32;
1534 } else if (isa<PointerType>(Ty))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001535 sz = thePointerTy.getSizeInBits();
1536 else
1537 sz = Ty->getPrimitiveSizeInBits();
1538 if (isABI)
1539 O << "\t.param .b" << sz << " ";
1540 else
1541 O << "\t.reg .b" << sz << " ";
1542 printParamName(I, paramIndex, O);
1543 continue;
1544 }
1545
1546 // param has byVal attribute. So should be a pointer
1547 const PointerType *PTy = dyn_cast<PointerType>(Ty);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001548 assert(PTy && "Param with byval attribute should be a pointer type");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001549 Type *ETy = PTy->getElementType();
1550
1551 if (isABI || isKernelFunc) {
Gautam Chakrabarti2c283402014-01-28 18:35:29 +00001552 // Just print .param .align <a> .b8 .param[size];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001553 // <a> = PAL.getparamalignment
1554 // size = typeallocsize of element type
Justin Holewinski0497ab12013-03-30 14:29:21 +00001555 unsigned align = PAL.getParamAlignment(paramIndex + 1);
Justin Holewinski2dc9d072012-11-09 23:50:24 +00001556 if (align == 0)
1557 align = TD->getABITypeAlignment(ETy);
1558
Justin Holewinskiae556d32012-05-04 20:18:50 +00001559 unsigned sz = TD->getTypeAllocSize(ETy);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001560 O << "\t.param .align " << align << " .b8 ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001561 printParamName(I, paramIndex, O);
1562 O << "[" << sz << "]";
1563 continue;
1564 } else {
1565 // Split the ETy into constituent parts and
1566 // print .param .b<size> <name> for each part.
1567 // Further, if a part is vector, print the above for
1568 // each vector element.
1569 SmallVector<EVT, 16> vtparts;
1570 ComputeValueVTs(*TLI, ETy, vtparts);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001571 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001572 unsigned elems = 1;
1573 EVT elemtype = vtparts[i];
1574 if (vtparts[i].isVector()) {
1575 elems = vtparts[i].getVectorNumElements();
1576 elemtype = vtparts[i].getVectorElementType();
1577 }
1578
Justin Holewinski0497ab12013-03-30 14:29:21 +00001579 for (unsigned j = 0, je = elems; j != je; ++j) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001580 unsigned sz = elemtype.getSizeInBits();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001581 if (elemtype.isInteger() && (sz < 32))
1582 sz = 32;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001583 O << "\t.reg .b" << sz << " ";
1584 printParamName(I, paramIndex, O);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001585 if (j < je - 1)
1586 O << ",\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001587 ++paramIndex;
1588 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001589 if (i < e - 1)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001590 O << ",\n";
1591 }
1592 --paramIndex;
1593 continue;
1594 }
1595 }
1596
1597 O << "\n)\n";
1598}
1599
1600void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1601 raw_ostream &O) {
1602 const Function *F = MF.getFunction();
1603 emitFunctionParamList(F, O);
1604}
1605
Justin Holewinski0497ab12013-03-30 14:29:21 +00001606void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1607 const MachineFunction &MF) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001608 SmallString<128> Str;
1609 raw_svector_ostream O(Str);
1610
1611 // Map the global virtual register number to a register class specific
1612 // virtual register number starting from 1 with that class.
Eric Christopherfc6de422014-08-05 02:39:49 +00001613 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001614 //unsigned numRegClasses = TRI->getNumRegClasses();
1615
1616 // Emit the Fake Stack Object
1617 const MachineFrameInfo *MFI = MF.getFrameInfo();
1618 int NumBytes = (int) MFI->getStackSize();
1619 if (NumBytes) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001620 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1621 << getFunctionNumber() << "[" << NumBytes << "];\n";
Eric Christopher02389e32015-02-19 00:08:27 +00001622 if (static_cast<const NVPTXTargetMachine &>(MF.getTarget()).is64Bit()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001623 O << "\t.reg .b64 \t%SP;\n";
1624 O << "\t.reg .b64 \t%SPL;\n";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001625 } else {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001626 O << "\t.reg .b32 \t%SP;\n";
1627 O << "\t.reg .b32 \t%SPL;\n";
1628 }
1629 }
1630
1631 // Go through all virtual registers to establish the mapping between the
1632 // global virtual
1633 // register number and the per class virtual register number.
1634 // We use the per class virtual register number in the ptx output.
1635 unsigned int numVRs = MRI->getNumVirtRegs();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001636 for (unsigned i = 0; i < numVRs; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001637 unsigned int vr = TRI->index2VirtReg(i);
1638 const TargetRegisterClass *RC = MRI->getRegClass(vr);
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001639 DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001640 int n = regmap.size();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001641 regmap.insert(std::make_pair(vr, n + 1));
Justin Holewinskiae556d32012-05-04 20:18:50 +00001642 }
1643
1644 // Emit register declarations
1645 // @TODO: Extract out the real register usage
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001646 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1647 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1648 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1649 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
Justin Holewinski3e037d92014-07-16 16:26:58 +00001650 // O << "\t.reg .s64 %rd<" << NVPTXNumRegisters << ">;\n";
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001651 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
Justin Holewinski3e037d92014-07-16 16:26:58 +00001652 // O << "\t.reg .f64 %fd<" << NVPTXNumRegisters << ">;\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001653
1654 // Emit declaration of the virtual registers or 'physical' registers for
1655 // each register class
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001656 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1657 const TargetRegisterClass *RC = TRI->getRegClass(i);
1658 DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
1659 std::string rcname = getNVPTXRegClassName(RC);
1660 std::string rcStr = getNVPTXRegClassStr(RC);
1661 int n = regmap.size();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001662
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001663 // Only declare those registers that may be used.
1664 if (n) {
1665 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1666 << ">;\n";
1667 }
1668 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001669
Lang Hames9ff69c82015-04-24 19:11:51 +00001670 OutStreamer->EmitRawText(O.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +00001671}
1672
Justin Holewinskiae556d32012-05-04 20:18:50 +00001673void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001674 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
Justin Holewinskiae556d32012-05-04 20:18:50 +00001675 bool ignored;
1676 unsigned int numHex;
1677 const char *lead;
1678
Justin Holewinski0497ab12013-03-30 14:29:21 +00001679 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001680 numHex = 8;
1681 lead = "0f";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001682 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001683 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1684 numHex = 16;
1685 lead = "0d";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001686 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001687 } else
1688 llvm_unreachable("unsupported fp type");
1689
1690 APInt API = APF.bitcastToAPInt();
1691 std::string hexstr(utohexstr(API.getZExtValue()));
1692 O << lead;
1693 if (hexstr.length() < numHex)
1694 O << std::string(numHex - hexstr.length(), '0');
1695 O << utohexstr(API.getZExtValue());
1696}
1697
Justin Holewinski01f89f02013-05-20 12:13:32 +00001698void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1699 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001700 O << CI->getValue();
1701 return;
1702 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001703 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001704 printFPConstant(CFP, O);
1705 return;
1706 }
1707 if (isa<ConstantPointerNull>(CPV)) {
1708 O << "0";
1709 return;
1710 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001711 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
Justin Holewinski9d852a82014-04-09 15:39:11 +00001712 PointerType *PTy = dyn_cast<PointerType>(GVar->getType());
1713 bool IsNonGenericPointer = false;
1714 if (PTy && PTy->getAddressSpace() != 0) {
1715 IsNonGenericPointer = true;
1716 }
1717 if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
1718 O << "generic(";
1719 O << *getSymbol(GVar);
1720 O << ")";
1721 } else {
1722 O << *getSymbol(GVar);
1723 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001724 return;
1725 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001726 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1727 const Value *v = Cexpr->stripPointerCasts();
Justin Holewinski9d852a82014-04-09 15:39:11 +00001728 PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
1729 bool IsNonGenericPointer = false;
1730 if (PTy && PTy->getAddressSpace() != 0) {
1731 IsNonGenericPointer = true;
1732 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001733 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
Justin Holewinski9d852a82014-04-09 15:39:11 +00001734 if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
1735 O << "generic(";
1736 O << *getSymbol(GVar);
1737 O << ")";
1738 } else {
1739 O << *getSymbol(GVar);
1740 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001741 return;
1742 } else {
Matt Arsenault31a52ad2014-12-16 19:16:17 +00001743 O << *lowerConstant(CPV);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001744 return;
1745 }
1746 }
1747 llvm_unreachable("Not scalar type found in printScalarConstant()");
1748}
1749
Justin Holewinski01f89f02013-05-20 12:13:32 +00001750void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001751 AggBuffer *aggBuffer) {
1752
Eric Christopher8b770652015-01-26 19:03:15 +00001753 const DataLayout *TD = TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001754
1755 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1756 int s = TD->getTypeAllocSize(CPV->getType());
Justin Holewinski0497ab12013-03-30 14:29:21 +00001757 if (s < Bytes)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001758 s = Bytes;
1759 aggBuffer->addZeros(s);
1760 return;
1761 }
1762
1763 unsigned char *ptr;
1764 switch (CPV->getType()->getTypeID()) {
1765
1766 case Type::IntegerTyID: {
1767 const Type *ETy = CPV->getType();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001768 if (ETy == Type::getInt8Ty(CPV->getContext())) {
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001769 unsigned char c = (unsigned char)cast<ConstantInt>(CPV)->getZExtValue();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001770 ptr = &c;
1771 aggBuffer->addBytes(ptr, 1, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001772 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001773 short int16 = (short)cast<ConstantInt>(CPV)->getZExtValue();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001774 ptr = (unsigned char *)&int16;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001775 aggBuffer->addBytes(ptr, 2, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001776 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001777 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001778 int int32 = (int)(constInt->getZExtValue());
1779 ptr = (unsigned char *)&int32;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001780 aggBuffer->addBytes(ptr, 4, Bytes);
1781 break;
Justin Holewinski01f89f02013-05-20 12:13:32 +00001782 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1783 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001784 ConstantFoldConstantExpression(Cexpr, *TD))) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001785 int int32 = (int)(constInt->getZExtValue());
1786 ptr = (unsigned char *)&int32;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001787 aggBuffer->addBytes(ptr, 4, Bytes);
1788 break;
1789 }
1790 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1791 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
Jingyue Wu312fd022015-04-24 02:57:30 +00001792 aggBuffer->addSymbol(v, Cexpr->getOperand(0));
Justin Holewinskiae556d32012-05-04 20:18:50 +00001793 aggBuffer->addZeros(4);
1794 break;
1795 }
1796 }
Craig Topperbdf39a42012-05-24 07:02:50 +00001797 llvm_unreachable("unsupported integer const type");
Justin Holewinski0497ab12013-03-30 14:29:21 +00001798 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001799 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001800 long long int64 = (long long)(constInt->getZExtValue());
1801 ptr = (unsigned char *)&int64;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001802 aggBuffer->addBytes(ptr, 8, Bytes);
1803 break;
Justin Holewinski01f89f02013-05-20 12:13:32 +00001804 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1805 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001806 ConstantFoldConstantExpression(Cexpr, *TD))) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001807 long long int64 = (long long)(constInt->getZExtValue());
1808 ptr = (unsigned char *)&int64;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001809 aggBuffer->addBytes(ptr, 8, Bytes);
1810 break;
1811 }
1812 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1813 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
Jingyue Wu312fd022015-04-24 02:57:30 +00001814 aggBuffer->addSymbol(v, Cexpr->getOperand(0));
Justin Holewinskiae556d32012-05-04 20:18:50 +00001815 aggBuffer->addZeros(8);
1816 break;
1817 }
1818 }
1819 llvm_unreachable("unsupported integer const type");
Craig Topperbdf39a42012-05-24 07:02:50 +00001820 } else
Justin Holewinskiae556d32012-05-04 20:18:50 +00001821 llvm_unreachable("unsupported integer const type");
1822 break;
1823 }
1824 case Type::FloatTyID:
1825 case Type::DoubleTyID: {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001826 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001827 const Type *Ty = CFP->getType();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001828 if (Ty == Type::getFloatTy(CPV->getContext())) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001829 float float32 = (float) CFP->getValueAPF().convertToFloat();
1830 ptr = (unsigned char *)&float32;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001831 aggBuffer->addBytes(ptr, 4, Bytes);
1832 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1833 double float64 = CFP->getValueAPF().convertToDouble();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001834 ptr = (unsigned char *)&float64;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001835 aggBuffer->addBytes(ptr, 8, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001836 } else {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001837 llvm_unreachable("unsupported fp const type");
1838 }
1839 break;
1840 }
1841 case Type::PointerTyID: {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001842 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
Jingyue Wu312fd022015-04-24 02:57:30 +00001843 aggBuffer->addSymbol(GVar, GVar);
Justin Holewinski01f89f02013-05-20 12:13:32 +00001844 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1845 const Value *v = Cexpr->stripPointerCasts();
Jingyue Wu312fd022015-04-24 02:57:30 +00001846 aggBuffer->addSymbol(v, Cexpr);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001847 }
1848 unsigned int s = TD->getTypeAllocSize(CPV->getType());
1849 aggBuffer->addZeros(s);
1850 break;
1851 }
1852
1853 case Type::ArrayTyID:
1854 case Type::VectorTyID:
1855 case Type::StructTyID: {
1856 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
Justin Holewinski95564bd2013-09-19 12:51:46 +00001857 isa<ConstantStruct>(CPV) || isa<ConstantDataSequential>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001858 int ElementSize = TD->getTypeAllocSize(CPV->getType());
1859 bufferAggregateConstant(CPV, aggBuffer);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001860 if (Bytes > ElementSize)
1861 aggBuffer->addZeros(Bytes - ElementSize);
1862 } else if (isa<ConstantAggregateZero>(CPV))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001863 aggBuffer->addZeros(Bytes);
1864 else
1865 llvm_unreachable("Unexpected Constant type");
1866 break;
1867 }
1868
1869 default:
1870 llvm_unreachable("unsupported type");
1871 }
1872}
1873
Justin Holewinski01f89f02013-05-20 12:13:32 +00001874void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001875 AggBuffer *aggBuffer) {
Eric Christopher8b770652015-01-26 19:03:15 +00001876 const DataLayout *TD = TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001877 int Bytes;
1878
1879 // Old constants
1880 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1881 if (CPV->getNumOperands())
1882 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1883 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1884 return;
1885 }
1886
1887 if (const ConstantDataSequential *CDS =
Justin Holewinski0497ab12013-03-30 14:29:21 +00001888 dyn_cast<ConstantDataSequential>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001889 if (CDS->getNumElements())
1890 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1891 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1892 aggBuffer);
1893 return;
1894 }
1895
Justin Holewinskiae556d32012-05-04 20:18:50 +00001896 if (isa<ConstantStruct>(CPV)) {
1897 if (CPV->getNumOperands()) {
1898 StructType *ST = cast<StructType>(CPV->getType());
1899 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001900 if (i == (e - 1))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001901 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
Justin Holewinski0497ab12013-03-30 14:29:21 +00001902 TD->getTypeAllocSize(ST) -
1903 TD->getStructLayout(ST)->getElementOffset(i);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001904 else
Justin Holewinski0497ab12013-03-30 14:29:21 +00001905 Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
1906 TD->getStructLayout(ST)->getElementOffset(i);
1907 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001908 }
1909 }
1910 return;
1911 }
Craig Topperbdf39a42012-05-24 07:02:50 +00001912 llvm_unreachable("unsupported constant type in printAggregateConstant()");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001913}
1914
1915// buildTypeNameMap - Run through symbol table looking for type names.
1916//
1917
Justin Holewinskiae556d32012-05-04 20:18:50 +00001918bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
1919
1920 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
1921
Justin Holewinski0497ab12013-03-30 14:29:21 +00001922 if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
1923 !PI->second.compare("struct._image2d_t") ||
1924 !PI->second.compare("struct._image3d_t")))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001925 return true;
1926
1927 return false;
1928}
1929
Justin Holewinskiae556d32012-05-04 20:18:50 +00001930
Justin Holewinski0497ab12013-03-30 14:29:21 +00001931bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
1932 switch (MI.getOpcode()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001933 default:
1934 return false;
Justin Holewinski0497ab12013-03-30 14:29:21 +00001935 case NVPTX::CallArgBeginInst:
1936 case NVPTX::CallArgEndInst0:
1937 case NVPTX::CallArgEndInst1:
1938 case NVPTX::CallArgF32:
1939 case NVPTX::CallArgF64:
1940 case NVPTX::CallArgI16:
1941 case NVPTX::CallArgI32:
1942 case NVPTX::CallArgI32imm:
1943 case NVPTX::CallArgI64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001944 case NVPTX::CallArgParam:
1945 case NVPTX::CallVoidInst:
1946 case NVPTX::CallVoidInstReg:
1947 case NVPTX::Callseq_End:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001948 case NVPTX::CallVoidInstReg64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001949 case NVPTX::DeclareParamInst:
1950 case NVPTX::DeclareRetMemInst:
1951 case NVPTX::DeclareRetRegInst:
1952 case NVPTX::DeclareRetScalarInst:
1953 case NVPTX::DeclareScalarParamInst:
1954 case NVPTX::DeclareScalarRegInst:
1955 case NVPTX::StoreParamF32:
1956 case NVPTX::StoreParamF64:
1957 case NVPTX::StoreParamI16:
1958 case NVPTX::StoreParamI32:
1959 case NVPTX::StoreParamI64:
1960 case NVPTX::StoreParamI8:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001961 case NVPTX::StoreRetvalF32:
1962 case NVPTX::StoreRetvalF64:
1963 case NVPTX::StoreRetvalI16:
1964 case NVPTX::StoreRetvalI32:
1965 case NVPTX::StoreRetvalI64:
1966 case NVPTX::StoreRetvalI8:
1967 case NVPTX::LastCallArgF32:
1968 case NVPTX::LastCallArgF64:
1969 case NVPTX::LastCallArgI16:
1970 case NVPTX::LastCallArgI32:
1971 case NVPTX::LastCallArgI32imm:
1972 case NVPTX::LastCallArgI64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001973 case NVPTX::LastCallArgParam:
1974 case NVPTX::LoadParamMemF32:
1975 case NVPTX::LoadParamMemF64:
1976 case NVPTX::LoadParamMemI16:
1977 case NVPTX::LoadParamMemI32:
1978 case NVPTX::LoadParamMemI64:
1979 case NVPTX::LoadParamMemI8:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001980 case NVPTX::PrototypeInst:
1981 case NVPTX::DBG_VALUE:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001982 return true;
1983 }
1984 return false;
1985}
1986
Justin Holewinski3d2a9762015-04-28 17:18:30 +00001987/// lowerConstantForGV - Return an MCExpr for the given Constant. This is mostly
1988/// a copy from AsmPrinter::lowerConstant, except customized to only handle
1989/// expressions that are representable in PTX and create
1990/// NVPTXGenericMCSymbolRefExpr nodes for addrspacecast instructions.
1991const MCExpr *
1992NVPTXAsmPrinter::lowerConstantForGV(const Constant *CV, bool ProcessingGeneric) {
1993 MCContext &Ctx = OutContext;
1994
1995 if (CV->isNullValue() || isa<UndefValue>(CV))
1996 return MCConstantExpr::Create(0, Ctx);
1997
1998 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1999 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
2000
2001 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
2002 const MCSymbolRefExpr *Expr =
2003 MCSymbolRefExpr::Create(getSymbol(GV), Ctx);
2004 if (ProcessingGeneric) {
2005 return NVPTXGenericMCSymbolRefExpr::Create(Expr, Ctx);
2006 } else {
2007 return Expr;
2008 }
2009 }
2010
2011 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
2012 if (!CE) {
2013 llvm_unreachable("Unknown constant value to lower!");
2014 }
2015
2016 switch (CE->getOpcode()) {
2017 default:
2018 // If the code isn't optimized, there may be outstanding folding
2019 // opportunities. Attempt to fold the expression using DataLayout as a
2020 // last resort before giving up.
2021 if (Constant *C = ConstantFoldConstantExpression(CE, *TM.getDataLayout()))
2022 if (C != CE)
2023 return lowerConstantForGV(C, ProcessingGeneric);
2024
2025 // Otherwise report the problem to the user.
2026 {
2027 std::string S;
2028 raw_string_ostream OS(S);
2029 OS << "Unsupported expression in static initializer: ";
2030 CE->printAsOperand(OS, /*PrintType=*/false,
2031 !MF ? nullptr : MF->getFunction()->getParent());
2032 report_fatal_error(OS.str());
2033 }
2034
2035 case Instruction::AddrSpaceCast: {
2036 // Strip the addrspacecast and pass along the operand
2037 PointerType *DstTy = cast<PointerType>(CE->getType());
2038 if (DstTy->getAddressSpace() == 0) {
2039 return lowerConstantForGV(cast<const Constant>(CE->getOperand(0)), true);
2040 }
2041 std::string S;
2042 raw_string_ostream OS(S);
2043 OS << "Unsupported expression in static initializer: ";
2044 CE->printAsOperand(OS, /*PrintType=*/ false,
2045 !MF ? 0 : MF->getFunction()->getParent());
2046 report_fatal_error(OS.str());
2047 }
2048
2049 case Instruction::GetElementPtr: {
2050 const DataLayout &DL = *TM.getDataLayout();
2051
2052 // Generate a symbolic expression for the byte address
2053 APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
2054 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
2055
2056 const MCExpr *Base = lowerConstantForGV(CE->getOperand(0),
2057 ProcessingGeneric);
2058 if (!OffsetAI)
2059 return Base;
2060
2061 int64_t Offset = OffsetAI.getSExtValue();
2062 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
2063 Ctx);
2064 }
2065
2066 case Instruction::Trunc:
2067 // We emit the value and depend on the assembler to truncate the generated
2068 // expression properly. This is important for differences between
2069 // blockaddress labels. Since the two labels are in the same function, it
2070 // is reasonable to treat their delta as a 32-bit value.
2071 // FALL THROUGH.
2072 case Instruction::BitCast:
2073 return lowerConstantForGV(CE->getOperand(0), ProcessingGeneric);
2074
2075 case Instruction::IntToPtr: {
2076 const DataLayout &DL = *TM.getDataLayout();
2077
2078 // Handle casts to pointers by changing them into casts to the appropriate
2079 // integer type. This promotes constant folding and simplifies this code.
2080 Constant *Op = CE->getOperand(0);
2081 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
2082 false/*ZExt*/);
2083 return lowerConstantForGV(Op, ProcessingGeneric);
2084 }
2085
2086 case Instruction::PtrToInt: {
2087 const DataLayout &DL = *TM.getDataLayout();
2088
2089 // Support only foldable casts to/from pointers that can be eliminated by
2090 // changing the pointer to the appropriately sized integer type.
2091 Constant *Op = CE->getOperand(0);
2092 Type *Ty = CE->getType();
2093
2094 const MCExpr *OpExpr = lowerConstantForGV(Op, ProcessingGeneric);
2095
2096 // We can emit the pointer value into this slot if the slot is an
2097 // integer slot equal to the size of the pointer.
2098 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
2099 return OpExpr;
2100
2101 // Otherwise the pointer is smaller than the resultant integer, mask off
2102 // the high bits so we are sure to get a proper truncation if the input is
2103 // a constant expr.
2104 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
2105 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
2106 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
2107 }
2108
2109 // The MC library also has a right-shift operator, but it isn't consistently
2110 // signed or unsigned between different targets.
2111 case Instruction::Add: {
2112 const MCExpr *LHS = lowerConstantForGV(CE->getOperand(0), ProcessingGeneric);
2113 const MCExpr *RHS = lowerConstantForGV(CE->getOperand(1), ProcessingGeneric);
2114 switch (CE->getOpcode()) {
2115 default: llvm_unreachable("Unknown binary operator constant cast expr");
2116 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
2117 }
2118 }
2119 }
2120}
2121
2122// Copy of MCExpr::print customized for NVPTX
2123void NVPTXAsmPrinter::printMCExpr(const MCExpr &Expr, raw_ostream &OS) {
2124 switch (Expr.getKind()) {
2125 case MCExpr::Target:
2126 return cast<MCTargetExpr>(&Expr)->PrintImpl(OS);
2127 case MCExpr::Constant:
2128 OS << cast<MCConstantExpr>(Expr).getValue();
2129 return;
2130
2131 case MCExpr::SymbolRef: {
2132 const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(Expr);
2133 const MCSymbol &Sym = SRE.getSymbol();
2134 OS << Sym;
2135 return;
2136 }
2137
2138 case MCExpr::Unary: {
2139 const MCUnaryExpr &UE = cast<MCUnaryExpr>(Expr);
2140 switch (UE.getOpcode()) {
2141 case MCUnaryExpr::LNot: OS << '!'; break;
2142 case MCUnaryExpr::Minus: OS << '-'; break;
2143 case MCUnaryExpr::Not: OS << '~'; break;
2144 case MCUnaryExpr::Plus: OS << '+'; break;
2145 }
2146 printMCExpr(*UE.getSubExpr(), OS);
2147 return;
2148 }
2149
2150 case MCExpr::Binary: {
2151 const MCBinaryExpr &BE = cast<MCBinaryExpr>(Expr);
2152
2153 // Only print parens around the LHS if it is non-trivial.
2154 if (isa<MCConstantExpr>(BE.getLHS()) || isa<MCSymbolRefExpr>(BE.getLHS()) ||
2155 isa<NVPTXGenericMCSymbolRefExpr>(BE.getLHS())) {
2156 printMCExpr(*BE.getLHS(), OS);
2157 } else {
2158 OS << '(';
2159 printMCExpr(*BE.getLHS(), OS);
2160 OS<< ')';
2161 }
2162
2163 switch (BE.getOpcode()) {
2164 case MCBinaryExpr::Add:
2165 // Print "X-42" instead of "X+-42".
2166 if (const MCConstantExpr *RHSC = dyn_cast<MCConstantExpr>(BE.getRHS())) {
2167 if (RHSC->getValue() < 0) {
2168 OS << RHSC->getValue();
2169 return;
2170 }
2171 }
2172
2173 OS << '+';
2174 break;
2175 default: llvm_unreachable("Unhandled binary operator");
2176 }
2177
2178 // Only print parens around the LHS if it is non-trivial.
2179 if (isa<MCConstantExpr>(BE.getRHS()) || isa<MCSymbolRefExpr>(BE.getRHS())) {
2180 printMCExpr(*BE.getRHS(), OS);
2181 } else {
2182 OS << '(';
2183 printMCExpr(*BE.getRHS(), OS);
2184 OS << ')';
2185 }
2186 return;
2187 }
2188 }
2189
2190 llvm_unreachable("Invalid expression kind!");
2191}
2192
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002193/// PrintAsmOperand - Print out an operand for an inline asm expression.
2194///
2195bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2196 unsigned AsmVariant,
2197 const char *ExtraCode, raw_ostream &O) {
2198 if (ExtraCode && ExtraCode[0]) {
2199 if (ExtraCode[1] != 0)
2200 return true; // Unknown modifier.
2201
2202 switch (ExtraCode[0]) {
2203 default:
2204 // See if this is a generic print operand
2205 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2206 case 'r':
2207 break;
2208 }
2209 }
2210
2211 printOperand(MI, OpNo, O);
2212
2213 return false;
2214}
2215
2216bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2217 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2218 const char *ExtraCode, raw_ostream &O) {
2219 if (ExtraCode && ExtraCode[0])
2220 return true; // Unknown modifier
2221
2222 O << '[';
2223 printMemOperand(MI, OpNo, O);
2224 O << ']';
2225
2226 return false;
2227}
2228
2229void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2230 raw_ostream &O, const char *Modifier) {
2231 const MachineOperand &MO = MI->getOperand(opNum);
2232 switch (MO.getType()) {
2233 case MachineOperand::MO_Register:
2234 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2235 if (MO.getReg() == NVPTX::VRDepot)
2236 O << DEPOTNAME << getFunctionNumber();
2237 else
2238 O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2239 } else {
Justin Holewinski660597d2013-10-11 12:39:36 +00002240 emitVirtualRegister(MO.getReg(), O);
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002241 }
2242 return;
2243
2244 case MachineOperand::MO_Immediate:
2245 if (!Modifier)
2246 O << MO.getImm();
2247 else if (strstr(Modifier, "vec") == Modifier)
2248 printVecModifiedImmediate(MO, Modifier, O);
2249 else
2250 llvm_unreachable(
2251 "Don't know how to handle modifier on immediate operand");
2252 return;
2253
2254 case MachineOperand::MO_FPImmediate:
2255 printFPConstant(MO.getFPImm(), O);
2256 break;
2257
2258 case MachineOperand::MO_GlobalAddress:
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00002259 O << *getSymbol(MO.getGlobal());
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002260 break;
2261
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002262 case MachineOperand::MO_MachineBasicBlock:
2263 O << *MO.getMBB()->getSymbol();
2264 return;
2265
2266 default:
2267 llvm_unreachable("Operand type not supported.");
2268 }
2269}
2270
2271void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2272 raw_ostream &O, const char *Modifier) {
2273 printOperand(MI, opNum, O);
2274
2275 if (Modifier && !strcmp(Modifier, "add")) {
2276 O << ", ";
2277 printOperand(MI, opNum + 1, O);
2278 } else {
2279 if (MI->getOperand(opNum + 1).isImm() &&
2280 MI->getOperand(opNum + 1).getImm() == 0)
2281 return; // don't print ',0' or '+0'
2282 O << "+";
2283 printOperand(MI, opNum + 1, O);
2284 }
2285}
2286
Justin Holewinskiae556d32012-05-04 20:18:50 +00002287void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2288 std::stringstream temp;
Yaron Keren075759a2015-03-30 15:42:36 +00002289 LineReader *reader = this->getReader(filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002290 temp << "\n//";
2291 temp << filename.str();
2292 temp << ":";
2293 temp << line;
2294 temp << " ";
2295 temp << reader->readLine(line);
2296 temp << "\n";
Lang Hames9ff69c82015-04-24 19:11:51 +00002297 this->OutStreamer->EmitRawText(temp.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +00002298}
2299
Justin Holewinskiae556d32012-05-04 20:18:50 +00002300LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
Craig Topper062a2ba2014-04-25 05:30:21 +00002301 if (!reader) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00002302 reader = new LineReader(filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002303 }
2304
2305 if (reader->fileName() != filename) {
2306 delete reader;
Justin Holewinski0497ab12013-03-30 14:29:21 +00002307 reader = new LineReader(filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002308 }
2309
2310 return reader;
2311}
2312
Justin Holewinski0497ab12013-03-30 14:29:21 +00002313std::string LineReader::readLine(unsigned lineNum) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00002314 if (lineNum < theCurLine) {
2315 theCurLine = 0;
Justin Holewinski0497ab12013-03-30 14:29:21 +00002316 fstr.seekg(0, std::ios::beg);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002317 }
2318 while (theCurLine < lineNum) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00002319 fstr.getline(buff, 500);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002320 theCurLine++;
2321 }
2322 return buff;
2323}
2324
2325// Force static initialization.
2326extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2327 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2328 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2329}