helper.cpp 45.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
/*===================== begin_copyright_notice ==================================

Copyright (c) 2017 Intel Corporation

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


======================= end_copyright_notice ==================================*/

#include "Compiler/CISACodeGen/helper.h"
#include "Compiler/CISACodeGen/CISACodeGen.h"
#include "Compiler/Optimizer/OpenCLPasses/KernelArgs.hpp"
#include "Compiler/MetaDataUtilsWrapper.h"

#include "common/LLVMWarningsPush.hpp"
#include <llvm/IR/GetElementPtrTypeIterator.h>
#include <llvm/Analysis/ValueTracking.h>

#include <llvmWrapper/Support/KnownBits.h>
#include <llvmWrapper/IR/Instructions.h>

#include "common/LLVMWarningsPop.hpp"

#include "GenISAIntrinsics/GenIntrinsicInst.h"
#include "Compiler/CISACodeGen/ShaderCodeGen.hpp"

#include "common/secure_mem.h"

#include <stack>

using namespace llvm;
using namespace GenISAIntrinsic;

/************************************************************************
This file contains helper functions for the code generator
Many functions use X-MACRO, that allow us to separate data about encoding
to the logic of the helper functions

************************************************************************/

namespace IGC
{
typedef union _gfxResourceAddrSpace
{
    struct _bits
    {
        unsigned int       bufId                 : 16;
        unsigned int       bufType               : 4;
        unsigned int       indirect              : 1;     // bool
        unsigned int       reserved              : 11;
    } bits;
    uint32_t u32Val;
} GFXResourceAddrSpace;

unsigned EncodeAS4GFXResource(
    const llvm::Value& bufIdx,
    BufferType bufType,
    unsigned uniqueIndAS)
{
    GFXResourceAddrSpace temp;
    temp.u32Val = 0;
    assert( (bufType+1) < 16 );
    temp.bits.bufType = bufType + 1;
    if (bufType == SLM)
    {
        return ADDRESS_SPACE_LOCAL; // We use addrspace 3 for SLM
    }
    else if (bufType == STATELESS_READONLY)
    {
        return ADDRESS_SPACE_CONSTANT; 
    }
    else if (bufType == STATELESS)
    {
        return ADDRESS_SPACE_GLOBAL;
    }
    else if (llvm::isa<llvm::ConstantInt>(&bufIdx))
    {
        unsigned int bufId = (unsigned int)(llvm::cast<llvm::ConstantInt>(&bufIdx)->getZExtValue());
        assert( bufId < (1 << 31) );
        temp.bits.bufId = bufId;
        return temp.u32Val;
    }

    // if it is indirect-buf, it is front-end's job to give a proper(unique) address-space per access
    temp.bits.bufId = uniqueIndAS;
    temp.bits.indirect = 1;
    return temp.u32Val;
}

unsigned SetBufferAsBindless(unsigned addressSpaceOfPtr, BufferType bufferType)
{
    GFXResourceAddrSpace temp = {};
    temp.u32Val = addressSpaceOfPtr;

    // Mark buffer as it is bindless for further processing
    if (bufferType == BufferType::RESOURCE ||
        bufferType == BufferType::CONSTANT_BUFFER ||
        bufferType == BufferType::UAV)
    {
        temp.bits.bufType = IGC::BINDLESS + 1;
    }
    else if (bufferType == BufferType::SAMPLER)
    {
        temp.bits.bufType = IGC::BINDLESS_SAMPLER + 1;
    }
    else
    {
        // other types of buffers shouldn't reach this part.
        assert(0);
    }

    return temp.u32Val;
}

bool UsesTypedConstantBuffer(CodeGenContext* pContext)
{
    if(pContext->m_DriverInfo.UsesTypedConstantBuffers3D() &&
        pContext->type != ShaderType::COMPUTE_SHADER)
    {
        return true;
    }
    if(pContext->m_DriverInfo.UsesTypedConstantBuffersGPGPU() &&
        pContext->type == ShaderType::COMPUTE_SHADER)
    {
        return true;
    }
    return false;
}

///
/// if you want resource-dimension, use GetBufferDimension()
///
BufferType DecodeAS4GFXResource(unsigned addrSpace, bool& directIndexing, unsigned& bufId)
{
    GFXResourceAddrSpace temp;
    temp.u32Val = addrSpace;

    directIndexing = (temp.bits.indirect == 0);
    bufId = temp.bits.bufId;

    if(addrSpace == ADDRESS_SPACE_LOCAL)
    {
        return SLM;
    }
    unsigned bufType = temp.bits.bufType - 1;
    if (bufType < BUFFER_TYPE_UNKNOWN)
    {
        return (BufferType)bufType;
    }
    return BUFFER_TYPE_UNKNOWN;
}
///
/// returns constant buffer load offset
///
int getConstantBufferLoadOffset(llvm::LoadInst *ld)
{
    int offset = 0;
    Value* ptr = ld->getPointerOperand();
    if (isa<ConstantPointerNull>(ptr))
    {
        offset = 0;
    }
    else if (IntToPtrInst* itop = dyn_cast<IntToPtrInst>(ptr))
    {
        ConstantInt* ci = dyn_cast<ConstantInt>(
            itop->getOperand(0));
        if (ci)
        {
            offset = int_cast<unsigned>(ci->getZExtValue());
        }
    }
    else if (ConstantExpr* itop = dyn_cast<ConstantExpr>(ptr))
    {
        if (itop->getOpcode() == Instruction::IntToPtr)
        {
            offset = int_cast<unsigned>(
                cast<ConstantInt>(itop->getOperand(0))->getZExtValue());
        }
    }
    return offset;
}
///
/// returns info if direct addressing is used
///
bool IsDirectIdx(unsigned addrSpace)
{
    GFXResourceAddrSpace temp;
    temp.u32Val = addrSpace;
    return (temp.bits.indirect == 0);
}

llvm::LoadInst* cloneLoad(llvm::LoadInst *Orig, llvm::Value *Ptr)
{
    llvm::LoadInst *LI = new llvm::LoadInst(Ptr, "", Orig);
    LI->setVolatile(Orig->isVolatile());
    LI->setAlignment(Orig->getAlignment());
    if (LI->isAtomic())
    {
        LI->setAtomic(Orig->getOrdering(), IGCLLVM::getSyncScopeID(Orig));
    }
    // Clone metadata
    llvm::SmallVector<std::pair<unsigned, llvm::MDNode *>, 4> MDs;
    Orig->getAllMetadata(MDs);
    for (llvm::SmallVectorImpl<std::pair<unsigned, llvm::MDNode *> >::iterator
         MI = MDs.begin(), ME = MDs.end(); MI != ME; ++MI)
    {
        LI->setMetadata(MI->first, MI->second);
    }
    return LI;
}

llvm::StoreInst* cloneStore(llvm::StoreInst *Orig, llvm::Value *Val, llvm::Value *Ptr)
{
    llvm::StoreInst *SI = new llvm::StoreInst(Val, Ptr, Orig);
    SI->setVolatile(Orig->isVolatile());
    SI->setAlignment(Orig->getAlignment());
    if (SI->isAtomic())
    {
        SI->setAtomic(Orig->getOrdering(), IGCLLVM::getSyncScopeID(Orig));
    }
    // Clone metadata
    llvm::SmallVector<std::pair<unsigned, llvm::MDNode *>, 4> MDs;
    Orig->getAllMetadata(MDs);
    for (llvm::SmallVectorImpl<std::pair<unsigned, llvm::MDNode *> >::iterator
         MI = MDs.begin(), ME = MDs.end(); MI != ME; ++MI)
    {
        SI->setMetadata(MI->first, MI->second);
    }
    return SI;
}

// Create a ldraw from a load instruction
Value* CreateLoadRawIntrinsic(LoadInst *inst, Instruction* bufPtr, Value *offsetVal)
{
	Module* module = inst->getParent()->getParent()->getParent();
    Function* func = nullptr;
    IRBuilder<> builder(inst);

    llvm::Type* tys[2];
    tys[0] = inst->getType();
    tys[1] = bufPtr->getType();
    func = GenISAIntrinsic::getDeclaration(module, inst->getType()->isVectorTy() ? llvm::GenISAIntrinsic::GenISA_ldrawvector_indexed : llvm::GenISAIntrinsic::GenISA_ldraw_indexed, tys);

	unsigned alignment = (inst->getType()->getScalarSizeInBits() / 8);
	if (inst->getAlignment() > 0)
	{
		alignment = inst->getAlignment();
	}

	Value* attr[] =
	{
		bufPtr,
		offsetVal,
		builder.getInt32(alignment)
	};
	Value* ld = builder.CreateCall(func, attr);
	assert(ld->getType() == inst->getType());
	return ld;
}

// Creates a storeraw from a store instruction
Value* CreateStoreRawIntrinsic(StoreInst *inst, Instruction* bufPtr, Value* offsetVal)
{
	Module* module = inst->getParent()->getParent()->getParent();
	Function* func = nullptr;
	IRBuilder<> builder(inst);
	Value *storeVal = inst->getValueOperand();
	if (storeVal->getType()->isVectorTy())
	{
		llvm::Type* tys[2];
		tys[0] = bufPtr->getType();
		tys[1] = inst->getValueOperand()->getType();
		func = GenISAIntrinsic::getDeclaration(module, llvm::GenISAIntrinsic::GenISA_storerawvector_indexed, tys);
	}
	else
	{
		llvm::Type* dataType = storeVal->getType();
		assert(dataType->getPrimitiveSizeInBits() == 16 || dataType->getPrimitiveSizeInBits() == 32);

		llvm::Type* types[2] = {
			bufPtr->getType(),
			storeVal->getType() };

		func = GenISAIntrinsic::getDeclaration(module, llvm::GenISAIntrinsic::GenISA_storeraw_indexed, types);
	}
	Value* attr[] =
	{
		bufPtr,
		offsetVal,
		storeVal
	};
	Value* st = builder.CreateCall(func, attr);
	return st;
}

///
/// Tries to trace a resource pointer (texture/sampler/buffer) back to
/// the pointer source. Also returns a vector of all instructions in the search path
///
Value* TracePointerSource(Value* resourcePtr, bool hasBranching, bool fillList, 
    std::vector<Value*> &instList, llvm::SmallSet<PHINode*, 8>& visitedPHIs)
{
    Value* srcPtr = nullptr;
    Value* baseValue = resourcePtr;

    while (true)
    {
        if (fillList)
        {
            instList.push_back(baseValue);
        }

        unsigned bufId = 0;
        IGC::BufferType bufTy = BUFFER_TYPE_UNKNOWN;
        IGC::BufferAccessType accessTy = BUFFER_ACCESS_TYPE_UNKNOWN;
        if (GetResourcePointerInfo(baseValue, bufId, bufTy, accessTy))
        {
            srcPtr = baseValue;
            break;
        }
        else if (isa<Argument>(baseValue))
        {
            // For compute, resource comes from the kernel args
            srcPtr = baseValue;
            break;
        }
344 345 346 347 348 349 350 351 352
        else if (auto allocaInst = dyn_cast<AllocaInst>(baseValue))
        {
            if (auto md = allocaInst->getMetadata("igc.read_only_array"))
            {
                // Found alloca marked as read_only array.
                srcPtr = baseValue;
            }
            break;
        }
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
        else if (CastInst* inst = dyn_cast<CastInst>(baseValue))
        {
            baseValue = inst->getOperand(0);
        }
        else if (GetElementPtrInst* inst = dyn_cast<GetElementPtrInst>(baseValue))
        {
            baseValue = inst->getOperand(0);
        }
        else if (PHINode* inst = dyn_cast<PHINode>(baseValue))
        {
            if (visitedPHIs.count(inst) != 0)
            { 
                // stop if we've seen this phi node before
				return baseValue;
            }
            visitedPHIs.insert(inst);
            for(unsigned int i = 0; i < inst->getNumIncomingValues(); ++i)
            {
                // All phi paths must be trace-able and trace back to the same source
                Value* phiVal = inst->getIncomingValue(i);
				std::vector<Value*> splitList;
                Value* phiSrcPtr = TracePointerSource(phiVal, true, fillList, splitList, visitedPHIs);
                if (phiSrcPtr == nullptr)
                {
					// Incoming value not trace-able, bail out.
                    return nullptr;
                }
				else if (isa<PHINode>(phiSrcPtr) && phiSrcPtr == baseValue)
				{
					// Found a loop in one of the phi paths. We can still trace as long as all the other paths match
					continue;
				}
				else if (srcPtr == nullptr)
				{
					// Found a path to the source pointer. We only save the instructions used in this path
					srcPtr = phiSrcPtr;
					instList.insert(instList.end(), splitList.begin(), splitList.end());
				}
                else if (srcPtr != phiSrcPtr)
                {
					// The source pointers have diverged. Bail out.
                    return nullptr;
                }
            }
            break;
        }
        else if (SelectInst *inst = dyn_cast<SelectInst>(baseValue))
        {
            if (hasBranching)
            {
                // only allow a single branching instruction to be supported for now
                // if both select and PHI are present, or there are multiples of each, we bail
                break;
            }
            // Trace both operands of the select instruction. Both have to be traced back to the same
            // source pointer, otherwise we can't determine which one to use.
            Value* selectSrc0 = TracePointerSource(inst->getOperand(1), true, fillList, instList, visitedPHIs);
            Value* selectSrc1 = TracePointerSource(inst->getOperand(2), true, false, instList, visitedPHIs);
            if (selectSrc0 && selectSrc1 && selectSrc0 == selectSrc1)
            {
                srcPtr = selectSrc0;
                break;
            }
            return nullptr;
        }
418 419 420 421 422 423 424 425 426 427 428 429
        else if(LoadInst *inst = dyn_cast<LoadInst>(baseValue)) 
        {
            if (inst->getPointerAddressSpace() == 0)
            {
                // May be local array of resources:
                baseValue = inst->getPointerOperand();
            }
            else
            {
                break;
            }
        }
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
        else
        {
            // Unsupported instruction in search chain. Don't continue.
            break;
        }
    }
    return srcPtr;
}

///
/// Only trace the GetBufferPtr instruction (ignore GetElementPtr)
///
Value* TracePointerSource(Value* resourcePtr)
{
    std::vector<Value*> tempList; //unused
    llvm::SmallSet<PHINode*, 8> visitedPHIs;
    return TracePointerSource(resourcePtr, false, false, tempList, visitedPHIs);
}

Value* TracePointerSource(Value* resourcePtr, bool hasBranching, bool fillList, std::vector<Value*> &instList)
{
    llvm::SmallSet<PHINode*, 8> visitedPHIs;
    return TracePointerSource(resourcePtr, hasBranching, fillList, instList, visitedPHIs);
}

static BufferAccessType getDefaultAccessType(BufferType bufTy)
{
    switch (bufTy)
    {
    case BufferType::CONSTANT_BUFFER:
    case BufferType::RESOURCE:
    case BufferType::BINDLESS_READONLY:
    case BufferType::STATELESS_READONLY:
    case BufferType::SAMPLER:
        return BufferAccessType::ACCESS_READ;

    case BufferType::UAV:
    case BufferType::SLM:
    case BufferType::POINTER:
    case BufferType::BINDLESS:
    case BufferType::STATELESS:
        return BufferAccessType::ACCESS_READWRITE;

    case BufferType::RENDER_TARGET:
        return BufferAccessType::ACCESS_WRITE;

    default:
        assert(false && "Invalid buffer type");
        return BufferAccessType::ACCESS_READWRITE;
    }
}

bool GetResourcePointerInfo(Value* srcPtr, unsigned &resID, IGC::BufferType &resTy, BufferAccessType& accessTy)
{
    accessTy = BufferAccessType::ACCESS_READWRITE;
	if (GenIntrinsicInst* inst = dyn_cast<GenIntrinsicInst>(srcPtr))
    {
        // For bindless pointers with encoded metadata
        if(inst->getIntrinsicID() == GenISAIntrinsic::GenISA_RuntimeValue)
        {
            if (inst->hasOperandBundles())
            {
                auto resIDBundle = inst->getOperandBundle("resID");
                auto resTyBundle = inst->getOperandBundle("resTy");
                auto accessTyBundle = inst->getOperandBundle("accessTy");
                if (resIDBundle && resTyBundle)
                {
                    resID = (unsigned) (cast<ConstantInt>(resIDBundle->Inputs.front()))->getZExtValue();
                    resTy = (BufferType) (cast<ConstantInt>(resTyBundle->Inputs.front()))->getZExtValue();

                    if (accessTyBundle)
                        accessTy = (BufferAccessType) (cast<ConstantInt>(accessTyBundle->Inputs.front()))->getZExtValue();
                    else
                        accessTy = getDefaultAccessType(resTy);
                    return true;
                }
            }
        }
		// For GetBufferPtr instructions with buffer info in the operands
        else if(inst->getIntrinsicID() == GenISAIntrinsic::GenISA_GetBufferPtr)
		{
            Value *bufIdV = inst->getOperand(0);
            Value *bufTyV = inst->getOperand(1);
            if (isa<ConstantInt>(bufIdV) && isa<ConstantInt>(bufTyV))
            {
                resID = (unsigned)(cast<ConstantInt>(bufIdV)->getZExtValue());
                resTy = (IGC::BufferType)(cast<ConstantInt>(bufTyV)->getZExtValue());
				accessTy = getDefaultAccessType(resTy);
                return true;
            }
        }
    }
    return false;
}

///
/// Replaces oldPtr with newPtr in a sample/ld intrinsic's argument list. The new instrinsic will
/// replace the old one in the module
///
void ChangePtrTypeInIntrinsic(llvm::GenIntrinsicInst *&pIntr, llvm::Value* oldPtr, llvm::Value* newPtr)
{
    llvm::Module *pModule = pIntr->getParent()->getParent()->getParent();
    llvm::Function *pCalledFunc = pIntr->getCalledFunction();

    // Look at the intrinsic and figure out which pointer to change
    int num_ops = pIntr->getNumArgOperands();
    llvm::SmallVector<llvm::Value*, 5> args;

    for(int i = 0; i < num_ops; ++i)
    {
        if(pIntr->getArgOperand(i) == oldPtr)
            args.push_back(newPtr);
        else
            args.push_back(pIntr->getArgOperand(i));
    }

    llvm::Function *pNewIntr = nullptr;
    llvm::SmallVector<llvm::Type*, 4> overloadedTys;
    GenISAIntrinsic::ID id = pIntr->getIntrinsicID();
    switch(id)
    {
        case llvm::GenISAIntrinsic::GenISA_ldmcsptr:
            overloadedTys.push_back(pCalledFunc->getReturnType());
            overloadedTys.push_back(args[0]->getType());
            overloadedTys.push_back(newPtr->getType());
            break;
        case llvm::GenISAIntrinsic::GenISA_ldptr:
        case llvm::GenISAIntrinsic::GenISA_ldmsptr:
            overloadedTys.push_back(pCalledFunc->getReturnType());
            overloadedTys.push_back(newPtr->getType());
            break;
        case llvm::GenISAIntrinsic::GenISA_resinfoptr:
        case llvm::GenISAIntrinsic::GenISA_readsurfaceinfoptr:
        case llvm::GenISAIntrinsic::GenISA_sampleinfoptr:
            overloadedTys.push_back(newPtr->getType());
            break;
        case llvm::GenISAIntrinsic::GenISA_sampleptr:
        case llvm::GenISAIntrinsic::GenISA_sampleBptr:
        case llvm::GenISAIntrinsic::GenISA_sampleCptr:
        case llvm::GenISAIntrinsic::GenISA_sampleDptr:
        case llvm::GenISAIntrinsic::GenISA_sampleLptr:
        case llvm::GenISAIntrinsic::GenISA_sampleBCptr:
        case llvm::GenISAIntrinsic::GenISA_sampleDCptr:
        case llvm::GenISAIntrinsic::GenISA_sampleLCptr:
        case llvm::GenISAIntrinsic::GenISA_gather4ptr:
        case llvm::GenISAIntrinsic::GenISA_gather4POptr:
        case llvm::GenISAIntrinsic::GenISA_gather4Cptr:
        case llvm::GenISAIntrinsic::GenISA_gather4POCptr:
        case llvm::GenISAIntrinsic::GenISA_lodptr:
        {
            // Figure out the intrinsic operands for texture & sampler
            llvm::Value *pTextureValue = nullptr, *pSamplerValue = nullptr;
            getTextureAndSamplerOperands(pIntr, pTextureValue, pSamplerValue);

            overloadedTys.push_back(pCalledFunc->getReturnType());
            overloadedTys.push_back(pIntr->getOperand(0)->getType());

            if(pTextureValue == oldPtr)
            {
                overloadedTys.push_back(newPtr->getType());
                if(pSamplerValue)
                {
                    // Samplerless messages will not have sampler in signature.
                    overloadedTys.push_back(pSamplerValue->getType());
                }
            }
            else if(pSamplerValue == oldPtr)
            {
                overloadedTys.push_back(pTextureValue->getType());
                overloadedTys.push_back(newPtr->getType());
            }

            break;
        }
        case llvm::GenISAIntrinsic::GenISA_typedread:
        case llvm::GenISAIntrinsic::GenISA_typedwrite:
            overloadedTys.push_back(newPtr->getType());
            break;
        case llvm::GenISAIntrinsic::GenISA_intatomicraw:
        case llvm::GenISAIntrinsic::GenISA_icmpxchgatomicraw:
        case GenISAIntrinsic::GenISA_intatomicrawA64:
        case GenISAIntrinsic::GenISA_icmpxchgatomicrawA64:
            overloadedTys.push_back(pIntr->getType());
            overloadedTys.push_back(newPtr->getType());
            if(id == GenISAIntrinsic::GenISA_intatomicrawA64)
            {
                args[0] = args[1];
                args[1] = CastInst::CreatePointerCast(args[1], Type::getInt32Ty(pModule->getContext()), "", pIntr);
                id = GenISAIntrinsic::GenISA_intatomicraw;
            }
            else if(id == GenISAIntrinsic::GenISA_icmpxchgatomicrawA64)
            {
                args[0] = args[1];
                args[1] = CastInst::CreatePointerCast(args[1], Type::getInt32Ty(pModule->getContext()), "", pIntr);
                id = GenISAIntrinsic::GenISA_icmpxchgatomicraw;
            }
            break;
        default:
            assert(0 && "Unknown intrinsic encountered while changing pointer types");
            break;
    }

    pNewIntr = llvm::GenISAIntrinsic::getDeclaration(
                                                     pModule,
                                                     id,
                                                     overloadedTys);

    llvm::CallInst *pNewCall = llvm::CallInst::Create(pNewIntr, args, "", pIntr);

    pIntr->replaceAllUsesWith(pNewCall);
    pIntr->eraseFromParent();

    pIntr = llvm::cast<llvm::GenIntrinsicInst>(pNewCall);
}

///
/// Returns the sampler/texture pointers for resource access intrinsics
///
void getTextureAndSamplerOperands(llvm::GenIntrinsicInst *pIntr, llvm::Value*& pTextureValue, llvm::Value*& pSamplerValue)
{
    if (llvm::SamplerLoadIntrinsic *pSamplerLoadInst = llvm::dyn_cast<llvm::SamplerLoadIntrinsic>(pIntr))
    {
        pTextureValue = pSamplerLoadInst->getTextureValue();
        pSamplerValue = nullptr;
    }
    else if (llvm::SampleIntrinsic *pSampleInst = llvm::dyn_cast<llvm::SampleIntrinsic>(pIntr))
    {
        pTextureValue = pSampleInst->getTextureValue();
        pSamplerValue = pSampleInst->getSamplerValue();
    }
    else if (llvm::SamplerGatherIntrinsic *pGatherInst = llvm::dyn_cast<llvm::SamplerGatherIntrinsic>(pIntr))
    {
        pTextureValue = pGatherInst->getTextureValue();
        pSamplerValue = pGatherInst->getSamplerValue();
    }
    else
    {
        pTextureValue = nullptr;
        pSamplerValue = nullptr;
        switch (pIntr->getIntrinsicID())
        {
            case llvm::GenISAIntrinsic::GenISA_resinfoptr:
            case llvm::GenISAIntrinsic::GenISA_readsurfaceinfoptr:
            case llvm::GenISAIntrinsic::GenISA_sampleinfoptr:
            case llvm::GenISAIntrinsic::GenISA_typedwrite:
            case llvm::GenISAIntrinsic::GenISA_typedread:
                pTextureValue = pIntr->getOperand(0);
                break;
            default:
                break;
        }
    }
}

EOPCODE GetOpCode(const llvm::Instruction* inst)
{
    if(const GenIntrinsicInst *CI = dyn_cast<GenIntrinsicInst>( inst ))
    {
        unsigned ID = CI->getIntrinsicID();
        return (EOPCODE)(OPCODE(ID,e_Intrinsic));
    }
    else if(const IntrinsicInst *CI = llvm::dyn_cast<llvm::IntrinsicInst>( inst ))
    {
        unsigned ID = CI->getIntrinsicID();
        return (EOPCODE)(OPCODE(ID,e_Intrinsic));
    }
    return (EOPCODE)(OPCODE(inst->getOpcode(),e_Instruction));
}

BufferType GetBufferType(uint addrSpace)
{
    bool directIndexing = false;
    unsigned int bufId = 0;
    return DecodeAS4GFXResource(addrSpace, directIndexing, bufId);
}

bool IsReadOnlyLoadDirectCB(llvm::Instruction *pLLVMInst,
    uint& cbId, llvm::Value* &eltPtrVal, BufferType& bufType)
{
    LoadInst *inst = dyn_cast<LoadInst>(pLLVMInst);
    if(!inst)
    {
        return false;
    }
    bool isInvLoad = inst->getMetadata(LLVMContext::MD_invariant_load) != nullptr;
    unsigned as = inst->getPointerAddressSpace();
    bool directBuf;
    // cbId gets filled in the following call;
    bufType = IGC::DecodeAS4GFXResource(as, directBuf, cbId);
    if((bufType == CONSTANT_BUFFER || bufType == RESOURCE || isInvLoad) && directBuf)
    {
        Value *ptrVal = inst->getPointerOperand();
        // skip bitcast and find the real address computation
        while(isa<BitCastInst>(ptrVal))
        {
            ptrVal = cast<BitCastInst>(ptrVal)->getOperand(0);
        }
        if(isa<ConstantPointerNull>(ptrVal) ||
            isa<IntToPtrInst>(ptrVal) ||
            isa<GetElementPtrInst>(ptrVal) ||
            isa<ConstantExpr>(ptrVal) ||
            isa<Argument>(ptrVal))
        {
            eltPtrVal = ptrVal;
            return true;
        }
    }
    return false;
}

bool IsLoadFromDirectCB(llvm::Instruction *pLLVMInst, uint& cbId, llvm::Value* &eltPtrVal)
{
    BufferType bufType = BUFFER_TYPE_UNKNOWN;
    bool isReadOnly = IsReadOnlyLoadDirectCB(pLLVMInst, cbId, eltPtrVal, bufType);
    return isReadOnly && bufType == CONSTANT_BUFFER;
}
    
/// this is texture-load not buffer-load
bool isLdInstruction(llvm::Instruction* inst)
{
    return isa<SamplerLoadIntrinsic>(inst);
}

// function returns the position of the texture operand for sample/ld instructions
llvm::Value* getTextureIndexArgBasedOnOpcode(llvm::Instruction* inst)
{
    if (isLdInstruction(inst))
    {
        return cast<SamplerLoadIntrinsic>(inst)->getTextureValue();
    }
    else if (isSampleInstruction(inst))
    {
        return cast<SampleIntrinsic>(inst)->getTextureValue();
    }
    else if (isGather4Instruction(inst))
    {
        return cast<SamplerGatherIntrinsic>(inst)->getTextureValue();
    }

    return nullptr;
}

int findSampleInstructionTextureIdx(llvm::Instruction* inst)
{
    // fetch the textureArgIdx.
    Value* ptr = getTextureIndexArgBasedOnOpcode(inst);
    unsigned textureIdx = -1;

    if (ptr && ptr->getType()->isPointerTy())
    {
        BufferType bufType = BUFFER_TYPE_UNKNOWN;
        if (!(isa<GenIntrinsicInst>(ptr) &&
            cast<GenIntrinsicInst>(ptr)->getIntrinsicID() == GenISAIntrinsic::GenISA_GetBufferPtr))
        {
            uint as = ptr->getType()->getPointerAddressSpace();
            bool directIndexing;
            bufType = DecodeAS4GFXResource(as, directIndexing, textureIdx);
            if (bufType == UAV)
            {
                // dont do any clustering on read/write images
                textureIdx = -1;
            }
        }
    }
    else if (ptr)
    {
        if (llvm::dyn_cast<llvm::ConstantInt>(ptr))
        {
            textureIdx = int_cast<unsigned>(GetImmediateVal(ptr));
        }
    }

    return textureIdx;
}

bool isSampleLoadGather4InfoInstruction(llvm::Instruction* inst)
{
    if (isa<GenIntrinsicInst>(inst))
    {
        switch ((cast<GenIntrinsicInst>(inst))->getIntrinsicID())
        {
        case GenISAIntrinsic::GenISA_sampleptr:
        case GenISAIntrinsic::GenISA_sampleBptr:
        case GenISAIntrinsic::GenISA_sampleCptr:
        case GenISAIntrinsic::GenISA_sampleDptr:
        case GenISAIntrinsic::GenISA_sampleDCptr:
        case GenISAIntrinsic::GenISA_sampleLptr:
        case GenISAIntrinsic::GenISA_sampleLCptr:
        case GenISAIntrinsic::GenISA_sampleBCptr:
        case GenISAIntrinsic::GenISA_lodptr:
        case GenISAIntrinsic::GenISA_ldptr:
        case GenISAIntrinsic::GenISA_ldmsptr:
        case GenISAIntrinsic::GenISA_ldmsptr16bit:
        case GenISAIntrinsic::GenISA_ldmcsptr:
        case GenISAIntrinsic::GenISA_sampleinfoptr:
        case GenISAIntrinsic::GenISA_resinfoptr:
        case GenISAIntrinsic::GenISA_gather4ptr:
        case GenISAIntrinsic::GenISA_gather4Cptr:
        case GenISAIntrinsic::GenISA_gather4POptr:
        case GenISAIntrinsic::GenISA_gather4POCptr:
            return true;
        default:
            return false;
        }
    }

    return false;
}

bool isSampleInstruction(llvm::Instruction* inst)
{
    return isa<SampleIntrinsic>(inst);
}

bool isInfoInstruction(llvm::Instruction* inst)
{
    return isa<InfoIntrinsic>(inst);
}

bool isGather4Instruction(llvm::Instruction* inst)
{
    return isa<SamplerGatherIntrinsic>(inst);
}

bool IsMediaIOIntrinsic(llvm::Instruction* inst)
{
    if (auto *pGI = dyn_cast<llvm::GenIntrinsicInst>(inst))
    {
        GenISAIntrinsic::ID id = pGI->getIntrinsicID();

        return id == GenISAIntrinsic::GenISA_MediaBlockRead ||
            id == GenISAIntrinsic::GenISA_MediaBlockWrite;
    }

    return false;
}

bool isSubGroupIntrinsic(const llvm::Instruction *I)
{
    const GenIntrinsicInst *GII = dyn_cast<GenIntrinsicInst>(I);
    if (!GII)
        return false;

    switch (GII->getIntrinsicID())
    {
    case GenISAIntrinsic::GenISA_WaveShuffleIndex:
    case GenISAIntrinsic::GenISA_simdShuffleDown:
    case GenISAIntrinsic::GenISA_simdBlockRead:
    case GenISAIntrinsic::GenISA_simdBlockWrite:
    case GenISAIntrinsic::GenISA_simdMediaBlockRead:
    case GenISAIntrinsic::GenISA_simdMediaBlockWrite:
    case GenISAIntrinsic::GenISA_MediaBlockWrite:
    case GenISAIntrinsic::GenISA_MediaBlockRead:
        return true;
    default:
        return false;
    }
}

bool isURBWriteIntrinsic(const llvm::Instruction *I)
{
    const GenIntrinsicInst *GII = dyn_cast<GenIntrinsicInst>(I);
    if (!GII)
        return false;

    return GII->getIntrinsicID() == GenISA_URBWrite;
  
}

bool isReadInput(llvm::Instruction *pLLVMInstr);

#define DECLARE_OPCODE(instName, llvmType, name, modifiers, sat, pred, condMod, mathIntrinsic, atomicIntrinsic, regioning) \
    case name:\
    return modifiers;
bool SupportsModifier(llvm::Instruction* inst)
{
    if(llvm::CmpInst* cmp = dyn_cast<llvm::ICmpInst>(inst))
    {
        // special case, cmp supports modifier unless it is unsigned
        return !cmp->isUnsigned();
    }
    switch(GetOpCode(inst))
    {
#include "opCode.h"
    default:
        return false;
    }
}
#undef DECLARE_OPCODE

#define DECLARE_OPCODE(instName, llvmType, name, modifiers, sat, pred, condMod, mathIntrinsic, atomicIntrinsic, regioning) \
    case name:\
    return sat;
bool SupportsSaturate(llvm::Instruction* inst)
{
    switch(GetOpCode(inst))
    {
#include "opCode.h"
    default:
        break;
    }
    return false;
}
#undef DECLARE_OPCODE

#define DECLARE_OPCODE(instName, llvmType, name, modifiers, sat, pred, condMod, mathIntrinsic, atomicIntrinsic, regioning) \
    case name:\
    return pred;
bool SupportsPredicate(llvm::Instruction* inst)
{
    switch(GetOpCode(inst))
    {
#include "opCode.h"
    default:
        return false;
    }
}
#undef DECLARE_OPCODE

#define DECLARE_OPCODE(instName, llvmType, name, modifiers, sat, pred, condMod, mathIntrinsic, atomicIntrinsic, regioning) \
    case name:\
    return condMod;
bool SupportsCondModifier(llvm::Instruction* inst)
{
    switch(GetOpCode(inst))
    {
#include "opCode.h"
    default:
        return false;
    }
}
#undef DECLARE_OPCODE

#define DECLARE_OPCODE(instName, llvmType, name, modifiers, sat, pred, condMod, mathIntrinsic, atomicIntrinsic, regioning) \
    case name:\
    return regioning;
bool SupportsRegioning(llvm::Instruction* inst)
{
    switch (GetOpCode(inst))
    {
#include "opCode.h"
    default:
        break;
    }
    return false;
}
#undef DECLARE_OPCODE

#define DECLARE_OPCODE(instName, llvmType, name, modifiers, sat, pred, condMod, mathIntrinsic, atomicIntrinsic, regioning) \
    case name:\
    return mathIntrinsic;
bool IsMathIntrinsic(EOPCODE opcode)
{
    switch(opcode)
    {
#include "opCode.h"
    default:
        return false;
    }
}
#undef DECLARE_OPCODE

#define DECLARE_OPCODE(instName, llvmType, name, modifiers, sat, pred, condMod, mathIntrinsic, atomicIntrinsic, regioning) \
    case name:\
    return atomicIntrinsic;
bool IsAtomicIntrinsic(EOPCODE opcode)
{
    switch (opcode)
    {
#include "opCode.h"
    default:
        return false;
    }
}
#undef DECLARE_OPCODE

// for now just include shuffle, reduce and scan,
// which have simd32 implementations and should not be split into two instances
bool IsSubGroupIntrinsicWithSimd32Implementation(EOPCODE opcode)
{
    return (opcode == llvm_waveAll || 
            opcode == llvm_wavePrefix || 
            opcode == llvm_waveShuffleIndex);
}


bool IsGradientIntrinsic(EOPCODE opcode)
{
    return(opcode == llvm_gradientX ||
        opcode == llvm_gradientY ||
        opcode == llvm_gradientXfine ||
        opcode == llvm_gradientYfine);
}

bool ComputesGradient(llvm::Instruction *inst)
{
    llvm::SampleIntrinsic *sampleInst = dyn_cast<llvm::SampleIntrinsic>(inst);
    if (sampleInst && sampleInst->IsDerivative())
    {
        return true;
    }
    if (IsGradientIntrinsic(GetOpCode(inst)))
    {
        return true;
    }
    return false;
}

llvm::Value* ExtractElementFromInsertChain(llvm::Value *inst, int pos)
{

    llvm::ConstantDataVector *cstV = llvm::dyn_cast<llvm::ConstantDataVector>(inst);
    if (cstV != NULL) {
        return cstV->getElementAsConstant(pos);
    }

    llvm::InsertElementInst *ie = llvm::dyn_cast<llvm::InsertElementInst>(inst);
    while (ie != NULL) {
        int64_t iOffset = llvm::dyn_cast<llvm::ConstantInt>(ie->getOperand(2))->getSExtValue();
        assert(iOffset>=0);
        if (iOffset == pos) {
            return ie->getOperand(1);
        }
        llvm::Value *insertBase = ie->getOperand(0);
        ie = llvm::dyn_cast<llvm::InsertElementInst>(insertBase);
    }
    return NULL;
}

bool ExtractVec4FromInsertChain(llvm::Value *inst, llvm::Value *elem[4], llvm::SmallVector<llvm::Instruction*, 10> &instructionToRemove)
{
    llvm::ConstantDataVector *cstV = llvm::dyn_cast<llvm::ConstantDataVector>(inst);
    if (cstV != NULL) {
        assert(cstV->getNumElements() == 4);
        for (int i = 0; i < 4; i++) {
            elem[i] = cstV->getElementAsConstant(i);
        }
        return true;
    }

    for (int i = 0; i<4; i++) {
        elem[i] = NULL;
    }
    
    int count = 0;
    llvm::InsertElementInst *ie = llvm::dyn_cast<llvm::InsertElementInst>(inst);
    while (ie != NULL) {
        int64_t iOffset = llvm::dyn_cast<llvm::ConstantInt>(ie->getOperand(2))->getSExtValue();
        assert(iOffset>=0);
        if (elem[iOffset] == NULL) {
            elem[iOffset] = ie->getOperand(1);
            count++;
            if (ie->hasOneUse()) {
                instructionToRemove.push_back(ie);
            }
        }
        llvm::Value *insertBase = ie->getOperand(0);
        ie = llvm::dyn_cast<llvm::InsertElementInst>(insertBase);
    }
    return (count == 4);
}

void VectorToElement(llvm::Value *inst, llvm::Value *elem[], llvm::Type *int32Ty, llvm::Instruction *insert_before, int vsize)
{
    for (int i = 0; i < vsize; i++) {
        if (elem[i] == nullptr) {
            // Create an ExtractElementInst
            elem[i] = llvm::ExtractElementInst::Create(inst, llvm::ConstantInt::get(int32Ty, i), "", insert_before);
        }
    }
}

llvm::Value* ElementToVector(llvm::Value *elem[], llvm::Type *int32Ty, llvm::Instruction *insert_before, int vsize)
{
    llvm::VectorType *vt = llvm::VectorType::get(elem[0]->getType(), vsize);
    llvm::Value *vecValue = llvm::UndefValue::get(vt);

    for (int i = 0; i < vsize; ++i)
    {
harshad untwale's avatar
harshad untwale committed
1109

1110
        vecValue = llvm::InsertElementInst::Create(vecValue, elem[i], llvm::ConstantInt::get(int32Ty, i), "", insert_before);
harshad untwale's avatar
harshad untwale committed
1111
        ((Instruction*)vecValue)->setDebugLoc(insert_before->getDebugLoc());
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
    }
    return vecValue;
}

bool IsUnsignedCmp(const llvm::CmpInst::Predicate Pred)
{
    switch (Pred) {
    case llvm::CmpInst::ICMP_UGT:
    case llvm::CmpInst::ICMP_UGE:
    case llvm::CmpInst::ICMP_ULT:
    case llvm::CmpInst::ICMP_ULE:
        return true;
    default:
        break;
    }
    return false;
}

bool IsSignedCmp(const llvm::CmpInst::Predicate Pred)
{
    switch (Pred)
    {
    case llvm::CmpInst::ICMP_SGT:
    case llvm::CmpInst::ICMP_SGE:
    case llvm::CmpInst::ICMP_SLT:
    case llvm::CmpInst::ICMP_SLE:
        return true;
    default:
        break;
    }
    return false;
}

// isA64Ptr - Queries whether given pointer type requires 64-bit representation in vISA
bool isA64Ptr(llvm::PointerType *PT, CodeGenContext* pContext)
{
    return pContext->getRegisterPointerSizeInBits(PT->getAddressSpace()) == 64;
}

bool IsBitCastForLifetimeMark(const llvm::Value *V)
{
    if (!V || !llvm::isa<llvm::BitCastInst>(V))
    {
        return false;
    }
    for (llvm::Value::const_user_iterator it = V->user_begin(), e = V->user_end(); it != e; ++it)
    {
        const llvm::IntrinsicInst *inst = llvm::dyn_cast<const llvm::IntrinsicInst>(*it);
        if (!inst)
        {
            return false;
        }
        llvm::Intrinsic::ID  IID = inst->getIntrinsicID();
        if (IID != llvm::Intrinsic::lifetime_start &&
            IID != llvm::Intrinsic::lifetime_end)
        {
            return false;
        }
    }
    return true;
}

Value* mutatePtrType(Value* ptrv, PointerType* newType,
    IRBuilder<>& builder, const Twine&)
{
    if (isa<ConstantPointerNull>(ptrv))
    {
        return ConstantPointerNull::get(newType);
    }
    else
    {
        if (ConstantExpr* cexpr = dyn_cast<ConstantExpr>(ptrv))
        {
            assert(cexpr->getOpcode() == Instruction::IntToPtr);
            Value* offset = cexpr->getOperand(0);
            ptrv = builder.CreateIntToPtr(offset, newType);
        }
        else
        {
            ptrv->mutateType(newType);
        }
    }
    return ptrv;
}

/*
cmp.l.f0.0 (8) null:d       r0.0<0;1,0>:w    0x0000:w         { Align1, N1, NoMask, NoCompact }
(-f0.0) jmpi Test
(-f0.0) sendc (8) null:ud      r120.0<0;1,0>:f  0x00000025  0x08031400:ud    { Align1, N1, EOT, NoCompact }
nop
Test :
nop

*/

static const unsigned int CRastHeader_SIMD8[] =
{
    0x05600010,0x20001a24,0x1e000000,0x00000000,
    0x00110020,0x34000004,0x0e001400,0x00000020,
    0x05710032,0x20003a00,0x06000f00,0x88031400,
    0x00000000,0x00000000,0x00000000,0x00000000,
};

/*
cmp.l.f0.0 (16) null:d       r0.0 < 0; 1, 0 > : w    0x0000 : w{ Align1, N1, NoMask, NoCompact }
(-f0.0) jmpi(1) Test { Align1, N1, NoMask, NoCompact }
(-f0.0) sendc(16) null : ud      r120.0 < 0; 1, 0 > : f  0x00000025 0x90031000 : ud{ Align1, N1, EOT, NoCompact }
nop
Test :
nop

*/
static const unsigned int CRastHeader_SIMD16[] =
{
    0x05800010, 0x20001A24, 0x1E000000, 0x00000000,
    0x00110020, 0x34000004, 0x0E001400, 0x00000020,
    0x05910032, 0x20003A00, 0x06000F00, 0x90031000,
    0x00000000, 0x00000000, 0x00000000, 0x00000000,
};

/*
cmp.l.f0.0 (16) null:d       r0.0 < 0; 1, 0 > : w    0x0000 : w{ Align1, N1, NoMask, NoCompact }
(-f0.0) jmpi Test
(-f0.0) sendc(16) null : w r120.0 < 0; 1, 0 > : ud  0x00000005 0x10031000 : ud{ Align1, N1, NoCompact }
(-f0.0) sendc(16) null : w r120.0 < 0; 1, 0 > : f  0x00000025  0x10031800 : ud{ Align1, N5, EOT, NoCompact }
nop
Test :
nop

*/

static const unsigned int CRastHeader_SIMD32[] =
{
    0x05800010,0x20001a24,0x1e000000,0x00000000,
    0x00110020,0x34000004,0x0e001400,0x00000020,
    0x05910032,0x20000260,0x06000f00,0x10031000,
    0x05912032,0x20003a60,0x06000f00,0x90031800,
};


unsigned int AppendConservativeRastWAHeader(IGC::SProgramOutput* program, SIMDMode simdmode)
{
     unsigned int headerSize = 0;
     const unsigned int* pHeader = nullptr;

    if (program && (program->m_programSize > 0 ))
    {
        switch (simdmode)
        {
        case SIMDMode::SIMD8: 
            headerSize = sizeof(CRastHeader_SIMD8);
            pHeader = CRastHeader_SIMD8;
            break;

        case SIMDMode::SIMD16: 
            headerSize = sizeof(CRastHeader_SIMD16);
            pHeader = CRastHeader_SIMD16;
            break;

        case SIMDMode::SIMD32: 
            headerSize = sizeof(CRastHeader_SIMD32);
            pHeader = CRastHeader_SIMD32;
            break;

        default: assert("Invalid SIMD Mode for Conservative Raster WA");
                    break;
        }

        unsigned int newSize = program->m_programSize + headerSize;
        void* newBinary = IGC::aligned_malloc(newSize, 16);
        memcpy_s(newBinary, newSize, pHeader, headerSize);
        memcpy_s((char*)newBinary + headerSize, newSize, program->m_programBin, program->m_programSize);
        IGC::aligned_free(program->m_programBin);
        program->m_programBin = newBinary;
        program->m_programSize = newSize;
    }
    return headerSize;
}

bool DSDualPatchEnabled(class CodeGenContext* ctx)
{
    return ctx->platform.supportDSDualPatchDispatch() &&
        ctx->platform.WaDisableDSDualPatchMode() &&
        !(ctx->m_DriverInfo.APIDisableDSDualPatchDispatch()) &&
        IGC_IS_FLAG_DISABLED(DisableDSDualPatch);
}

Function* getUniqueEntryFunc(const IGCMD::MetaDataUtils *pM)
{
	Function *entryFunc = nullptr;
	for (auto i = pM->begin_FunctionsInfo(), e = pM->end_FunctionsInfo(); i != e; ++i)
	{
		IGCMD::FunctionInfoMetaDataHandle Info = i->second;
		if (Info->getType() != IGCMD::FunctionTypeEnum::EntryFunctionType)
		{
			continue;
		}

		const Function *F = i->first;
		if (!entryFunc)
		{
			entryFunc = const_cast<Function*>(F);
		}
		else
		{
			assert(false && "Not a single entry func!");
		}
	}
	assert(entryFunc && "No entry func!");
	return entryFunc;
}

// If true, the codegen will likely not emit instruction for this instruction.
bool isNoOpInst(Instruction* I, CodeGenContext* Ctx)
{
    if (isa<BitCastInst>(I) ||
        isa<IntToPtrInst>(I) ||
        isa<PtrToIntInst>(I))
    {
        // Don't bother with constant operands
        if (isa<Constant>(I->getOperand(0))) {
            return false;
        }

        Type* dTy = I->getType();
        Type* sTy = I->getOperand(0)->getType();
        PointerType *dPTy = dyn_cast<PointerType>(dTy);
        PointerType *sPTy = dyn_cast<PointerType>(sTy);
        uint32_t dBits = dPTy ? Ctx->getRegisterPointerSizeInBits(dPTy->getAddressSpace())
                              : dTy->getPrimitiveSizeInBits();
        uint32_t sBits = sPTy ? Ctx->getRegisterPointerSizeInBits(sPTy->getAddressSpace())
                              : sTy->getPrimitiveSizeInBits();
        if (dBits == 0 || sBits == 0 || dBits != sBits) {
            // Not primitive type or not equal in size (inttoptr, etc)
            return false;
        }

        VectorType* dVTy = dyn_cast<VectorType>(dTy);
        VectorType* sVTy = dyn_cast<VectorType>(sTy);
        int d_nelts = dVTy ? (int)dVTy->getNumElements() : 1;
        int s_nelts = sVTy ? (int)sVTy->getNumElements() : 1;
        if (d_nelts != s_nelts) {
            // Vector relayout bitcast.
            return false;
        }
        return true;
    }
    return false;
}

//
// Given a value, check if it is likely a positive number.
//
// This function works best if llvm.assume() is used in the bif libraries to
// give ValueTracking hints.  ex:
//
// size_t get_local_id(uint dim)
// {
//    size_t ret = __builtin_IB_get_local_id()
//    __builtin_assume(ret >= 0);
//    __builtin_assume(ret <= 0x0000ffff)
//    return ret;
// }
// 
// This implementation relies completly on native llvm functions
//
//
//
bool valueIsPositive(
	Value* V,
	const DataLayout *DL,
	llvm::AssumptionCache *AC,
	llvm::Instruction *CxtI)
{
#if LLVM_VERSION_MAJOR == 4
	bool isKnownNegative = false;
	bool isKnownPositive = false;
	llvm::ComputeSignBit(
		V,
		isKnownPositive,
		isKnownNegative,
		*DL,
		0,
		AC,
		CxtI);
	return isKnownPositive;
Lukasz Wesierski's avatar
Lukasz Wesierski committed
1398
#elif LLVM_VERSION_MAJOR >= 7
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425
	return computeKnownBits(
		V,
		*DL,
		0,
		AC,
		CxtI).isNonNegative();
#endif
}

void appendToUsed(llvm::Module &M, ArrayRef<GlobalValue *> Values)
{
    std::string Name = "llvm.used";
    GlobalVariable *GV = M.getGlobalVariable(Name);
    SmallPtrSet<Constant *, 16> InitAsSet;
    SmallVector<Constant *, 16> Init;
    if (GV) {
        ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
        for (auto &Op : CA->operands()) {
            Constant *C = cast_or_null<Constant>(Op);
            if (InitAsSet.insert(C).second)
                Init.push_back(C);
        }
        GV->eraseFromParent();
    }

    Type *Int8PtrTy = llvm::Type::getInt8PtrTy(M.getContext());
    for (auto *V : Values) {
1426 1427 1428 1429 1430
        Constant *C = V;
        if(V->getType()->getAddressSpace() != 0)
            C = ConstantExpr::getAddrSpaceCast(V, Int8PtrTy);
        else
            C = ConstantExpr::getBitCast(V, Int8PtrTy);
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443
        if (InitAsSet.insert(C).second)
            Init.push_back(C);
    }

    if (Init.empty())
        return;

    ArrayType *ATy = ArrayType::get(Int8PtrTy, Init.size());
    GV = new llvm::GlobalVariable(M, ATy, false, GlobalValue::AppendingLinkage,
                                  ConstantArray::get(ATy, Init), Name);
    GV->setSection("llvm.metadata");
}

1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486
bool safeScheduleUp(llvm::BasicBlock *BB, llvm::Value *V, llvm::Instruction *&InsertPos, llvm::DenseSet<llvm::Instruction *> Scheduled)
{
    llvm::Instruction *I = llvm::dyn_cast<llvm::Instruction>(V);
    if (!I)
        return false;

    // Skip value defined in other BBs.
    if (I->getParent() != BB)
        return false;

    // Skip phi-node as they are eventually defined in other BBs.
    if (llvm::isa<llvm::PHINode>(I))
        return false;

    // Don't re-schedule instruction again.
    if (Scheduled.count(I)) {
        if (InsertPos && !isInstPrecede(I, InsertPos))
            InsertPos = I;
        return false;
    }

    bool Changed = false;

    // Try to schedule all its operands first.
    for (auto OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI)
        Changed |= safeScheduleUp(BB, OI->get(), InsertPos, Scheduled);

    // Mark this instruction `visited`.
    Scheduled.insert(I);

    // Skip if the instruction is already defined before insertion position.
    if (InsertPos && isInstPrecede(I, InsertPos))
        return Changed;

    // Schedule itself.
    if (InsertPos) {
        I->removeFromParent();
        I->insertAfter(InsertPos);
    }

    InsertPos = I;
    return true;
}
1487
} // namespace IGC