blob: 652a4995569e6de494a0a53f4444f03a3ca85a1c [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 Holewinski30d56a72014-04-09 15:39:15 +000020#include "NVPTXMachineFunctionInfo.h"
Justin Holewinskia2a63d22013-08-06 14:13:27 +000021#include "NVPTXMCExpr.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"
30#include "llvm/CodeGen/MachineModuleInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/CodeGen/MachineRegisterInfo.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000032#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/DerivedTypes.h"
34#include "llvm/IR/Function.h"
35#include "llvm/IR/GlobalVariable.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000036#include "llvm/IR/Mangler.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000037#include "llvm/IR/Module.h"
38#include "llvm/IR/Operator.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000039#include "llvm/MC/MCStreamer.h"
40#include "llvm/MC/MCSymbol.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000041#include "llvm/Support/CommandLine.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000042#include "llvm/Support/ErrorHandling.h"
43#include "llvm/Support/FormattedStream.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000044#include "llvm/Support/Path.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000045#include "llvm/Support/TargetRegistry.h"
46#include "llvm/Support/TimeValue.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000047#include "llvm/Target/TargetLoweringObjectFile.h"
Bill Wendlinge38859d2012-06-28 00:05:13 +000048#include <sstream>
Justin Holewinskiae556d32012-05-04 20:18:50 +000049using namespace llvm;
50
Justin Holewinskiae556d32012-05-04 20:18:50 +000051#define DEPOTNAME "__local_depot"
52
53static cl::opt<bool>
Nadav Rotem7f27e0b2013-10-18 23:38:13 +000054EmitLineNumbers("nvptx-emit-line-numbers", cl::Hidden,
Justin Holewinskiae556d32012-05-04 20:18:50 +000055 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
56 cl::init(true));
57
Benjamin Kramer7ad41002013-10-27 11:31:46 +000058static cl::opt<bool>
Nadav Rotem7f27e0b2013-10-18 23:38:13 +000059InterleaveSrc("nvptx-emit-src", cl::ZeroOrMore, cl::Hidden,
Justin Holewinski0497ab12013-03-30 14:29:21 +000060 cl::desc("NVPTX Specific: Emit source line in ptx file"),
Benjamin Kramer7ad41002013-10-27 11:31:46 +000061 cl::init(false));
Justin Holewinskiae556d32012-05-04 20:18:50 +000062
Justin Holewinski2c5ac702012-11-16 21:03:51 +000063namespace {
64/// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
65/// depends.
Justin Holewinski01f89f02013-05-20 12:13:32 +000066void DiscoverDependentGlobals(const Value *V,
67 DenseSet<const GlobalVariable *> &Globals) {
68 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
Justin Holewinski2c5ac702012-11-16 21:03:51 +000069 Globals.insert(GV);
70 else {
Justin Holewinski01f89f02013-05-20 12:13:32 +000071 if (const User *U = dyn_cast<User>(V)) {
Justin Holewinski2c5ac702012-11-16 21:03:51 +000072 for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
73 DiscoverDependentGlobals(U->getOperand(i), Globals);
74 }
75 }
76 }
77}
Justin Holewinskiae556d32012-05-04 20:18:50 +000078
Justin Holewinski2c5ac702012-11-16 21:03:51 +000079/// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
80/// instances to be emitted, but only after any dependents have been added
81/// first.
Justin Holewinski0497ab12013-03-30 14:29:21 +000082void VisitGlobalVariableForEmission(
Justin Holewinski01f89f02013-05-20 12:13:32 +000083 const GlobalVariable *GV, SmallVectorImpl<const GlobalVariable *> &Order,
84 DenseSet<const GlobalVariable *> &Visited,
85 DenseSet<const GlobalVariable *> &Visiting) {
Justin Holewinski2c5ac702012-11-16 21:03:51 +000086 // Have we already visited this one?
Justin Holewinski0497ab12013-03-30 14:29:21 +000087 if (Visited.count(GV))
88 return;
Justin Holewinski2c5ac702012-11-16 21:03:51 +000089
90 // Do we have a circular dependency?
91 if (Visiting.count(GV))
92 report_fatal_error("Circular dependency found in global variable set");
93
94 // Start visiting this global
95 Visiting.insert(GV);
96
97 // 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
114// @TODO: This is a copy from AsmPrinter.cpp. The function is static, so we
115// cannot just link to the existing version.
116/// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
117///
118using namespace nvptx;
119const MCExpr *nvptx::LowerConstant(const Constant *CV, AsmPrinter &AP) {
120 MCContext &Ctx = AP.OutContext;
121
122 if (CV->isNullValue() || isa<UndefValue>(CV))
123 return MCConstantExpr::Create(0, Ctx);
124
125 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
126 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
127
128 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
Rafael Espindola79858aa2013-10-29 17:07:16 +0000129 return MCSymbolRefExpr::Create(AP.getSymbol(GV), Ctx);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000130
131 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
132 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
133
134 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
Craig Topper062a2ba2014-04-25 05:30:21 +0000135 if (!CE)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000136 llvm_unreachable("Unknown constant value to lower!");
137
Justin Holewinskiae556d32012-05-04 20:18:50 +0000138 switch (CE->getOpcode()) {
139 default:
140 // If the code isn't optimized, there may be outstanding folding
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000141 // opportunities. Attempt to fold the expression using DataLayout as a
Justin Holewinskiae556d32012-05-04 20:18:50 +0000142 // last resort before giving up.
Justin Holewinski0497ab12013-03-30 14:29:21 +0000143 if (Constant *C = ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000144 if (C != CE)
145 return LowerConstant(C, AP);
146
147 // Otherwise report the problem to the user.
148 {
Alp Tokere69170a2014-06-26 22:52:05 +0000149 std::string S;
150 raw_string_ostream OS(S);
Justin Holewinski0497ab12013-03-30 14:29:21 +0000151 OS << "Unsupported expression in static initializer: ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000152 CE->printAsOperand(OS, /*PrintType=*/ false,
Craig Topper062a2ba2014-04-25 05:30:21 +0000153 !AP.MF ? nullptr : AP.MF->getFunction()->getParent());
Justin Holewinski0497ab12013-03-30 14:29:21 +0000154 report_fatal_error(OS.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000155 }
Justin Holewinski9d852a82014-04-09 15:39:11 +0000156 case Instruction::AddrSpaceCast: {
157 // Strip any addrspace(1)->addrspace(0) addrspace casts. These will be
158 // handled by the generic() logic in the MCExpr printer
159 PointerType *DstTy = cast<PointerType>(CE->getType());
160 PointerType *SrcTy = cast<PointerType>(CE->getOperand(0)->getType());
161 if (SrcTy->getAddressSpace() == 1 && DstTy->getAddressSpace() == 0) {
162 return LowerConstant(cast<const Constant>(CE->getOperand(0)), AP);
163 }
164 std::string S;
165 raw_string_ostream OS(S);
166 OS << "Unsupported expression in static initializer: ";
167 CE->printAsOperand(OS, /*PrintType=*/ false,
Craig Topper062a2ba2014-04-25 05:30:21 +0000168 !AP.MF ? nullptr : AP.MF->getFunction()->getParent());
Justin Holewinski9d852a82014-04-09 15:39:11 +0000169 report_fatal_error(OS.str());
170 }
Justin Holewinskiae556d32012-05-04 20:18:50 +0000171 case Instruction::GetElementPtr: {
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000172 const DataLayout &TD = *AP.TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000173 // Generate a symbolic expression for the byte address
Nuno Lopesb6ad9822012-12-30 16:25:48 +0000174 APInt OffsetAI(TD.getPointerSizeInBits(), 0);
175 cast<GEPOperator>(CE)->accumulateConstantOffset(TD, OffsetAI);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000176
177 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
Nuno Lopesb6ad9822012-12-30 16:25:48 +0000178 if (!OffsetAI)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000179 return Base;
180
Nuno Lopesb6ad9822012-12-30 16:25:48 +0000181 int64_t Offset = OffsetAI.getSExtValue();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000182 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
183 Ctx);
184 }
185
186 case Instruction::Trunc:
187 // We emit the value and depend on the assembler to truncate the generated
188 // expression properly. This is important for differences between
189 // blockaddress labels. Since the two labels are in the same function, it
190 // is reasonable to treat their delta as a 32-bit value.
Justin Holewinski0497ab12013-03-30 14:29:21 +0000191 // FALL THROUGH.
Justin Holewinskiae556d32012-05-04 20:18:50 +0000192 case Instruction::BitCast:
193 return LowerConstant(CE->getOperand(0), AP);
194
195 case Instruction::IntToPtr: {
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000196 const DataLayout &TD = *AP.TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000197 // Handle casts to pointers by changing them into casts to the appropriate
198 // integer type. This promotes constant folding and simplifies this code.
199 Constant *Op = CE->getOperand(0);
Chandler Carruth7ec50852012-11-01 08:07:29 +0000200 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
Justin Holewinski0497ab12013-03-30 14:29:21 +0000201 false /*ZExt*/);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000202 return LowerConstant(Op, AP);
203 }
204
205 case Instruction::PtrToInt: {
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000206 const DataLayout &TD = *AP.TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000207 // Support only foldable casts to/from pointers that can be eliminated by
208 // changing the pointer to the appropriately sized integer type.
209 Constant *Op = CE->getOperand(0);
210 Type *Ty = CE->getType();
211
212 const MCExpr *OpExpr = LowerConstant(Op, AP);
213
214 // We can emit the pointer value into this slot if the slot is an
215 // integer slot equal to the size of the pointer.
216 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
217 return OpExpr;
218
219 // Otherwise the pointer is smaller than the resultant integer, mask off
220 // the high bits so we are sure to get a proper truncation if the input is
221 // a constant expr.
222 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
Justin Holewinski0497ab12013-03-30 14:29:21 +0000223 const MCExpr *MaskExpr =
224 MCConstantExpr::Create(~0ULL >> (64 - InBits), Ctx);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000225 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
226 }
227
Justin Holewinski0497ab12013-03-30 14:29:21 +0000228 // The MC library also has a right-shift operator, but it isn't consistently
Justin Holewinskiae556d32012-05-04 20:18:50 +0000229 // signed or unsigned between different targets.
230 case Instruction::Add:
231 case Instruction::Sub:
232 case Instruction::Mul:
233 case Instruction::SDiv:
234 case Instruction::SRem:
235 case Instruction::Shl:
236 case Instruction::And:
237 case Instruction::Or:
238 case Instruction::Xor: {
239 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
240 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
241 switch (CE->getOpcode()) {
Justin Holewinski0497ab12013-03-30 14:29:21 +0000242 default:
243 llvm_unreachable("Unknown binary operator constant cast expr");
244 case Instruction::Add:
245 return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
246 case Instruction::Sub:
247 return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
248 case Instruction::Mul:
249 return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
250 case Instruction::SDiv:
251 return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
252 case Instruction::SRem:
253 return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
254 case Instruction::Shl:
255 return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
256 case Instruction::And:
257 return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
258 case Instruction::Or:
259 return MCBinaryExpr::CreateOr(LHS, RHS, Ctx);
260 case Instruction::Xor:
261 return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000262 }
263 }
264 }
265}
266
Justin Holewinski0497ab12013-03-30 14:29:21 +0000267void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000268 if (!EmitLineNumbers)
269 return;
270 if (ignoreLoc(MI))
271 return;
272
273 DebugLoc curLoc = MI.getDebugLoc();
274
275 if (prevDebugLoc.isUnknown() && curLoc.isUnknown())
276 return;
277
278 if (prevDebugLoc == curLoc)
279 return;
280
281 prevDebugLoc = curLoc;
282
283 if (curLoc.isUnknown())
284 return;
285
Justin Holewinskiae556d32012-05-04 20:18:50 +0000286 const MachineFunction *MF = MI.getParent()->getParent();
287 //const TargetMachine &TM = MF->getTarget();
288
289 const LLVMContext &ctx = MF->getFunction()->getContext();
290 DIScope Scope(curLoc.getScope(ctx));
291
Manman Ren983a16c2013-06-28 05:43:10 +0000292 assert((!Scope || Scope.isScope()) &&
293 "Scope of a DebugLoc should be null or a DIScope.");
294 if (!Scope)
295 return;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000296
297 StringRef fileName(Scope.getFilename());
298 StringRef dirName(Scope.getDirectory());
299 SmallString<128> FullPathName = dirName;
300 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
301 sys::path::append(FullPathName, fileName);
302 fileName = FullPathName.str();
303 }
304
305 if (filenameMap.find(fileName.str()) == filenameMap.end())
306 return;
307
Justin Holewinskiae556d32012-05-04 20:18:50 +0000308 // Emit the line from the source file.
Benjamin Kramer7ad41002013-10-27 11:31:46 +0000309 if (InterleaveSrc)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000310 this->emitSrcInText(fileName.str(), curLoc.getLine());
311
312 std::stringstream temp;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000313 temp << "\t.loc " << filenameMap[fileName.str()] << " " << curLoc.getLine()
314 << " " << curLoc.getCol();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000315 OutStreamer.EmitRawText(Twine(temp.str().c_str()));
316}
317
318void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
319 SmallString<128> Str;
320 raw_svector_ostream OS(Str);
321 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
322 emitLineNumberAsDotLoc(*MI);
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000323
324 MCInst Inst;
325 lowerToMCInst(MI, Inst);
David Woodhousee6c13e42014-01-28 23:12:42 +0000326 EmitToStreamer(OutStreamer, Inst);
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000327}
328
Justin Holewinski30d56a72014-04-09 15:39:15 +0000329// Handle symbol backtracking for targets that do not support image handles
330bool NVPTXAsmPrinter::lowerImageHandleOperand(const MachineInstr *MI,
331 unsigned OpNo, MCOperand &MCOp) {
332 const MachineOperand &MO = MI->getOperand(OpNo);
333
334 switch (MI->getOpcode()) {
335 default: return false;
336 case NVPTX::TEX_1D_F32_I32:
337 case NVPTX::TEX_1D_F32_F32:
338 case NVPTX::TEX_1D_F32_F32_LEVEL:
339 case NVPTX::TEX_1D_F32_F32_GRAD:
340 case NVPTX::TEX_1D_I32_I32:
341 case NVPTX::TEX_1D_I32_F32:
342 case NVPTX::TEX_1D_I32_F32_LEVEL:
343 case NVPTX::TEX_1D_I32_F32_GRAD:
344 case NVPTX::TEX_1D_ARRAY_F32_I32:
345 case NVPTX::TEX_1D_ARRAY_F32_F32:
346 case NVPTX::TEX_1D_ARRAY_F32_F32_LEVEL:
347 case NVPTX::TEX_1D_ARRAY_F32_F32_GRAD:
348 case NVPTX::TEX_1D_ARRAY_I32_I32:
349 case NVPTX::TEX_1D_ARRAY_I32_F32:
350 case NVPTX::TEX_1D_ARRAY_I32_F32_LEVEL:
351 case NVPTX::TEX_1D_ARRAY_I32_F32_GRAD:
352 case NVPTX::TEX_2D_F32_I32:
353 case NVPTX::TEX_2D_F32_F32:
354 case NVPTX::TEX_2D_F32_F32_LEVEL:
355 case NVPTX::TEX_2D_F32_F32_GRAD:
356 case NVPTX::TEX_2D_I32_I32:
357 case NVPTX::TEX_2D_I32_F32:
358 case NVPTX::TEX_2D_I32_F32_LEVEL:
359 case NVPTX::TEX_2D_I32_F32_GRAD:
360 case NVPTX::TEX_2D_ARRAY_F32_I32:
361 case NVPTX::TEX_2D_ARRAY_F32_F32:
362 case NVPTX::TEX_2D_ARRAY_F32_F32_LEVEL:
363 case NVPTX::TEX_2D_ARRAY_F32_F32_GRAD:
364 case NVPTX::TEX_2D_ARRAY_I32_I32:
365 case NVPTX::TEX_2D_ARRAY_I32_F32:
366 case NVPTX::TEX_2D_ARRAY_I32_F32_LEVEL:
367 case NVPTX::TEX_2D_ARRAY_I32_F32_GRAD:
368 case NVPTX::TEX_3D_F32_I32:
369 case NVPTX::TEX_3D_F32_F32:
370 case NVPTX::TEX_3D_F32_F32_LEVEL:
371 case NVPTX::TEX_3D_F32_F32_GRAD:
372 case NVPTX::TEX_3D_I32_I32:
373 case NVPTX::TEX_3D_I32_F32:
374 case NVPTX::TEX_3D_I32_F32_LEVEL:
375 case NVPTX::TEX_3D_I32_F32_GRAD:
376 {
377 // This is a texture fetch, so operand 4 is a texref and operand 5 is
378 // a samplerref
379 if (OpNo == 4) {
380 lowerImageHandleSymbol(MO.getImm(), MCOp);
381 return true;
382 }
383 if (OpNo == 5) {
384 lowerImageHandleSymbol(MO.getImm(), MCOp);
385 return true;
386 }
387
388 return false;
389 }
390 case NVPTX::SULD_1D_I8_TRAP:
391 case NVPTX::SULD_1D_I16_TRAP:
392 case NVPTX::SULD_1D_I32_TRAP:
393 case NVPTX::SULD_1D_ARRAY_I8_TRAP:
394 case NVPTX::SULD_1D_ARRAY_I16_TRAP:
395 case NVPTX::SULD_1D_ARRAY_I32_TRAP:
396 case NVPTX::SULD_2D_I8_TRAP:
397 case NVPTX::SULD_2D_I16_TRAP:
398 case NVPTX::SULD_2D_I32_TRAP:
399 case NVPTX::SULD_2D_ARRAY_I8_TRAP:
400 case NVPTX::SULD_2D_ARRAY_I16_TRAP:
401 case NVPTX::SULD_2D_ARRAY_I32_TRAP:
402 case NVPTX::SULD_3D_I8_TRAP:
403 case NVPTX::SULD_3D_I16_TRAP:
404 case NVPTX::SULD_3D_I32_TRAP: {
405 // This is a V1 surface load, so operand 1 is a surfref
406 if (OpNo == 1) {
407 lowerImageHandleSymbol(MO.getImm(), MCOp);
408 return true;
409 }
410
411 return false;
412 }
413 case NVPTX::SULD_1D_V2I8_TRAP:
414 case NVPTX::SULD_1D_V2I16_TRAP:
415 case NVPTX::SULD_1D_V2I32_TRAP:
416 case NVPTX::SULD_1D_ARRAY_V2I8_TRAP:
417 case NVPTX::SULD_1D_ARRAY_V2I16_TRAP:
418 case NVPTX::SULD_1D_ARRAY_V2I32_TRAP:
419 case NVPTX::SULD_2D_V2I8_TRAP:
420 case NVPTX::SULD_2D_V2I16_TRAP:
421 case NVPTX::SULD_2D_V2I32_TRAP:
422 case NVPTX::SULD_2D_ARRAY_V2I8_TRAP:
423 case NVPTX::SULD_2D_ARRAY_V2I16_TRAP:
424 case NVPTX::SULD_2D_ARRAY_V2I32_TRAP:
425 case NVPTX::SULD_3D_V2I8_TRAP:
426 case NVPTX::SULD_3D_V2I16_TRAP:
427 case NVPTX::SULD_3D_V2I32_TRAP: {
428 // This is a V2 surface load, so operand 2 is a surfref
429 if (OpNo == 2) {
430 lowerImageHandleSymbol(MO.getImm(), MCOp);
431 return true;
432 }
433
434 return false;
435 }
436 case NVPTX::SULD_1D_V4I8_TRAP:
437 case NVPTX::SULD_1D_V4I16_TRAP:
438 case NVPTX::SULD_1D_V4I32_TRAP:
439 case NVPTX::SULD_1D_ARRAY_V4I8_TRAP:
440 case NVPTX::SULD_1D_ARRAY_V4I16_TRAP:
441 case NVPTX::SULD_1D_ARRAY_V4I32_TRAP:
442 case NVPTX::SULD_2D_V4I8_TRAP:
443 case NVPTX::SULD_2D_V4I16_TRAP:
444 case NVPTX::SULD_2D_V4I32_TRAP:
445 case NVPTX::SULD_2D_ARRAY_V4I8_TRAP:
446 case NVPTX::SULD_2D_ARRAY_V4I16_TRAP:
447 case NVPTX::SULD_2D_ARRAY_V4I32_TRAP:
448 case NVPTX::SULD_3D_V4I8_TRAP:
449 case NVPTX::SULD_3D_V4I16_TRAP:
450 case NVPTX::SULD_3D_V4I32_TRAP: {
451 // This is a V4 surface load, so operand 4 is a surfref
452 if (OpNo == 4) {
453 lowerImageHandleSymbol(MO.getImm(), MCOp);
454 return true;
455 }
456
457 return false;
458 }
459 case NVPTX::SUST_B_1D_B8_TRAP:
460 case NVPTX::SUST_B_1D_B16_TRAP:
461 case NVPTX::SUST_B_1D_B32_TRAP:
462 case NVPTX::SUST_B_1D_V2B8_TRAP:
463 case NVPTX::SUST_B_1D_V2B16_TRAP:
464 case NVPTX::SUST_B_1D_V2B32_TRAP:
465 case NVPTX::SUST_B_1D_V4B8_TRAP:
466 case NVPTX::SUST_B_1D_V4B16_TRAP:
467 case NVPTX::SUST_B_1D_V4B32_TRAP:
468 case NVPTX::SUST_B_1D_ARRAY_B8_TRAP:
469 case NVPTX::SUST_B_1D_ARRAY_B16_TRAP:
470 case NVPTX::SUST_B_1D_ARRAY_B32_TRAP:
471 case NVPTX::SUST_B_1D_ARRAY_V2B8_TRAP:
472 case NVPTX::SUST_B_1D_ARRAY_V2B16_TRAP:
473 case NVPTX::SUST_B_1D_ARRAY_V2B32_TRAP:
474 case NVPTX::SUST_B_1D_ARRAY_V4B8_TRAP:
475 case NVPTX::SUST_B_1D_ARRAY_V4B16_TRAP:
476 case NVPTX::SUST_B_1D_ARRAY_V4B32_TRAP:
477 case NVPTX::SUST_B_2D_B8_TRAP:
478 case NVPTX::SUST_B_2D_B16_TRAP:
479 case NVPTX::SUST_B_2D_B32_TRAP:
480 case NVPTX::SUST_B_2D_V2B8_TRAP:
481 case NVPTX::SUST_B_2D_V2B16_TRAP:
482 case NVPTX::SUST_B_2D_V2B32_TRAP:
483 case NVPTX::SUST_B_2D_V4B8_TRAP:
484 case NVPTX::SUST_B_2D_V4B16_TRAP:
485 case NVPTX::SUST_B_2D_V4B32_TRAP:
486 case NVPTX::SUST_B_2D_ARRAY_B8_TRAP:
487 case NVPTX::SUST_B_2D_ARRAY_B16_TRAP:
488 case NVPTX::SUST_B_2D_ARRAY_B32_TRAP:
489 case NVPTX::SUST_B_2D_ARRAY_V2B8_TRAP:
490 case NVPTX::SUST_B_2D_ARRAY_V2B16_TRAP:
491 case NVPTX::SUST_B_2D_ARRAY_V2B32_TRAP:
492 case NVPTX::SUST_B_2D_ARRAY_V4B8_TRAP:
493 case NVPTX::SUST_B_2D_ARRAY_V4B16_TRAP:
494 case NVPTX::SUST_B_2D_ARRAY_V4B32_TRAP:
495 case NVPTX::SUST_B_3D_B8_TRAP:
496 case NVPTX::SUST_B_3D_B16_TRAP:
497 case NVPTX::SUST_B_3D_B32_TRAP:
498 case NVPTX::SUST_B_3D_V2B8_TRAP:
499 case NVPTX::SUST_B_3D_V2B16_TRAP:
500 case NVPTX::SUST_B_3D_V2B32_TRAP:
501 case NVPTX::SUST_B_3D_V4B8_TRAP:
502 case NVPTX::SUST_B_3D_V4B16_TRAP:
503 case NVPTX::SUST_B_3D_V4B32_TRAP:
504 case NVPTX::SUST_P_1D_B8_TRAP:
505 case NVPTX::SUST_P_1D_B16_TRAP:
506 case NVPTX::SUST_P_1D_B32_TRAP:
507 case NVPTX::SUST_P_1D_V2B8_TRAP:
508 case NVPTX::SUST_P_1D_V2B16_TRAP:
509 case NVPTX::SUST_P_1D_V2B32_TRAP:
510 case NVPTX::SUST_P_1D_V4B8_TRAP:
511 case NVPTX::SUST_P_1D_V4B16_TRAP:
512 case NVPTX::SUST_P_1D_V4B32_TRAP:
513 case NVPTX::SUST_P_1D_ARRAY_B8_TRAP:
514 case NVPTX::SUST_P_1D_ARRAY_B16_TRAP:
515 case NVPTX::SUST_P_1D_ARRAY_B32_TRAP:
516 case NVPTX::SUST_P_1D_ARRAY_V2B8_TRAP:
517 case NVPTX::SUST_P_1D_ARRAY_V2B16_TRAP:
518 case NVPTX::SUST_P_1D_ARRAY_V2B32_TRAP:
519 case NVPTX::SUST_P_1D_ARRAY_V4B8_TRAP:
520 case NVPTX::SUST_P_1D_ARRAY_V4B16_TRAP:
521 case NVPTX::SUST_P_1D_ARRAY_V4B32_TRAP:
522 case NVPTX::SUST_P_2D_B8_TRAP:
523 case NVPTX::SUST_P_2D_B16_TRAP:
524 case NVPTX::SUST_P_2D_B32_TRAP:
525 case NVPTX::SUST_P_2D_V2B8_TRAP:
526 case NVPTX::SUST_P_2D_V2B16_TRAP:
527 case NVPTX::SUST_P_2D_V2B32_TRAP:
528 case NVPTX::SUST_P_2D_V4B8_TRAP:
529 case NVPTX::SUST_P_2D_V4B16_TRAP:
530 case NVPTX::SUST_P_2D_V4B32_TRAP:
531 case NVPTX::SUST_P_2D_ARRAY_B8_TRAP:
532 case NVPTX::SUST_P_2D_ARRAY_B16_TRAP:
533 case NVPTX::SUST_P_2D_ARRAY_B32_TRAP:
534 case NVPTX::SUST_P_2D_ARRAY_V2B8_TRAP:
535 case NVPTX::SUST_P_2D_ARRAY_V2B16_TRAP:
536 case NVPTX::SUST_P_2D_ARRAY_V2B32_TRAP:
537 case NVPTX::SUST_P_2D_ARRAY_V4B8_TRAP:
538 case NVPTX::SUST_P_2D_ARRAY_V4B16_TRAP:
539 case NVPTX::SUST_P_2D_ARRAY_V4B32_TRAP:
540 case NVPTX::SUST_P_3D_B8_TRAP:
541 case NVPTX::SUST_P_3D_B16_TRAP:
542 case NVPTX::SUST_P_3D_B32_TRAP:
543 case NVPTX::SUST_P_3D_V2B8_TRAP:
544 case NVPTX::SUST_P_3D_V2B16_TRAP:
545 case NVPTX::SUST_P_3D_V2B32_TRAP:
546 case NVPTX::SUST_P_3D_V4B8_TRAP:
547 case NVPTX::SUST_P_3D_V4B16_TRAP:
548 case NVPTX::SUST_P_3D_V4B32_TRAP: {
549 // This is a surface store, so operand 0 is a surfref
550 if (OpNo == 0) {
551 lowerImageHandleSymbol(MO.getImm(), MCOp);
552 return true;
553 }
554
555 return false;
556 }
557 case NVPTX::TXQ_CHANNEL_ORDER:
558 case NVPTX::TXQ_CHANNEL_DATA_TYPE:
559 case NVPTX::TXQ_WIDTH:
560 case NVPTX::TXQ_HEIGHT:
561 case NVPTX::TXQ_DEPTH:
562 case NVPTX::TXQ_ARRAY_SIZE:
563 case NVPTX::TXQ_NUM_SAMPLES:
564 case NVPTX::TXQ_NUM_MIPMAP_LEVELS:
565 case NVPTX::SUQ_CHANNEL_ORDER:
566 case NVPTX::SUQ_CHANNEL_DATA_TYPE:
567 case NVPTX::SUQ_WIDTH:
568 case NVPTX::SUQ_HEIGHT:
569 case NVPTX::SUQ_DEPTH:
570 case NVPTX::SUQ_ARRAY_SIZE: {
571 // This is a query, so operand 1 is a surfref/texref
572 if (OpNo == 1) {
573 lowerImageHandleSymbol(MO.getImm(), MCOp);
574 return true;
575 }
576
577 return false;
578 }
579 }
580}
581
582void NVPTXAsmPrinter::lowerImageHandleSymbol(unsigned Index, MCOperand &MCOp) {
583 // Ewwww
584 TargetMachine &TM = const_cast<TargetMachine&>(MF->getTarget());
585 NVPTXTargetMachine &nvTM = static_cast<NVPTXTargetMachine&>(TM);
586 const NVPTXMachineFunctionInfo *MFI = MF->getInfo<NVPTXMachineFunctionInfo>();
587 const char *Sym = MFI->getImageHandleSymbol(Index);
588 std::string *SymNamePtr =
589 nvTM.getManagedStrPool()->getManagedString(Sym);
590 MCOp = GetSymbolRef(OutContext.GetOrCreateSymbol(
591 StringRef(SymNamePtr->c_str())));
592}
593
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000594void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
595 OutMI.setOpcode(MI->getOpcode());
Justin Holewinski30d56a72014-04-09 15:39:15 +0000596 const NVPTXSubtarget &ST = TM.getSubtarget<NVPTXSubtarget>();
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000597
Justin Holewinski3d49e5c2013-11-15 12:30:04 +0000598 // Special: Do not mangle symbol operand of CALL_PROTOTYPE
599 if (MI->getOpcode() == NVPTX::CALL_PROTOTYPE) {
600 const MachineOperand &MO = MI->getOperand(0);
Justin Holewinski30d56a72014-04-09 15:39:15 +0000601 OutMI.addOperand(GetSymbolRef(
Justin Holewinski3d49e5c2013-11-15 12:30:04 +0000602 OutContext.GetOrCreateSymbol(Twine(MO.getSymbolName()))));
603 return;
604 }
605
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000606 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
607 const MachineOperand &MO = MI->getOperand(i);
608
609 MCOperand MCOp;
Justin Holewinski30d56a72014-04-09 15:39:15 +0000610 if (!ST.hasImageHandles()) {
611 if (lowerImageHandleOperand(MI, i, MCOp)) {
612 OutMI.addOperand(MCOp);
613 continue;
614 }
615 }
616
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000617 if (lowerOperand(MO, MCOp))
618 OutMI.addOperand(MCOp);
619 }
620}
621
622bool NVPTXAsmPrinter::lowerOperand(const MachineOperand &MO,
623 MCOperand &MCOp) {
624 switch (MO.getType()) {
625 default: llvm_unreachable("unknown operand type");
626 case MachineOperand::MO_Register:
627 MCOp = MCOperand::CreateReg(encodeVirtualRegister(MO.getReg()));
628 break;
629 case MachineOperand::MO_Immediate:
630 MCOp = MCOperand::CreateImm(MO.getImm());
631 break;
632 case MachineOperand::MO_MachineBasicBlock:
633 MCOp = MCOperand::CreateExpr(MCSymbolRefExpr::Create(
634 MO.getMBB()->getSymbol(), OutContext));
635 break;
636 case MachineOperand::MO_ExternalSymbol:
Justin Holewinski30d56a72014-04-09 15:39:15 +0000637 MCOp = GetSymbolRef(GetExternalSymbolSymbol(MO.getSymbolName()));
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000638 break;
639 case MachineOperand::MO_GlobalAddress:
Justin Holewinski30d56a72014-04-09 15:39:15 +0000640 MCOp = GetSymbolRef(getSymbol(MO.getGlobal()));
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000641 break;
642 case MachineOperand::MO_FPImmediate: {
643 const ConstantFP *Cnt = MO.getFPImm();
644 APFloat Val = Cnt->getValueAPF();
645
646 switch (Cnt->getType()->getTypeID()) {
647 default: report_fatal_error("Unsupported FP type"); break;
648 case Type::FloatTyID:
649 MCOp = MCOperand::CreateExpr(
650 NVPTXFloatMCExpr::CreateConstantFPSingle(Val, OutContext));
651 break;
652 case Type::DoubleTyID:
653 MCOp = MCOperand::CreateExpr(
654 NVPTXFloatMCExpr::CreateConstantFPDouble(Val, OutContext));
655 break;
656 }
657 break;
658 }
659 }
660 return true;
661}
662
663unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
Justin Holewinski871ec932013-08-06 14:13:31 +0000664 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
665 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000666
Justin Holewinski871ec932013-08-06 14:13:31 +0000667 DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
668 unsigned RegNum = RegMap[Reg];
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000669
Justin Holewinski871ec932013-08-06 14:13:31 +0000670 // Encode the register class in the upper 4 bits
671 // Must be kept in sync with NVPTXInstPrinter::printRegName
672 unsigned Ret = 0;
673 if (RC == &NVPTX::Int1RegsRegClass) {
674 Ret = (1 << 28);
675 } else if (RC == &NVPTX::Int16RegsRegClass) {
676 Ret = (2 << 28);
677 } else if (RC == &NVPTX::Int32RegsRegClass) {
678 Ret = (3 << 28);
679 } else if (RC == &NVPTX::Int64RegsRegClass) {
680 Ret = (4 << 28);
681 } else if (RC == &NVPTX::Float32RegsRegClass) {
682 Ret = (5 << 28);
683 } else if (RC == &NVPTX::Float64RegsRegClass) {
684 Ret = (6 << 28);
685 } else {
686 report_fatal_error("Bad register class");
687 }
688
689 // Insert the vreg number
690 Ret |= (RegNum & 0x0FFFFFFF);
691 return Ret;
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000692 } else {
Justin Holewinski871ec932013-08-06 14:13:31 +0000693 // Some special-use registers are actually physical registers.
694 // Encode this as the register class ID of 0 and the real register ID.
695 return Reg & 0x0FFFFFFF;
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000696 }
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000697}
698
Justin Holewinski30d56a72014-04-09 15:39:15 +0000699MCOperand NVPTXAsmPrinter::GetSymbolRef(const MCSymbol *Symbol) {
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000700 const MCExpr *Expr;
Justin Holewinski8b24e1e2013-08-06 23:06:42 +0000701 Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None,
702 OutContext);
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000703 return MCOperand::CreateExpr(Expr);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000704}
705
Justin Holewinski0497ab12013-03-30 14:29:21 +0000706void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000707 const DataLayout *TD = TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000708 const TargetLowering *TLI = TM.getTargetLowering();
709
710 Type *Ty = F->getReturnType();
711
712 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
713
714 if (Ty->getTypeID() == Type::VoidTyID)
715 return;
716
717 O << " (";
718
719 if (isABI) {
Rafael Espindola08013342013-12-07 19:34:20 +0000720 if (Ty->isFloatingPointTy() || Ty->isIntegerTy()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000721 unsigned size = 0;
722 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
723 size = ITy->getBitWidth();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000724 if (size < 32)
725 size = 32;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000726 } else {
Justin Holewinski0497ab12013-03-30 14:29:21 +0000727 assert(Ty->isFloatingPointTy() && "Floating point type expected here");
Justin Holewinskiae556d32012-05-04 20:18:50 +0000728 size = Ty->getPrimitiveSizeInBits();
729 }
730
731 O << ".param .b" << size << " func_retval0";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000732 } else if (isa<PointerType>(Ty)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000733 O << ".param .b" << TLI->getPointerTy().getSizeInBits()
Justin Holewinski0497ab12013-03-30 14:29:21 +0000734 << " func_retval0";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000735 } else {
Justin Holewinski0497ab12013-03-30 14:29:21 +0000736 if ((Ty->getTypeID() == Type::StructTyID) || isa<VectorType>(Ty)) {
Justin Holewinski0da75852014-06-27 18:35:08 +0000737 unsigned totalsz = TD->getTypeAllocSize(Ty);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000738 unsigned retAlignment = 0;
739 if (!llvm::getAlign(*F, 0, retAlignment))
740 retAlignment = TD->getABITypeAlignment(Ty);
Justin Holewinski0497ab12013-03-30 14:29:21 +0000741 O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
742 << "]";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000743 } else
Justin Holewinski0497ab12013-03-30 14:29:21 +0000744 assert(false && "Unknown return type");
Justin Holewinskiae556d32012-05-04 20:18:50 +0000745 }
746 } else {
747 SmallVector<EVT, 16> vtparts;
748 ComputeValueVTs(*TLI, Ty, vtparts);
749 unsigned idx = 0;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000750 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000751 unsigned elems = 1;
752 EVT elemtype = vtparts[i];
753 if (vtparts[i].isVector()) {
754 elems = vtparts[i].getVectorNumElements();
755 elemtype = vtparts[i].getVectorElementType();
756 }
757
Justin Holewinski0497ab12013-03-30 14:29:21 +0000758 for (unsigned j = 0, je = elems; j != je; ++j) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000759 unsigned sz = elemtype.getSizeInBits();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000760 if (elemtype.isInteger() && (sz < 32))
761 sz = 32;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000762 O << ".reg .b" << sz << " func_retval" << idx;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000763 if (j < je - 1)
764 O << ", ";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000765 ++idx;
766 }
Justin Holewinski0497ab12013-03-30 14:29:21 +0000767 if (i < e - 1)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000768 O << ", ";
769 }
770 }
771 O << ") ";
772 return;
773}
774
775void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
776 raw_ostream &O) {
777 const Function *F = MF.getFunction();
778 printReturnValStr(F, O);
779}
780
781void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
782 SmallString<128> Str;
783 raw_svector_ostream O(Str);
784
Justin Holewinski01f89f02013-05-20 12:13:32 +0000785 if (!GlobalsEmitted) {
786 emitGlobals(*MF->getFunction()->getParent());
787 GlobalsEmitted = true;
788 }
789
Justin Holewinskiae556d32012-05-04 20:18:50 +0000790 // Set up
791 MRI = &MF->getRegInfo();
792 F = MF->getFunction();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000793 emitLinkageDirective(F, O);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000794 if (llvm::isKernelFunction(*F))
795 O << ".entry ";
796 else {
797 O << ".func ";
798 printReturnValStr(*MF, O);
799 }
800
801 O << *CurrentFnSym;
802
803 emitFunctionParamList(*MF, O);
804
805 if (llvm::isKernelFunction(*F))
806 emitKernelFunctionDirectives(*F, O);
807
808 OutStreamer.EmitRawText(O.str());
809
810 prevDebugLoc = DebugLoc();
811}
812
813void NVPTXAsmPrinter::EmitFunctionBodyStart() {
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +0000814 VRegMapping.clear();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000815 OutStreamer.EmitRawText(StringRef("{\n"));
816 setAndEmitFunctionVirtualRegisters(*MF);
817
818 SmallString<128> Str;
819 raw_svector_ostream O(Str);
820 emitDemotedVars(MF->getFunction(), O);
821 OutStreamer.EmitRawText(O.str());
822}
823
824void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
825 OutStreamer.EmitRawText(StringRef("}\n"));
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +0000826 VRegMapping.clear();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000827}
828
Justin Holewinski660597d2013-10-11 12:39:36 +0000829void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
830 unsigned RegNo = MI->getOperand(0).getReg();
831 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
832 if (TRI->isVirtualRegister(RegNo)) {
833 OutStreamer.AddComment(Twine("implicit-def: ") +
834 getVirtualRegisterName(RegNo));
835 } else {
836 OutStreamer.AddComment(Twine("implicit-def: ") +
837 TM.getRegisterInfo()->getName(RegNo));
838 }
839 OutStreamer.AddBlankLine();
840}
841
Justin Holewinski0497ab12013-03-30 14:29:21 +0000842void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
843 raw_ostream &O) const {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000844 // If the NVVM IR has some of reqntid* specified, then output
845 // the reqntid directive, and set the unspecified ones to 1.
846 // If none of reqntid* is specified, don't output reqntid directive.
847 unsigned reqntidx, reqntidy, reqntidz;
848 bool specified = false;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000849 if (llvm::getReqNTIDx(F, reqntidx) == false)
850 reqntidx = 1;
851 else
852 specified = true;
853 if (llvm::getReqNTIDy(F, reqntidy) == false)
854 reqntidy = 1;
855 else
856 specified = true;
857 if (llvm::getReqNTIDz(F, reqntidz) == false)
858 reqntidz = 1;
859 else
860 specified = true;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000861
862 if (specified)
Justin Holewinski0497ab12013-03-30 14:29:21 +0000863 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
864 << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000865
866 // If the NVVM IR has some of maxntid* specified, then output
867 // the maxntid directive, and set the unspecified ones to 1.
868 // If none of maxntid* is specified, don't output maxntid directive.
869 unsigned maxntidx, maxntidy, maxntidz;
870 specified = false;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000871 if (llvm::getMaxNTIDx(F, maxntidx) == false)
872 maxntidx = 1;
873 else
874 specified = true;
875 if (llvm::getMaxNTIDy(F, maxntidy) == false)
876 maxntidy = 1;
877 else
878 specified = true;
879 if (llvm::getMaxNTIDz(F, maxntidz) == false)
880 maxntidz = 1;
881 else
882 specified = true;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000883
884 if (specified)
Justin Holewinski0497ab12013-03-30 14:29:21 +0000885 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
886 << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000887
888 unsigned mincta;
889 if (llvm::getMinCTASm(F, mincta))
890 O << ".minnctapersm " << mincta << "\n";
891}
892
Justin Holewinski660597d2013-10-11 12:39:36 +0000893std::string
894NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
895 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000896
Justin Holewinski660597d2013-10-11 12:39:36 +0000897 std::string Name;
898 raw_string_ostream NameStr(Name);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000899
Justin Holewinski660597d2013-10-11 12:39:36 +0000900 VRegRCMap::const_iterator I = VRegMapping.find(RC);
901 assert(I != VRegMapping.end() && "Bad register class");
902 const DenseMap<unsigned, unsigned> &RegMap = I->second;
903
904 VRegMap::const_iterator VI = RegMap.find(Reg);
905 assert(VI != RegMap.end() && "Bad virtual register");
906 unsigned MappedVR = VI->second;
907
908 NameStr << getNVPTXRegClassStr(RC) << MappedVR;
909
910 NameStr.flush();
911 return Name;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000912}
913
Justin Holewinski660597d2013-10-11 12:39:36 +0000914void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
Justin Holewinski0497ab12013-03-30 14:29:21 +0000915 raw_ostream &O) {
Justin Holewinski660597d2013-10-11 12:39:36 +0000916 O << getVirtualRegisterName(vr);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000917}
918
Justin Holewinski0497ab12013-03-30 14:29:21 +0000919void NVPTXAsmPrinter::printVecModifiedImmediate(
920 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
921 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
922 int Imm = (int) MO.getImm();
923 if (0 == strcmp(Modifier, "vecelem"))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000924 O << "_" << vecelem[Imm];
Justin Holewinski0497ab12013-03-30 14:29:21 +0000925 else if (0 == strcmp(Modifier, "vecv4comm1")) {
926 if ((Imm < 0) || (Imm > 3))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000927 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000928 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
929 if ((Imm < 4) || (Imm > 7))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000930 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000931 } else if (0 == strcmp(Modifier, "vecv4pos")) {
932 if (Imm < 0)
933 Imm = 0;
934 O << "_" << vecelem[Imm % 4];
935 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
936 if ((Imm < 0) || (Imm > 1))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000937 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000938 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
939 if ((Imm < 2) || (Imm > 3))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000940 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000941 } else if (0 == strcmp(Modifier, "vecv2pos")) {
942 if (Imm < 0)
943 Imm = 0;
944 O << "_" << vecelem[Imm % 2];
945 } else
Craig Topperbdf39a42012-05-24 07:02:50 +0000946 llvm_unreachable("Unknown Modifier on immediate operand");
Justin Holewinskiae556d32012-05-04 20:18:50 +0000947}
948
Justin Holewinskidc5e3b62013-06-28 17:58:04 +0000949
950
Justin Holewinski0497ab12013-03-30 14:29:21 +0000951void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000952
Justin Holewinski0497ab12013-03-30 14:29:21 +0000953 emitLinkageDirective(F, O);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000954 if (llvm::isKernelFunction(*F))
955 O << ".entry ";
956 else
957 O << ".func ";
958 printReturnValStr(F, O);
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +0000959 O << *getSymbol(F) << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000960 emitFunctionParamList(F, O);
961 O << ";\n";
962}
963
Justin Holewinski0497ab12013-03-30 14:29:21 +0000964static bool usedInGlobalVarDef(const Constant *C) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000965 if (!C)
966 return false;
967
968 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
969 if (GV->getName().str() == "llvm.used")
970 return false;
971 return true;
972 }
973
Chandler Carruthcdf47882014-03-09 03:16:01 +0000974 for (const User *U : C->users())
975 if (const Constant *C = dyn_cast<Constant>(U))
976 if (usedInGlobalVarDef(C))
977 return true;
978
Justin Holewinskiae556d32012-05-04 20:18:50 +0000979 return false;
980}
981
Justin Holewinski0497ab12013-03-30 14:29:21 +0000982static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000983 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
984 if (othergv->getName().str() == "llvm.used")
985 return true;
986 }
987
988 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
989 if (instr->getParent() && instr->getParent()->getParent()) {
990 const Function *curFunc = instr->getParent()->getParent();
991 if (oneFunc && (curFunc != oneFunc))
992 return false;
993 oneFunc = curFunc;
994 return true;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000995 } else
Justin Holewinskiae556d32012-05-04 20:18:50 +0000996 return false;
997 }
998
999 if (const MDNode *md = dyn_cast<MDNode>(U))
1000 if (md->hasName() && ((md->getName().str() == "llvm.dbg.gv") ||
Justin Holewinski0497ab12013-03-30 14:29:21 +00001001 (md->getName().str() == "llvm.dbg.sp")))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001002 return true;
1003
Chandler Carruthcdf47882014-03-09 03:16:01 +00001004 for (const User *UU : U->users())
1005 if (usedInOneFunc(UU, oneFunc) == false)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001006 return false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001007
Justin Holewinskiae556d32012-05-04 20:18:50 +00001008 return true;
1009}
1010
1011/* Find out if a global variable can be demoted to local scope.
1012 * Currently, this is valid for CUDA shared variables, which have local
1013 * scope and global lifetime. So the conditions to check are :
1014 * 1. Is the global variable in shared address space?
1015 * 2. Does it have internal linkage?
1016 * 3. Is the global variable referenced only in one function?
1017 */
1018static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
1019 if (gv->hasInternalLinkage() == false)
1020 return false;
1021 const PointerType *Pty = gv->getType();
1022 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
1023 return false;
1024
Craig Topper062a2ba2014-04-25 05:30:21 +00001025 const Function *oneFunc = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001026
1027 bool flag = usedInOneFunc(gv, oneFunc);
1028 if (flag == false)
1029 return false;
1030 if (!oneFunc)
1031 return false;
1032 f = oneFunc;
1033 return true;
1034}
1035
1036static bool useFuncSeen(const Constant *C,
1037 llvm::DenseMap<const Function *, bool> &seenMap) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001038 for (const User *U : C->users()) {
1039 if (const Constant *cu = dyn_cast<Constant>(U)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001040 if (useFuncSeen(cu, seenMap))
1041 return true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001042 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001043 const BasicBlock *bb = I->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001044 if (!bb)
1045 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001046 const Function *caller = bb->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001047 if (!caller)
1048 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001049 if (seenMap.find(caller) != seenMap.end())
1050 return true;
1051 }
1052 }
1053 return false;
1054}
1055
Justin Holewinski01f89f02013-05-20 12:13:32 +00001056void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001057 llvm::DenseMap<const Function *, bool> seenMap;
Justin Holewinski0497ab12013-03-30 14:29:21 +00001058 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001059 const Function *F = FI;
1060
1061 if (F->isDeclaration()) {
1062 if (F->use_empty())
1063 continue;
1064 if (F->getIntrinsicID())
1065 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001066 emitDeclaration(F, O);
1067 continue;
1068 }
Chandler Carruthcdf47882014-03-09 03:16:01 +00001069 for (const User *U : F->users()) {
1070 if (const Constant *C = dyn_cast<Constant>(U)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001071 if (usedInGlobalVarDef(C)) {
1072 // The use is in the initialization of a global variable
1073 // that is a function pointer, so print a declaration
1074 // for the original function
Justin Holewinskiae556d32012-05-04 20:18:50 +00001075 emitDeclaration(F, O);
1076 break;
1077 }
1078 // Emit a declaration of this function if the function that
1079 // uses this constant expr has already been seen.
1080 if (useFuncSeen(C, seenMap)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001081 emitDeclaration(F, O);
1082 break;
1083 }
1084 }
1085
Chandler Carruthcdf47882014-03-09 03:16:01 +00001086 if (!isa<Instruction>(U))
Justin Holewinski0497ab12013-03-30 14:29:21 +00001087 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001088 const Instruction *instr = cast<Instruction>(U);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001089 const BasicBlock *bb = instr->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001090 if (!bb)
1091 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001092 const Function *caller = bb->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001093 if (!caller)
1094 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001095
1096 // If a caller has already been seen, then the caller is
1097 // appearing in the module before the callee. so print out
1098 // a declaration for the callee.
1099 if (seenMap.find(caller) != seenMap.end()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001100 emitDeclaration(F, O);
1101 break;
1102 }
1103 }
1104 seenMap[F] = true;
1105 }
1106}
1107
1108void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
1109 DebugInfoFinder DbgFinder;
1110 DbgFinder.processModule(M);
1111
Justin Holewinski0497ab12013-03-30 14:29:21 +00001112 unsigned i = 1;
Alon Mishnead312152014-03-18 09:41:07 +00001113 for (DICompileUnit DIUnit : DbgFinder.compile_units()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001114 StringRef Filename(DIUnit.getFilename());
1115 StringRef Dirname(DIUnit.getDirectory());
1116 SmallString<128> FullPathName = Dirname;
1117 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
1118 sys::path::append(FullPathName, Filename);
1119 Filename = FullPathName.str();
1120 }
1121 if (filenameMap.find(Filename.str()) != filenameMap.end())
1122 continue;
1123 filenameMap[Filename.str()] = i;
1124 OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
1125 ++i;
1126 }
1127
Alon Mishnead312152014-03-18 09:41:07 +00001128 for (DISubprogram SP : DbgFinder.subprograms()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001129 StringRef Filename(SP.getFilename());
1130 StringRef Dirname(SP.getDirectory());
1131 SmallString<128> FullPathName = Dirname;
1132 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
1133 sys::path::append(FullPathName, Filename);
1134 Filename = FullPathName.str();
1135 }
1136 if (filenameMap.find(Filename.str()) != filenameMap.end())
1137 continue;
1138 filenameMap[Filename.str()] = i;
1139 ++i;
1140 }
1141}
1142
Justin Holewinski0497ab12013-03-30 14:29:21 +00001143bool NVPTXAsmPrinter::doInitialization(Module &M) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001144
1145 SmallString<128> Str1;
1146 raw_svector_ostream OS1(Str1);
1147
1148 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
1149 MMI->AnalyzeModule(M);
1150
1151 // We need to call the parent's one explicitly.
1152 //bool Result = AsmPrinter::doInitialization(M);
1153
1154 // Initialize TargetLoweringObjectFile.
Justin Holewinski0497ab12013-03-30 14:29:21 +00001155 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
1156 .Initialize(OutContext, TM);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001157
Rafael Espindola58873562014-01-03 19:21:54 +00001158 Mang = new Mangler(TM.getDataLayout());
Justin Holewinskiae556d32012-05-04 20:18:50 +00001159
1160 // Emit header before any dwarf directives are emitted below.
1161 emitHeader(M, OS1);
1162 OutStreamer.EmitRawText(OS1.str());
1163
Justin Holewinskiae556d32012-05-04 20:18:50 +00001164 // Already commented out
1165 //bool Result = AsmPrinter::doInitialization(M);
1166
Justin Holewinskid2bbdf02013-07-01 13:00:14 +00001167 // Emit module-level inline asm if it exists.
1168 if (!M.getModuleInlineAsm().empty()) {
1169 OutStreamer.AddComment("Start of file scope inline assembly");
1170 OutStreamer.AddBlankLine();
1171 OutStreamer.EmitRawText(StringRef(M.getModuleInlineAsm()));
1172 OutStreamer.AddBlankLine();
1173 OutStreamer.AddComment("End of file scope inline assembly");
1174 OutStreamer.AddBlankLine();
1175 }
1176
Justin Holewinskiae556d32012-05-04 20:18:50 +00001177 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
1178 recordAndEmitFilenames(M);
1179
Justin Holewinski01f89f02013-05-20 12:13:32 +00001180 GlobalsEmitted = false;
1181
1182 return false; // success
1183}
1184
1185void NVPTXAsmPrinter::emitGlobals(const Module &M) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001186 SmallString<128> Str2;
1187 raw_svector_ostream OS2(Str2);
1188
1189 emitDeclarations(M, OS2);
1190
Justin Holewinski2c5ac702012-11-16 21:03:51 +00001191 // As ptxas does not support forward references of globals, we need to first
1192 // sort the list of module-level globals in def-use order. We visit each
1193 // global variable in order, and ensure that we emit it *after* its dependent
1194 // globals. We use a little extra memory maintaining both a set and a list to
1195 // have fast searches while maintaining a strict ordering.
Justin Holewinski01f89f02013-05-20 12:13:32 +00001196 SmallVector<const GlobalVariable *, 8> Globals;
1197 DenseSet<const GlobalVariable *> GVVisited;
1198 DenseSet<const GlobalVariable *> GVVisiting;
Justin Holewinski2c5ac702012-11-16 21:03:51 +00001199
1200 // Visit each global variable, in order
Justin Holewinski01f89f02013-05-20 12:13:32 +00001201 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1202 I != E; ++I)
Justin Holewinski2c5ac702012-11-16 21:03:51 +00001203 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
1204
Justin Holewinski0497ab12013-03-30 14:29:21 +00001205 assert(GVVisited.size() == M.getGlobalList().size() &&
Justin Holewinski2c5ac702012-11-16 21:03:51 +00001206 "Missed a global variable");
1207 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
1208
1209 // Print out module-level global variables in proper order
1210 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1211 printModuleLevelGV(Globals[i], OS2);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001212
1213 OS2 << '\n';
1214
1215 OutStreamer.EmitRawText(OS2.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +00001216}
1217
Justin Holewinski0497ab12013-03-30 14:29:21 +00001218void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001219 O << "//\n";
1220 O << "// Generated by LLVM NVPTX Back-End\n";
1221 O << "//\n";
1222 O << "\n";
1223
Justin Holewinski1812ee92012-11-12 03:16:43 +00001224 unsigned PTXVersion = nvptxSubtarget.getPTXVersion();
1225 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001226
1227 O << ".target ";
1228 O << nvptxSubtarget.getTargetName();
1229
1230 if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
1231 O << ", texmode_independent";
1232 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1233 if (!nvptxSubtarget.hasDouble())
1234 O << ", map_f64_to_f32";
1235 }
1236
1237 if (MAI->doesSupportDebugInformation())
1238 O << ", debug";
1239
1240 O << "\n";
1241
1242 O << ".address_size ";
1243 if (nvptxSubtarget.is64Bit())
1244 O << "64";
1245 else
1246 O << "32";
1247 O << "\n";
1248
1249 O << "\n";
1250}
1251
1252bool NVPTXAsmPrinter::doFinalization(Module &M) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001253
1254 // If we did not emit any functions, then the global declarations have not
1255 // yet been emitted.
1256 if (!GlobalsEmitted) {
1257 emitGlobals(M);
1258 GlobalsEmitted = true;
1259 }
1260
Justin Holewinskiae556d32012-05-04 20:18:50 +00001261 // XXX Temproarily remove global variables so that doFinalization() will not
1262 // emit them again (global variables are emitted at beginning).
1263
1264 Module::GlobalListType &global_list = M.getGlobalList();
1265 int i, n = global_list.size();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001266 GlobalVariable **gv_array = new GlobalVariable *[n];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001267
1268 // first, back-up GlobalVariable in gv_array
1269 i = 0;
1270 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001271 I != E; ++I)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001272 gv_array[i++] = &*I;
1273
1274 // second, empty global_list
1275 while (!global_list.empty())
1276 global_list.remove(global_list.begin());
1277
1278 // call doFinalization
1279 bool ret = AsmPrinter::doFinalization(M);
1280
1281 // now we restore global variables
Justin Holewinski0497ab12013-03-30 14:29:21 +00001282 for (i = 0; i < n; i++)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001283 global_list.insert(global_list.end(), gv_array[i]);
1284
Justin Holewinski59596952014-04-09 15:38:52 +00001285 clearAnnotationCache(&M);
1286
Justin Holewinskiae556d32012-05-04 20:18:50 +00001287 delete[] gv_array;
1288 return ret;
1289
Justin Holewinskiae556d32012-05-04 20:18:50 +00001290 //bool Result = AsmPrinter::doFinalization(M);
1291 // Instead of calling the parents doFinalization, we may
1292 // clone parents doFinalization and customize here.
1293 // Currently, we if NVISA out the EmitGlobals() in
1294 // parent's doFinalization, which is too intrusive.
1295 //
1296 // Same for the doInitialization.
1297 //return Result;
1298}
1299
1300// This function emits appropriate linkage directives for
1301// functions and global variables.
1302//
1303// extern function declaration -> .extern
1304// extern function definition -> .visible
1305// external global variable with init -> .visible
1306// external without init -> .extern
1307// appending -> not allowed, assert.
Justin Holewinski7d5bf662014-06-27 18:35:10 +00001308// for any linkage other than
1309// internal, private, linker_private,
1310// linker_private_weak, linker_private_weak_def_auto,
1311// we emit -> .weak.
Justin Holewinskiae556d32012-05-04 20:18:50 +00001312
Justin Holewinski0497ab12013-03-30 14:29:21 +00001313void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
1314 raw_ostream &O) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001315 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1316 if (V->hasExternalLinkage()) {
1317 if (isa<GlobalVariable>(V)) {
1318 const GlobalVariable *GVar = cast<GlobalVariable>(V);
1319 if (GVar) {
1320 if (GVar->hasInitializer())
1321 O << ".visible ";
1322 else
1323 O << ".extern ";
1324 }
1325 } else if (V->isDeclaration())
1326 O << ".extern ";
1327 else
1328 O << ".visible ";
1329 } else if (V->hasAppendingLinkage()) {
1330 std::string msg;
1331 msg.append("Error: ");
1332 msg.append("Symbol ");
1333 if (V->hasName())
1334 msg.append(V->getName().str());
1335 msg.append("has unsupported appending linkage type");
1336 llvm_unreachable(msg.c_str());
Justin Holewinski7d5bf662014-06-27 18:35:10 +00001337 } else if (!V->hasInternalLinkage() &&
1338 !V->hasPrivateLinkage()) {
1339 O << ".weak ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001340 }
1341 }
1342}
1343
Justin Holewinski01f89f02013-05-20 12:13:32 +00001344void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1345 raw_ostream &O,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001346 bool processDemoted) {
1347
1348 // Skip meta data
1349 if (GVar->hasSection()) {
Rafael Espindola64c1e182014-06-03 02:41:57 +00001350 if (GVar->getSection() == StringRef("llvm.metadata"))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001351 return;
1352 }
1353
Justin Holewinski73cb5de2014-06-27 18:35:53 +00001354 // Skip LLVM intrinsic global variables
1355 if (GVar->getName().startswith("llvm.") ||
1356 GVar->getName().startswith("nvvm."))
1357 return;
1358
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001359 const DataLayout *TD = TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001360
1361 // GlobalVariables are always constant pointers themselves.
1362 const PointerType *PTy = GVar->getType();
1363 Type *ETy = PTy->getElementType();
1364
1365 if (GVar->hasExternalLinkage()) {
1366 if (GVar->hasInitializer())
1367 O << ".visible ";
1368 else
1369 O << ".extern ";
1370 }
1371
1372 if (llvm::isTexture(*GVar)) {
1373 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1374 return;
1375 }
1376
1377 if (llvm::isSurface(*GVar)) {
1378 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1379 return;
1380 }
1381
1382 if (GVar->isDeclaration()) {
1383 // (extern) declarations, no definition or initializer
1384 // Currently the only known declaration is for an automatic __local
1385 // (.shared) promoted to global.
1386 emitPTXGlobalVariable(GVar, O);
1387 O << ";\n";
1388 return;
1389 }
1390
1391 if (llvm::isSampler(*GVar)) {
1392 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1393
Craig Topper062a2ba2014-04-25 05:30:21 +00001394 const Constant *Initializer = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001395 if (GVar->hasInitializer())
1396 Initializer = GVar->getInitializer();
Craig Topper062a2ba2014-04-25 05:30:21 +00001397 const ConstantInt *CI = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001398 if (Initializer)
1399 CI = dyn_cast<ConstantInt>(Initializer);
1400 if (CI) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001401 unsigned sample = CI->getZExtValue();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001402
1403 O << " = { ";
1404
Justin Holewinski0497ab12013-03-30 14:29:21 +00001405 for (int i = 0,
1406 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1407 i < 3; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001408 O << "addr_mode_" << i << " = ";
1409 switch (addr) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001410 case 0:
1411 O << "wrap";
1412 break;
1413 case 1:
1414 O << "clamp_to_border";
1415 break;
1416 case 2:
1417 O << "clamp_to_edge";
1418 break;
1419 case 3:
1420 O << "wrap";
1421 break;
1422 case 4:
1423 O << "mirror";
1424 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001425 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001426 O << ", ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001427 }
1428 O << "filter_mode = ";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001429 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1430 case 0:
1431 O << "nearest";
1432 break;
1433 case 1:
1434 O << "linear";
1435 break;
1436 case 2:
Craig Topper2a30d782014-06-18 05:05:13 +00001437 llvm_unreachable("Anisotropic filtering is not supported");
Justin Holewinski0497ab12013-03-30 14:29:21 +00001438 default:
1439 O << "nearest";
1440 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001441 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001442 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001443 O << ", force_unnormalized_coords = 1";
1444 }
1445 O << " }";
1446 }
1447
1448 O << ";\n";
1449 return;
1450 }
1451
1452 if (GVar->hasPrivateLinkage()) {
1453
1454 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1455 return;
1456
1457 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1458 if (!strncmp(GVar->getName().data(), "filename", 8))
1459 return;
1460 if (GVar->use_empty())
1461 return;
1462 }
1463
Craig Topper062a2ba2014-04-25 05:30:21 +00001464 const Function *demotedFunc = nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001465 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1466 O << "// " << GVar->getName().str() << " has been demoted\n";
1467 if (localDecls.find(demotedFunc) != localDecls.end())
1468 localDecls[demotedFunc].push_back(GVar);
1469 else {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001470 std::vector<const GlobalVariable *> temp;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001471 temp.push_back(GVar);
1472 localDecls[demotedFunc] = temp;
1473 }
1474 return;
1475 }
1476
1477 O << ".";
1478 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1479 if (GVar->getAlignment() == 0)
1480 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1481 else
1482 O << " .align " << GVar->getAlignment();
1483
Rafael Espindola08013342013-12-07 19:34:20 +00001484 if (ETy->isSingleValueType()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001485 O << " .";
Justin Holewinski700b6fa2013-05-20 12:13:28 +00001486 // Special case: ABI requires that we use .u8 for predicates
1487 if (ETy->isIntegerTy(1))
1488 O << "u8";
1489 else
1490 O << getPTXFundamentalTypeStr(ETy, false);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001491 O << " ";
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00001492 O << *getSymbol(GVar);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001493
1494 // Ptx allows variable initilization only for constant and global state
1495 // spaces.
1496 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
Justin Holewinski0497ab12013-03-30 14:29:21 +00001497 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1498 GVar->hasInitializer()) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001499 const Constant *Initializer = GVar->getInitializer();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001500 if (!Initializer->isNullValue()) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001501 O << " = ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001502 printScalarConstant(Initializer, O);
1503 }
1504 }
1505 } else {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001506 unsigned int ElementSize = 0;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001507
1508 // Although PTX has direct support for struct type and array type and
1509 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1510 // targets that support these high level field accesses. Structs, arrays
1511 // and vectors are lowered into arrays of bytes.
1512 switch (ETy->getTypeID()) {
1513 case Type::StructTyID:
1514 case Type::ArrayTyID:
1515 case Type::VectorTyID:
1516 ElementSize = TD->getTypeStoreSize(ETy);
1517 // Ptx allows variable initilization only for constant and
1518 // global state spaces.
1519 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
Justin Holewinski0497ab12013-03-30 14:29:21 +00001520 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1521 GVar->hasInitializer()) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001522 const Constant *Initializer = GVar->getInitializer();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001523 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001524 AggBuffer aggBuffer(ElementSize, O, *this);
1525 bufferAggregateConstant(Initializer, &aggBuffer);
1526 if (aggBuffer.numSymbols) {
1527 if (nvptxSubtarget.is64Bit()) {
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00001528 O << " .u64 " << *getSymbol(GVar) << "[";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001529 O << ElementSize / 8;
1530 } else {
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00001531 O << " .u32 " << *getSymbol(GVar) << "[";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001532 O << ElementSize / 4;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001533 }
1534 O << "]";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001535 } else {
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00001536 O << " .b8 " << *getSymbol(GVar) << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001537 O << ElementSize;
1538 O << "]";
1539 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001540 O << " = {";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001541 aggBuffer.print();
1542 O << "}";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001543 } else {
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00001544 O << " .b8 " << *getSymbol(GVar);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001545 if (ElementSize) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001546 O << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001547 O << ElementSize;
1548 O << "]";
1549 }
1550 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001551 } else {
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00001552 O << " .b8 " << *getSymbol(GVar);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001553 if (ElementSize) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001554 O << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001555 O << ElementSize;
1556 O << "]";
1557 }
1558 }
1559 break;
1560 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001561 llvm_unreachable("type not supported yet");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001562 }
1563
1564 }
1565 O << ";\n";
1566}
1567
1568void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1569 if (localDecls.find(f) == localDecls.end())
1570 return;
1571
Justin Holewinski01f89f02013-05-20 12:13:32 +00001572 std::vector<const GlobalVariable *> &gvars = localDecls[f];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001573
Justin Holewinski0497ab12013-03-30 14:29:21 +00001574 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001575 O << "\t// demoted variable\n\t";
1576 printModuleLevelGV(gvars[i], O, true);
1577 }
1578}
1579
1580void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1581 raw_ostream &O) const {
1582 switch (AddressSpace) {
1583 case llvm::ADDRESS_SPACE_LOCAL:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001584 O << "local";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001585 break;
1586 case llvm::ADDRESS_SPACE_GLOBAL:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001587 O << "global";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001588 break;
1589 case llvm::ADDRESS_SPACE_CONST:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001590 O << "const";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001591 break;
1592 case llvm::ADDRESS_SPACE_SHARED:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001593 O << "shared";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001594 break;
1595 default:
Justin Holewinski36a50992013-02-09 13:34:15 +00001596 report_fatal_error("Bad address space found while emitting PTX");
1597 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001598 }
1599}
1600
Justin Holewinski0497ab12013-03-30 14:29:21 +00001601std::string
1602NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001603 switch (Ty->getTypeID()) {
1604 default:
1605 llvm_unreachable("unexpected type");
1606 break;
1607 case Type::IntegerTyID: {
1608 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1609 if (NumBits == 1)
1610 return "pred";
1611 else if (NumBits <= 64) {
1612 std::string name = "u";
1613 return name + utostr(NumBits);
1614 } else {
1615 llvm_unreachable("Integer too large");
1616 break;
1617 }
1618 break;
1619 }
1620 case Type::FloatTyID:
1621 return "f32";
1622 case Type::DoubleTyID:
1623 return "f64";
1624 case Type::PointerTyID:
1625 if (nvptxSubtarget.is64Bit())
Justin Holewinski0497ab12013-03-30 14:29:21 +00001626 if (useB4PTR)
1627 return "b64";
1628 else
1629 return "u64";
1630 else if (useB4PTR)
1631 return "b32";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001632 else
Justin Holewinski0497ab12013-03-30 14:29:21 +00001633 return "u32";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001634 }
1635 llvm_unreachable("unexpected type");
Craig Topper062a2ba2014-04-25 05:30:21 +00001636 return nullptr;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001637}
1638
Justin Holewinski0497ab12013-03-30 14:29:21 +00001639void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001640 raw_ostream &O) {
1641
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001642 const DataLayout *TD = TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001643
1644 // GlobalVariables are always constant pointers themselves.
1645 const PointerType *PTy = GVar->getType();
1646 Type *ETy = PTy->getElementType();
1647
1648 O << ".";
1649 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1650 if (GVar->getAlignment() == 0)
1651 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1652 else
1653 O << " .align " << GVar->getAlignment();
1654
Rafael Espindola08013342013-12-07 19:34:20 +00001655 if (ETy->isSingleValueType()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001656 O << " .";
1657 O << getPTXFundamentalTypeStr(ETy);
1658 O << " ";
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00001659 O << *getSymbol(GVar);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001660 return;
1661 }
1662
Justin Holewinski0497ab12013-03-30 14:29:21 +00001663 int64_t ElementSize = 0;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001664
1665 // Although PTX has direct support for struct type and array type and LLVM IR
1666 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1667 // support these high level field accesses. Structs and arrays are lowered
1668 // into arrays of bytes.
1669 switch (ETy->getTypeID()) {
1670 case Type::StructTyID:
1671 case Type::ArrayTyID:
1672 case Type::VectorTyID:
1673 ElementSize = TD->getTypeStoreSize(ETy);
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00001674 O << " .b8 " << *getSymbol(GVar) << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001675 if (ElementSize) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001676 O << itostr(ElementSize);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001677 }
1678 O << "]";
1679 break;
1680 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001681 llvm_unreachable("type not supported yet");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001682 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001683 return;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001684}
1685
Justin Holewinski0497ab12013-03-30 14:29:21 +00001686static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
Rafael Espindola08013342013-12-07 19:34:20 +00001687 if (Ty->isSingleValueType())
Justin Holewinskiae556d32012-05-04 20:18:50 +00001688 return TD->getPrefTypeAlignment(Ty);
1689
1690 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1691 if (ATy)
1692 return getOpenCLAlignment(TD, ATy->getElementType());
1693
1694 const VectorType *VTy = dyn_cast<VectorType>(Ty);
1695 if (VTy) {
1696 Type *ETy = VTy->getElementType();
1697 unsigned int numE = VTy->getNumElements();
1698 unsigned int alignE = TD->getPrefTypeAlignment(ETy);
1699 if (numE == 3)
Justin Holewinski0497ab12013-03-30 14:29:21 +00001700 return 4 * alignE;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001701 else
Justin Holewinski0497ab12013-03-30 14:29:21 +00001702 return numE * alignE;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001703 }
1704
1705 const StructType *STy = dyn_cast<StructType>(Ty);
1706 if (STy) {
1707 unsigned int alignStruct = 1;
1708 // Go through each element of the struct and find the
1709 // largest alignment.
Justin Holewinski0497ab12013-03-30 14:29:21 +00001710 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001711 Type *ETy = STy->getElementType(i);
1712 unsigned int align = getOpenCLAlignment(TD, ETy);
1713 if (align > alignStruct)
1714 alignStruct = align;
1715 }
1716 return alignStruct;
1717 }
1718
1719 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1720 if (FTy)
Chandler Carruth5da3f052012-11-01 09:14:31 +00001721 return TD->getPointerPrefAlignment();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001722 return TD->getPrefTypeAlignment(Ty);
1723}
1724
1725void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1726 int paramIndex, raw_ostream &O) {
1727 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1728 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00001729 O << *getSymbol(I->getParent()) << "_param_" << paramIndex;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001730 else {
1731 std::string argName = I->getName();
1732 const char *p = argName.c_str();
1733 while (*p) {
1734 if (*p == '.')
1735 O << "_";
1736 else
1737 O << *p;
1738 p++;
1739 }
1740 }
1741}
1742
1743void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1744 Function::const_arg_iterator I, E;
1745 int i = 0;
1746
1747 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1748 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1749 O << *CurrentFnSym << "_param_" << paramIndex;
1750 return;
1751 }
1752
1753 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001754 if (i == paramIndex) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001755 printParamName(I, paramIndex, O);
1756 return;
1757 }
1758 }
1759 llvm_unreachable("paramIndex out of bound");
1760}
1761
Justin Holewinski0497ab12013-03-30 14:29:21 +00001762void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001763 const DataLayout *TD = TM.getDataLayout();
Bill Wendlinge94d8432012-12-07 23:16:57 +00001764 const AttributeSet &PAL = F->getAttributes();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001765 const TargetLowering *TLI = TM.getTargetLowering();
1766 Function::const_arg_iterator I, E;
1767 unsigned paramIndex = 0;
1768 bool first = true;
1769 bool isKernelFunc = llvm::isKernelFunction(*F);
1770 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1771 MVT thePointerTy = TLI->getPointerTy();
1772
1773 O << "(\n";
1774
1775 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
Justin Holewinskie9884092013-03-24 21:17:47 +00001776 Type *Ty = I->getType();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001777
1778 if (!first)
1779 O << ",\n";
1780
1781 first = false;
1782
1783 // Handle image/sampler parameters
Justin Holewinski30d56a72014-04-09 15:39:15 +00001784 if (isKernelFunction(*F)) {
1785 if (isSampler(*I) || isImage(*I)) {
1786 if (isImage(*I)) {
1787 std::string sname = I->getName();
1788 if (isImageWriteOnly(*I) || isImageReadWrite(*I)) {
1789 if (nvptxSubtarget.hasImageHandles())
1790 O << "\t.param .u64 .ptr .surfref ";
1791 else
1792 O << "\t.param .surfref ";
1793 O << *CurrentFnSym << "_param_" << paramIndex;
1794 }
1795 else { // Default image is read_only
1796 if (nvptxSubtarget.hasImageHandles())
1797 O << "\t.param .u64 .ptr .texref ";
1798 else
1799 O << "\t.param .texref ";
1800 O << *CurrentFnSym << "_param_" << paramIndex;
1801 }
1802 } else {
1803 if (nvptxSubtarget.hasImageHandles())
1804 O << "\t.param .u64 .ptr .samplerref ";
1805 else
1806 O << "\t.param .samplerref ";
1807 O << *CurrentFnSym << "_param_" << paramIndex;
1808 }
1809 continue;
1810 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001811 }
1812
Justin Holewinski0497ab12013-03-30 14:29:21 +00001813 if (PAL.hasAttribute(paramIndex + 1, Attribute::ByVal) == false) {
Gautam Chakrabarti2c283402014-01-28 18:35:29 +00001814 if (Ty->isAggregateType() || Ty->isVectorTy()) {
1815 // Just print .param .align <a> .b8 .param[size];
Justin Holewinskie9884092013-03-24 21:17:47 +00001816 // <a> = PAL.getparamalignment
1817 // size = typeallocsize of element type
Justin Holewinski0497ab12013-03-30 14:29:21 +00001818 unsigned align = PAL.getParamAlignment(paramIndex + 1);
Justin Holewinskie9884092013-03-24 21:17:47 +00001819 if (align == 0)
1820 align = TD->getABITypeAlignment(Ty);
1821
1822 unsigned sz = TD->getTypeAllocSize(Ty);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001823 O << "\t.param .align " << align << " .b8 ";
Justin Holewinskie9884092013-03-24 21:17:47 +00001824 printParamName(I, paramIndex, O);
1825 O << "[" << sz << "]";
1826
1827 continue;
1828 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001829 // Just a scalar
1830 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1831 if (isKernelFunc) {
1832 if (PTy) {
1833 // Special handling for pointer arguments to kernel
1834 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1835
1836 if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
1837 Type *ETy = PTy->getElementType();
1838 int addrSpace = PTy->getAddressSpace();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001839 switch (addrSpace) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001840 default:
1841 O << ".ptr ";
1842 break;
Justin Holewinskib96d1392013-06-10 13:29:47 +00001843 case llvm::ADDRESS_SPACE_CONST:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001844 O << ".ptr .const ";
1845 break;
1846 case llvm::ADDRESS_SPACE_SHARED:
1847 O << ".ptr .shared ";
1848 break;
1849 case llvm::ADDRESS_SPACE_GLOBAL:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001850 O << ".ptr .global ";
1851 break;
1852 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001853 O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001854 }
1855 printParamName(I, paramIndex, O);
1856 continue;
1857 }
1858
1859 // non-pointer scalar to kernel func
Justin Holewinski700b6fa2013-05-20 12:13:28 +00001860 O << "\t.param .";
1861 // Special case: predicate operands become .u8 types
1862 if (Ty->isIntegerTy(1))
1863 O << "u8";
1864 else
1865 O << getPTXFundamentalTypeStr(Ty);
1866 O << " ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001867 printParamName(I, paramIndex, O);
1868 continue;
1869 }
1870 // Non-kernel function, just print .param .b<size> for ABI
Alp Tokerf907b892013-12-05 05:44:44 +00001871 // and .reg .b<size> for non-ABI
Justin Holewinskiae556d32012-05-04 20:18:50 +00001872 unsigned sz = 0;
1873 if (isa<IntegerType>(Ty)) {
1874 sz = cast<IntegerType>(Ty)->getBitWidth();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001875 if (sz < 32)
1876 sz = 32;
1877 } else if (isa<PointerType>(Ty))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001878 sz = thePointerTy.getSizeInBits();
1879 else
1880 sz = Ty->getPrimitiveSizeInBits();
1881 if (isABI)
1882 O << "\t.param .b" << sz << " ";
1883 else
1884 O << "\t.reg .b" << sz << " ";
1885 printParamName(I, paramIndex, O);
1886 continue;
1887 }
1888
1889 // param has byVal attribute. So should be a pointer
1890 const PointerType *PTy = dyn_cast<PointerType>(Ty);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001891 assert(PTy && "Param with byval attribute should be a pointer type");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001892 Type *ETy = PTy->getElementType();
1893
1894 if (isABI || isKernelFunc) {
Gautam Chakrabarti2c283402014-01-28 18:35:29 +00001895 // Just print .param .align <a> .b8 .param[size];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001896 // <a> = PAL.getparamalignment
1897 // size = typeallocsize of element type
Justin Holewinski0497ab12013-03-30 14:29:21 +00001898 unsigned align = PAL.getParamAlignment(paramIndex + 1);
Justin Holewinski2dc9d072012-11-09 23:50:24 +00001899 if (align == 0)
1900 align = TD->getABITypeAlignment(ETy);
1901
Justin Holewinskiae556d32012-05-04 20:18:50 +00001902 unsigned sz = TD->getTypeAllocSize(ETy);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001903 O << "\t.param .align " << align << " .b8 ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001904 printParamName(I, paramIndex, O);
1905 O << "[" << sz << "]";
1906 continue;
1907 } else {
1908 // Split the ETy into constituent parts and
1909 // print .param .b<size> <name> for each part.
1910 // Further, if a part is vector, print the above for
1911 // each vector element.
1912 SmallVector<EVT, 16> vtparts;
1913 ComputeValueVTs(*TLI, ETy, vtparts);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001914 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001915 unsigned elems = 1;
1916 EVT elemtype = vtparts[i];
1917 if (vtparts[i].isVector()) {
1918 elems = vtparts[i].getVectorNumElements();
1919 elemtype = vtparts[i].getVectorElementType();
1920 }
1921
Justin Holewinski0497ab12013-03-30 14:29:21 +00001922 for (unsigned j = 0, je = elems; j != je; ++j) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001923 unsigned sz = elemtype.getSizeInBits();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001924 if (elemtype.isInteger() && (sz < 32))
1925 sz = 32;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001926 O << "\t.reg .b" << sz << " ";
1927 printParamName(I, paramIndex, O);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001928 if (j < je - 1)
1929 O << ",\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001930 ++paramIndex;
1931 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001932 if (i < e - 1)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001933 O << ",\n";
1934 }
1935 --paramIndex;
1936 continue;
1937 }
1938 }
1939
1940 O << "\n)\n";
1941}
1942
1943void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1944 raw_ostream &O) {
1945 const Function *F = MF.getFunction();
1946 emitFunctionParamList(F, O);
1947}
1948
Justin Holewinski0497ab12013-03-30 14:29:21 +00001949void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1950 const MachineFunction &MF) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001951 SmallString<128> Str;
1952 raw_svector_ostream O(Str);
1953
1954 // Map the global virtual register number to a register class specific
1955 // virtual register number starting from 1 with that class.
1956 const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
1957 //unsigned numRegClasses = TRI->getNumRegClasses();
1958
1959 // Emit the Fake Stack Object
1960 const MachineFrameInfo *MFI = MF.getFrameInfo();
1961 int NumBytes = (int) MFI->getStackSize();
1962 if (NumBytes) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001963 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1964 << getFunctionNumber() << "[" << NumBytes << "];\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001965 if (nvptxSubtarget.is64Bit()) {
1966 O << "\t.reg .b64 \t%SP;\n";
1967 O << "\t.reg .b64 \t%SPL;\n";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001968 } else {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001969 O << "\t.reg .b32 \t%SP;\n";
1970 O << "\t.reg .b32 \t%SPL;\n";
1971 }
1972 }
1973
1974 // Go through all virtual registers to establish the mapping between the
1975 // global virtual
1976 // register number and the per class virtual register number.
1977 // We use the per class virtual register number in the ptx output.
1978 unsigned int numVRs = MRI->getNumVirtRegs();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001979 for (unsigned i = 0; i < numVRs; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001980 unsigned int vr = TRI->index2VirtReg(i);
1981 const TargetRegisterClass *RC = MRI->getRegClass(vr);
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001982 DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001983 int n = regmap.size();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001984 regmap.insert(std::make_pair(vr, n + 1));
Justin Holewinskiae556d32012-05-04 20:18:50 +00001985 }
1986
1987 // Emit register declarations
1988 // @TODO: Extract out the real register usage
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001989 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1990 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1991 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1992 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1993 // O << "\t.reg .s64 %rl<" << NVPTXNumRegisters << ">;\n";
1994 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1995 // O << "\t.reg .f64 %fl<" << NVPTXNumRegisters << ">;\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001996
1997 // Emit declaration of the virtual registers or 'physical' registers for
1998 // each register class
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001999 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
2000 const TargetRegisterClass *RC = TRI->getRegClass(i);
2001 DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
2002 std::string rcname = getNVPTXRegClassName(RC);
2003 std::string rcStr = getNVPTXRegClassStr(RC);
2004 int n = regmap.size();
Justin Holewinskiae556d32012-05-04 20:18:50 +00002005
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00002006 // Only declare those registers that may be used.
2007 if (n) {
2008 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
2009 << ">;\n";
2010 }
2011 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00002012
2013 OutStreamer.EmitRawText(O.str());
2014}
2015
Justin Holewinskiae556d32012-05-04 20:18:50 +00002016void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00002017 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
Justin Holewinskiae556d32012-05-04 20:18:50 +00002018 bool ignored;
2019 unsigned int numHex;
2020 const char *lead;
2021
Justin Holewinski0497ab12013-03-30 14:29:21 +00002022 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00002023 numHex = 8;
2024 lead = "0f";
Justin Holewinski0497ab12013-03-30 14:29:21 +00002025 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002026 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
2027 numHex = 16;
2028 lead = "0d";
Justin Holewinski0497ab12013-03-30 14:29:21 +00002029 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002030 } else
2031 llvm_unreachable("unsupported fp type");
2032
2033 APInt API = APF.bitcastToAPInt();
2034 std::string hexstr(utohexstr(API.getZExtValue()));
2035 O << lead;
2036 if (hexstr.length() < numHex)
2037 O << std::string(numHex - hexstr.length(), '0');
2038 O << utohexstr(API.getZExtValue());
2039}
2040
Justin Holewinski01f89f02013-05-20 12:13:32 +00002041void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
2042 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00002043 O << CI->getValue();
2044 return;
2045 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00002046 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00002047 printFPConstant(CFP, O);
2048 return;
2049 }
2050 if (isa<ConstantPointerNull>(CPV)) {
2051 O << "0";
2052 return;
2053 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00002054 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
Justin Holewinski9d852a82014-04-09 15:39:11 +00002055 PointerType *PTy = dyn_cast<PointerType>(GVar->getType());
2056 bool IsNonGenericPointer = false;
2057 if (PTy && PTy->getAddressSpace() != 0) {
2058 IsNonGenericPointer = true;
2059 }
2060 if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
2061 O << "generic(";
2062 O << *getSymbol(GVar);
2063 O << ")";
2064 } else {
2065 O << *getSymbol(GVar);
2066 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00002067 return;
2068 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00002069 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
2070 const Value *v = Cexpr->stripPointerCasts();
Justin Holewinski9d852a82014-04-09 15:39:11 +00002071 PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
2072 bool IsNonGenericPointer = false;
2073 if (PTy && PTy->getAddressSpace() != 0) {
2074 IsNonGenericPointer = true;
2075 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00002076 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
Justin Holewinski9d852a82014-04-09 15:39:11 +00002077 if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
2078 O << "generic(";
2079 O << *getSymbol(GVar);
2080 O << ")";
2081 } else {
2082 O << *getSymbol(GVar);
2083 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00002084 return;
2085 } else {
2086 O << *LowerConstant(CPV, *this);
2087 return;
2088 }
2089 }
2090 llvm_unreachable("Not scalar type found in printScalarConstant()");
2091}
2092
Justin Holewinski01f89f02013-05-20 12:13:32 +00002093void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
Justin Holewinskiae556d32012-05-04 20:18:50 +00002094 AggBuffer *aggBuffer) {
2095
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002096 const DataLayout *TD = TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00002097
2098 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
2099 int s = TD->getTypeAllocSize(CPV->getType());
Justin Holewinski0497ab12013-03-30 14:29:21 +00002100 if (s < Bytes)
Justin Holewinskiae556d32012-05-04 20:18:50 +00002101 s = Bytes;
2102 aggBuffer->addZeros(s);
2103 return;
2104 }
2105
2106 unsigned char *ptr;
2107 switch (CPV->getType()->getTypeID()) {
2108
2109 case Type::IntegerTyID: {
2110 const Type *ETy = CPV->getType();
Justin Holewinski0497ab12013-03-30 14:29:21 +00002111 if (ETy == Type::getInt8Ty(CPV->getContext())) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00002112 unsigned char c =
2113 (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
2114 ptr = &c;
2115 aggBuffer->addBytes(ptr, 1, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00002116 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
2117 short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
2118 ptr = (unsigned char *)&int16;
Justin Holewinskiae556d32012-05-04 20:18:50 +00002119 aggBuffer->addBytes(ptr, 2, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00002120 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00002121 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00002122 int int32 = (int)(constInt->getZExtValue());
2123 ptr = (unsigned char *)&int32;
Justin Holewinskiae556d32012-05-04 20:18:50 +00002124 aggBuffer->addBytes(ptr, 4, Bytes);
2125 break;
Justin Holewinski01f89f02013-05-20 12:13:32 +00002126 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
2127 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
Justin Holewinski0497ab12013-03-30 14:29:21 +00002128 ConstantFoldConstantExpression(Cexpr, TD))) {
2129 int int32 = (int)(constInt->getZExtValue());
2130 ptr = (unsigned char *)&int32;
Justin Holewinskiae556d32012-05-04 20:18:50 +00002131 aggBuffer->addBytes(ptr, 4, Bytes);
2132 break;
2133 }
2134 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
2135 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
2136 aggBuffer->addSymbol(v);
2137 aggBuffer->addZeros(4);
2138 break;
2139 }
2140 }
Craig Topperbdf39a42012-05-24 07:02:50 +00002141 llvm_unreachable("unsupported integer const type");
Justin Holewinski0497ab12013-03-30 14:29:21 +00002142 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00002143 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00002144 long long int64 = (long long)(constInt->getZExtValue());
2145 ptr = (unsigned char *)&int64;
Justin Holewinskiae556d32012-05-04 20:18:50 +00002146 aggBuffer->addBytes(ptr, 8, Bytes);
2147 break;
Justin Holewinski01f89f02013-05-20 12:13:32 +00002148 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
2149 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
Justin Holewinski0497ab12013-03-30 14:29:21 +00002150 ConstantFoldConstantExpression(Cexpr, TD))) {
2151 long long int64 = (long long)(constInt->getZExtValue());
2152 ptr = (unsigned char *)&int64;
Justin Holewinskiae556d32012-05-04 20:18:50 +00002153 aggBuffer->addBytes(ptr, 8, Bytes);
2154 break;
2155 }
2156 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
2157 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
2158 aggBuffer->addSymbol(v);
2159 aggBuffer->addZeros(8);
2160 break;
2161 }
2162 }
2163 llvm_unreachable("unsupported integer const type");
Craig Topperbdf39a42012-05-24 07:02:50 +00002164 } else
Justin Holewinskiae556d32012-05-04 20:18:50 +00002165 llvm_unreachable("unsupported integer const type");
2166 break;
2167 }
2168 case Type::FloatTyID:
2169 case Type::DoubleTyID: {
Justin Holewinski01f89f02013-05-20 12:13:32 +00002170 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
Justin Holewinski0497ab12013-03-30 14:29:21 +00002171 const Type *Ty = CFP->getType();
Justin Holewinskiae556d32012-05-04 20:18:50 +00002172 if (Ty == Type::getFloatTy(CPV->getContext())) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00002173 float float32 = (float) CFP->getValueAPF().convertToFloat();
2174 ptr = (unsigned char *)&float32;
Justin Holewinskiae556d32012-05-04 20:18:50 +00002175 aggBuffer->addBytes(ptr, 4, Bytes);
2176 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
2177 double float64 = CFP->getValueAPF().convertToDouble();
Justin Holewinski0497ab12013-03-30 14:29:21 +00002178 ptr = (unsigned char *)&float64;
Justin Holewinskiae556d32012-05-04 20:18:50 +00002179 aggBuffer->addBytes(ptr, 8, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00002180 } else {
Justin Holewinskiae556d32012-05-04 20:18:50 +00002181 llvm_unreachable("unsupported fp const type");
2182 }
2183 break;
2184 }
2185 case Type::PointerTyID: {
Justin Holewinski01f89f02013-05-20 12:13:32 +00002186 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00002187 aggBuffer->addSymbol(GVar);
Justin Holewinski01f89f02013-05-20 12:13:32 +00002188 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
2189 const Value *v = Cexpr->stripPointerCasts();
Justin Holewinskiae556d32012-05-04 20:18:50 +00002190 aggBuffer->addSymbol(v);
2191 }
2192 unsigned int s = TD->getTypeAllocSize(CPV->getType());
2193 aggBuffer->addZeros(s);
2194 break;
2195 }
2196
2197 case Type::ArrayTyID:
2198 case Type::VectorTyID:
2199 case Type::StructTyID: {
2200 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
Justin Holewinski95564bd2013-09-19 12:51:46 +00002201 isa<ConstantStruct>(CPV) || isa<ConstantDataSequential>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00002202 int ElementSize = TD->getTypeAllocSize(CPV->getType());
2203 bufferAggregateConstant(CPV, aggBuffer);
Justin Holewinski0497ab12013-03-30 14:29:21 +00002204 if (Bytes > ElementSize)
2205 aggBuffer->addZeros(Bytes - ElementSize);
2206 } else if (isa<ConstantAggregateZero>(CPV))
Justin Holewinskiae556d32012-05-04 20:18:50 +00002207 aggBuffer->addZeros(Bytes);
2208 else
2209 llvm_unreachable("Unexpected Constant type");
2210 break;
2211 }
2212
2213 default:
2214 llvm_unreachable("unsupported type");
2215 }
2216}
2217
Justin Holewinski01f89f02013-05-20 12:13:32 +00002218void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
Justin Holewinskiae556d32012-05-04 20:18:50 +00002219 AggBuffer *aggBuffer) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002220 const DataLayout *TD = TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00002221 int Bytes;
2222
2223 // Old constants
2224 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
2225 if (CPV->getNumOperands())
2226 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
2227 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
2228 return;
2229 }
2230
2231 if (const ConstantDataSequential *CDS =
Justin Holewinski0497ab12013-03-30 14:29:21 +00002232 dyn_cast<ConstantDataSequential>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00002233 if (CDS->getNumElements())
2234 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
2235 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
2236 aggBuffer);
2237 return;
2238 }
2239
Justin Holewinskiae556d32012-05-04 20:18:50 +00002240 if (isa<ConstantStruct>(CPV)) {
2241 if (CPV->getNumOperands()) {
2242 StructType *ST = cast<StructType>(CPV->getType());
2243 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00002244 if (i == (e - 1))
Justin Holewinskiae556d32012-05-04 20:18:50 +00002245 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
Justin Holewinski0497ab12013-03-30 14:29:21 +00002246 TD->getTypeAllocSize(ST) -
2247 TD->getStructLayout(ST)->getElementOffset(i);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002248 else
Justin Holewinski0497ab12013-03-30 14:29:21 +00002249 Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
2250 TD->getStructLayout(ST)->getElementOffset(i);
2251 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002252 }
2253 }
2254 return;
2255 }
Craig Topperbdf39a42012-05-24 07:02:50 +00002256 llvm_unreachable("unsupported constant type in printAggregateConstant()");
Justin Holewinskiae556d32012-05-04 20:18:50 +00002257}
2258
2259// buildTypeNameMap - Run through symbol table looking for type names.
2260//
2261
Justin Holewinskiae556d32012-05-04 20:18:50 +00002262bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
2263
2264 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
2265
Justin Holewinski0497ab12013-03-30 14:29:21 +00002266 if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
2267 !PI->second.compare("struct._image2d_t") ||
2268 !PI->second.compare("struct._image3d_t")))
Justin Holewinskiae556d32012-05-04 20:18:50 +00002269 return true;
2270
2271 return false;
2272}
2273
Justin Holewinskiae556d32012-05-04 20:18:50 +00002274
Justin Holewinski0497ab12013-03-30 14:29:21 +00002275bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
2276 switch (MI.getOpcode()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00002277 default:
2278 return false;
Justin Holewinski0497ab12013-03-30 14:29:21 +00002279 case NVPTX::CallArgBeginInst:
2280 case NVPTX::CallArgEndInst0:
2281 case NVPTX::CallArgEndInst1:
2282 case NVPTX::CallArgF32:
2283 case NVPTX::CallArgF64:
2284 case NVPTX::CallArgI16:
2285 case NVPTX::CallArgI32:
2286 case NVPTX::CallArgI32imm:
2287 case NVPTX::CallArgI64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00002288 case NVPTX::CallArgParam:
2289 case NVPTX::CallVoidInst:
2290 case NVPTX::CallVoidInstReg:
2291 case NVPTX::Callseq_End:
Justin Holewinskiae556d32012-05-04 20:18:50 +00002292 case NVPTX::CallVoidInstReg64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00002293 case NVPTX::DeclareParamInst:
2294 case NVPTX::DeclareRetMemInst:
2295 case NVPTX::DeclareRetRegInst:
2296 case NVPTX::DeclareRetScalarInst:
2297 case NVPTX::DeclareScalarParamInst:
2298 case NVPTX::DeclareScalarRegInst:
2299 case NVPTX::StoreParamF32:
2300 case NVPTX::StoreParamF64:
2301 case NVPTX::StoreParamI16:
2302 case NVPTX::StoreParamI32:
2303 case NVPTX::StoreParamI64:
2304 case NVPTX::StoreParamI8:
Justin Holewinski0497ab12013-03-30 14:29:21 +00002305 case NVPTX::StoreRetvalF32:
2306 case NVPTX::StoreRetvalF64:
2307 case NVPTX::StoreRetvalI16:
2308 case NVPTX::StoreRetvalI32:
2309 case NVPTX::StoreRetvalI64:
2310 case NVPTX::StoreRetvalI8:
2311 case NVPTX::LastCallArgF32:
2312 case NVPTX::LastCallArgF64:
2313 case NVPTX::LastCallArgI16:
2314 case NVPTX::LastCallArgI32:
2315 case NVPTX::LastCallArgI32imm:
2316 case NVPTX::LastCallArgI64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00002317 case NVPTX::LastCallArgParam:
2318 case NVPTX::LoadParamMemF32:
2319 case NVPTX::LoadParamMemF64:
2320 case NVPTX::LoadParamMemI16:
2321 case NVPTX::LoadParamMemI32:
2322 case NVPTX::LoadParamMemI64:
2323 case NVPTX::LoadParamMemI8:
Justin Holewinski0497ab12013-03-30 14:29:21 +00002324 case NVPTX::PrototypeInst:
2325 case NVPTX::DBG_VALUE:
Justin Holewinskiae556d32012-05-04 20:18:50 +00002326 return true;
2327 }
2328 return false;
2329}
2330
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002331/// PrintAsmOperand - Print out an operand for an inline asm expression.
2332///
2333bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2334 unsigned AsmVariant,
2335 const char *ExtraCode, raw_ostream &O) {
2336 if (ExtraCode && ExtraCode[0]) {
2337 if (ExtraCode[1] != 0)
2338 return true; // Unknown modifier.
2339
2340 switch (ExtraCode[0]) {
2341 default:
2342 // See if this is a generic print operand
2343 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2344 case 'r':
2345 break;
2346 }
2347 }
2348
2349 printOperand(MI, OpNo, O);
2350
2351 return false;
2352}
2353
2354bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2355 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2356 const char *ExtraCode, raw_ostream &O) {
2357 if (ExtraCode && ExtraCode[0])
2358 return true; // Unknown modifier
2359
2360 O << '[';
2361 printMemOperand(MI, OpNo, O);
2362 O << ']';
2363
2364 return false;
2365}
2366
2367void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2368 raw_ostream &O, const char *Modifier) {
2369 const MachineOperand &MO = MI->getOperand(opNum);
2370 switch (MO.getType()) {
2371 case MachineOperand::MO_Register:
2372 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2373 if (MO.getReg() == NVPTX::VRDepot)
2374 O << DEPOTNAME << getFunctionNumber();
2375 else
2376 O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2377 } else {
Justin Holewinski660597d2013-10-11 12:39:36 +00002378 emitVirtualRegister(MO.getReg(), O);
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002379 }
2380 return;
2381
2382 case MachineOperand::MO_Immediate:
2383 if (!Modifier)
2384 O << MO.getImm();
2385 else if (strstr(Modifier, "vec") == Modifier)
2386 printVecModifiedImmediate(MO, Modifier, O);
2387 else
2388 llvm_unreachable(
2389 "Don't know how to handle modifier on immediate operand");
2390 return;
2391
2392 case MachineOperand::MO_FPImmediate:
2393 printFPConstant(MO.getFPImm(), O);
2394 break;
2395
2396 case MachineOperand::MO_GlobalAddress:
Eli Bendersky6a0ccfb2014-03-31 16:11:57 +00002397 O << *getSymbol(MO.getGlobal());
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002398 break;
2399
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00002400 case MachineOperand::MO_MachineBasicBlock:
2401 O << *MO.getMBB()->getSymbol();
2402 return;
2403
2404 default:
2405 llvm_unreachable("Operand type not supported.");
2406 }
2407}
2408
2409void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2410 raw_ostream &O, const char *Modifier) {
2411 printOperand(MI, opNum, O);
2412
2413 if (Modifier && !strcmp(Modifier, "add")) {
2414 O << ", ";
2415 printOperand(MI, opNum + 1, O);
2416 } else {
2417 if (MI->getOperand(opNum + 1).isImm() &&
2418 MI->getOperand(opNum + 1).getImm() == 0)
2419 return; // don't print ',0' or '+0'
2420 O << "+";
2421 printOperand(MI, opNum + 1, O);
2422 }
2423}
2424
2425
Justin Holewinskiae556d32012-05-04 20:18:50 +00002426// Force static initialization.
2427extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2428 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2429 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2430}
2431
Justin Holewinskiae556d32012-05-04 20:18:50 +00002432void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2433 std::stringstream temp;
Justin Holewinski0497ab12013-03-30 14:29:21 +00002434 LineReader *reader = this->getReader(filename.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +00002435 temp << "\n//";
2436 temp << filename.str();
2437 temp << ":";
2438 temp << line;
2439 temp << " ";
2440 temp << reader->readLine(line);
2441 temp << "\n";
2442 this->OutStreamer.EmitRawText(Twine(temp.str()));
2443}
2444
Justin Holewinskiae556d32012-05-04 20:18:50 +00002445LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
Craig Topper062a2ba2014-04-25 05:30:21 +00002446 if (!reader) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00002447 reader = new LineReader(filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002448 }
2449
2450 if (reader->fileName() != filename) {
2451 delete reader;
Justin Holewinski0497ab12013-03-30 14:29:21 +00002452 reader = new LineReader(filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002453 }
2454
2455 return reader;
2456}
2457
Justin Holewinski0497ab12013-03-30 14:29:21 +00002458std::string LineReader::readLine(unsigned lineNum) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00002459 if (lineNum < theCurLine) {
2460 theCurLine = 0;
Justin Holewinski0497ab12013-03-30 14:29:21 +00002461 fstr.seekg(0, std::ios::beg);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002462 }
2463 while (theCurLine < lineNum) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00002464 fstr.getline(buff, 500);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002465 theCurLine++;
2466 }
2467 return buff;
2468}
2469
2470// Force static initialization.
2471extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2472 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2473 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2474}