1 //===-- NVPTXAsmPrinter.cpp - NVPTX LLVM assembly writer ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to NVPTX assembly language.
13 //===----------------------------------------------------------------------===//
15 #include "NVPTXAsmPrinter.h"
16 #include "InstPrinter/NVPTXInstPrinter.h"
17 #include "MCTargetDesc/NVPTXMCAsmInfo.h"
19 #include "NVPTXInstrInfo.h"
20 #include "NVPTXMachineFunctionInfo.h"
21 #include "NVPTXMCExpr.h"
22 #include "NVPTXRegisterInfo.h"
23 #include "NVPTXTargetMachine.h"
24 #include "NVPTXUtilities.h"
25 #include "cl_common_defines.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Analysis/ConstantFolding.h"
28 #include "llvm/CodeGen/Analysis.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineModuleInfo.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/IR/DebugInfo.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Mangler.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/IR/Operator.h"
39 #include "llvm/MC/MCStreamer.h"
40 #include "llvm/MC/MCSymbol.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/Support/TargetRegistry.h"
46 #include "llvm/Support/TimeValue.h"
47 #include "llvm/Target/TargetLoweringObjectFile.h"
51 #define DEPOTNAME "__local_depot"
54 EmitLineNumbers("nvptx-emit-line-numbers", cl::Hidden,
55 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
59 InterleaveSrc("nvptx-emit-src", cl::ZeroOrMore, cl::Hidden,
60 cl::desc("NVPTX Specific: Emit source line in ptx file"),
64 /// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
66 void DiscoverDependentGlobals(const Value *V,
67 DenseSet<const GlobalVariable *> &Globals) {
68 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
71 if (const User *U = dyn_cast<User>(V)) {
72 for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
73 DiscoverDependentGlobals(U->getOperand(i), Globals);
79 /// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
80 /// instances to be emitted, but only after any dependents have been added
82 void VisitGlobalVariableForEmission(
83 const GlobalVariable *GV, SmallVectorImpl<const GlobalVariable *> &Order,
84 DenseSet<const GlobalVariable *> &Visited,
85 DenseSet<const GlobalVariable *> &Visiting) {
86 // Have we already visited this one?
87 if (Visited.count(GV))
90 // Do we have a circular dependency?
91 if (Visiting.count(GV))
92 report_fatal_error("Circular dependency found in global variable set");
94 // Start visiting this global
97 // Make sure we visit all dependents first
98 DenseSet<const GlobalVariable *> Others;
99 for (unsigned i = 0, e = GV->getNumOperands(); i != e; ++i)
100 DiscoverDependentGlobals(GV->getOperand(i), Others);
102 for (DenseSet<const GlobalVariable *>::iterator I = Others.begin(),
105 VisitGlobalVariableForEmission(*I, Order, Visited, Visiting);
107 // Now we can visit ourself
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.
118 using namespace nvptx;
119 const MCExpr *nvptx::LowerConstant(const Constant *CV, AsmPrinter &AP) {
120 MCContext &Ctx = AP.OutContext;
122 if (CV->isNullValue() || isa<UndefValue>(CV))
123 return MCConstantExpr::Create(0, Ctx);
125 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
126 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
128 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
129 return MCSymbolRefExpr::Create(AP.getSymbol(GV), Ctx);
131 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
132 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
134 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
136 llvm_unreachable("Unknown constant value to lower!");
138 switch (CE->getOpcode()) {
140 // If the code isn't optimized, there may be outstanding folding
141 // opportunities. Attempt to fold the expression using DataLayout as a
142 // last resort before giving up.
143 if (Constant *C = ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
145 return LowerConstant(C, AP);
147 // Otherwise report the problem to the user.
150 OS << "Unsupported expression in static initializer: ";
151 CE->printAsOperand(OS, /*PrintType=*/ false,
152 !AP.MF ? nullptr : AP.MF->getFunction()->getParent());
153 report_fatal_error(OS.str());
155 case Instruction::AddrSpaceCast: {
156 // Strip any addrspace(1)->addrspace(0) addrspace casts. These will be
157 // handled by the generic() logic in the MCExpr printer
158 PointerType *DstTy = cast<PointerType>(CE->getType());
159 PointerType *SrcTy = cast<PointerType>(CE->getOperand(0)->getType());
160 if (SrcTy->getAddressSpace() == 1 && DstTy->getAddressSpace() == 0) {
161 return LowerConstant(cast<const Constant>(CE->getOperand(0)), AP);
164 raw_string_ostream OS(S);
165 OS << "Unsupported expression in static initializer: ";
166 CE->printAsOperand(OS, /*PrintType=*/ false,
167 !AP.MF ? nullptr : AP.MF->getFunction()->getParent());
168 report_fatal_error(OS.str());
170 case Instruction::GetElementPtr: {
171 const DataLayout &TD = *AP.TM.getDataLayout();
172 // Generate a symbolic expression for the byte address
173 APInt OffsetAI(TD.getPointerSizeInBits(), 0);
174 cast<GEPOperator>(CE)->accumulateConstantOffset(TD, OffsetAI);
176 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
180 int64_t Offset = OffsetAI.getSExtValue();
181 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
185 case Instruction::Trunc:
186 // We emit the value and depend on the assembler to truncate the generated
187 // expression properly. This is important for differences between
188 // blockaddress labels. Since the two labels are in the same function, it
189 // is reasonable to treat their delta as a 32-bit value.
191 case Instruction::BitCast:
192 return LowerConstant(CE->getOperand(0), AP);
194 case Instruction::IntToPtr: {
195 const DataLayout &TD = *AP.TM.getDataLayout();
196 // Handle casts to pointers by changing them into casts to the appropriate
197 // integer type. This promotes constant folding and simplifies this code.
198 Constant *Op = CE->getOperand(0);
199 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
201 return LowerConstant(Op, AP);
204 case Instruction::PtrToInt: {
205 const DataLayout &TD = *AP.TM.getDataLayout();
206 // Support only foldable casts to/from pointers that can be eliminated by
207 // changing the pointer to the appropriately sized integer type.
208 Constant *Op = CE->getOperand(0);
209 Type *Ty = CE->getType();
211 const MCExpr *OpExpr = LowerConstant(Op, AP);
213 // We can emit the pointer value into this slot if the slot is an
214 // integer slot equal to the size of the pointer.
215 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
218 // Otherwise the pointer is smaller than the resultant integer, mask off
219 // the high bits so we are sure to get a proper truncation if the input is
221 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
222 const MCExpr *MaskExpr =
223 MCConstantExpr::Create(~0ULL >> (64 - InBits), Ctx);
224 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
227 // The MC library also has a right-shift operator, but it isn't consistently
228 // signed or unsigned between different targets.
229 case Instruction::Add:
230 case Instruction::Sub:
231 case Instruction::Mul:
232 case Instruction::SDiv:
233 case Instruction::SRem:
234 case Instruction::Shl:
235 case Instruction::And:
236 case Instruction::Or:
237 case Instruction::Xor: {
238 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
239 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
240 switch (CE->getOpcode()) {
242 llvm_unreachable("Unknown binary operator constant cast expr");
243 case Instruction::Add:
244 return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
245 case Instruction::Sub:
246 return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
247 case Instruction::Mul:
248 return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
249 case Instruction::SDiv:
250 return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
251 case Instruction::SRem:
252 return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
253 case Instruction::Shl:
254 return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
255 case Instruction::And:
256 return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
257 case Instruction::Or:
258 return MCBinaryExpr::CreateOr(LHS, RHS, Ctx);
259 case Instruction::Xor:
260 return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
266 void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
267 if (!EmitLineNumbers)
272 DebugLoc curLoc = MI.getDebugLoc();
274 if (prevDebugLoc.isUnknown() && curLoc.isUnknown())
277 if (prevDebugLoc == curLoc)
280 prevDebugLoc = curLoc;
282 if (curLoc.isUnknown())
285 const MachineFunction *MF = MI.getParent()->getParent();
286 //const TargetMachine &TM = MF->getTarget();
288 const LLVMContext &ctx = MF->getFunction()->getContext();
289 DIScope Scope(curLoc.getScope(ctx));
291 assert((!Scope || Scope.isScope()) &&
292 "Scope of a DebugLoc should be null or a DIScope.");
296 StringRef fileName(Scope.getFilename());
297 StringRef dirName(Scope.getDirectory());
298 SmallString<128> FullPathName = dirName;
299 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
300 sys::path::append(FullPathName, fileName);
301 fileName = FullPathName.str();
304 if (filenameMap.find(fileName.str()) == filenameMap.end())
307 // Emit the line from the source file.
309 this->emitSrcInText(fileName.str(), curLoc.getLine());
311 std::stringstream temp;
312 temp << "\t.loc " << filenameMap[fileName.str()] << " " << curLoc.getLine()
313 << " " << curLoc.getCol();
314 OutStreamer.EmitRawText(Twine(temp.str().c_str()));
317 void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
318 SmallString<128> Str;
319 raw_svector_ostream OS(Str);
320 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
321 emitLineNumberAsDotLoc(*MI);
324 lowerToMCInst(MI, Inst);
325 EmitToStreamer(OutStreamer, Inst);
328 // Handle symbol backtracking for targets that do not support image handles
329 bool NVPTXAsmPrinter::lowerImageHandleOperand(const MachineInstr *MI,
330 unsigned OpNo, MCOperand &MCOp) {
331 const MachineOperand &MO = MI->getOperand(OpNo);
333 switch (MI->getOpcode()) {
334 default: return false;
335 case NVPTX::TEX_1D_F32_I32:
336 case NVPTX::TEX_1D_F32_F32:
337 case NVPTX::TEX_1D_F32_F32_LEVEL:
338 case NVPTX::TEX_1D_F32_F32_GRAD:
339 case NVPTX::TEX_1D_I32_I32:
340 case NVPTX::TEX_1D_I32_F32:
341 case NVPTX::TEX_1D_I32_F32_LEVEL:
342 case NVPTX::TEX_1D_I32_F32_GRAD:
343 case NVPTX::TEX_1D_ARRAY_F32_I32:
344 case NVPTX::TEX_1D_ARRAY_F32_F32:
345 case NVPTX::TEX_1D_ARRAY_F32_F32_LEVEL:
346 case NVPTX::TEX_1D_ARRAY_F32_F32_GRAD:
347 case NVPTX::TEX_1D_ARRAY_I32_I32:
348 case NVPTX::TEX_1D_ARRAY_I32_F32:
349 case NVPTX::TEX_1D_ARRAY_I32_F32_LEVEL:
350 case NVPTX::TEX_1D_ARRAY_I32_F32_GRAD:
351 case NVPTX::TEX_2D_F32_I32:
352 case NVPTX::TEX_2D_F32_F32:
353 case NVPTX::TEX_2D_F32_F32_LEVEL:
354 case NVPTX::TEX_2D_F32_F32_GRAD:
355 case NVPTX::TEX_2D_I32_I32:
356 case NVPTX::TEX_2D_I32_F32:
357 case NVPTX::TEX_2D_I32_F32_LEVEL:
358 case NVPTX::TEX_2D_I32_F32_GRAD:
359 case NVPTX::TEX_2D_ARRAY_F32_I32:
360 case NVPTX::TEX_2D_ARRAY_F32_F32:
361 case NVPTX::TEX_2D_ARRAY_F32_F32_LEVEL:
362 case NVPTX::TEX_2D_ARRAY_F32_F32_GRAD:
363 case NVPTX::TEX_2D_ARRAY_I32_I32:
364 case NVPTX::TEX_2D_ARRAY_I32_F32:
365 case NVPTX::TEX_2D_ARRAY_I32_F32_LEVEL:
366 case NVPTX::TEX_2D_ARRAY_I32_F32_GRAD:
367 case NVPTX::TEX_3D_F32_I32:
368 case NVPTX::TEX_3D_F32_F32:
369 case NVPTX::TEX_3D_F32_F32_LEVEL:
370 case NVPTX::TEX_3D_F32_F32_GRAD:
371 case NVPTX::TEX_3D_I32_I32:
372 case NVPTX::TEX_3D_I32_F32:
373 case NVPTX::TEX_3D_I32_F32_LEVEL:
374 case NVPTX::TEX_3D_I32_F32_GRAD:
376 // This is a texture fetch, so operand 4 is a texref and operand 5 is
379 lowerImageHandleSymbol(MO.getImm(), MCOp);
383 lowerImageHandleSymbol(MO.getImm(), MCOp);
389 case NVPTX::SULD_1D_I8_TRAP:
390 case NVPTX::SULD_1D_I16_TRAP:
391 case NVPTX::SULD_1D_I32_TRAP:
392 case NVPTX::SULD_1D_ARRAY_I8_TRAP:
393 case NVPTX::SULD_1D_ARRAY_I16_TRAP:
394 case NVPTX::SULD_1D_ARRAY_I32_TRAP:
395 case NVPTX::SULD_2D_I8_TRAP:
396 case NVPTX::SULD_2D_I16_TRAP:
397 case NVPTX::SULD_2D_I32_TRAP:
398 case NVPTX::SULD_2D_ARRAY_I8_TRAP:
399 case NVPTX::SULD_2D_ARRAY_I16_TRAP:
400 case NVPTX::SULD_2D_ARRAY_I32_TRAP:
401 case NVPTX::SULD_3D_I8_TRAP:
402 case NVPTX::SULD_3D_I16_TRAP:
403 case NVPTX::SULD_3D_I32_TRAP: {
404 // This is a V1 surface load, so operand 1 is a surfref
406 lowerImageHandleSymbol(MO.getImm(), MCOp);
412 case NVPTX::SULD_1D_V2I8_TRAP:
413 case NVPTX::SULD_1D_V2I16_TRAP:
414 case NVPTX::SULD_1D_V2I32_TRAP:
415 case NVPTX::SULD_1D_ARRAY_V2I8_TRAP:
416 case NVPTX::SULD_1D_ARRAY_V2I16_TRAP:
417 case NVPTX::SULD_1D_ARRAY_V2I32_TRAP:
418 case NVPTX::SULD_2D_V2I8_TRAP:
419 case NVPTX::SULD_2D_V2I16_TRAP:
420 case NVPTX::SULD_2D_V2I32_TRAP:
421 case NVPTX::SULD_2D_ARRAY_V2I8_TRAP:
422 case NVPTX::SULD_2D_ARRAY_V2I16_TRAP:
423 case NVPTX::SULD_2D_ARRAY_V2I32_TRAP:
424 case NVPTX::SULD_3D_V2I8_TRAP:
425 case NVPTX::SULD_3D_V2I16_TRAP:
426 case NVPTX::SULD_3D_V2I32_TRAP: {
427 // This is a V2 surface load, so operand 2 is a surfref
429 lowerImageHandleSymbol(MO.getImm(), MCOp);
435 case NVPTX::SULD_1D_V4I8_TRAP:
436 case NVPTX::SULD_1D_V4I16_TRAP:
437 case NVPTX::SULD_1D_V4I32_TRAP:
438 case NVPTX::SULD_1D_ARRAY_V4I8_TRAP:
439 case NVPTX::SULD_1D_ARRAY_V4I16_TRAP:
440 case NVPTX::SULD_1D_ARRAY_V4I32_TRAP:
441 case NVPTX::SULD_2D_V4I8_TRAP:
442 case NVPTX::SULD_2D_V4I16_TRAP:
443 case NVPTX::SULD_2D_V4I32_TRAP:
444 case NVPTX::SULD_2D_ARRAY_V4I8_TRAP:
445 case NVPTX::SULD_2D_ARRAY_V4I16_TRAP:
446 case NVPTX::SULD_2D_ARRAY_V4I32_TRAP:
447 case NVPTX::SULD_3D_V4I8_TRAP:
448 case NVPTX::SULD_3D_V4I16_TRAP:
449 case NVPTX::SULD_3D_V4I32_TRAP: {
450 // This is a V4 surface load, so operand 4 is a surfref
452 lowerImageHandleSymbol(MO.getImm(), MCOp);
458 case NVPTX::SUST_B_1D_B8_TRAP:
459 case NVPTX::SUST_B_1D_B16_TRAP:
460 case NVPTX::SUST_B_1D_B32_TRAP:
461 case NVPTX::SUST_B_1D_V2B8_TRAP:
462 case NVPTX::SUST_B_1D_V2B16_TRAP:
463 case NVPTX::SUST_B_1D_V2B32_TRAP:
464 case NVPTX::SUST_B_1D_V4B8_TRAP:
465 case NVPTX::SUST_B_1D_V4B16_TRAP:
466 case NVPTX::SUST_B_1D_V4B32_TRAP:
467 case NVPTX::SUST_B_1D_ARRAY_B8_TRAP:
468 case NVPTX::SUST_B_1D_ARRAY_B16_TRAP:
469 case NVPTX::SUST_B_1D_ARRAY_B32_TRAP:
470 case NVPTX::SUST_B_1D_ARRAY_V2B8_TRAP:
471 case NVPTX::SUST_B_1D_ARRAY_V2B16_TRAP:
472 case NVPTX::SUST_B_1D_ARRAY_V2B32_TRAP:
473 case NVPTX::SUST_B_1D_ARRAY_V4B8_TRAP:
474 case NVPTX::SUST_B_1D_ARRAY_V4B16_TRAP:
475 case NVPTX::SUST_B_1D_ARRAY_V4B32_TRAP:
476 case NVPTX::SUST_B_2D_B8_TRAP:
477 case NVPTX::SUST_B_2D_B16_TRAP:
478 case NVPTX::SUST_B_2D_B32_TRAP:
479 case NVPTX::SUST_B_2D_V2B8_TRAP:
480 case NVPTX::SUST_B_2D_V2B16_TRAP:
481 case NVPTX::SUST_B_2D_V2B32_TRAP:
482 case NVPTX::SUST_B_2D_V4B8_TRAP:
483 case NVPTX::SUST_B_2D_V4B16_TRAP:
484 case NVPTX::SUST_B_2D_V4B32_TRAP:
485 case NVPTX::SUST_B_2D_ARRAY_B8_TRAP:
486 case NVPTX::SUST_B_2D_ARRAY_B16_TRAP:
487 case NVPTX::SUST_B_2D_ARRAY_B32_TRAP:
488 case NVPTX::SUST_B_2D_ARRAY_V2B8_TRAP:
489 case NVPTX::SUST_B_2D_ARRAY_V2B16_TRAP:
490 case NVPTX::SUST_B_2D_ARRAY_V2B32_TRAP:
491 case NVPTX::SUST_B_2D_ARRAY_V4B8_TRAP:
492 case NVPTX::SUST_B_2D_ARRAY_V4B16_TRAP:
493 case NVPTX::SUST_B_2D_ARRAY_V4B32_TRAP:
494 case NVPTX::SUST_B_3D_B8_TRAP:
495 case NVPTX::SUST_B_3D_B16_TRAP:
496 case NVPTX::SUST_B_3D_B32_TRAP:
497 case NVPTX::SUST_B_3D_V2B8_TRAP:
498 case NVPTX::SUST_B_3D_V2B16_TRAP:
499 case NVPTX::SUST_B_3D_V2B32_TRAP:
500 case NVPTX::SUST_B_3D_V4B8_TRAP:
501 case NVPTX::SUST_B_3D_V4B16_TRAP:
502 case NVPTX::SUST_B_3D_V4B32_TRAP:
503 case NVPTX::SUST_P_1D_B8_TRAP:
504 case NVPTX::SUST_P_1D_B16_TRAP:
505 case NVPTX::SUST_P_1D_B32_TRAP:
506 case NVPTX::SUST_P_1D_V2B8_TRAP:
507 case NVPTX::SUST_P_1D_V2B16_TRAP:
508 case NVPTX::SUST_P_1D_V2B32_TRAP:
509 case NVPTX::SUST_P_1D_V4B8_TRAP:
510 case NVPTX::SUST_P_1D_V4B16_TRAP:
511 case NVPTX::SUST_P_1D_V4B32_TRAP:
512 case NVPTX::SUST_P_1D_ARRAY_B8_TRAP:
513 case NVPTX::SUST_P_1D_ARRAY_B16_TRAP:
514 case NVPTX::SUST_P_1D_ARRAY_B32_TRAP:
515 case NVPTX::SUST_P_1D_ARRAY_V2B8_TRAP:
516 case NVPTX::SUST_P_1D_ARRAY_V2B16_TRAP:
517 case NVPTX::SUST_P_1D_ARRAY_V2B32_TRAP:
518 case NVPTX::SUST_P_1D_ARRAY_V4B8_TRAP:
519 case NVPTX::SUST_P_1D_ARRAY_V4B16_TRAP:
520 case NVPTX::SUST_P_1D_ARRAY_V4B32_TRAP:
521 case NVPTX::SUST_P_2D_B8_TRAP:
522 case NVPTX::SUST_P_2D_B16_TRAP:
523 case NVPTX::SUST_P_2D_B32_TRAP:
524 case NVPTX::SUST_P_2D_V2B8_TRAP:
525 case NVPTX::SUST_P_2D_V2B16_TRAP:
526 case NVPTX::SUST_P_2D_V2B32_TRAP:
527 case NVPTX::SUST_P_2D_V4B8_TRAP:
528 case NVPTX::SUST_P_2D_V4B16_TRAP:
529 case NVPTX::SUST_P_2D_V4B32_TRAP:
530 case NVPTX::SUST_P_2D_ARRAY_B8_TRAP:
531 case NVPTX::SUST_P_2D_ARRAY_B16_TRAP:
532 case NVPTX::SUST_P_2D_ARRAY_B32_TRAP:
533 case NVPTX::SUST_P_2D_ARRAY_V2B8_TRAP:
534 case NVPTX::SUST_P_2D_ARRAY_V2B16_TRAP:
535 case NVPTX::SUST_P_2D_ARRAY_V2B32_TRAP:
536 case NVPTX::SUST_P_2D_ARRAY_V4B8_TRAP:
537 case NVPTX::SUST_P_2D_ARRAY_V4B16_TRAP:
538 case NVPTX::SUST_P_2D_ARRAY_V4B32_TRAP:
539 case NVPTX::SUST_P_3D_B8_TRAP:
540 case NVPTX::SUST_P_3D_B16_TRAP:
541 case NVPTX::SUST_P_3D_B32_TRAP:
542 case NVPTX::SUST_P_3D_V2B8_TRAP:
543 case NVPTX::SUST_P_3D_V2B16_TRAP:
544 case NVPTX::SUST_P_3D_V2B32_TRAP:
545 case NVPTX::SUST_P_3D_V4B8_TRAP:
546 case NVPTX::SUST_P_3D_V4B16_TRAP:
547 case NVPTX::SUST_P_3D_V4B32_TRAP: {
548 // This is a surface store, so operand 0 is a surfref
550 lowerImageHandleSymbol(MO.getImm(), MCOp);
556 case NVPTX::TXQ_CHANNEL_ORDER:
557 case NVPTX::TXQ_CHANNEL_DATA_TYPE:
558 case NVPTX::TXQ_WIDTH:
559 case NVPTX::TXQ_HEIGHT:
560 case NVPTX::TXQ_DEPTH:
561 case NVPTX::TXQ_ARRAY_SIZE:
562 case NVPTX::TXQ_NUM_SAMPLES:
563 case NVPTX::TXQ_NUM_MIPMAP_LEVELS:
564 case NVPTX::SUQ_CHANNEL_ORDER:
565 case NVPTX::SUQ_CHANNEL_DATA_TYPE:
566 case NVPTX::SUQ_WIDTH:
567 case NVPTX::SUQ_HEIGHT:
568 case NVPTX::SUQ_DEPTH:
569 case NVPTX::SUQ_ARRAY_SIZE: {
570 // This is a query, so operand 1 is a surfref/texref
572 lowerImageHandleSymbol(MO.getImm(), MCOp);
581 void NVPTXAsmPrinter::lowerImageHandleSymbol(unsigned Index, MCOperand &MCOp) {
583 TargetMachine &TM = const_cast<TargetMachine&>(MF->getTarget());
584 NVPTXTargetMachine &nvTM = static_cast<NVPTXTargetMachine&>(TM);
585 const NVPTXMachineFunctionInfo *MFI = MF->getInfo<NVPTXMachineFunctionInfo>();
586 const char *Sym = MFI->getImageHandleSymbol(Index);
587 std::string *SymNamePtr =
588 nvTM.getManagedStrPool()->getManagedString(Sym);
589 MCOp = GetSymbolRef(OutContext.GetOrCreateSymbol(
590 StringRef(SymNamePtr->c_str())));
593 void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
594 OutMI.setOpcode(MI->getOpcode());
595 const NVPTXSubtarget &ST = TM.getSubtarget<NVPTXSubtarget>();
597 // Special: Do not mangle symbol operand of CALL_PROTOTYPE
598 if (MI->getOpcode() == NVPTX::CALL_PROTOTYPE) {
599 const MachineOperand &MO = MI->getOperand(0);
600 OutMI.addOperand(GetSymbolRef(
601 OutContext.GetOrCreateSymbol(Twine(MO.getSymbolName()))));
605 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
606 const MachineOperand &MO = MI->getOperand(i);
609 if (!ST.hasImageHandles()) {
610 if (lowerImageHandleOperand(MI, i, MCOp)) {
611 OutMI.addOperand(MCOp);
616 if (lowerOperand(MO, MCOp))
617 OutMI.addOperand(MCOp);
621 bool NVPTXAsmPrinter::lowerOperand(const MachineOperand &MO,
623 switch (MO.getType()) {
624 default: llvm_unreachable("unknown operand type");
625 case MachineOperand::MO_Register:
626 MCOp = MCOperand::CreateReg(encodeVirtualRegister(MO.getReg()));
628 case MachineOperand::MO_Immediate:
629 MCOp = MCOperand::CreateImm(MO.getImm());
631 case MachineOperand::MO_MachineBasicBlock:
632 MCOp = MCOperand::CreateExpr(MCSymbolRefExpr::Create(
633 MO.getMBB()->getSymbol(), OutContext));
635 case MachineOperand::MO_ExternalSymbol:
636 MCOp = GetSymbolRef(GetExternalSymbolSymbol(MO.getSymbolName()));
638 case MachineOperand::MO_GlobalAddress:
639 MCOp = GetSymbolRef(getSymbol(MO.getGlobal()));
641 case MachineOperand::MO_FPImmediate: {
642 const ConstantFP *Cnt = MO.getFPImm();
643 APFloat Val = Cnt->getValueAPF();
645 switch (Cnt->getType()->getTypeID()) {
646 default: report_fatal_error("Unsupported FP type"); break;
647 case Type::FloatTyID:
648 MCOp = MCOperand::CreateExpr(
649 NVPTXFloatMCExpr::CreateConstantFPSingle(Val, OutContext));
651 case Type::DoubleTyID:
652 MCOp = MCOperand::CreateExpr(
653 NVPTXFloatMCExpr::CreateConstantFPDouble(Val, OutContext));
662 unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
663 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
664 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
666 DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
667 unsigned RegNum = RegMap[Reg];
669 // Encode the register class in the upper 4 bits
670 // Must be kept in sync with NVPTXInstPrinter::printRegName
672 if (RC == &NVPTX::Int1RegsRegClass) {
674 } else if (RC == &NVPTX::Int16RegsRegClass) {
676 } else if (RC == &NVPTX::Int32RegsRegClass) {
678 } else if (RC == &NVPTX::Int64RegsRegClass) {
680 } else if (RC == &NVPTX::Float32RegsRegClass) {
682 } else if (RC == &NVPTX::Float64RegsRegClass) {
685 report_fatal_error("Bad register class");
688 // Insert the vreg number
689 Ret |= (RegNum & 0x0FFFFFFF);
692 // Some special-use registers are actually physical registers.
693 // Encode this as the register class ID of 0 and the real register ID.
694 return Reg & 0x0FFFFFFF;
698 MCOperand NVPTXAsmPrinter::GetSymbolRef(const MCSymbol *Symbol) {
700 Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None,
702 return MCOperand::CreateExpr(Expr);
705 void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
706 const DataLayout *TD = TM.getDataLayout();
707 const TargetLowering *TLI = TM.getTargetLowering();
709 Type *Ty = F->getReturnType();
711 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
713 if (Ty->getTypeID() == Type::VoidTyID)
719 if (Ty->isFloatingPointTy() || Ty->isIntegerTy()) {
721 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
722 size = ITy->getBitWidth();
726 assert(Ty->isFloatingPointTy() && "Floating point type expected here");
727 size = Ty->getPrimitiveSizeInBits();
730 O << ".param .b" << size << " func_retval0";
731 } else if (isa<PointerType>(Ty)) {
732 O << ".param .b" << TLI->getPointerTy().getSizeInBits()
735 if ((Ty->getTypeID() == Type::StructTyID) || isa<VectorType>(Ty)) {
736 SmallVector<EVT, 16> vtparts;
737 ComputeValueVTs(*TLI, Ty, vtparts);
738 unsigned totalsz = 0;
739 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
741 EVT elemtype = vtparts[i];
742 if (vtparts[i].isVector()) {
743 elems = vtparts[i].getVectorNumElements();
744 elemtype = vtparts[i].getVectorElementType();
746 for (unsigned j = 0, je = elems; j != je; ++j) {
747 unsigned sz = elemtype.getSizeInBits();
748 if (elemtype.isInteger() && (sz < 8))
753 unsigned retAlignment = 0;
754 if (!llvm::getAlign(*F, 0, retAlignment))
755 retAlignment = TD->getABITypeAlignment(Ty);
756 O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
759 assert(false && "Unknown return type");
762 SmallVector<EVT, 16> vtparts;
763 ComputeValueVTs(*TLI, Ty, vtparts);
765 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
767 EVT elemtype = vtparts[i];
768 if (vtparts[i].isVector()) {
769 elems = vtparts[i].getVectorNumElements();
770 elemtype = vtparts[i].getVectorElementType();
773 for (unsigned j = 0, je = elems; j != je; ++j) {
774 unsigned sz = elemtype.getSizeInBits();
775 if (elemtype.isInteger() && (sz < 32))
777 O << ".reg .b" << sz << " func_retval" << idx;
790 void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
792 const Function *F = MF.getFunction();
793 printReturnValStr(F, O);
796 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
797 SmallString<128> Str;
798 raw_svector_ostream O(Str);
800 if (!GlobalsEmitted) {
801 emitGlobals(*MF->getFunction()->getParent());
802 GlobalsEmitted = true;
806 MRI = &MF->getRegInfo();
807 F = MF->getFunction();
808 emitLinkageDirective(F, O);
809 if (llvm::isKernelFunction(*F))
813 printReturnValStr(*MF, O);
818 emitFunctionParamList(*MF, O);
820 if (llvm::isKernelFunction(*F))
821 emitKernelFunctionDirectives(*F, O);
823 OutStreamer.EmitRawText(O.str());
825 prevDebugLoc = DebugLoc();
828 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
830 OutStreamer.EmitRawText(StringRef("{\n"));
831 setAndEmitFunctionVirtualRegisters(*MF);
833 SmallString<128> Str;
834 raw_svector_ostream O(Str);
835 emitDemotedVars(MF->getFunction(), O);
836 OutStreamer.EmitRawText(O.str());
839 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
840 OutStreamer.EmitRawText(StringRef("}\n"));
844 void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
845 unsigned RegNo = MI->getOperand(0).getReg();
846 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
847 if (TRI->isVirtualRegister(RegNo)) {
848 OutStreamer.AddComment(Twine("implicit-def: ") +
849 getVirtualRegisterName(RegNo));
851 OutStreamer.AddComment(Twine("implicit-def: ") +
852 TM.getRegisterInfo()->getName(RegNo));
854 OutStreamer.AddBlankLine();
857 void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
858 raw_ostream &O) const {
859 // If the NVVM IR has some of reqntid* specified, then output
860 // the reqntid directive, and set the unspecified ones to 1.
861 // If none of reqntid* is specified, don't output reqntid directive.
862 unsigned reqntidx, reqntidy, reqntidz;
863 bool specified = false;
864 if (llvm::getReqNTIDx(F, reqntidx) == false)
868 if (llvm::getReqNTIDy(F, reqntidy) == false)
872 if (llvm::getReqNTIDz(F, reqntidz) == false)
878 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
881 // If the NVVM IR has some of maxntid* specified, then output
882 // the maxntid directive, and set the unspecified ones to 1.
883 // If none of maxntid* is specified, don't output maxntid directive.
884 unsigned maxntidx, maxntidy, maxntidz;
886 if (llvm::getMaxNTIDx(F, maxntidx) == false)
890 if (llvm::getMaxNTIDy(F, maxntidy) == false)
894 if (llvm::getMaxNTIDz(F, maxntidz) == false)
900 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
904 if (llvm::getMinCTASm(F, mincta))
905 O << ".minnctapersm " << mincta << "\n";
909 NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
910 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
913 raw_string_ostream NameStr(Name);
915 VRegRCMap::const_iterator I = VRegMapping.find(RC);
916 assert(I != VRegMapping.end() && "Bad register class");
917 const DenseMap<unsigned, unsigned> &RegMap = I->second;
919 VRegMap::const_iterator VI = RegMap.find(Reg);
920 assert(VI != RegMap.end() && "Bad virtual register");
921 unsigned MappedVR = VI->second;
923 NameStr << getNVPTXRegClassStr(RC) << MappedVR;
929 void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
931 O << getVirtualRegisterName(vr);
934 void NVPTXAsmPrinter::printVecModifiedImmediate(
935 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
936 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
937 int Imm = (int) MO.getImm();
938 if (0 == strcmp(Modifier, "vecelem"))
939 O << "_" << vecelem[Imm];
940 else if (0 == strcmp(Modifier, "vecv4comm1")) {
941 if ((Imm < 0) || (Imm > 3))
943 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
944 if ((Imm < 4) || (Imm > 7))
946 } else if (0 == strcmp(Modifier, "vecv4pos")) {
949 O << "_" << vecelem[Imm % 4];
950 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
951 if ((Imm < 0) || (Imm > 1))
953 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
954 if ((Imm < 2) || (Imm > 3))
956 } else if (0 == strcmp(Modifier, "vecv2pos")) {
959 O << "_" << vecelem[Imm % 2];
961 llvm_unreachable("Unknown Modifier on immediate operand");
966 void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
968 emitLinkageDirective(F, O);
969 if (llvm::isKernelFunction(*F))
973 printReturnValStr(F, O);
974 O << *getSymbol(F) << "\n";
975 emitFunctionParamList(F, O);
979 static bool usedInGlobalVarDef(const Constant *C) {
983 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
984 if (GV->getName().str() == "llvm.used")
989 for (const User *U : C->users())
990 if (const Constant *C = dyn_cast<Constant>(U))
991 if (usedInGlobalVarDef(C))
997 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
998 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
999 if (othergv->getName().str() == "llvm.used")
1003 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
1004 if (instr->getParent() && instr->getParent()->getParent()) {
1005 const Function *curFunc = instr->getParent()->getParent();
1006 if (oneFunc && (curFunc != oneFunc))
1014 if (const MDNode *md = dyn_cast<MDNode>(U))
1015 if (md->hasName() && ((md->getName().str() == "llvm.dbg.gv") ||
1016 (md->getName().str() == "llvm.dbg.sp")))
1019 for (const User *UU : U->users())
1020 if (usedInOneFunc(UU, oneFunc) == false)
1026 /* Find out if a global variable can be demoted to local scope.
1027 * Currently, this is valid for CUDA shared variables, which have local
1028 * scope and global lifetime. So the conditions to check are :
1029 * 1. Is the global variable in shared address space?
1030 * 2. Does it have internal linkage?
1031 * 3. Is the global variable referenced only in one function?
1033 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
1034 if (gv->hasInternalLinkage() == false)
1036 const PointerType *Pty = gv->getType();
1037 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
1040 const Function *oneFunc = nullptr;
1042 bool flag = usedInOneFunc(gv, oneFunc);
1051 static bool useFuncSeen(const Constant *C,
1052 llvm::DenseMap<const Function *, bool> &seenMap) {
1053 for (const User *U : C->users()) {
1054 if (const Constant *cu = dyn_cast<Constant>(U)) {
1055 if (useFuncSeen(cu, seenMap))
1057 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
1058 const BasicBlock *bb = I->getParent();
1061 const Function *caller = bb->getParent();
1064 if (seenMap.find(caller) != seenMap.end())
1071 void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
1072 llvm::DenseMap<const Function *, bool> seenMap;
1073 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
1074 const Function *F = FI;
1076 if (F->isDeclaration()) {
1079 if (F->getIntrinsicID())
1081 emitDeclaration(F, O);
1084 for (const User *U : F->users()) {
1085 if (const Constant *C = dyn_cast<Constant>(U)) {
1086 if (usedInGlobalVarDef(C)) {
1087 // The use is in the initialization of a global variable
1088 // that is a function pointer, so print a declaration
1089 // for the original function
1090 emitDeclaration(F, O);
1093 // Emit a declaration of this function if the function that
1094 // uses this constant expr has already been seen.
1095 if (useFuncSeen(C, seenMap)) {
1096 emitDeclaration(F, O);
1101 if (!isa<Instruction>(U))
1103 const Instruction *instr = cast<Instruction>(U);
1104 const BasicBlock *bb = instr->getParent();
1107 const Function *caller = bb->getParent();
1111 // If a caller has already been seen, then the caller is
1112 // appearing in the module before the callee. so print out
1113 // a declaration for the callee.
1114 if (seenMap.find(caller) != seenMap.end()) {
1115 emitDeclaration(F, O);
1123 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
1124 DebugInfoFinder DbgFinder;
1125 DbgFinder.processModule(M);
1128 for (DICompileUnit DIUnit : DbgFinder.compile_units()) {
1129 StringRef Filename(DIUnit.getFilename());
1130 StringRef Dirname(DIUnit.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();
1136 if (filenameMap.find(Filename.str()) != filenameMap.end())
1138 filenameMap[Filename.str()] = i;
1139 OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
1143 for (DISubprogram SP : DbgFinder.subprograms()) {
1144 StringRef Filename(SP.getFilename());
1145 StringRef Dirname(SP.getDirectory());
1146 SmallString<128> FullPathName = Dirname;
1147 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
1148 sys::path::append(FullPathName, Filename);
1149 Filename = FullPathName.str();
1151 if (filenameMap.find(Filename.str()) != filenameMap.end())
1153 filenameMap[Filename.str()] = i;
1158 bool NVPTXAsmPrinter::doInitialization(Module &M) {
1160 SmallString<128> Str1;
1161 raw_svector_ostream OS1(Str1);
1163 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
1164 MMI->AnalyzeModule(M);
1166 // We need to call the parent's one explicitly.
1167 //bool Result = AsmPrinter::doInitialization(M);
1169 // Initialize TargetLoweringObjectFile.
1170 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
1171 .Initialize(OutContext, TM);
1173 Mang = new Mangler(TM.getDataLayout());
1175 // Emit header before any dwarf directives are emitted below.
1177 OutStreamer.EmitRawText(OS1.str());
1179 // Already commented out
1180 //bool Result = AsmPrinter::doInitialization(M);
1182 // Emit module-level inline asm if it exists.
1183 if (!M.getModuleInlineAsm().empty()) {
1184 OutStreamer.AddComment("Start of file scope inline assembly");
1185 OutStreamer.AddBlankLine();
1186 OutStreamer.EmitRawText(StringRef(M.getModuleInlineAsm()));
1187 OutStreamer.AddBlankLine();
1188 OutStreamer.AddComment("End of file scope inline assembly");
1189 OutStreamer.AddBlankLine();
1192 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
1193 recordAndEmitFilenames(M);
1195 GlobalsEmitted = false;
1197 return false; // success
1200 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
1201 SmallString<128> Str2;
1202 raw_svector_ostream OS2(Str2);
1204 emitDeclarations(M, OS2);
1206 // As ptxas does not support forward references of globals, we need to first
1207 // sort the list of module-level globals in def-use order. We visit each
1208 // global variable in order, and ensure that we emit it *after* its dependent
1209 // globals. We use a little extra memory maintaining both a set and a list to
1210 // have fast searches while maintaining a strict ordering.
1211 SmallVector<const GlobalVariable *, 8> Globals;
1212 DenseSet<const GlobalVariable *> GVVisited;
1213 DenseSet<const GlobalVariable *> GVVisiting;
1215 // Visit each global variable, in order
1216 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1218 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
1220 assert(GVVisited.size() == M.getGlobalList().size() &&
1221 "Missed a global variable");
1222 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
1224 // Print out module-level global variables in proper order
1225 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1226 printModuleLevelGV(Globals[i], OS2);
1230 OutStreamer.EmitRawText(OS2.str());
1233 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O) {
1235 O << "// Generated by LLVM NVPTX Back-End\n";
1239 unsigned PTXVersion = nvptxSubtarget.getPTXVersion();
1240 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
1243 O << nvptxSubtarget.getTargetName();
1245 if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
1246 O << ", texmode_independent";
1247 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1248 if (!nvptxSubtarget.hasDouble())
1249 O << ", map_f64_to_f32";
1252 if (MAI->doesSupportDebugInformation())
1257 O << ".address_size ";
1258 if (nvptxSubtarget.is64Bit())
1267 bool NVPTXAsmPrinter::doFinalization(Module &M) {
1269 // If we did not emit any functions, then the global declarations have not
1270 // yet been emitted.
1271 if (!GlobalsEmitted) {
1273 GlobalsEmitted = true;
1276 // XXX Temproarily remove global variables so that doFinalization() will not
1277 // emit them again (global variables are emitted at beginning).
1279 Module::GlobalListType &global_list = M.getGlobalList();
1280 int i, n = global_list.size();
1281 GlobalVariable **gv_array = new GlobalVariable *[n];
1283 // first, back-up GlobalVariable in gv_array
1285 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
1287 gv_array[i++] = &*I;
1289 // second, empty global_list
1290 while (!global_list.empty())
1291 global_list.remove(global_list.begin());
1293 // call doFinalization
1294 bool ret = AsmPrinter::doFinalization(M);
1296 // now we restore global variables
1297 for (i = 0; i < n; i++)
1298 global_list.insert(global_list.end(), gv_array[i]);
1300 clearAnnotationCache(&M);
1305 //bool Result = AsmPrinter::doFinalization(M);
1306 // Instead of calling the parents doFinalization, we may
1307 // clone parents doFinalization and customize here.
1308 // Currently, we if NVISA out the EmitGlobals() in
1309 // parent's doFinalization, which is too intrusive.
1311 // Same for the doInitialization.
1315 // This function emits appropriate linkage directives for
1316 // functions and global variables.
1318 // extern function declaration -> .extern
1319 // extern function definition -> .visible
1320 // external global variable with init -> .visible
1321 // external without init -> .extern
1322 // appending -> not allowed, assert.
1324 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
1326 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1327 if (V->hasExternalLinkage()) {
1328 if (isa<GlobalVariable>(V)) {
1329 const GlobalVariable *GVar = cast<GlobalVariable>(V);
1331 if (GVar->hasInitializer())
1336 } else if (V->isDeclaration())
1340 } else if (V->hasAppendingLinkage()) {
1342 msg.append("Error: ");
1343 msg.append("Symbol ");
1345 msg.append(V->getName().str());
1346 msg.append("has unsupported appending linkage type");
1347 llvm_unreachable(msg.c_str());
1352 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1354 bool processDemoted) {
1357 if (GVar->hasSection()) {
1358 if (GVar->getSection() == StringRef("llvm.metadata"))
1362 const DataLayout *TD = TM.getDataLayout();
1364 // GlobalVariables are always constant pointers themselves.
1365 const PointerType *PTy = GVar->getType();
1366 Type *ETy = PTy->getElementType();
1368 if (GVar->hasExternalLinkage()) {
1369 if (GVar->hasInitializer())
1375 if (llvm::isTexture(*GVar)) {
1376 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1380 if (llvm::isSurface(*GVar)) {
1381 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1385 if (GVar->isDeclaration()) {
1386 // (extern) declarations, no definition or initializer
1387 // Currently the only known declaration is for an automatic __local
1388 // (.shared) promoted to global.
1389 emitPTXGlobalVariable(GVar, O);
1394 if (llvm::isSampler(*GVar)) {
1395 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1397 const Constant *Initializer = nullptr;
1398 if (GVar->hasInitializer())
1399 Initializer = GVar->getInitializer();
1400 const ConstantInt *CI = nullptr;
1402 CI = dyn_cast<ConstantInt>(Initializer);
1404 unsigned sample = CI->getZExtValue();
1409 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1411 O << "addr_mode_" << i << " = ";
1417 O << "clamp_to_border";
1420 O << "clamp_to_edge";
1431 O << "filter_mode = ";
1432 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1440 llvm_unreachable("Anisotropic filtering is not supported");
1445 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
1446 O << ", force_unnormalized_coords = 1";
1455 if (GVar->hasPrivateLinkage()) {
1457 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1460 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1461 if (!strncmp(GVar->getName().data(), "filename", 8))
1463 if (GVar->use_empty())
1467 const Function *demotedFunc = nullptr;
1468 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1469 O << "// " << GVar->getName().str() << " has been demoted\n";
1470 if (localDecls.find(demotedFunc) != localDecls.end())
1471 localDecls[demotedFunc].push_back(GVar);
1473 std::vector<const GlobalVariable *> temp;
1474 temp.push_back(GVar);
1475 localDecls[demotedFunc] = temp;
1481 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1482 if (GVar->getAlignment() == 0)
1483 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1485 O << " .align " << GVar->getAlignment();
1487 if (ETy->isSingleValueType()) {
1489 // Special case: ABI requires that we use .u8 for predicates
1490 if (ETy->isIntegerTy(1))
1493 O << getPTXFundamentalTypeStr(ETy, false);
1495 O << *getSymbol(GVar);
1497 // Ptx allows variable initilization only for constant and global state
1499 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1500 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1501 GVar->hasInitializer()) {
1502 const Constant *Initializer = GVar->getInitializer();
1503 if (!Initializer->isNullValue()) {
1505 printScalarConstant(Initializer, O);
1509 unsigned int ElementSize = 0;
1511 // Although PTX has direct support for struct type and array type and
1512 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1513 // targets that support these high level field accesses. Structs, arrays
1514 // and vectors are lowered into arrays of bytes.
1515 switch (ETy->getTypeID()) {
1516 case Type::StructTyID:
1517 case Type::ArrayTyID:
1518 case Type::VectorTyID:
1519 ElementSize = TD->getTypeStoreSize(ETy);
1520 // Ptx allows variable initilization only for constant and
1521 // global state spaces.
1522 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1523 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1524 GVar->hasInitializer()) {
1525 const Constant *Initializer = GVar->getInitializer();
1526 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1527 AggBuffer aggBuffer(ElementSize, O, *this);
1528 bufferAggregateConstant(Initializer, &aggBuffer);
1529 if (aggBuffer.numSymbols) {
1530 if (nvptxSubtarget.is64Bit()) {
1531 O << " .u64 " << *getSymbol(GVar) << "[";
1532 O << ElementSize / 8;
1534 O << " .u32 " << *getSymbol(GVar) << "[";
1535 O << ElementSize / 4;
1539 O << " .b8 " << *getSymbol(GVar) << "[";
1547 O << " .b8 " << *getSymbol(GVar);
1555 O << " .b8 " << *getSymbol(GVar);
1564 llvm_unreachable("type not supported yet");
1571 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1572 if (localDecls.find(f) == localDecls.end())
1575 std::vector<const GlobalVariable *> &gvars = localDecls[f];
1577 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
1578 O << "\t// demoted variable\n\t";
1579 printModuleLevelGV(gvars[i], O, true);
1583 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1584 raw_ostream &O) const {
1585 switch (AddressSpace) {
1586 case llvm::ADDRESS_SPACE_LOCAL:
1589 case llvm::ADDRESS_SPACE_GLOBAL:
1592 case llvm::ADDRESS_SPACE_CONST:
1595 case llvm::ADDRESS_SPACE_SHARED:
1599 report_fatal_error("Bad address space found while emitting PTX");
1605 NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
1606 switch (Ty->getTypeID()) {
1608 llvm_unreachable("unexpected type");
1610 case Type::IntegerTyID: {
1611 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1614 else if (NumBits <= 64) {
1615 std::string name = "u";
1616 return name + utostr(NumBits);
1618 llvm_unreachable("Integer too large");
1623 case Type::FloatTyID:
1625 case Type::DoubleTyID:
1627 case Type::PointerTyID:
1628 if (nvptxSubtarget.is64Bit())
1638 llvm_unreachable("unexpected type");
1642 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1645 const DataLayout *TD = TM.getDataLayout();
1647 // GlobalVariables are always constant pointers themselves.
1648 const PointerType *PTy = GVar->getType();
1649 Type *ETy = PTy->getElementType();
1652 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1653 if (GVar->getAlignment() == 0)
1654 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1656 O << " .align " << GVar->getAlignment();
1658 if (ETy->isSingleValueType()) {
1660 O << getPTXFundamentalTypeStr(ETy);
1662 O << *getSymbol(GVar);
1666 int64_t ElementSize = 0;
1668 // Although PTX has direct support for struct type and array type and LLVM IR
1669 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1670 // support these high level field accesses. Structs and arrays are lowered
1671 // into arrays of bytes.
1672 switch (ETy->getTypeID()) {
1673 case Type::StructTyID:
1674 case Type::ArrayTyID:
1675 case Type::VectorTyID:
1676 ElementSize = TD->getTypeStoreSize(ETy);
1677 O << " .b8 " << *getSymbol(GVar) << "[";
1679 O << itostr(ElementSize);
1684 llvm_unreachable("type not supported yet");
1689 static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
1690 if (Ty->isSingleValueType())
1691 return TD->getPrefTypeAlignment(Ty);
1693 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1695 return getOpenCLAlignment(TD, ATy->getElementType());
1697 const VectorType *VTy = dyn_cast<VectorType>(Ty);
1699 Type *ETy = VTy->getElementType();
1700 unsigned int numE = VTy->getNumElements();
1701 unsigned int alignE = TD->getPrefTypeAlignment(ETy);
1705 return numE * alignE;
1708 const StructType *STy = dyn_cast<StructType>(Ty);
1710 unsigned int alignStruct = 1;
1711 // Go through each element of the struct and find the
1712 // largest alignment.
1713 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1714 Type *ETy = STy->getElementType(i);
1715 unsigned int align = getOpenCLAlignment(TD, ETy);
1716 if (align > alignStruct)
1717 alignStruct = align;
1722 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1724 return TD->getPointerPrefAlignment();
1725 return TD->getPrefTypeAlignment(Ty);
1728 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1729 int paramIndex, raw_ostream &O) {
1730 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1731 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
1732 O << *getSymbol(I->getParent()) << "_param_" << paramIndex;
1734 std::string argName = I->getName();
1735 const char *p = argName.c_str();
1746 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1747 Function::const_arg_iterator I, E;
1750 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1751 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1752 O << *CurrentFnSym << "_param_" << paramIndex;
1756 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
1757 if (i == paramIndex) {
1758 printParamName(I, paramIndex, O);
1762 llvm_unreachable("paramIndex out of bound");
1765 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1766 const DataLayout *TD = TM.getDataLayout();
1767 const AttributeSet &PAL = F->getAttributes();
1768 const TargetLowering *TLI = TM.getTargetLowering();
1769 Function::const_arg_iterator I, E;
1770 unsigned paramIndex = 0;
1772 bool isKernelFunc = llvm::isKernelFunction(*F);
1773 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1774 MVT thePointerTy = TLI->getPointerTy();
1778 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1779 Type *Ty = I->getType();
1786 // Handle image/sampler parameters
1787 if (isKernelFunction(*F)) {
1788 if (isSampler(*I) || isImage(*I)) {
1790 std::string sname = I->getName();
1791 if (isImageWriteOnly(*I) || isImageReadWrite(*I)) {
1792 if (nvptxSubtarget.hasImageHandles())
1793 O << "\t.param .u64 .ptr .surfref ";
1795 O << "\t.param .surfref ";
1796 O << *CurrentFnSym << "_param_" << paramIndex;
1798 else { // Default image is read_only
1799 if (nvptxSubtarget.hasImageHandles())
1800 O << "\t.param .u64 .ptr .texref ";
1802 O << "\t.param .texref ";
1803 O << *CurrentFnSym << "_param_" << paramIndex;
1806 if (nvptxSubtarget.hasImageHandles())
1807 O << "\t.param .u64 .ptr .samplerref ";
1809 O << "\t.param .samplerref ";
1810 O << *CurrentFnSym << "_param_" << paramIndex;
1816 if (PAL.hasAttribute(paramIndex + 1, Attribute::ByVal) == false) {
1817 if (Ty->isAggregateType() || Ty->isVectorTy()) {
1818 // Just print .param .align <a> .b8 .param[size];
1819 // <a> = PAL.getparamalignment
1820 // size = typeallocsize of element type
1821 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1823 align = TD->getABITypeAlignment(Ty);
1825 unsigned sz = TD->getTypeAllocSize(Ty);
1826 O << "\t.param .align " << align << " .b8 ";
1827 printParamName(I, paramIndex, O);
1828 O << "[" << sz << "]";
1833 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1836 // Special handling for pointer arguments to kernel
1837 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1839 if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
1840 Type *ETy = PTy->getElementType();
1841 int addrSpace = PTy->getAddressSpace();
1842 switch (addrSpace) {
1846 case llvm::ADDRESS_SPACE_CONST:
1847 O << ".ptr .const ";
1849 case llvm::ADDRESS_SPACE_SHARED:
1850 O << ".ptr .shared ";
1852 case llvm::ADDRESS_SPACE_GLOBAL:
1853 O << ".ptr .global ";
1856 O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
1858 printParamName(I, paramIndex, O);
1862 // non-pointer scalar to kernel func
1864 // Special case: predicate operands become .u8 types
1865 if (Ty->isIntegerTy(1))
1868 O << getPTXFundamentalTypeStr(Ty);
1870 printParamName(I, paramIndex, O);
1873 // Non-kernel function, just print .param .b<size> for ABI
1874 // and .reg .b<size> for non-ABI
1876 if (isa<IntegerType>(Ty)) {
1877 sz = cast<IntegerType>(Ty)->getBitWidth();
1880 } else if (isa<PointerType>(Ty))
1881 sz = thePointerTy.getSizeInBits();
1883 sz = Ty->getPrimitiveSizeInBits();
1885 O << "\t.param .b" << sz << " ";
1887 O << "\t.reg .b" << sz << " ";
1888 printParamName(I, paramIndex, O);
1892 // param has byVal attribute. So should be a pointer
1893 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1894 assert(PTy && "Param with byval attribute should be a pointer type");
1895 Type *ETy = PTy->getElementType();
1897 if (isABI || isKernelFunc) {
1898 // Just print .param .align <a> .b8 .param[size];
1899 // <a> = PAL.getparamalignment
1900 // size = typeallocsize of element type
1901 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1903 align = TD->getABITypeAlignment(ETy);
1905 unsigned sz = TD->getTypeAllocSize(ETy);
1906 O << "\t.param .align " << align << " .b8 ";
1907 printParamName(I, paramIndex, O);
1908 O << "[" << sz << "]";
1911 // Split the ETy into constituent parts and
1912 // print .param .b<size> <name> for each part.
1913 // Further, if a part is vector, print the above for
1914 // each vector element.
1915 SmallVector<EVT, 16> vtparts;
1916 ComputeValueVTs(*TLI, ETy, vtparts);
1917 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
1919 EVT elemtype = vtparts[i];
1920 if (vtparts[i].isVector()) {
1921 elems = vtparts[i].getVectorNumElements();
1922 elemtype = vtparts[i].getVectorElementType();
1925 for (unsigned j = 0, je = elems; j != je; ++j) {
1926 unsigned sz = elemtype.getSizeInBits();
1927 if (elemtype.isInteger() && (sz < 32))
1929 O << "\t.reg .b" << sz << " ";
1930 printParamName(I, paramIndex, O);
1946 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1948 const Function *F = MF.getFunction();
1949 emitFunctionParamList(F, O);
1952 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1953 const MachineFunction &MF) {
1954 SmallString<128> Str;
1955 raw_svector_ostream O(Str);
1957 // Map the global virtual register number to a register class specific
1958 // virtual register number starting from 1 with that class.
1959 const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
1960 //unsigned numRegClasses = TRI->getNumRegClasses();
1962 // Emit the Fake Stack Object
1963 const MachineFrameInfo *MFI = MF.getFrameInfo();
1964 int NumBytes = (int) MFI->getStackSize();
1966 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1967 << getFunctionNumber() << "[" << NumBytes << "];\n";
1968 if (nvptxSubtarget.is64Bit()) {
1969 O << "\t.reg .b64 \t%SP;\n";
1970 O << "\t.reg .b64 \t%SPL;\n";
1972 O << "\t.reg .b32 \t%SP;\n";
1973 O << "\t.reg .b32 \t%SPL;\n";
1977 // Go through all virtual registers to establish the mapping between the
1979 // register number and the per class virtual register number.
1980 // We use the per class virtual register number in the ptx output.
1981 unsigned int numVRs = MRI->getNumVirtRegs();
1982 for (unsigned i = 0; i < numVRs; i++) {
1983 unsigned int vr = TRI->index2VirtReg(i);
1984 const TargetRegisterClass *RC = MRI->getRegClass(vr);
1985 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1986 int n = regmap.size();
1987 regmap.insert(std::make_pair(vr, n + 1));
1990 // Emit register declarations
1991 // @TODO: Extract out the real register usage
1992 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1993 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1994 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1995 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1996 // O << "\t.reg .s64 %rl<" << NVPTXNumRegisters << ">;\n";
1997 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1998 // O << "\t.reg .f64 %fl<" << NVPTXNumRegisters << ">;\n";
2000 // Emit declaration of the virtual registers or 'physical' registers for
2001 // each register class
2002 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
2003 const TargetRegisterClass *RC = TRI->getRegClass(i);
2004 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
2005 std::string rcname = getNVPTXRegClassName(RC);
2006 std::string rcStr = getNVPTXRegClassStr(RC);
2007 int n = regmap.size();
2009 // Only declare those registers that may be used.
2011 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
2016 OutStreamer.EmitRawText(O.str());
2019 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
2020 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
2022 unsigned int numHex;
2025 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
2028 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
2029 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
2032 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
2034 llvm_unreachable("unsupported fp type");
2036 APInt API = APF.bitcastToAPInt();
2037 std::string hexstr(utohexstr(API.getZExtValue()));
2039 if (hexstr.length() < numHex)
2040 O << std::string(numHex - hexstr.length(), '0');
2041 O << utohexstr(API.getZExtValue());
2044 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
2045 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
2046 O << CI->getValue();
2049 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
2050 printFPConstant(CFP, O);
2053 if (isa<ConstantPointerNull>(CPV)) {
2057 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
2058 PointerType *PTy = dyn_cast<PointerType>(GVar->getType());
2059 bool IsNonGenericPointer = false;
2060 if (PTy && PTy->getAddressSpace() != 0) {
2061 IsNonGenericPointer = true;
2063 if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
2065 O << *getSymbol(GVar);
2068 O << *getSymbol(GVar);
2072 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
2073 const Value *v = Cexpr->stripPointerCasts();
2074 PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
2075 bool IsNonGenericPointer = false;
2076 if (PTy && PTy->getAddressSpace() != 0) {
2077 IsNonGenericPointer = true;
2079 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
2080 if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
2082 O << *getSymbol(GVar);
2085 O << *getSymbol(GVar);
2089 O << *LowerConstant(CPV, *this);
2093 llvm_unreachable("Not scalar type found in printScalarConstant()");
2096 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
2097 AggBuffer *aggBuffer) {
2099 const DataLayout *TD = TM.getDataLayout();
2101 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
2102 int s = TD->getTypeAllocSize(CPV->getType());
2105 aggBuffer->addZeros(s);
2110 switch (CPV->getType()->getTypeID()) {
2112 case Type::IntegerTyID: {
2113 const Type *ETy = CPV->getType();
2114 if (ETy == Type::getInt8Ty(CPV->getContext())) {
2116 (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
2118 aggBuffer->addBytes(ptr, 1, Bytes);
2119 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
2120 short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
2121 ptr = (unsigned char *)&int16;
2122 aggBuffer->addBytes(ptr, 2, Bytes);
2123 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
2124 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
2125 int int32 = (int)(constInt->getZExtValue());
2126 ptr = (unsigned char *)&int32;
2127 aggBuffer->addBytes(ptr, 4, Bytes);
2129 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
2130 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
2131 ConstantFoldConstantExpression(Cexpr, TD))) {
2132 int int32 = (int)(constInt->getZExtValue());
2133 ptr = (unsigned char *)&int32;
2134 aggBuffer->addBytes(ptr, 4, Bytes);
2137 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
2138 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
2139 aggBuffer->addSymbol(v);
2140 aggBuffer->addZeros(4);
2144 llvm_unreachable("unsupported integer const type");
2145 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
2146 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
2147 long long int64 = (long long)(constInt->getZExtValue());
2148 ptr = (unsigned char *)&int64;
2149 aggBuffer->addBytes(ptr, 8, Bytes);
2151 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
2152 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
2153 ConstantFoldConstantExpression(Cexpr, TD))) {
2154 long long int64 = (long long)(constInt->getZExtValue());
2155 ptr = (unsigned char *)&int64;
2156 aggBuffer->addBytes(ptr, 8, Bytes);
2159 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
2160 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
2161 aggBuffer->addSymbol(v);
2162 aggBuffer->addZeros(8);
2166 llvm_unreachable("unsupported integer const type");
2168 llvm_unreachable("unsupported integer const type");
2171 case Type::FloatTyID:
2172 case Type::DoubleTyID: {
2173 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
2174 const Type *Ty = CFP->getType();
2175 if (Ty == Type::getFloatTy(CPV->getContext())) {
2176 float float32 = (float) CFP->getValueAPF().convertToFloat();
2177 ptr = (unsigned char *)&float32;
2178 aggBuffer->addBytes(ptr, 4, Bytes);
2179 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
2180 double float64 = CFP->getValueAPF().convertToDouble();
2181 ptr = (unsigned char *)&float64;
2182 aggBuffer->addBytes(ptr, 8, Bytes);
2184 llvm_unreachable("unsupported fp const type");
2188 case Type::PointerTyID: {
2189 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
2190 aggBuffer->addSymbol(GVar);
2191 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
2192 const Value *v = Cexpr->stripPointerCasts();
2193 aggBuffer->addSymbol(v);
2195 unsigned int s = TD->getTypeAllocSize(CPV->getType());
2196 aggBuffer->addZeros(s);
2200 case Type::ArrayTyID:
2201 case Type::VectorTyID:
2202 case Type::StructTyID: {
2203 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
2204 isa<ConstantStruct>(CPV) || isa<ConstantDataSequential>(CPV)) {
2205 int ElementSize = TD->getTypeAllocSize(CPV->getType());
2206 bufferAggregateConstant(CPV, aggBuffer);
2207 if (Bytes > ElementSize)
2208 aggBuffer->addZeros(Bytes - ElementSize);
2209 } else if (isa<ConstantAggregateZero>(CPV))
2210 aggBuffer->addZeros(Bytes);
2212 llvm_unreachable("Unexpected Constant type");
2217 llvm_unreachable("unsupported type");
2221 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
2222 AggBuffer *aggBuffer) {
2223 const DataLayout *TD = TM.getDataLayout();
2227 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
2228 if (CPV->getNumOperands())
2229 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
2230 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
2234 if (const ConstantDataSequential *CDS =
2235 dyn_cast<ConstantDataSequential>(CPV)) {
2236 if (CDS->getNumElements())
2237 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
2238 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
2243 if (isa<ConstantStruct>(CPV)) {
2244 if (CPV->getNumOperands()) {
2245 StructType *ST = cast<StructType>(CPV->getType());
2246 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
2248 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
2249 TD->getTypeAllocSize(ST) -
2250 TD->getStructLayout(ST)->getElementOffset(i);
2252 Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
2253 TD->getStructLayout(ST)->getElementOffset(i);
2254 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
2259 llvm_unreachable("unsupported constant type in printAggregateConstant()");
2262 // buildTypeNameMap - Run through symbol table looking for type names.
2265 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
2267 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
2269 if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
2270 !PI->second.compare("struct._image2d_t") ||
2271 !PI->second.compare("struct._image3d_t")))
2278 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
2279 switch (MI.getOpcode()) {
2282 case NVPTX::CallArgBeginInst:
2283 case NVPTX::CallArgEndInst0:
2284 case NVPTX::CallArgEndInst1:
2285 case NVPTX::CallArgF32:
2286 case NVPTX::CallArgF64:
2287 case NVPTX::CallArgI16:
2288 case NVPTX::CallArgI32:
2289 case NVPTX::CallArgI32imm:
2290 case NVPTX::CallArgI64:
2291 case NVPTX::CallArgParam:
2292 case NVPTX::CallVoidInst:
2293 case NVPTX::CallVoidInstReg:
2294 case NVPTX::Callseq_End:
2295 case NVPTX::CallVoidInstReg64:
2296 case NVPTX::DeclareParamInst:
2297 case NVPTX::DeclareRetMemInst:
2298 case NVPTX::DeclareRetRegInst:
2299 case NVPTX::DeclareRetScalarInst:
2300 case NVPTX::DeclareScalarParamInst:
2301 case NVPTX::DeclareScalarRegInst:
2302 case NVPTX::StoreParamF32:
2303 case NVPTX::StoreParamF64:
2304 case NVPTX::StoreParamI16:
2305 case NVPTX::StoreParamI32:
2306 case NVPTX::StoreParamI64:
2307 case NVPTX::StoreParamI8:
2308 case NVPTX::StoreRetvalF32:
2309 case NVPTX::StoreRetvalF64:
2310 case NVPTX::StoreRetvalI16:
2311 case NVPTX::StoreRetvalI32:
2312 case NVPTX::StoreRetvalI64:
2313 case NVPTX::StoreRetvalI8:
2314 case NVPTX::LastCallArgF32:
2315 case NVPTX::LastCallArgF64:
2316 case NVPTX::LastCallArgI16:
2317 case NVPTX::LastCallArgI32:
2318 case NVPTX::LastCallArgI32imm:
2319 case NVPTX::LastCallArgI64:
2320 case NVPTX::LastCallArgParam:
2321 case NVPTX::LoadParamMemF32:
2322 case NVPTX::LoadParamMemF64:
2323 case NVPTX::LoadParamMemI16:
2324 case NVPTX::LoadParamMemI32:
2325 case NVPTX::LoadParamMemI64:
2326 case NVPTX::LoadParamMemI8:
2327 case NVPTX::PrototypeInst:
2328 case NVPTX::DBG_VALUE:
2334 /// PrintAsmOperand - Print out an operand for an inline asm expression.
2336 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2337 unsigned AsmVariant,
2338 const char *ExtraCode, raw_ostream &O) {
2339 if (ExtraCode && ExtraCode[0]) {
2340 if (ExtraCode[1] != 0)
2341 return true; // Unknown modifier.
2343 switch (ExtraCode[0]) {
2345 // See if this is a generic print operand
2346 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2352 printOperand(MI, OpNo, O);
2357 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2358 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2359 const char *ExtraCode, raw_ostream &O) {
2360 if (ExtraCode && ExtraCode[0])
2361 return true; // Unknown modifier
2364 printMemOperand(MI, OpNo, O);
2370 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2371 raw_ostream &O, const char *Modifier) {
2372 const MachineOperand &MO = MI->getOperand(opNum);
2373 switch (MO.getType()) {
2374 case MachineOperand::MO_Register:
2375 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2376 if (MO.getReg() == NVPTX::VRDepot)
2377 O << DEPOTNAME << getFunctionNumber();
2379 O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2381 emitVirtualRegister(MO.getReg(), O);
2385 case MachineOperand::MO_Immediate:
2388 else if (strstr(Modifier, "vec") == Modifier)
2389 printVecModifiedImmediate(MO, Modifier, O);
2392 "Don't know how to handle modifier on immediate operand");
2395 case MachineOperand::MO_FPImmediate:
2396 printFPConstant(MO.getFPImm(), O);
2399 case MachineOperand::MO_GlobalAddress:
2400 O << *getSymbol(MO.getGlobal());
2403 case MachineOperand::MO_MachineBasicBlock:
2404 O << *MO.getMBB()->getSymbol();
2408 llvm_unreachable("Operand type not supported.");
2412 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2413 raw_ostream &O, const char *Modifier) {
2414 printOperand(MI, opNum, O);
2416 if (Modifier && !strcmp(Modifier, "add")) {
2418 printOperand(MI, opNum + 1, O);
2420 if (MI->getOperand(opNum + 1).isImm() &&
2421 MI->getOperand(opNum + 1).getImm() == 0)
2422 return; // don't print ',0' or '+0'
2424 printOperand(MI, opNum + 1, O);
2429 // Force static initialization.
2430 extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2431 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2432 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2435 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2436 std::stringstream temp;
2437 LineReader *reader = this->getReader(filename.str());
2439 temp << filename.str();
2443 temp << reader->readLine(line);
2445 this->OutStreamer.EmitRawText(Twine(temp.str()));
2448 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2450 reader = new LineReader(filename);
2453 if (reader->fileName() != filename) {
2455 reader = new LineReader(filename);
2461 std::string LineReader::readLine(unsigned lineNum) {
2462 if (lineNum < theCurLine) {
2464 fstr.seekg(0, std::ios::beg);
2466 while (theCurLine < lineNum) {
2467 fstr.getline(buff, 500);
2473 // Force static initialization.
2474 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2475 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2476 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);