void CGUIDialogSmartPlaylistEditor::OnInitWindow()
{
  m_cancelled = false;

  SendMessage(GUI_MSG_ITEM_SELECT, CONTROL_LIMIT, m_playlist.m_limit);

  std::vector<PLAYLIST_TYPE> allowedTypes;
  if (m_mode == "partymusic")
  {
    allowedTypes.push_back(TYPE_SONGS);
    allowedTypes.push_back(TYPE_MIXED);
  }
  else if (m_mode == "partyvideo")
  {
    allowedTypes.push_back(TYPE_MUSICVIDEOS);
    allowedTypes.push_back(TYPE_MIXED);
  }
  else if (m_mode == "music")
  { // music types + mixed
    allowedTypes.push_back(TYPE_SONGS);
    allowedTypes.push_back(TYPE_ALBUMS);
    allowedTypes.push_back(TYPE_ARTISTS);
    allowedTypes.push_back(TYPE_MIXED);
  }
  else if (m_mode == "video")
  { // general category for videos
    allowedTypes.push_back(TYPE_MOVIES);
    allowedTypes.push_back(TYPE_TVSHOWS);
    allowedTypes.push_back(TYPE_EPISODES);
    allowedTypes.push_back(TYPE_MUSICVIDEOS);
    allowedTypes.push_back(TYPE_MIXED);
  }
  // add to the spinner
  std::vector< std::pair<std::string, int> > labels;
  for (unsigned int i = 0; i < allowedTypes.size(); i++)
    labels.push_back(make_pair(GetLocalizedType(allowedTypes[i]), allowedTypes[i]));
  // check our playlist type is allowed
  PLAYLIST_TYPE type = ConvertType(m_playlist.GetType());
  bool allowed = false;
  for (unsigned int i = 0; i < allowedTypes.size(); i++)
    if (type == allowedTypes[i])
      allowed = true;
  if (!allowed && allowedTypes.size())
    type = allowedTypes[0];

  SET_CONTROL_LABELS(CONTROL_TYPE, type, &labels);
  m_playlist.SetType(ConvertType(type));
  UpdateButtons();

  SET_CONTROL_LABEL(CONTROL_HEADING, 21432);

  CGUIDialog::OnInitWindow();
}
Beispiel #2
0
void MAP_PlaceObjects(Map *map, char *fileName) {
	int x, y;		// Object's coordinates from file 
	char type;		// Object's type from tile
	int total = 0;	// Total of objects placed

	FILE *f;
	f = fopen(fileName, "r");
        
	if(f == NULL){
        printf("ERROR: File not found.\n");
    }

	int mapColumns = map->width;

	while(fscanf(f, "%d %d %c\n", &y, &x, &type) == 3) {
		/*printf("Place object type %c on (%d, %d)\n", type, x, y);*/
		
		// If this position is grass...
			if(map->positions[y * mapColumns + x].terrain == MAP_TileGrass) {	
			// If position is empty, no restrictions
			if(map->positions[y * mapColumns + x].numObjs == 0) {
				map->positions[y * mapColumns + x].objs[0] = ConvertType(type);
				map->positions[y * mapColumns + x].numObjs++;
				total++;
			}

			// If position is occupied...
			else {
				// ... check if the combination of objects is possible 
				bool allow = true;
				for(int k = 0; k < map->positions[y * mapColumns + x].numObjs; k++) {
					if(!AllowObjectsCombination(map->positions[y * mapColumns + x].objs[k], ConvertType(type))) {
						allow = false;
					}
				}
				if(allow) {
					map->positions[y * mapColumns + x].objs[map->positions[y * mapColumns + x].numObjs + 1] = ConvertType(type);
					map->positions[y * mapColumns + x].numObjs++;
					total++;
				}
			}
		}
	}

	printf("Total of objects placed: %d\n", total);

	fclose(f);
}
Beispiel #3
0
/* Target hook for llvm-abi.h. It returns true if an aggregate of the
   specified type should be passed in a number of registers of mixed types.
   It also returns a vector of types that correspond to the registers used
   for parameter passing. */
bool 
llvm_rs6000_should_pass_aggregate_in_mixed_regs(tree TreeType, const Type* Ty,
                                              std::vector<const Type*>&Elts) {
  // FIXME there are plenty of ppc64 cases that need this.
  if (TARGET_64BIT)
    return false;

  // If this is a small fixed size type, investigate it.
  HOST_WIDE_INT SrcSize = int_size_in_bytes(TreeType);
  if (SrcSize <= 0 || SrcSize > 16)
    return false;

  const StructType *STy = dyn_cast<StructType>(Ty);
  if (!STy) return false;

  // A struct containing only a float, double or Altivec field, possibly with
  // some zero-length fields as well, must be passed as the field type.
  // Note this does not apply to long double, nor generic vectors.
  // Other single-element structs may be passed this way as well, but
  // only if the type size matches the element's type size (structs that
  // violate this can be created with __aligned__).
  tree tType = isSingleElementStructOrArray(TreeType, true, false);
  if (tType && int_size_in_bytes(tType)==SrcSize && TYPE_MODE(tType)!=TFmode &&
      (TREE_CODE(tType)!=VECTOR_TYPE || SrcSize==16)) {
    Elts.push_back(ConvertType(tType));
    return true;
  }

  Elts.clear();
  return false;
}
llvm::Function* WasmImportFunction::GetFunction(WasmModule* module) {
  if (function_ == nullptr) {
    // This probably should be done better but will work like this for now.
    std::string full_name = module_name_ + "_" + function_name_;

    // Now what we really want is the parameters of this method.
    std::vector<llvm::Type*> params;
    Populate(params);

    // Add to the name the type of the arguments for the import.
    //  Again, probably not what we want finally but this will work.
    //  My problem right now is how to handle the variadic functions well.
    for (auto elem : params) {
      full_name += "_";
      full_name += GetTypeName(elem);
    }

    BISON_PRINT("Import Function not created yet: Internal name: %s Module: %s Function: %s -> Full %s\n", internal_name_.c_str(), module_name_.c_str(), function_name_.c_str(), full_name.c_str());

    // Now get the result type.
    llvm::Type* result_type = ConvertType(result_);

    // Finally, create the function type.
    llvm::FunctionType* fct_type = llvm::FunctionType::get(result_type, params, false);

    // Now create the function.
    function_ = llvm::Function::Create(fct_type, llvm::Function::ExternalLinkage, full_name, module->GetModule());
  }

  // Paranoid.
  assert(function_ != nullptr);

  // Finally we can return the function_.
  return function_;
}
Beispiel #5
0
AGDOCTYPE CXMLDlg::GetCurrentDocType(HTREEITEM pItem)
{
	HTREEITEM pChildItem = m_treeOutput.GetChildItem(pItem);
	if (!pChildItem)
	{
		ASSERT(false);
		return DOC_DEFAULT;
	}

	while (pChildItem)
	{
		CString szTitle;
		CString szValue;
		Separate(m_treeOutput.GetItemText(pChildItem), szTitle, szValue);

		if (!szTitle.CompareNoCase(_T("type")))
		{
			return (ConvertType(szValue));
		}

		pChildItem = m_treeOutput.GetNextItem(pChildItem, TVGN_NEXT);
	}

	ASSERT(false);
	return DOC_DEFAULT;
}
void WasmImportFunction::Populate(std::vector<llvm::Type*>& params) {
  if (fields_ != nullptr) {
    for (std::list<FunctionField*>::const_iterator it = fields_->begin();
                                                   it != fields_->end();
                                                   it++) {
      const FunctionField* ff = *it;

      // Is it a result?
      const ResultField* rf = dynamic_cast<const ResultField*>(ff);
      if (rf != nullptr) {
        // We only support one return.
        assert(result_ == VOID);

        result_ = rf->GetType();
      } else {
        // What about a parameter?
        const ParamField* pf = dynamic_cast<const ParamField*>(ff);

        // In the case of an import function, it has to either be a result or a parameter...
        assert (pf != nullptr);

        Local* local = pf->GetLocal();

        const std::deque<LocalElem*>& list = local->GetList();

        for (auto elem : list) {
          params.push_back(ConvertType(elem->GetType()));
        }
      }
    }
  }
}
void CGUIDialogSmartPlaylistEditor::OnType()
{
  CGUIMessage msg(GUI_MSG_ITEM_SELECTED, GetID(), CONTROL_TYPE);
  OnMessage(msg);
  m_playlist.SetType(ConvertType((PLAYLIST_TYPE)msg.GetParam1()));
  UpdateButtons();
}
Beispiel #8
0
/// HandleReturnType - This is invoked by the target-independent code for the
/// return type. It potentially breaks down the argument and invokes methods
/// on the client that indicate how its pieces should be handled.  This
/// handles things like returning structures via hidden parameters.
void DefaultABI::HandleReturnType(tree type, tree fn, bool isBuiltin) {
  unsigned Offset = 0;
  const Type *Ty = ConvertType(type);
  if (Ty->isVectorTy()) {
    // Vector handling is weird on x86.  In particular builtin and
    // non-builtin function of the same return types can use different
    // calling conventions.
    tree ScalarType = LLVM_SHOULD_RETURN_VECTOR_AS_SCALAR(type, isBuiltin);
    if (ScalarType)
      C.HandleAggregateResultAsScalar(ConvertType(ScalarType));
    else if (LLVM_SHOULD_RETURN_VECTOR_AS_SHADOW(type, isBuiltin))
      C.HandleScalarShadowResult(Ty->getPointerTo(), false);
    else
      C.HandleScalarResult(Ty);
  } else if (Ty->isSingleValueType() || Ty->isVoidTy()) {
    // Return scalar values normally.
    C.HandleScalarResult(Ty);
  } else if (doNotUseShadowReturn(type, fn, C.getCallingConv())) {
    tree SingleElt = LLVM_SHOULD_RETURN_SELT_STRUCT_AS_SCALAR(type);
    if (SingleElt && TYPE_SIZE(SingleElt) && 
	TREE_CODE(TYPE_SIZE(SingleElt)) == INTEGER_CST &&
	TREE_INT_CST_LOW(TYPE_SIZE_UNIT(type)) == 
	TREE_INT_CST_LOW(TYPE_SIZE_UNIT(SingleElt))) {
      C.HandleAggregateResultAsScalar(ConvertType(SingleElt));
    } else {
      // Otherwise return as an integer value large enough to hold the entire
      // aggregate.
      if (const Type *AggrTy = LLVM_AGGR_TYPE_FOR_STRUCT_RETURN(type,
                                  C.getCallingConv()))
	C.HandleAggregateResultAsAggregate(AggrTy);
      else if (const Type* ScalarTy = 
	       LLVM_SCALAR_TYPE_FOR_STRUCT_RETURN(type, &Offset))
	C.HandleAggregateResultAsScalar(ScalarTy, Offset);
      else {
	assert(0 && "Unable to determine how to return this aggregate!");
	abort();
      }
    }
  } else {
    // If the function is returning a struct or union, we pass the pointer to
    // the struct as the first argument to the function.

    // FIXME: should return the hidden first argument for some targets
    // (e.g. ELF i386).
    C.HandleAggregateShadowResult(Ty->getPointerTo(), false);
  }
}
llvm::Value* MemoryExpression::GetPointer(WasmFunction*fct, llvm::IRBuilder<>& builder) const {
  llvm::Type* ptr_type= nullptr;

  if (type_ == INT_32 || type_ == INT_64) {
    switch (size_) {
      case 8:
        ptr_type= llvm::Type::getInt8PtrTy(llvm::getGlobalContext());
        break;
      case 16:
        ptr_type= llvm::Type::getInt16PtrTy(llvm::getGlobalContext());
        break;
      case 32:
        ptr_type= llvm::Type::getInt32PtrTy(llvm::getGlobalContext());
        break;
      case 64:
        ptr_type= llvm::Type::getInt64PtrTy(llvm::getGlobalContext());
        break;
      default:
        assert(0);
        break;
    }
  } else {
    switch (size_) {
      case 32:
        ptr_type= llvm::Type::getFloatPtrTy(llvm::getGlobalContext());
        break;
      case 64:
        ptr_type= llvm::Type::getDoublePtrTy(llvm::getGlobalContext());
        break;
      default:
        assert(0);
        break;
    }
  }

  assert(ptr_type != nullptr);

  // Create the base address in the same right type.
  llvm::Type* dest_type = ConvertType(type_);

  llvm::Value* address_i = address_->Codegen(fct, builder);
  llvm::Value* local_base = fct->GetLocalBase();
  llvm::Type* type_64 = llvm::Type::getInt64Ty(llvm::getGlobalContext());
  local_base = builder.CreatePtrToInt(local_base, type_64, "base");

  llvm::Type* address_type = address_i->getType();
  assert(address_type->isIntegerTy() == true);
  int bw = address_i->getType()->getIntegerBitWidth();

  // If not 64, transform it into 64.
  if (bw != 64) {
    address_i = HandleIntegerTypeCast(address_i, type_64, bw, 64, false, builder);
  }

  address_i = builder.CreateAdd(address_i, local_base, "add_with_offset");

  return builder.CreateIntToPtr(address_i, ptr_type, "ptr");
}
Beispiel #10
0
void PostgreSqlDbAdapter::ConvertTable(Table* pTab) {
	SerializableList::compatibility_iterator node = pTab->GetFirstChildNode();
	while( node ) {
		if( node->GetData()->IsKindOf( CLASSINFO(Column)) )  {
			Column* col = (Column*) node->GetData();
			col->SetType(ConvertType(col->GetType()));
		}
		node = node->GetNext();
	}
}
///------------------------------------------------------------------
/// Retrieves a double property from the specified Node
///------------------------------------------------------------------
float GetDoubleProperty( const XMLNode& node, const std::string& propertyName, float defaultValue )
{
	std::string	propertyString	= GetPropertyValueAsString( node, propertyName );
	float		propertyValue	= defaultValue ;

	if ( propertyString.length() )
		ConvertType( propertyString, propertyValue );

	return propertyValue ;
}
Beispiel #12
0
// Return LLVM Type if TYPE can be returned as an aggregate, 
// otherwise return NULL.
Type *llvm_mips_aggr_type_for_struct_return(tree type) {
  Type *Ty = ConvertType(type);

  StructType *STy = cast<StructType>(Ty);
  std::vector<Type *> ElementTypes;

  // Special handling for _Complex.
  if (llvm_mips_should_not_return_complex_in_memory(type)) {
    ElementTypes.push_back(Type::getDoubleTy(Context));
    ElementTypes.push_back(Type::getDoubleTy(Context));
    return StructType::get(Context, ElementTypes, STy->isPacked());
  } 

  return NULL;
}
llvm::Value* Load::ResizeIntegerIfNeed(llvm::Value* value,
                                        llvm::Type* value_type,
                                        ETYPE destination_type,
                                        bool sign,
                                        llvm::IRBuilder<>& builder) {
  // Get size differences.
  int value_type_bw = value_type->getIntegerBitWidth();
  size_t type_size = GetTypeSize(type_);

  if (value_type_bw != type_size) {
    // Then it depends on sign.
    value = HandleIntegerTypeCast(value, ConvertType(type_),
                                  value_type_bw,
                                  type_size,
                                  sign, builder);
  }

  return value;
}
Beispiel #14
0
/**
 * @brief Set option value.
 * 
 * Set new value for option. If automatic conversion is not allowed,
 * type of value must match to type set when option was initialised.
 * @param [in] value New value to set.
 * @param [in] allowConversion Is automatic type conversion allowed?
 * @sa COption::Init()
 */
int COption::Set(varprop::VariantValue value, bool allowConversion)
{
	int retVal = OPT_OK;

	// Check that type matches
	varprop::VT_TYPE inType = value.GetType();
	if (value.GetType() != m_value.GetType())
	{
		if (allowConversion)
		{
			if (ConvertType(value, m_value.GetType()))
				return Set(value);
		}
		_RPTF1(_CRT_ERROR, "Wrong type for option: %s", m_strName.c_str());
		return OPT_WRONG_TYPE;
	}

	switch (inType)
	{
	case varprop::VT_NULL:
		retVal = OPT_UNKNOWN_TYPE;
		break;
	case varprop::VT_BOOL:
		m_value.SetBool(value.GetBool());
		break;
	case varprop::VT_INT:
		m_value.SetInt(value.GetInt());
		break;
	case varprop::VT_FLOAT:
		m_value.SetFloat(value.GetFloat());
		break;
	case varprop::VT_STRING:
		m_value.SetString(value.GetString());
		break;
	case varprop::VT_TIME:
		m_value.SetTime(value.GetTime());
		break;
	default:
		retVal = OPT_UNKNOWN_TYPE;
	}
	return retVal;
}
Beispiel #15
0
/**
 * @brief Set option value.
 * 
 * Set new value for option. If automatic conversion is not allowed,
 * type of value must match to type set when option was initialised.
 * @param [in] value New value to set.
 * @param [in] allowConversion Is automatic type conversion allowed?
 * @sa COption::Init()
 */
int COption::Set(const varprop::VariantValue& value, bool allowConversion)
{
	int retVal = COption::OPT_OK;

	// Check that type matches
	varprop::VT_TYPE inType = value.GetType();
	if (value.GetType() != m_value.GetType())
	{
		if (allowConversion)
		{
			varprop::VariantValue val(value);
			if (ConvertType(val, m_value.GetType()))
				return Set(val);
		}
		return COption::OPT_WRONG_TYPE;
	}

	switch (inType)
	{
	case varprop::VT_NULL:
		retVal = OPT_UNKNOWN_TYPE;
		break;
	case varprop::VT_BOOL:
		m_value.SetBool(value.GetBool());
		break;
	case varprop::VT_INT:
		m_value.SetInt(value.GetInt());
		break;
	case varprop::VT_FLOAT:
		m_value.SetFloat(value.GetFloat());
		break;
	case varprop::VT_STRING:
		m_value.SetString(value.GetString());
		break;
	case varprop::VT_TIME:
		m_value.SetTime(value.GetTime());
		break;
	default:
		retVal = OPT_UNKNOWN_TYPE;
	}
	return retVal;
}
		void AddTypeInstanceTemplateVariableTypes(Context& context, const AST::Node<AST::TypeInstance>& astTypeInstanceNode) {
			const auto typeInstance = context.scopeStack().back().typeInstance();
			
			// Add types of template variables.
			for (auto astTemplateVarNode: *(astTypeInstanceNode->templateVariables)) {
				const auto& templateVarName = astTemplateVarNode->name;
				const auto semTemplateVar = typeInstance->namedTemplateVariables().at(templateVarName);
				
				const auto& astVarType = astTemplateVarNode->varType;
				const auto semVarType = ConvertType(context, astVarType);
				
				if (!semVarType->isBuiltInBool() && !semVarType->isBuiltInTypename()) {
					throw ErrorException(makeString("Template variable '%s' in type '%s' has invalid type '%s', at position %s.",
						templateVarName.c_str(), typeInstance->name().toString().c_str(),
						semVarType->toString().c_str(),
						astTemplateVarNode.location().toString().c_str()));
				}
				
				semTemplateVar->setType(semVarType);
			}
		}
/// ValidateRegisterVariable - Check that a static "asm" variable is
/// well-formed.  If not, emit error messages and return true.  If so, return
/// false.
bool ValidateRegisterVariable(tree decl) {
  const char *Name = IDENTIFIER_POINTER(DECL_ASSEMBLER_NAME(decl));
  int RegNumber = decode_reg_name(Name);
  const Type *Ty = ConvertType(TREE_TYPE(decl));

  // If this has already been processed, don't emit duplicate error messages.
  if (DECL_LLVM_SET_P(decl)) {
    // Error state encoded into DECL_LLVM.
    return cast<ConstantInt>(DECL_LLVM(decl))->getZExtValue();
  }
  
  /* Detect errors in declaring global registers.  */
  if (RegNumber == -1)
    error("%Jregister name not specified for %qD", decl, decl);
  else if (RegNumber < 0)
    error("%Jinvalid register name for %qD", decl, decl);
  else if (TYPE_MODE(TREE_TYPE(decl)) == BLKmode)
    error("%Jdata type of %qD isn%'t suitable for a register", decl, decl);
#if 0 // FIXME: enable this.
  else if (!HARD_REGNO_MODE_OK(RegNumber, TYPE_MODE(TREE_TYPE(decl))))
    error("%Jregister specified for %qD isn%'t suitable for data type",
          decl, decl);
#endif
  else if (DECL_INITIAL(decl) != 0 && TREE_STATIC(decl))
    error("global register variable has initial value");
  else if (!Ty->isFirstClassType())
    sorry("%JLLVM cannot handle register variable %qD, report a bug",
          decl, decl);
  else {
    if (TREE_THIS_VOLATILE(decl))
      warning("volatile register variables don%'t work as you might wish");
    
    SET_DECL_LLVM(decl, ConstantInt::getFalse());
    return false;  // Everything ok.
  }
  SET_DECL_LLVM(decl, ConstantInt::getTrue());
  return true;
}
Beispiel #18
0
HRESULT ConvertDeclaration( const D3DVERTEXELEMENT9 original[ MAX_VERTEX_ELEMENTS ], std::vector<D3D11_INPUT_ELEMENT_DESC>& output)
{
	app::console() << std::endl;
	for( UINT i = 0; i < MAX_VERTEX_ELEMENTS; ++i )
	{
		if( original[i].Stream == 0xFF )
			break;
		// Convert this element
		D3D11_INPUT_ELEMENT_DESC item;
		item.SemanticName			= ConvertSemantic( static_cast< D3DDECLUSAGE >( original[i].Usage ) );
		item.SemanticIndex			= original[i].UsageIndex;
		item.AlignedByteOffset		= original[i].Offset;
		item.InputSlot				= original[i].Stream;
		item.InputSlotClass		= D3D11_INPUT_PER_VERTEX_DATA;
		item.InstanceDataStepRate	= 0;
		item.Format				= ConvertType( static_cast< D3DDECLTYPE >( original[i].Type ) );
		
		app::console() << item.SemanticName << std::endl;

		output.push_back(item);
	}

	return S_OK;
}
// make_decl_llvm - Create the DECL_RTL for a VAR_DECL or FUNCTION_DECL.  DECL
// should have static storage duration.  In other words, it should not be an
// automatic variable, including PARM_DECLs.
//
// There is, however, one exception: this function handles variables explicitly
// placed in a particular register by the user.
//
// This function corresponds to make_decl_rtl in varasm.c, and is implicitly
// called by DECL_LLVM if a decl doesn't have an LLVM set.
//
void make_decl_llvm(tree decl) {
#ifdef ENABLE_CHECKING
  // Check that we are not being given an automatic variable.
  // A weak alias has TREE_PUBLIC set but not the other bits.
  if (TREE_CODE(decl) == PARM_DECL || TREE_CODE(decl) == RESULT_DECL
      || (TREE_CODE(decl) == VAR_DECL && !TREE_STATIC(decl) &&
          !TREE_PUBLIC(decl) && !DECL_EXTERNAL(decl) && !DECL_REGISTER(decl)))
    abort();
  // And that we were not given a type or a label.  */
  else if (TREE_CODE(decl) == TYPE_DECL || TREE_CODE(decl) == LABEL_DECL)
    abort ();
#endif
  
  // For a duplicate declaration, we can be called twice on the
  // same DECL node.  Don't discard the LLVM already made.
  if (DECL_LLVM_SET_P(decl)) return;

  if (errorcount || sorrycount)
    return;  // Do not process broken code.
  
  
  // Global register variable with asm name, e.g.:
  // register unsigned long esp __asm__("ebp");
  if (TREE_CODE(decl) != FUNCTION_DECL && DECL_REGISTER(decl)) {
    // This  just verifies that the variable is ok.  The actual "load/store"
    // code paths handle accesses to the variable.
    ValidateRegisterVariable(decl);
    return;
  }
  
  timevar_push(TV_LLVM_GLOBALS);

  const char *Name = "";
  if (DECL_NAME(decl))
    if (tree AssemblerName = DECL_ASSEMBLER_NAME(decl))
      Name = IDENTIFIER_POINTER(AssemblerName);
  
  // Now handle ordinary static variables and functions (in memory).
  // Also handle vars declared register invalidly.
  if (Name[0] == 1) {
#ifdef REGISTER_PREFIX
    if (strlen (REGISTER_PREFIX) != 0) {
      int reg_number = decode_reg_name(Name);
      if (reg_number >= 0 || reg_number == -3)
        error("%Jregister name given for non-register variable %qD",
              decl, decl);
    }
#endif
  }
  
  // Specifying a section attribute on a variable forces it into a
  // non-.bss section, and thus it cannot be common.
  if (TREE_CODE(decl) == VAR_DECL && DECL_SECTION_NAME(decl) != NULL_TREE &&
      DECL_INITIAL(decl) == NULL_TREE && DECL_COMMON(decl))
    DECL_COMMON(decl) = 0;
  
  // Variables can't be both common and weak.
  if (TREE_CODE(decl) == VAR_DECL && DECL_WEAK(decl))
    DECL_COMMON(decl) = 0;
  
  // Okay, now we need to create an LLVM global variable or function for this
  // object.  Note that this is quite possibly a forward reference to the
  // object, so its type may change later.
  if (TREE_CODE(decl) == FUNCTION_DECL) {
    assert(Name[0] && "Function with empty name!");
    // If this function has already been created, reuse the decl.  This happens
    // when we have something like __builtin_memset and memset in the same file.
    Function *FnEntry = TheModule->getFunction(Name);
    if (FnEntry == 0) {
      unsigned CC;
      const FunctionType *Ty = 
        TheTypeConverter->ConvertFunctionType(TREE_TYPE(decl), decl, NULL, CC);
      FnEntry = new Function(Ty, Function::ExternalLinkage, Name, TheModule);
      FnEntry->setCallingConv(CC);

      // Check for external weak linkage
      if (DECL_EXTERNAL(decl) && DECL_WEAK(decl))
        FnEntry->setLinkage(Function::ExternalWeakLinkage);
      
#ifdef TARGET_ADJUST_LLVM_LINKAGE
      TARGET_ADJUST_LLVM_LINKAGE(FnEntry,decl);
#endif /* TARGET_ADJUST_LLVM_LINKAGE */

      // Handle visibility style
      if (TREE_PUBLIC(decl)) {
        if (DECL_VISIBILITY(decl) == VISIBILITY_HIDDEN)
          FnEntry->setVisibility(GlobalValue::HiddenVisibility);
        else if (DECL_VISIBILITY(decl) == VISIBILITY_PROTECTED)
          FnEntry->setVisibility(GlobalValue::ProtectedVisibility);
      }

      assert(FnEntry->getName() == Name &&"Preexisting fn with the same name!");
    }
    SET_DECL_LLVM(decl, FnEntry);
  } else {
    assert((TREE_CODE(decl) == VAR_DECL ||
            TREE_CODE(decl) == CONST_DECL) && "Not a function or var decl?");
    const Type *Ty = ConvertType(TREE_TYPE(decl));
    GlobalVariable *GV ;

    // If we have "extern void foo", make the global have type {} instead of
    // type void.
    if (Ty == Type::VoidTy) 
      Ty = StructType::get(std::vector<const Type*>(), false);
    
    if (Name[0] == 0) {   // Global has no name.
      GV = new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage, 0,
                              "", TheModule);

      // Check for external weak linkage
      if (DECL_EXTERNAL(decl) && DECL_WEAK(decl))
        GV->setLinkage(GlobalValue::ExternalWeakLinkage);
      
#ifdef TARGET_ADJUST_LLVM_LINKAGE
      TARGET_ADJUST_LLVM_LINKAGE(GV,decl);
#endif /* TARGET_ADJUST_LLVM_LINKAGE */

      // Handle visibility style
      if (TREE_PUBLIC(decl)) {
        if (DECL_VISIBILITY(decl) == VISIBILITY_HIDDEN)
          GV->setVisibility(GlobalValue::HiddenVisibility);
        else if (DECL_VISIBILITY(decl) == VISIBILITY_PROTECTED)
          GV->setVisibility(GlobalValue::ProtectedVisibility);
      }

    } else {
      // If the global has a name, prevent multiple vars with the same name from
      // being created.
      GlobalVariable *GVE = TheModule->getGlobalVariable(Name);
    
      if (GVE == 0) {
        GV = new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage,0,
                                Name, TheModule);

        // Check for external weak linkage
        if (DECL_EXTERNAL(decl) && DECL_WEAK(decl))
          GV->setLinkage(GlobalValue::ExternalWeakLinkage);
        
#ifdef TARGET_ADJUST_LLVM_LINKAGE
        TARGET_ADJUST_LLVM_LINKAGE(GV,decl);
#endif /* TARGET_ADJUST_LLVM_LINKAGE */

        // Handle visibility style
        if (TREE_PUBLIC(decl)) {
          if (DECL_VISIBILITY(decl) == VISIBILITY_HIDDEN)
            GV->setVisibility(GlobalValue::HiddenVisibility);
          else if (DECL_VISIBILITY(decl) == VISIBILITY_PROTECTED)
            GV->setVisibility(GlobalValue::ProtectedVisibility);
        }

        // If GV got renamed, then there is already an object with this name in
        // the symbol table.  If this happens, the old one must be a forward
        // decl, just replace it with a cast of the new one.
        if (GV->getName() != Name) {
          Function *F = TheModule->getFunction(Name);
          assert(F && F->isDeclaration() && "A function turned into a global?");
          
          // Replace any uses of "F" with uses of GV.
          Value *FInNewType = ConstantExpr::getBitCast(GV, F->getType());
          F->replaceAllUsesWith(FInNewType);
          
          // Update the decl that points to F.
          changeLLVMValue(F, FInNewType);

          // Now we can give GV the proper name.
          GV->takeName(F);
          
          // F is now dead, nuke it.
          F->eraseFromParent();
        }
        
      } else {
        GV = GVE;  // Global already created, reuse it.
      }
    }
    
    if ((TREE_READONLY(decl) && !TREE_SIDE_EFFECTS(decl)) || 
        TREE_CODE(decl) == CONST_DECL) {
      if (DECL_EXTERNAL(decl)) {
        // Mark external globals constant even though they could be marked
        // non-constant in the defining translation unit.  The definition of the
        // global determines whether the global is ultimately constant or not,
        // marking this constant will allow us to do some extra (legal)
        // optimizations that we would otherwise not be able to do.  (In C++,
        // any global that is 'C++ const' may not be readonly: it could have a
        // dynamic initializer.
        //
        GV->setConstant(true);
      } else {
        // Mark readonly globals with constant initializers constant.
        if (DECL_INITIAL(decl) != error_mark_node && // uninitialized?
            DECL_INITIAL(decl) &&
            (TREE_CONSTANT(DECL_INITIAL(decl)) ||
             TREE_CODE(DECL_INITIAL(decl)) == STRING_CST))
          GV->setConstant(true);
      }
    }

    // Set thread local (TLS)
    if (TREE_CODE(decl) == VAR_DECL && DECL_THREAD_LOCAL(decl))
      GV->setThreadLocal(true);

    SET_DECL_LLVM(decl, GV);
  }
  timevar_pop(TV_LLVM_GLOBALS);
}
Beispiel #20
0
/// HandleArgument - This is invoked by the target-independent code for each
/// argument type passed into the function.  It potentially breaks down the
/// argument and invokes methods on the client that indicate how its pieces
/// should be handled.  This handles things like decimating structures into
/// their fields.
void DefaultABI::HandleArgument(tree type, std::vector<const Type*> &ScalarElts,
				Attributes *Attributes) {
  unsigned Size = 0;
  bool DontCheckAlignment = false;
  const Type *Ty = ConvertType(type);
  // Figure out if this field is zero bits wide, e.g. {} or [0 x int].  Do
  // not include variable sized fields here.
  std::vector<const Type*> Elts;
  if (Ty->isVoidTy()) {
    // Handle void explicitly as an opaque type.
    const Type *OpTy = OpaqueType::get(getGlobalContext());
    C.HandleScalarArgument(OpTy, type);
    ScalarElts.push_back(OpTy);
  } else if (isPassedByInvisibleReference(type)) { // variable size -> by-ref.
    const Type *PtrTy = Ty->getPointerTo();
    C.HandleByInvisibleReferenceArgument(PtrTy, type);
    ScalarElts.push_back(PtrTy);
  } else if (Ty->isVectorTy()) {
    if (LLVM_SHOULD_PASS_VECTOR_IN_INTEGER_REGS(type)) {
      PassInIntegerRegisters(type, ScalarElts, 0, false);
    } else if (LLVM_SHOULD_PASS_VECTOR_USING_BYVAL_ATTR(type)) {
      C.HandleByValArgument(Ty, type);
      if (Attributes) {
	*Attributes |= Attribute::ByVal;
	*Attributes |= 
	  Attribute::constructAlignmentFromInt(LLVM_BYVAL_ALIGNMENT(type));
      }
    } else {
      C.HandleScalarArgument(Ty, type);
      ScalarElts.push_back(Ty);
    }
  } else if (LLVM_TRY_PASS_AGGREGATE_CUSTOM(type, ScalarElts,
					    C.getCallingConv(), &C)) {
    // Nothing to do.
  } else if (Ty->isSingleValueType()) {
    C.HandleScalarArgument(Ty, type);
    ScalarElts.push_back(Ty);
  } else if (LLVM_SHOULD_PASS_AGGREGATE_AS_FCA(type, Ty)) {
    C.HandleFCAArgument(Ty, type);
  } else if (LLVM_SHOULD_PASS_AGGREGATE_IN_MIXED_REGS(type, Ty,
						      C.getCallingConv(),
						      Elts)) {
    if (!LLVM_AGGREGATE_PARTIALLY_PASSED_IN_REGS(Elts, ScalarElts,
						 C.isShadowReturn(),
						 C.getCallingConv()))
      PassInMixedRegisters(Ty, Elts, ScalarElts);
    else {
      C.HandleByValArgument(Ty, type);
      if (Attributes) {
	*Attributes |= Attribute::ByVal;
	*Attributes |= 
	  Attribute::constructAlignmentFromInt(LLVM_BYVAL_ALIGNMENT(type));
      }
    }
  } else if (LLVM_SHOULD_PASS_AGGREGATE_USING_BYVAL_ATTR(type, Ty)) {
    C.HandleByValArgument(Ty, type);
    if (Attributes) {
      *Attributes |= Attribute::ByVal;
      *Attributes |= 
	Attribute::constructAlignmentFromInt(LLVM_BYVAL_ALIGNMENT(type));
    }
  } else if (LLVM_SHOULD_PASS_AGGREGATE_IN_INTEGER_REGS(type, &Size,
							&DontCheckAlignment)) {
    PassInIntegerRegisters(type, ScalarElts, Size, DontCheckAlignment);
  } else if (isZeroSizedStructOrUnion(type)) {
    // Zero sized struct or union, just drop it!
    ;
  } else if (TREE_CODE(type) == RECORD_TYPE) {
    for (tree Field = TYPE_FIELDS(type); Field; Field = TREE_CHAIN(Field))
      if (TREE_CODE(Field) == FIELD_DECL) {
	const tree Ftype = getDeclaredType(Field);
	const Type *FTy = ConvertType(Ftype);
	unsigned FNo = GET_LLVM_FIELD_INDEX(Field);
	assert(FNo != ~0U && "Case not handled yet!");

	// Currently, a bvyal type inside a non-byval struct is a zero-length
	// object inside a bigger object on x86-64.  This type should be
	// skipped (but only when it is inside a bigger object).
	// (We know there currently are no other such cases active because
	// they would hit the assert in FunctionPrologArgumentConversion::
	// HandleByValArgument.)
	if (!LLVM_SHOULD_PASS_AGGREGATE_USING_BYVAL_ATTR(Ftype, FTy)) {
	  C.EnterField(FNo, Ty);
	  HandleArgument(getDeclaredType(Field), ScalarElts);
	  C.ExitField();
	}
      }
  } else if (TREE_CODE(type) == COMPLEX_TYPE) {
    C.EnterField(0, Ty);
    HandleArgument(TREE_TYPE(type), ScalarElts);
    C.ExitField();
    C.EnterField(1, Ty);
    HandleArgument(TREE_TYPE(type), ScalarElts);
    C.ExitField();
  } else if ((TREE_CODE(type) == UNION_TYPE) ||
	     (TREE_CODE(type) == QUAL_UNION_TYPE)) {
    HandleUnion(type, ScalarElts);
  } else if (TREE_CODE(type) == ARRAY_TYPE) {
    const ArrayType *ATy = cast<ArrayType>(Ty);
    for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
      C.EnterField(i, Ty);
      HandleArgument(TREE_TYPE(type), ScalarElts);
      C.ExitField();
    }
  } else {
    assert(0 && "unknown aggregate type!");
    abort();
  }
}
Beispiel #21
0
ConditionalReader::ConditionalReader(PClip _child, const char* filename, const char _varname[], bool _show, IScriptEnvironment* env) :
    GenericVideoFilter(_child), show(_show), variableName(_varname)
{
    FILE * f;
    char *line;
    int lines;

    if ((f = fopen(filename, "rb")) == NULL)
        env->ThrowError("ConditionalReader: Could not open file '%s'.", filename);

    lines = 0;
    mode = MODE_UNKNOWN;

    while ((line = readline(f)) != NULL) {
        char *ptr;
        int fields;

        lines++;

        /* We skip spaces */
        ptr = skipspaces(line);

        /* Skip coment lines or empty lines */
        if(iscomment(ptr) || *ptr == '\0') {
            free(line);
            continue;
        }

        if (mode == MODE_UNKNOWN) {
            // We have not recieved a mode - We expect type.
            char keyword [1024];
            char type [1024];
            fields = sscanf(ptr,"%1023s %1023s", keyword, type);
            if (fields) {
                if (!strcasecmp((const char*)keyword, "type")) {
                    if (!strcasecmp((const char*)type, "int")) {
                        mode = MODE_INT;
                        intVal = new int[vi.num_frames];
                    } else if (!strcasecmp((const char*)type, "float")) {
                        mode = MODE_FLOAT;
                        floatVal = new float[vi.num_frames];
                    } else if (!strcasecmp((const char*)type, "bool")) {
                        mode = MODE_BOOL;
                        boolVal = new bool[vi.num_frames];
                    } else {
                        ThrowLine("ConditionalReader: Unknown 'type' specified in line %d", lines, env);
                    }// end if compare type
                }// end if compare keyword
            }// end if fields

        } else { // We have a defined mode and allocated the values.

            char keyword [1024];
            char type [1024];
            fields = sscanf(ptr,"%1023s %1023s", keyword, type);

            if (!strcasecmp((const char*)keyword, "default")) {
                AVSValue def = ConvertType((const char*)type, lines, env);
                SetRange(0, vi.num_frames-1, def);
                free(line);
                continue;
            } // end if "default"

            if (ptr[0] == 'R' || ptr[0] == 'r') {  // Range
                ptr++;
                ptr = skipspaces(ptr);
                int start;
                int stop;
                char value [64];
                fields = sscanf(ptr, "%d %d %63s", &start, &stop, value);

                if (fields != 3)
                    ThrowLine("ConditionalReader: Could not read range in line %d", lines, env);
                if (start > stop)
                    ThrowLine("ConditionalReader: The start frame is after the end frame in line %d", lines, env);

                AVSValue set = ConvertType((const char*)value, lines, env);
                SetRange(start, stop, set);
            } else if (ptr[0] == 'I' || ptr[0] == 'i') {  // Interpolate
                if (mode == MODE_BOOL)
                    ThrowLine("ConditionalReader: Cannot interpolate booleans in line %d", lines, env);

                ptr++;
                ptr = skipspaces(ptr);
                int start;
                int stop;
                char start_value [64];
                char stop_value [64];
                fields = sscanf(ptr, "%d %d %63s %63s", &start, &stop, start_value, stop_value);

                if (fields != 4)
                    ThrowLine("ConditionalReader: Could not read interpolation range in line %d", lines, env);
                if (start > stop)
                    ThrowLine("ConditionalReader: The start frame is after the end frame in line %d", lines, env);

                AVSValue set_start = ConvertType((const char*)start_value, lines, env);
                AVSValue set_stop = ConvertType((const char*)stop_value, lines, env);

                int range = stop-start;
                double diff = set_stop.AsFloat() - set_start.AsFloat();
                for (int i = 0; i<=range; i++) {
                    double where = (double)(i)/(double)range;
                    double n = where * diff + set_start.AsFloat();
                    SetFrame(i+start, (mode == MODE_FLOAT)
                             ? AVSValue(n)
                             : AVSValue((int) n));
                }
            } else {
                char value [64];
                int cframe;
                fields = sscanf(ptr, "%d %63s", &cframe, value);
                if (fields == 2) {
                    AVSValue set = ConvertType((const char*)value, lines, env);
                    SetFrame(cframe, set);
                } else {
                    AVXLOG_INFO("ConditionalReader: Ignored line %d.\n", lines);
                }
            }

        } // End we have defined type
        free(line);
    }// end while still some file left to read.

    /* We are done with the file */
    fclose(f);

    if (mode == MODE_UNKNOWN)
        env->ThrowError("ConditionalReader: Mode was not defined!");

}
entity_member_t* FindEntityMembers(object_t* object, char* str)
{
	int i, j, k, x, count, hit, hit_count, array_count;
	char *temp_str, *value_string, **current_array;
	void *variable_arrays[] = { FileVariableNames, PhysicsVariableNames, DirectVariableNames, 0};
	void *temp_test, **temp_array;
	entity_member_t *members;
	if(!object || !str)
	{
		return NULL;
	}
	if(!object->keys)
	{
		return NULL;
	}

	//Count KV Pairs and Prepare to Collect Hits
	count = CountMem(object->keys, sizeof(jsmntok_t));
	members = (entity_member_t*) malloc(sizeof(entity_member_t)*(count+1));
	if(!members)
	{
		return NULL;
	}

	memset(members, 0, sizeof(entity_member_t)*(count+1));
	
	hit = 0; hit_count = 0;
	value_string = NULL;

	//Iterate through single value keys
	for(i = 0; i < count; i++)
	{
		temp_str = JsmnToString(&object->keys[i], str);
		if(!temp_str)
		{
			continue;
		}

		//Iterate through variable names
		for(j = 0; variable_arrays[j]; j++)
		{
			current_array = (char**) variable_arrays[j];
			for(k = 0; current_array[k]; k++)
			{
				if(!strcmp(temp_str, current_array[k]))
				{
					hit = 1;
					value_string = JsmnToString(&object->values[i], str);
					members[hit_count].data = ConvertType( j, k,  value_string );
					members[hit_count].member_type = j;
					EntityMemberSetType(&members[hit_count], k);
					break;
				}
			}

			if(hit)
			{
				hit = 0;
				hit_count++;
				if(value_string) free(value_string);
				if(temp_str) free(temp_str);
				break;
			}
		}

	}

	count = CountMem(object->children, sizeof(object_t));

	//Check if no valueable targets
	if( (hit_count + count) == 0)
	{
		if(members) free(members);
		return NULL;
	}

	members = (entity_member_t*) realloc(members, sizeof(entity_member_t)*(hit_count+count+1));
	if(!members)
	{
		return NULL;
	}

	for(i = 0; i < count; i++)
	{
		temp_str = object->children[i].name;
		if(!temp_str)
		{
			continue;
		}
	
		for(j = 0; variable_arrays[j]; j++)
		{
			current_array = (char**) variable_arrays[j];
			for(k = 0; current_array[k]; k++)
			{
				if(!strcmp(temp_str, current_array[k]))
				{
					hit = 1;
					array_count = CountMem(object->children[i].values, sizeof(jsmntok_t));

					//Test for variable size to adjust our array
					value_string = JsmnToString(&object->children[i].values[0], str);
					temp_test = ConvertType(j, k, value_string );
					if(value_string) free(value_string);
#ifdef _WIN32
					x = _msize(temp_test);
#elif _LINUX
					x = malloc_size(temp_test);
#endif

					//Assign Values Accordingly
					if(x == sizeof(char*))
					{
						temp_array = (void**) malloc(sizeof(char*)*(array_count+1));
						if(!temp_array)
						{
							hit = 0;
							break;
						}

						((char**)temp_array)[0] = (char*) temp_test;

						for(x = 1; x < array_count; x++)
						{
							value_string = JsmnToString(&object->children[i].values[x], str);
							temp_test =  ConvertType(j, k, value_string );
							((char**)temp_array)[x] = (char*) temp_test;
								
							if(value_string) free(value_string);
						}

						((char**)temp_array)[array_count] = NULL;

					} else if( x == sizeof(cpFloat) )
					{
						temp_array = (void**) malloc(sizeof(cpFloat)*(array_count+1));
						if(!temp_array)
						{
							hit = 0;
							break;
						}
						((cpFloat*)temp_array)[0] = *(cpFloat*) temp_test;
						if(temp_test) free(temp_test);

						for(x = 1; x < array_count; x++)
						{
							value_string = JsmnToString(&object->children[i].values[x], str);
							temp_test = ConvertType(j, k, value_string );
							if(temp_test)
							{
								((cpFloat*)temp_array)[x] = *(cpFloat*) temp_test;
								free(temp_test);
							}
							
							if(value_string) free(value_string);
						}

						((cpFloat*)temp_array)[array_count] = (cpFloat) 0;

					} else
					{
						if(temp_test) free(temp_test);
						break;
					}
					
					
					
					members[hit_count].data = temp_array;
					members[hit_count].member_type = j;
					EntityMemberSetType(&members[hit_count], k);
					break;
				}
			}

			if(hit)
			{
				hit = 0;
				hit_count++;
				break;
			}
		}
	}

	//Check if we never hit a value
	if(hit_count == 0)
	{
		if(members) free(members);
		return NULL;
	}

	memset(&members[hit_count], 0, sizeof(entity_member_t));
	return members;
}
Beispiel #23
0
		SEM::Var* ConvertVar(Context& context, const Debug::VarInfo::Kind varKind, const AST::Node<AST::TypeVar>& astTypeVarNode) {
			const auto& location = astTypeVarNode.location();
			
			switch (astTypeVarNode->kind()) {
				case AST::TypeVar::ANYVAR: {
					throw ErrorException("'Any' vars not yet implemented for uninitialised variables.");
				}
				
				case AST::TypeVar::NAMEDVAR: {
					const auto& varName = astTypeVarNode->name();
					
					// Search all scopes outside of the current scope.
					const auto searchStartPosition = 1;
					if (varKind != Debug::VarInfo::VAR_MEMBER && !performSearch(context, Name::Relative() + varName, searchStartPosition).isNone()) {
						throw ErrorException(makeString("Variable '%s' shadows existing object at position %s.",
							varName.c_str(), location.toString().c_str()));
					}
					
					const auto varType = ConvertType(context, astTypeVarNode->namedType());
					
					// 'final' keyword uses a different lval type (which doesn't support
					// moving or re-assignment).
					const bool isFinalLval = astTypeVarNode->isFinal();
					
					const auto lvalType = makeLvalType(context, isFinalLval, varType);
					
					const auto var = SEM::Var::Basic(varType, lvalType);
					var->setMarkedUnused(astTypeVarNode->isUnused());
					var->setOverrideConst(astTypeVarNode->isOverrideConst());
					attachVar(context, varName, astTypeVarNode, var, varKind);
					return var;
				}
				
				case AST::TypeVar::PATTERNVAR: {
					const auto varType = ConvertType(context, astTypeVarNode->patternType())->resolveAliases();
					
					if (!varType->isDatatype()) {
						throw ErrorException(makeString("Can't pattern match for non-datatype '%s' at position %s.",
							varType->toString().c_str(), location.toString().c_str()));
					}
					
					const auto& astChildTypeVars = astTypeVarNode->typeVarList();
					const auto& typeChildVars = varType->getObjectType()->variables();
					
					if (astChildTypeVars->size() != typeChildVars.size()) {
						throw ErrorException(makeString("%llu pattern match children specified; %llu expected (for type '%s') at position %s.",
								(unsigned long long) astChildTypeVars->size(),
								(unsigned long long) typeChildVars.size(),
								varType->toString().c_str(),
								location.toString().c_str()));
					}
					
					const auto templateVarMap = varType->generateTemplateVarMap();
					
					std::vector<SEM::Var*> children;
					
					for (size_t i = 0; i < typeChildVars.size(); i++) {
						const auto& astVar = astChildTypeVars->at(i);
						children.push_back(ConvertVar(context, varKind, astVar));
					}
					
					return SEM::Var::Composite(varType, children);
				}
			}
			
			std::terminate();
		}
void MaterialDatabaseReader::ProcessElementBeginContent()
{
    if( MATCH_ELEMENT_NAME( L"Material" ) )
    {
        m_pCurrentMaterial = nullptr;

        const WCHAR* strName = FindAttribute( L"Name" );
        if( !strName )
            return;

        m_pCurrentMaterial = new ExportMaterialDefinition();
        m_pCurrentMaterial->strName = ConvertString( strName );

        const WCHAR* strDesc = FindAttribute( L"Description" );
        if( strDesc )
            m_pCurrentMaterial->strDescription = ConvertString( strDesc );

        g_Materials.push_back( m_pCurrentMaterial );
        return;
    }
    else if( MATCH_ELEMENT_NAME( L"Parameter" ) )
    {
        if( !m_pCurrentMaterial )
            return;

        if( m_pCurrentParam )
            return;

        const WCHAR* strName = FindAttribute( L"Name" );
        if( !strName )
            return;

        m_pCurrentParam = new ExportMaterialParameterDefinition();
        m_pCurrentParam->strName = ConvertString( strName );

        m_pCurrentMaterial->Parameters.push_back( m_pCurrentParam );

        const WCHAR* strDisplayName = FindAttribute( L"DisplayName" );
        if( strDisplayName )
            m_pCurrentParam->strDisplayName = ConvertString( strDisplayName );
        else
            m_pCurrentParam->strDisplayName = m_pCurrentParam->strName;

        const WCHAR* strDesc = FindAttribute( L"Description" );
        m_pCurrentParam->strDescription = ConvertString( strDesc );

        const WCHAR* strDisplayHint = FindAttribute( L"DisplayHint" );
        if( !strDisplayHint || wcslen( strDisplayHint ) < 1 )
            m_pCurrentParam->strDisplayHint = " ";
        else
            m_pCurrentParam->strDisplayHint = ConvertString( strDisplayHint );

        const WCHAR* strLoaderHint = FindAttribute( L"LoadHint" );
        m_pCurrentParam->strLoaderHint = ConvertString( strLoaderHint );

        const WCHAR* strType = FindAttribute( L"Type" );
        m_pCurrentParam->ParamType = ConvertType( strType );

        const WCHAR* strVisible = FindAttribute( L"ToolVisible" );
        m_pCurrentParam->bVisibleInTool = ConvertBool( strVisible, false );

        const WCHAR* strExport = FindAttribute( L"Export" );
        m_pCurrentParam->bExportToContentFile = ConvertBool( strExport, true );

        const WCHAR* strDetectAlpha = FindAttribute( L"DetectAlpha" );
        m_pCurrentParam->bDetectAlpha = ConvertBool( strDetectAlpha, false );

        const WCHAR* strDefaultValue = FindAttribute( L"DefaultValue" );
        m_pCurrentParam->strDefaultValue = ConvertString( strDefaultValue );
        return;
    }
}
/// emit_global_to_llvm - Emit the specified VAR_DECL or aggregate CONST_DECL to
/// LLVM as a global variable.  This function implements the end of
/// assemble_variable.
void emit_global_to_llvm(tree decl) {
  if (errorcount || sorrycount) return;

  // FIXME: Support alignment on globals: DECL_ALIGN.
  // FIXME: DECL_PRESERVE_P indicates the var is marked with attribute 'used'.

  // Global register variables don't turn into LLVM GlobalVariables.
  if (TREE_CODE(decl) == VAR_DECL && DECL_REGISTER(decl))
    return;

  timevar_push(TV_LLVM_GLOBALS);

  // Get or create the global variable now.
  GlobalVariable *GV = cast<GlobalVariable>(DECL_LLVM(decl));
  
  // Convert the initializer over.
  Constant *Init;
  if (DECL_INITIAL(decl) == 0 || DECL_INITIAL(decl) == error_mark_node) {
    // This global should be zero initialized.  Reconvert the type in case the
    // forward def of the global and the real def differ in type (e.g. declared
    // as 'int A[]', and defined as 'int A[100]').
    Init = Constant::getNullValue(ConvertType(TREE_TYPE(decl)));
  } else {
    assert((TREE_CONSTANT(DECL_INITIAL(decl)) || 
            TREE_CODE(DECL_INITIAL(decl)) == STRING_CST) &&
           "Global initializer should be constant!");
    
    // Temporarily set an initializer for the global, so we don't infinitely
    // recurse.  If we don't do this, we can hit cases where we see "oh a global
    // with an initializer hasn't been initialized yet, call emit_global_to_llvm
    // on it".  When constructing the initializer it might refer to itself.
    // this can happen for things like void *G = &G;
    //
    GV->setInitializer(UndefValue::get(GV->getType()->getElementType()));
    Init = TreeConstantToLLVM::Convert(DECL_INITIAL(decl));
  }

  // If we had a forward definition that has a type that disagrees with our
  // initializer, insert a cast now.  This sort of thing occurs when we have a
  // global union, and the LLVM type followed a union initializer that is
  // different from the union element used for the type.
  if (GV->getType()->getElementType() != Init->getType()) {
    GV->removeFromParent();
    GlobalVariable *NGV = new GlobalVariable(Init->getType(), GV->isConstant(),
                                             GlobalValue::ExternalLinkage, 0,
                                             GV->getName(), TheModule);
    GV->replaceAllUsesWith(ConstantExpr::getBitCast(NGV, GV->getType()));
    delete GV;
    SET_DECL_LLVM(decl, NGV);
    GV = NGV;
  }
 
  // Set the initializer.
  GV->setInitializer(Init);

  // Set thread local (TLS)
  if (TREE_CODE(decl) == VAR_DECL && DECL_THREAD_LOCAL(decl))
    GV->setThreadLocal(true);

  // Set the linkage.
  if (!TREE_PUBLIC(decl)) {
    GV->setLinkage(GlobalValue::InternalLinkage);
  } else if (DECL_WEAK(decl) || DECL_ONE_ONLY(decl) ||
             (DECL_COMMON(decl) &&  // DECL_COMMON is only meaningful if no init
              (!DECL_INITIAL(decl) || DECL_INITIAL(decl) == error_mark_node))) {
    // llvm-gcc also includes DECL_VIRTUAL_P here.
    GV->setLinkage(GlobalValue::WeakLinkage);
  } else if (DECL_COMDAT(decl)) {
    GV->setLinkage(GlobalValue::LinkOnceLinkage);
  }

#ifdef TARGET_ADJUST_LLVM_LINKAGE
  TARGET_ADJUST_LLVM_LINKAGE(GV,decl);
#endif /* TARGET_ADJUST_LLVM_LINKAGE */

  // Handle visibility style
  if (TREE_PUBLIC(decl)) {
    if (DECL_VISIBILITY(decl) == VISIBILITY_HIDDEN)
      GV->setVisibility(GlobalValue::HiddenVisibility);
    else if (DECL_VISIBILITY(decl) == VISIBILITY_PROTECTED)
      GV->setVisibility(GlobalValue::ProtectedVisibility);
  }

  // Set the section for the global.
  if (TREE_CODE(decl) == VAR_DECL || TREE_CODE(decl) == CONST_DECL) {
    if (DECL_SECTION_NAME(decl)) {
      GV->setSection(TREE_STRING_POINTER(DECL_SECTION_NAME(decl)));
#ifdef LLVM_IMPLICIT_TARGET_GLOBAL_VAR_SECTION
    } else if (const char *Section = 
                LLVM_IMPLICIT_TARGET_GLOBAL_VAR_SECTION(decl)) {
      GV->setSection(Section);
#endif
    }
    
    // Set the alignment for the global if one of the following condition is met
    // 1) DECL_ALIGN_UNIT does not match alignment as per ABI specification
    // 2) DECL_ALIGN is set by user.
    if (DECL_ALIGN_UNIT(decl)) {
      unsigned TargetAlign = getTargetData().getABITypeAlignment(GV->getType()->getElementType());
      if (DECL_USER_ALIGN(decl) || TargetAlign != DECL_ALIGN_UNIT(decl))
        GV->setAlignment(DECL_ALIGN_UNIT(decl));
    }

    // Handle used decls
    if (DECL_PRESERVE_P (decl)) {
      const Type *SBP= PointerType::get(Type::Int8Ty);
      AttributeUsedGlobals.push_back(ConstantExpr::getBitCast(GV, SBP));
    }
  
    // Add annotate attributes for globals
    if (DECL_ATTRIBUTES(decl))
      AddAnnotateAttrsToGlobal(GV, decl);
  }
  
  if (TheDebugInfo) TheDebugInfo->EmitGlobalVariable(GV, decl); 
  
  timevar_pop(TV_LLVM_GLOBALS);
}
bool CGUIDialogSmartPlaylistEditor::OnMessage(CGUIMessage& message)
{
  switch ( message.GetMessage() )
  {
  case GUI_MSG_CLICKED:
    {
      int iControl = message.GetSenderId();
      int iAction = message.GetParam1();
      if (iControl == CONTROL_RULE_LIST && (iAction == ACTION_SELECT_ITEM || iAction == ACTION_MOUSE_LEFT_CLICK))
        OnRuleList(GetSelectedItem());
      else if (iControl == CONTROL_RULE_ADD)
        OnRuleAdd();
      else if (iControl == CONTROL_RULE_EDIT)
        OnRuleList(GetSelectedItem());
      else if (iControl == CONTROL_RULE_REMOVE)
        OnRuleRemove(GetSelectedItem());
      else if (iControl == CONTROL_NAME)
        OnEditChanged(iControl, m_playlist.m_playlistName);
      else if (iControl == CONTROL_OK)
        OnOK();
      else if (iControl == CONTROL_CANCEL)
        OnCancel();
      else if (iControl == CONTROL_MATCH)
        OnMatch();
      else if (iControl == CONTROL_LIMIT)
        OnLimit();
      else if (iControl == CONTROL_ORDER_FIELD)
        OnOrder();
      else if (iControl == CONTROL_ORDER_DIRECTION)
        OnOrderDirection();
      else if (iControl == CONTROL_TYPE)
        OnType();
      else if (iControl == CONTROL_GROUP_BY)
        OnGroupBy();
      else if (iControl == CONTROL_GROUP_MIXED)
        OnGroupMixed();
      else
        return CGUIDialog::OnMessage(message);
      return true;
    }
    break;
  case GUI_MSG_FOCUSED:
    if (message.GetControlId() == CONTROL_RULE_REMOVE ||
        message.GetControlId() == CONTROL_RULE_EDIT)
      HighlightItem(GetSelectedItem());
    else
    {
      if (message.GetControlId() == CONTROL_RULE_LIST)
        UpdateRuleControlButtons();

      HighlightItem(-1);
    }
    break;
  case GUI_MSG_WINDOW_INIT:
    {
      const std::string& startupList = message.GetStringParam(0);
      if (!startupList.empty())
      {
        int party = 0;
        if (URIUtils::PathEquals(startupList, CProfilesManager::GetInstance().GetUserDataItem("PartyMode.xsp")))
          party = 1;
        else if (URIUtils::PathEquals(startupList, CProfilesManager::GetInstance().GetUserDataItem("PartyMode-Video.xsp")))
          party = 2;

        if ((party && !XFILE::CFile::Exists(startupList)) ||
             m_playlist.Load(startupList))
        {
          m_path = startupList;

          if (party == 1)
            m_mode = "partymusic";
          else if (party == 2)
            m_mode = "partyvideo";
          else
          {
            PLAYLIST_TYPE type = ConvertType(m_playlist.GetType());
            if (type == TYPE_SONGS || type == TYPE_ALBUMS || type == TYPE_ARTISTS)
              m_mode = "music";
            else
              m_mode = "video";
          }
        }
        else
          return false;
      }
    }
    break;
  }
  return CGUIDialog::OnMessage(message);
}
Beispiel #27
0
ConditionalReader::ConditionalReader(PClip _child, const char* filename, const char _varname[], bool _show, IScriptEnvironment* env)
 : GenericVideoFilter(_child), show(_show), variableName(_varname), mode(MODE_UNKNOWN), offset(0), stringcache(0)
{
  FILE * f;
  char *line = 0;
  int lines;

  if ((f = fopen(filename, "rb")) == NULL)
    env->ThrowError("ConditionalReader: Could not open file '%s'.", filename);

  lines = 0;

  try {
    while ((line = readline(f)) != NULL) {
      char *ptr;
      int fields;

      lines++;

      /* We skip spaces */
      ptr = skipspaces(line);

      /* Skip coment lines or empty lines */
      if(iscomment(ptr) || *ptr == '\0') {
        free(line);
        line = 0;
        continue;
      }

      if (mode == MODE_UNKNOWN) {
        // We have not recieved a mode - We expect type.
        char* keyword = ptr;

        ptr = findspace(ptr);
        if (*ptr) {
          *ptr++ = '\0';
          if (!lstrcmpi(keyword, "type")) {
            /* We skip spaces */
            char* type = skipspaces(ptr);

            ptr = findspace(type);
            *ptr = '\0';

            if (!lstrcmpi(type, "int")) {
              mode = MODE_INT;
              intVal = new int[vi.num_frames];
            } else if (!lstrcmpi(type, "float")) {
              mode = MODE_FLOAT;
              floatVal = new float[vi.num_frames];
            } else if (!lstrcmpi(type, "bool")) {
              mode = MODE_BOOL;
              boolVal = new bool[vi.num_frames];
            } else if (!lstrcmpi(type, "string")) {
              mode = MODE_STRING;
              stringVal = new const char*[vi.num_frames];
            } else {
              ThrowLine("ConditionalReader: Unknown 'Type' specified in line %d", lines, env);
            }// end if compare type
            SetRange(0, vi.num_frames-1, AVSValue());
          }// end if compare keyword
        }// end if fields

      } else { // We have a defined mode and allocated the values.

        char* keyword = ptr;
        char* type = findspace(keyword);

        if (*type) *type++ = '\0';

        if (!lstrcmpi(keyword, "default")) {
          AVSValue def = ConvertType(type, lines, env);
          SetRange(0, vi.num_frames-1, def);

        } else if (!lstrcmpi(keyword, "offset")) {
          fields = sscanf(type, "%d", &offset);
          if (fields != 1) 
            ThrowLine("ConditionalReader: Could not read Offset in line %d", lines, env);

        } else if (keyword[0] == 'R' || keyword[0] == 'r') {  // Range
          int start;
          int stop;

          type = skipspaces(type);
          fields = sscanf(type, "%d", &start);

          type = findspace(type);
          type = skipspaces(type);
          fields += sscanf(type, "%d", &stop);

          type = findspace(type);
          if (!*type || fields != 2)
            ThrowLine("ConditionalReader: Could not read Range in line %d", lines, env);

          if (start > stop)
            ThrowLine("ConditionalReader: The Range start frame is after the end frame in line %d", lines, env);

          AVSValue set = ConvertType(type+1, lines, env);
          SetRange(start, stop, set);

        } else if (keyword[0] == 'I' || keyword[0] == 'i') {  // Interpolate
          if (mode == MODE_BOOL)
            ThrowLine("ConditionalReader: Cannot Interpolate booleans in line %d", lines, env);

          if (mode == MODE_STRING)
            ThrowLine("ConditionalReader: Cannot Interpolate strings in line %d", lines, env);

          type = skipspaces(type);
          int start;
          int stop;
          char start_value[64];
          char stop_value[64];
          fields = sscanf(type, "%d %d %63s %63s", &start, &stop, start_value, stop_value);

          if (fields != 4) 
            ThrowLine("ConditionalReader: Could not read Interpolation range in line %d", lines, env);
          if (start > stop)
            ThrowLine("ConditionalReader: The Interpolation start frame is after the end frame in line %d", lines, env);

          start_value[63] = '\0';
          AVSValue set_start = ConvertType(start_value, lines, env);

          stop_value[63] = '\0';
          AVSValue set_stop = ConvertType(stop_value, lines, env);

          const int range = stop-start;
          const double diff = (set_stop.AsFloat() - set_start.AsFloat()) / range;
          for (int i = 0; i<=range; i++) {
            const double n = i * diff + set_start.AsFloat();
            SetFrame(i+start, (mode == MODE_FLOAT)
                    ? AVSValue(n)
                    : AVSValue((int)(n+0.5)));
          }
        } else {
          int cframe;
          fields = sscanf(keyword, "%d", &cframe);
          if (*type && fields == 1) {
            AVSValue set = ConvertType(type, lines, env);
            SetFrame(cframe, set);
          } else {
            ThrowLine("ConditionalReader: Do not understand line %d", lines, env);
          }
        }
      
      } // End we have defined type
      free(line);
      line = 0;
    }// end while still some file left to read.
  }
  catch (...) {
    if (line) free(line);
    fclose(f);
    CleanUp();
    throw;
  }

  /* We are done with the file */
  fclose(f);

  if (mode == MODE_UNKNOWN)
    env->ThrowError("ConditionalReader: Type was not defined!");

}
llvm::Value* Unop::Codegen(WasmFunction* fct, llvm::IRBuilder<>& builder) {
  bool is_intrinsic = false;
  OPERATION op = operation_->GetOperation();

  switch (op) {
    case CLZ_OPER:
    case CTZ_OPER:
    case POPCNT_OPER:
    case SQRT_OPER:
    case ABS_OPER:
    case CEIL_OPER:
    case FLOOR_OPER:
    case NEAREST_OPER:
      is_intrinsic = true;
      break;
    case TRUNC_OPER: {
        // Use the intrinsic value if we have the same type.
        //   Basically this is used for f32.trunc or f64.trunc...
        ConversionOperation* conversion = dynamic_cast<ConversionOperation*>(operation_);
        assert(conversion != nullptr);
        is_intrinsic = (conversion->GetSrc() == conversion->GetDest());
        break;
    }
    default:
      break;
  }

  if (is_intrinsic == true) {
    WasmModule* wasm_module = fct->GetModule();
    ETYPE type = operation_->GetType();
    llvm::Intrinsic::ID intrinsic;

    bool extra_true_arg = false;

    switch (op) {
      case CLZ_OPER:
        intrinsic = llvm::Intrinsic::ctlz;
        // We need to pass true as second argument to produce defined result for zero.
        extra_true_arg = true;
        break;
      case CTZ_OPER:
        intrinsic = llvm::Intrinsic::cttz;
        // We need to pass true as second argument to produce defined result for zero.
        extra_true_arg = true;
        break;
      case POPCNT_OPER:
        intrinsic = llvm::Intrinsic::ctpop;
        break;
      case SQRT_OPER:
        intrinsic = llvm::Intrinsic::sqrt;
        break;
      case ABS_OPER:
        intrinsic = llvm::Intrinsic::fabs;
        break;
      case CEIL_OPER:
        intrinsic = llvm::Intrinsic::ceil;
        break;
      case FLOOR_OPER:
        intrinsic = llvm::Intrinsic::floor;
        break;
      case TRUNC_OPER:
        intrinsic = llvm::Intrinsic::trunc;
        break;
      case NEAREST_OPER:
        intrinsic = llvm::Intrinsic::nearbyint;
        break;
      default:
        assert(0);
        return nullptr;
    }

    llvm::Function* intrinsic_fct = wasm_module->GetOrCreateIntrinsic(intrinsic, type);
    assert(intrinsic_fct != nullptr);

    std::vector<Value*> arg;
    arg.push_back(only_->Codegen(fct, builder));

    if (extra_true_arg) {
      llvm::Value* val_true = llvm::ConstantInt::get(llvm::getGlobalContext(), APInt(1, 0, false));
      arg.push_back(val_true);
    }

    return builder.CreateCall(intrinsic_fct, arg, "calltmp");
  } else {
    llvm::Value* rv = only_->Codegen(fct, builder);
    ETYPE type = operation_->GetType();

    switch (op) {
      case NEG_OPER: {
        llvm::Value* lv;
        if (type == FLOAT_32) {
          lv = llvm::ConstantFP::get(llvm::getGlobalContext(), APFloat(0.0f));
        } else {
          lv = llvm::ConstantFP::get(llvm::getGlobalContext(), APFloat(0.0));
        }
        return builder.CreateFSub(lv, rv, "subtmp");
      }

      case REINTERPRET_OPER:
        return builder.CreateBitCast(rv, ConvertType(type), DumpOperation(op));

      case EXTEND_OPER:
      case TRUNC_OPER:
      case PROMOTE_OPER:
      case DEMOTE_OPER:
      case CONVERT_OPER:
      case WRAP_OPER: {
        ConversionOperation* conversion = dynamic_cast<ConversionOperation*>(operation_);
        assert(conversion != nullptr);
        return HandleTypeCasts(rv, ConvertType(conversion->GetSrc()), ConvertType(type), operation_->GetSignedOrOrdered(), builder);
      }
    }

    assert(0);
    return nullptr;
  }
}