Search code examples
clualuajittorch

How does this C code (from lua library, Torch) even compile/work?


See https://github.com/torch/nn/blob/master/generic/Tanh.c

For example,

 static int nn_(Tanh_updateOutput)(lua_State *L)
{
   THTensor *input = luaT_checkudata(L, 2, torch_Tensor);
   THTensor *output = luaT_getfieldcheckudata(L, 1, "output", torch_Tensor);

   THTensor_(resizeAs)(output, input);

   if (input->nDimension == 1 || !THTensor_(isContiguous)(input) || !THTensor_(isContiguous)(output))
   {
    TH_TENSOR_APPLY2(real, output, real, input,   \
     *output_data = tanh(*input_data););
    }
  else
  {
   real* ptr_output = THTensor_(data)(output);
   real* ptr_input  = THTensor_(data)(input);
   long i;
 #pragma omp parallel for private(i)
for(i = 0; i < THTensor_(nElement)(input); i++)
  ptr_output[i] = tanh(ptr_input[i]);
}
return 1;
}

First, it I don't know how to interpret the first line:

 static int nn_(Tanh_updateOutput)(lua_State *L)

What are the arguments here? What does Tanh_updateOutput refer to? Does "nn_" have special meaning?

Second, "TH_TENSOR_APPLY2" and "THTensor_(...)" are both used but I don't see where they are defined? There are no other includes in this file?


Solution

  • nn_ is a macro. You can find the definition by searching the repository for "#define nn_"; it's in init.c:

    #define nn_(NAME) TH_CONCAT_3(nn_, Real, NAME)
    

    You can keep following the chain of macro definitions, and you'll probably end up with some token pasting thing that makes nn_(Tanh_updateOutput) expand to the name of the function.

    (It's weird that generic/Tanh.c doesn't have any includes; generic/Tanh.c must be included by some other file. That's unusual for .c files.)